到达边界时如何重置位置

2024-05-19 18:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 代码self游戏newlenifwidthscreen
2条回答

您只需测试snake是否在网格中并调用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()

边境检查

if (cur[0] >= 0 and cur[0] <= grid_width) and (cur[1] >= 0 and cur[1] <= grid_height):
    # we are within the borders
else:
    # we are not within the borders

您可能需要将if语句拆分,以便可以知道蛇已经离开了哪里

相关问题 更多 >