Problems with understanding language

So why doesn’t the tail grow now? Well, it never did, did it?

The problem is that append() returns an array - it doesn’t assign that array to anything. Basically, whoever wrote this didn’t use append() properly.

There are several other problems with this code as well. But I think the biggest problem, really, is that you ALREADY HAD this code. The best thing to do would be to take this code as an example and write a BETTER VERSION yourself, from scratch.

So let’s do that. Start with an empty sketch.

void setup(){
  size(600,400);
}

void draw(){
  background(0);
}

This code is already better than what you started with because it is 100% bug free & you understand it completely.

For most people, the next step is to try to write code. This is the wrong approach. For good coders, the next step is to break the large problem of “MAKE A SNAKE GAME” down into smaller steps. That’s better. But for once, we’re going to jump right into thinking with Portals. No wait, Objects. Now we’re thinking with Objects.

What sort of Objects would you need to have a snake game?

You need a snake.
You need food.
Anything else?
I can think of one that might be useful. A timer. That way we can avoid the weird t variable and how it was being used.

Let’s write those objects!

class Snake {
  // Maybe sme sort of way of storing body segments?
  int d; // Direction
  Snake() {
    d = 0;
  }
  void draw() {
  }
  void update() {
  }
  void grow() {
  }
  void onKeyPressed() {
  }
}

class Food {
  int x, y;
  Food() {
  }
  void draw() {
  }
  boolean wasEaten() {
    return false;
  }
}

class Timer {
  int time;
  int duration;
  Timer() {
    duration = 500;
    reset();
  }
  void reset() {
    time = millis() + duration;
  }
  boolean alarm() {
    if ( millis() > time ) {
      time = millis() + duration;
      return true;
    }
    return false;
  }
}

Why bother doing it this way?!?

This is why! Our main driving code becomes much easier to understand:

Snake snake;
Food food;
Timer timer;

void setup() {
  size(600, 400);
  snake = new Snake();
  food = new Food();
  timer = new Timer();
}

void draw() {
  background(0);
  if ( timer.alarm() ) {
    snake.update();
    if ( food.wasEaten() ) {
      snake.grow();
    }
  }
  food.draw();
  snake.draw();
}

void keyPressed() {
  snake.onKeyPressed();
}
2 Likes