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
x
24
24
1
if event.key == pygame.K_LEFT:
2
snake.direction = 2
3
elif event.key == pygame.K_RIGHT:
4
snake.direction = 3
5
elif event.key == pygame.K_UP:
6
snake.direction = 0
7
elif event.key == pygame.K_DOWN:
8
snake.direction = 1
9
def move(self):
10
if self.direction is 0:
11
self.dy = -self.block
12
self.dx = 0
13
if self.direction is 1:
14
self.dy = self.block
15
self.dx = 0
16
if self.direction is 2:
17
self.dy = 0
18
self.dx = -self.block
19
if self.direction is 3:
20
self.dy = 0
21
self.dx = self.block
22
self.x += self.dx
23
self.y += self.dy
24
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
1
17
17
1
def move(self):
2
if self.direction is 0:
3
self.dy = -self.block
4
self.dx = 0
5
if self.direction is 1:
6
self.dy = 0
7
self.dx = self.block
8
if self.direction is 2:
9
self.dy = 0
10
self.dx = -self.block
11
if self.direction is 3:
12
self.dy = self.block
13
self.dx = 0
14
15
self.x += self.dx
16
self.y += self.dy
17
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
1
5
1
if event.key == pygame.K_LEFT:
2
snake.direction = (snake.direction - 1) % 4
3
if event.key == pygame.K_RIGHT:
4
snake.direction = (snake.direction + 1) % 4
5