如何用只有两个键即左键和右键控制蛇



目前,我正在使用所有四个键来左右,向上和向下引导蛇。我想知道我怎么只能使用左右键来移动蛇。

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

谁能指导我怎么做?

if event.key == pygame.K_LEFT:
if snake.direction == 0
snake.direction = 2
elif snake.direction == 2
snake.direction = 1
elif snake.direction == 1
snake.direction = 3
elif snake.direction == 3
snake.direction = 0
elif event.key == pygame.K_RIGHT:
if snake.direction == 0
snake.direction = 3
elif snake.direction == 3
snake.direction = 1
elif snake.direction == 1
snake.direction = 2
elif snake.direction == 2
snake.direction = 0
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

这应该根据蛇之前行进的方向旋转蛇。

按如下方式定义方向:

  • 0:上移
  • 1:向右移动
  • 2:下移
  • 3:向右移动
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

按右时,将 1 加到snake.direction当按下左时减去 1。使用%(模(运算符(请参阅二进制算术运算(来确保结果处于愤怒状态 [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

不要根据按键设置方向,而是让左右键通过添加或减去当前方向来调整方向。

我还更改了move函数,使方向按顺时针顺序排列。

if event.key == pygame.K_LEFT:
snake.direction -= 1
elif event.key == pygame.K_RIGHT:
snake.direction += 1
if snake.direction > 3:
snake.direction = 0
elif snake.direction < 0:
snake.direction = 3
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 = self.block
self.dx = 0
if self.direction is 3:
self.dy = 0
self.dx = self.block
self.x += self.dx
self.y += self.dy

最新更新