Pygame贪吃蛇游戏禁止反向移动避免自碰撞问题咨询
实现思路
你只需要在Snake类的四个方向切换方法里增加反向判断逻辑即可,核心规则是:如果要切换的方向是当前移动方向的反方向,就忽略本次切换请求,其他情况正常更新方向。
修改代码片段
你只需要替换原来Snake类里的move_left、move_right、move_up、move_down四个方法即可:
def move_left(self): # 当前方向是右时不能直接切左 if self.direction != 'right': self.direction = 'left' def move_right(self): # 当前方向是左时不能直接切右 if self.direction != 'left': self.direction = 'right' def move_up(self): # 当前方向是下时不能直接切上 if self.direction != 'down': self.direction = 'up' def move_down(self): # 当前方向是上时不能直接切下 if self.direction != 'up': self.direction = 'down'
逻辑说明
- 当蛇正向右移动时,按下左键不会触发方向切换,只有先按上/下键把方向切换为纵向后,左键才会生效
- 上下方向的反向限制规则和左右完全一致
- 不需要修改其他代码逻辑,原有碰撞检测、计分、边界判定等功能都不受影响
内容的提问来源于stack exchange,提问作者Mushari
相关产品推荐
相关产品推荐

