Hi i’m working on making snake with a 2d array. Right now i’m trying to move a single square but i can’t get it to work. When moving up or left everthing works fine but when moving the square down or to the right it dosn’t draw the differences in the squares position. Can someone please take a look at my code below and tell me what i’m doing wrong.
Here is the main tab code:
int rows= 15;
int columns= 15;
String direction = "none";
sqaure[][] sqaurematrix = new sqaure[rows][columns];
void setup() {
size (375, 375);
for (int y=0; y<columns; y++) {
for (int x=0; x<rows; x++) {
sqaurematrix[x][y]= new sqaure(x, y);
println(sqaurematrix[x][y].xpos, sqaurematrix[x][y].ypos );
}
}
sqaurematrix[7][7].snakehead=true;
}
void draw() {
for (int y=0; y<columns; y++) {
for (int x=0; x<rows; x++) {
sqaurematrix[x][y].display();
}
}
for (int y=0; y<columns; y++) {
for (int x=0; x<rows; x++) {
sqaurematrix[x][y].move();
}
}
}
void keyPressed() {
if (key == 'w') {
direction = "up";
}
if (key == 's') {
direction = "down";
}
if (key == 'a') {
direction = "left";
}
if (key == 'd') {
direction = "right";
}
}
Here is the square object code:
class sqaure {
int xpos, ypos;
color c = color(0, 255, 0);
boolean snakehead = false;
sqaure(int xpos, int ypos) {
this.xpos = xpos;
this.ypos = ypos;
}
void display() {
if (snakehead) {
fill(0, 0, 255);
} else {
fill(c);
}
rect(xpos*25, ypos*25, 25, 25);
}
void move() {
if (snakehead) {
if (direction=="up" && ypos>0) {
snakehead=false;
sqaurematrix[xpos][ypos-1].snakehead=true;
}
if (direction=="down" && ypos<columns-1) {
snakehead=false;
sqaurematrix[xpos][ypos+1].snakehead=true;
}
if (direction=="right" && xpos<rows-1) {
snakehead=false;
sqaurematrix[xpos+1][ypos].snakehead=true;
}
if (direction=="left" && xpos>0) {
snakehead=false;
sqaurematrix[xpos-1][ypos].snakehead=true;
}
delay(500);
println(xpos,ypos);
}
}
}
As you can see, the function move() is called again and again for every cell, searching the cell with the snake head and moving it. But when we moved the snake head, we don’t store the information that we are done.
Instead the nested for-loop goes on. What happens now (when we clicked down or right) is that it finds the next cell with (the newly placed) snakehead being true in if (snakehead) {. So the snake head is moved again. And then again. So it falls down (or to the right).
Because of the search direction is right and down in the nested for loop, this happens.
BUT when the movement was up or left, the snake head is moved once but because the search direction is down, the moved snake head is not found nor moved again.
My solution
I told the function move() to return true once it found something and otherwise false.
And in draw() in the nested for-loop I said
if (squarematrix[x][y].move())return;
which means it leaves the nested for-loop (and the function). Hence, we don’t move the snake head again.