Tizer1000 Tizer1000 - 1 year ago 45
Python Question

Python - A bug with my snake game that I can't figure out

Note - this game is made using pygame

I have made this snake game and everything is working perfectly except one thing.
Sometimes, when the snake eats the apple the apple doesn't re-spawn. I think that this might happen when the apple spawns inside the snake but I wrote some code to check if the apple would spawn in the snake and if so choose a different position. Maybe I did it wrong?!

Answer Source

The bug is in your food.py source code file, in the get_food_position() function. Specifically the following line is causing your bug:

self.apple_pos = (random.randint(self.WIDTH-self.WIDTH, self.WIDTH), random.randint(self.HEIGHT-self.HEIGHT, self.HEIGHT))

When you observe the apple not re-spawning, that is because you are setting the tuple self.apple_pos to be outside your viewable area. You have to remember that the apple has height and width, so it cannot be drawn at the very extremes of your viewable area. You can prove this to yourself by forcibly setting self.apple_pos = (1280,720), and then setting it again to (1260,700).

The following correction to your code solves the problem:

self.apple_pos = (random.randint(0, self.WIDTH-20), random.randint(0, self.HEIGHT-20))

I chose the magic number 20 because your apple seems to have area 20x20 pixels.

You'll note that drawing the apple at (0,0) does not have this problem because the apple is placed by its own (0,0) coordinate, which is its upper left corner.