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.

                    if event.key == pygame.K_LEFT:
                        snake.direction = 2
                    elif event.key == pygame.K_RIGHT:
                        snake.direction = 3
                    elif event.key == pygame.K_UP:
                        snake.direction = 0
                    elif event.key == pygame.K_DOWN:
                        snake.direction = 1
    def move(self):
        if self.direction is 0:
            self.dy = -self.block
            self.dx = 0
        if self.direction is 1:
            self.dy = self.block
            self.dx = 0
        if self.direction is 2:
            self.dy = 0
            self.dx = -self.block
        if self.direction is 3:
            self.dy = 0
            self.dx = self.block
        self.x += self.dx
        self.y += self.dy

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
def move(self):
    if self.direction is 0:
        self.dy = -self.block
        self.dx = 0
    if self.direction is 1:
        self.dy = 0
        self.dx = self.block
    if self.direction is 2:
        self.dy = 0
        self.dx = -self.block
    if self.direction is 3:
        self.dy = self.block
        self.dx = 0

    self.x += self.dx
    self.y += self.dy

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]:

if event.key == pygame.K_LEFT:
    snake.direction = (snake.direction - 1) % 4
if event.key == pygame.K_RIGHT:
    snake.direction = (snake.direction + 1) % 4
Advertisement