Snake
Note
Requires: session 5 finished.
The snake moves by itself. You steer it with the arrow keys. Eat a piece of fruit: the snake grows one tile. Hit the wall or yourself: game over.
Getting started
Download the starter code and unpack the ZIP. Open main.py in Thonny and click Run. You see an empty grid. The controls and the timing are already there. You fill in the functions nieuw_fruit(), zet_stap() and teken().
How does it work?
Snake is played on a grid. The snake is a list of (column, row) coordinates. Every step you add a new head to the front of the list and remove the last element. When the snake eats fruit, you leave the last element in place, so the snake grows.
TILE = 20 # size of one tile in pixels
COLS = WIDTH // TILE
ROWS = HEIGHT // TILE
slang = [(10, 10), (9, 10), (8, 10)] # list of (column, row)
dx, dy = 1, 0 # direction: 1 step to the rightLoading and scaling images
The fruit pictures are 64×64 pixels. That is too big for one tile of 20×20. You load them with pygame.image.load() and then scale them with pygame.transform.scale(). This is already in the starter code.
surf = pygame.image.load('images/apple.png').convert_alpha()
fruit_images['apple'] = pygame.transform.scale(surf, (TILE, TILE))convert_alpha() makes sure the transparency of the picture works properly. pygame.transform.scale() returns a new Surface at the size you ask for. The original stays unchanged.
To put a scaled picture on the screen, you use screen.blit():
screen.blit(fruit_surf, (fruit_pos[0] * TILE, fruit_pos[1] * TILE))✅ Basic
- Fill in
nieuw_fruit(): pick a random fruit, find a free tile and store the position and the Surface. - Fill in
zet_stap(): work out the new head, add it to the front of the list, remove the last element. - Fill in
teken(): draw the grid (pygame.draw.line), the fruit (screen.blit), and every snake segment (pygame.draw.circle). Show the score withfont.render()andscreen.blit(). - Spawn fruit when the snake eats it: leave out
slang.pop()and callnieuw_fruit().
⭐ Stretch
- Game over when the head leaves the grid.
- Game over when the head hits one of its own segments (
nieuw_hoofd in slang[1:]). - Show a game-over screen with the score. Press R to restart.
🔥 Expert
- Raise the speed as the score goes up: lower
STAP_MSbased on the score (max(60, BASISINTERVAL - score * 10)). - Store the high score and show it next to the current score, also after a restart.
- Make sure fruit never spawns on a tile the snake already fills.
Downloads
- Starter code:
main.pywith the controls and timing ready; you fill in the functions. - Fruit images: if you start without the starter code (already included in the starter ZIP).
Fruit: Kenney Food Kit, CC0 (public domain). kenney.nl