Skip to main content

Game Update

With loop structure and data structures defined for the game, we now have to use our loop's structure to update our data, bringing one game state to the next.

Update Structure#

Here's a general outline for the structure of our update function:

  • Get user input
  • Decide which way the Snake should move
  • Check if the Snake is going to hit anything that will affect the game state & handle change
  • Move the Snake

User Input#

First thing's first, users interact with the Snake game through the joystick. Without the user input, nothing interesting happens in the game.

So, let's begin working on void updateSnake() by writing code to determine the joystick's position during a game tick:

snake.ino
void updateSnake() {  // Read joystick values  int xValue = analogRead(joyX);  int yValue = analogRead(joyY);  int xMap = map(xValue, 0,4095, -10, 10);  int yMap = map(yValue, 0,4095, -10, 10);}

The above code reads in the X and Y values from the joystick, and then maps the raw analog signal rage (0, 4095) to a more reasonable (-10, 10) range in the variables xMap and yMap.

With the joystick values read in, we can process them to decide which direction the user wants the Snake to turn:

snake.ino
void updateSnake() {  ... // EXISTING CODE
  // Handle movement logic  if (abs(xMap) > 3 || abs(yMap) > 3) { // Remove noise by making sure the joystick is turned at least 30% off an axis      if (abs(xMap) > abs(yMap)) {          if (xMap > 0) {              snake.dir = Direction::right;          } else {              snake.dir = Direction::left;          }      } else {          if (yMap > 0) {              snake.dir = Direction::down;          } else {              snake.dir = Direction::up;          }      }  }
info

The abs(val) function returns the absolute value of the number supplied to it.

drawing

This Content is Locked

Enter your GCA kit's access code to continue