Home > OS >  simple snake game in pygame movement limitation
simple snake game in pygame movement limitation

Time:12-09

Hi im building simple snake game, its almost finished but i have problem with snake movement. For example if the snake is moving right and i press left he goes into himslef. i probably can solve this problem but all my ideas are to complicated. im sure there are simplier soulutions

    def move_up(self):
        self.direction = "up"

    def move_down(self):
        self.direction = "down"

    def move_right(self):
        self.direction = "right"

    def move_left(self):
        self.direction = "left" ```

CodePudding user response:

there is no question in your title nor in description,

some mathematical resolution to your problem could be to put numbers to your directions, for example up=1 down=-1 left=2 right=-2 and then on keypress to change direction check:

if not actualPosition   newPosition:
    #dont do anything since collision
else:
    #do your action

CodePudding user response:

You can check if the new direction is different from the old one. If it is diffrent, you update the direction, otherwise you keep the same direction:

    def new_dir(self, new_dir):
        return new_dir if new_dir != self.direction else self.direction     

    def move_up(self):
        self.direction = self.new_dir("up")

    def move_down(self):
        self.direction = self.new_dir("down")

    def move_right(self):
        self.direction = self.new_dir("right")

    def move_left(self):
        self.direction = self.new_dir("left") 
  • Related