please format code with </> button * homework policy * asking questions
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);
}
}
}