Python 如何控制蛇只有两个键,即左键和右键
目前,我使用所有四个键来控制蛇的左、右、上、下方向。我想知道我怎么能只用左右键来移动蛇Python 如何控制蛇只有两个键,即左键和右键,python,pygame,game-physics,Python,Pygame,Game Physics,目前,我使用所有四个键来控制蛇的左、右、上、下方向。我想知道我怎么能只用左右键来移动蛇 if event.key == pygame.K_LEFT: snake.direction = 2 elif event.key == pygame.K_RIGHT: snake.direction = 3
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
有人能指导我怎么做吗 不要根据按键设置方向,而是让左右键通过增加或减少当前方向来调整方向 我还更改了
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
如果event.key==pygame.K_左:
方向-=1
elif event.key==pygame.K_RIGHT:
snake.direction+=1
如果snake.direction>3:
snake.direction=0
elif蛇形方向<0:
方向=3
def移动(自我):
如果self.direction为0:
self.dy=-self.block
self.dx=0
如果self.direction为1:
self.dy=0
self.dx=-self.block
如果self.direction为2:
self.dy=self.block
self.dx=0
如果self.direction为3:
self.dy=0
self.dx=self.block
self.x+=self.dx
self.y+=self.dy
这将根据蛇之前的移动方向旋转你的蛇
定义如下方向:
- 0:上移
- 1:向右移动
- 2:下移
- 3:向右移动
def移动(自):
如果self.direction为0:
self.dy=-self.block
self.dx=0
如果self.direction为1:
self.dy=0
self.dx=self.block
如果self.direction为2:
self.dy=0
self.dx=-self.block
如果self.direction为3:
self.dy=self.block
self.dx=0
self.x+=self.dx
self.y+=self.dy
按下右键时,将1添加到蛇形方向,按下左键时,将1减去。使用%
(模)运算符(请参阅)确保结果为rage[0,3]:
如果event.key==pygame.K_左:
snake.direction=(snake.direction-1)%4
如果event.key==pygame.K_RIGHT:
snake.direction=(snake.direction+1)%4
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