For Loop in Processing (snake game)

Hello,

remember to hit ctrl-t to get auto-format in processing.
Then you’ll see you had one misplaced }.

I rewrote some of the code. See below.

What you should do: Think of how the snake moves when it’s longer. Best use an array (or two arrays, one for xValues and one yValues) to keep track of the positions of each cell/ellipse within the snake. Your for loop essentially just displays each position / ellipse of the array.

Moving the snake means to copy from the head into the array and move each data one slot down the array.

Chrisir

Rewritten code
with not much changes

final int SNAKE_SIZE=20;

final int X_SPEED = 1;
final int Y_SPEED = 1;

int x = 250;
int y = 250;

int SNAKE_LENGTH=3;

// ---------------------------------------------------------------------------

void setup() {
  size(500, 500);
  background(220);

  y=250;
}

//ellipse(250,290,SNAKE_SIZE,SNAKE_SIZE);
void draw() {
  background(220);

  if (x >= 500 || x <= 0) {
    background(0);
  }
  if (y >= 500 || y <= 0) {
    background(0);
  }

  drawSnake();
}

void drawSnake() {
  int y2=0; 
  for (int i=0; i<SNAKE_LENGTH; i++) {
    ellipse(x, y+y2, SNAKE_SIZE, SNAKE_SIZE);
    y2+=20;
  }
}

void keyPressed() {
  if (key=='w') {
    drawSnake();
    y -= Y_SPEED;
  }
  if (key=='s') {
    drawSnake();
    y += Y_SPEED;
  }
  if (key=='a') {
    drawSnake();
    x -= X_SPEED;
  }
  if (key=='d') {
    drawSnake();
    x += X_SPEED;
  }
}
//

2 Likes