Skip to content
Advertisement

how to control snake with only two keys i.e left and right

currently, i’m using all four keys to steer the snake left, right, up and down. I’m wondering how can i only use left and right key to move the snake around.

JavaScript

can anyone guide me how to do that?

Advertisement

Answer

Define the directions as follows:

  • 0: move up
  • 1: move right
  • 2: move down
  • 3: move right
JavaScript

When right is pressed then add 1 to snake.direction and when left is pressed the subtract 1. Use the % (modulo) operator (see Binary arithmetic operations) to ensure tha the result is in rage [0, 3]:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement