Preventing adding the same direction twice Timer = 0 if len( direction_queue) > 1: direction_queue.pop( 0) # etc.įor direction_index, direction in enumerate( direction_queue): # Removed: direction = 'right' direction_queue = the last direction pressed) is checked to see if it's not in the opposite direction of the new direction before adding the new direction to the direction queue. The last item in the direction queue (i.e. When a key is pressed, the direction is added to the end of the direction queue. If the direction queue has more than one item, then the first item is removed from it on every tick. The first item in the queue is the direction the snake will move on the next tick.
In the above example, the player may have wanted the snake to move down for the next tick, and then left on the tick after.Ī direction queue is created. For example, if the snake moved right on the last tick, and then the player presses down then left before the next tick, then the snake will move left on the next tick.Īlso, the player may want to give multiple directions within a single tick. If key = keys.RIGHT and direction != 'left':Įlif key = keys.LEFT and direction != 'right':Įlif key = keys.DOWN and direction != 'up':Įlif key = keys.UP and direction != 'down':Ĭurrently, the snake can still go backwards if another direction and then the opposite direction is pressed within a single tick of the timer. The playing area is 20 cells wide and 15 cells high, and each cell has a side length of 15 pixels. If the new head position is at the same position as any of the snake's other segments, then the game is over. If the new head position is at the position same as the food's position, then the snake's tail is not removed, and the food is moved to a random position not occupied by the snake. its new head position) in the direction that the snake is going. its old tail position) is removed, and an item is added to the front (i.e. When the snake moves, then the last item in the sequence (i.e. The food is represented by a single X and Y position. The snake is represented by a sequence of X and Y positions. The game is over when the snake crashes into itself. The snake will wrap around to the other side of the screen when it goes off the edge. When the food is eaten it moves to another random position. Please send any feedback to snake.py RulesĮating food makes the snake grow. A tutorial for Python and Pygame Zero 1.2