Python Snake game

Let’s start using pygame to make games! Pretty fun assured.

Our first “real game” is a classic and is the Snake. In this classic game from the 80ies, you had to move a snake in a rectangular area to eat a fruit and as you go on with the game you become longer and faster. The problem is that you cannot hit the borders or yourself.

An image of this very complex game

Create the window

Let’s make something that could be the starting point for a lot of games: define a window that you can close.

import pygame

pygame.init()
window = pygame.display.set_mode((400,400))
clock = pygame.time.Clock()
loop = True
while loop:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			loop = False
pygame.quit()

Initialize the code with pygame.init()

pygame.init()

This will initialize pygame, making everything work fine so that you can use things like fonts etc. To use the fonts you can also use pygame.font.init(), but using pygame.init() makes this not necessary.

Window surface settings or display.set_mode(())

window = pygame.display.set_mode((400,400))

There is also the pygame.display.set_caption(“Title”) to give a name to the window. But we will do it later, maybe.

The time.Clock()

This is the frame rate. The higher it is the faster the window will be refreshed. Think to the game as a serious of frames (static pictures) that are updated on the screen one after another giving the sensation of movement (like the frames of a movie, if you take them one by one they are pictures that have little differences among them).

clock = pygame.time.Clock()

We will use the frame rate fps to increase the difficulty of the game.

The loop… while loop

This is the part that makes the sprite move and check if the user moves it, where the sprites are, if they collide, if the snake goes out of the screen. Now there is nothing of this. It just looks if the user clicks the quit button (the x of the window). If you do not write this code you cannot close the window without making the window crash.

loop = True
while loop:
	for event in pygame.event.get():
		if event.type == pygame.QUIT:
			loop = False
pygame.quit()

If loop is True the window runs, when loop is false (you press quit button) the window quits.

Adding the keys

Now we want to make the code look readable. Let’s put the screen and clock into a class called Game

import pygame
from dataclasses import dataclass

@dataclass
class Game:
    """A class for the screen and clock"""
    pygame.init()
    screen = pygame.display.set_mode((400,400))
    clock = pygame.time.Clock()

I am using @dataclass to use a type of class that is avaiable from Python 3.7 and that makes me save some memory.

Now the screen will be avaiable as Game.screen and the clock as Game.clock.

This is the part of the code where the loop starts and the game waits for an input of the user, listening to the pygame events and making a for loop in pygame.event.get() that :

loop = True
while loop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # Quit button (exit)
            loop = False

I want to make a nicer keys control code:

# =========== Loop Start ======= #
loop = True
while loop:
    for event in pygame.event.get():
        quit = event.type == pygame.QUIT
        pressed = pygame.key.get_pressed()
        if quit: loop = False
        elif (event.type == pygame.KEYDOWN): # Arrow keys (move)
            if pressed[pygame.K_RIGHT]: print("RIGHT")
            if pressed[pygame.K_UP]:    print("UP")
            if pressed[pygame.K_DOWN]:  print("DOWN")
            if pressed[pygame.K_LEFT]:  print("LEFT")

The Whole code is this:

import pygame
from dataclasses import dataclass

@dataclass
class Game:
    """A class for the screen and clock"""
    pygame.init()
    screen = pygame.display.set_mode((400,400))
    clock = pygame.time.Clock()

# =========== Loop Start ======= #
loop = True
while loop:
    for event in pygame.event.get():
        quit = event.type == pygame.QUIT
        pressed = pygame.key.get_pressed()
        if quit: loop = False
        elif (event.type == pygame.KEYDOWN): # Arrow keys (move)
            if pressed[pygame.K_RIGHT]: print("RIGHT")
            if pressed[pygame.K_UP]:    print("UP")
            if pressed[pygame.K_DOWN]:  print("DOWN")
            if pressed[pygame.K_LEFT]:  print("LEFT")


# ======================== when the loops ends, goes here =======
pygame.quit()

Now this code just make a window appear and when you hit the arrow keys it prints up, right, left and down. This means that it works. Now we just have to add the code to move our sprite.

To be continued…

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.