How to reset position when reached the border

Viewed 71

What I'm trying to do is to make the snake (since im making a snake game) reset its position when it has reached the border. But with my code, Instead the position of the snake will not reset when it reaches the border, and it'll just go over the border.

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

Any help would be much appreciated!, (if i reply late im sorry, its most likely because im asleep)

2 Answers

You just have to test if the snake is in the grid and invoke 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()

border check

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

you may want to split the if statement up so that you can tell where the snake has left

Related