首页 > 解决方案 > 到达边界时如何重置位置

问题描述

我想做的是让蛇(因为我在做蛇游戏)在到达边界时重置它的位置。但是使用我的代码,当蛇到达边界时,它的位置不会重置,它只会越过边界。

def move(self):
    cur = self.get_head_position()
    x, y = self.direction
    new = (((cur[0] + (x * gridsize))), (cur[1] + (y * gridsize)))
    if len(self.positions) > 2 and new in self.positions[2:]:
        self.reset()
    else:
        self.positions.insert(0, new)
        if len(self.positions) > self.length:
            self.positions.pop()



screen_width = 520
screen_height = 520

gridsize = 20
grid_width = screen_width / gridsize
grid_height = screen_height / gridsize

任何帮助将不胜感激!,(如果我回复晚了对不起,很可能是因为我睡着了)

标签: pythonpython-3.xpygame

解决方案


您只需要测试蛇是否在网格中并调用reset()

grid_x = new[0] // gridsize
grid_y = new[1] // gridsize
if not (0 <= grid_x < grid_width and 0 <= grid_y < grid_height):
    self.reset()

推荐阅读