We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Im playing around with a knights tour program. I have some code to draw out a chess board. In Draw() im stepping through a 2d array and checking for a value of 1. When 1 is found it should change the fill color to green. It functions correctly if I hard code the 1 into the matrix, but if I set the value to 1 with a MousePressed it wont change colors. When I try to set background(255) to refresh, it just makes the window white and the board doesn't draw.
int xCur,yCur,x,y,rWidth,rHeight,count;
int rows = 8;
int cols = 8;
int[][] boardArray = { {0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0}};
void setup(){
size(600,600);
x=1;
y=1;
count=1;
rWidth=width/8;
rHeight=height/8;
}
void draw(){
//background(255);
findMove();
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
count++; // counting number of board tiles
if(count % 2==0){ // toggle tile colors black and white
fill(255);
} else {
fill(0);
}
if(boardArray[i][j] == 1){ // color green if 1 is found
fill(0,255,0);
println("Detected");
}
rect(x,y,rWidth,rHeight);
y+=rHeight;
}
y=1;
x+=rWidth;
count++; //offset tile pattern
}
}
void findMove(){
xCur = 0;
yCur = 0;
if(boardArray[xCur+2][yCur+1] == 0){
//boardArray[xCur+2][yCur+1]=1; //this will turn on a green tile if uncommented
}
}
void mousePressed(){
println("Pressed");
boardArray[1][1]=1; // cannot get this line of code to work
}
Answers
You don't reset the variables after draw(), so x, y, count go to draw unseen sections of the sketch... This is visible if you uncomment the background() call: the first frame probably draw correctly the checkboard, but it is then erased, and the further rect() calls are way beyond the area.
Using println() of values is also useful when debugging.
Improvement proposal: compute x and y from i and j, thus they will be automatically reset. Or just avoid declaring them global (they are used in only one function), declare them at the start of draw().