In this tutorial, we will create a snake game with python and pygame. You can find full code here.
What is pygame?
It is a free and open source Python programming language library used for making a multimedia application like games. It is great for beginners as it’s simple and easy to use.
Installing pygame in Python:
There are two ways to do this.
- You can directly use pip install pygame in the command window or
- Download whl file from this link python extension packages according to your python version. Then use pip install whl_file_name.
Let’s create a snake game using pygame library. To Start with this, we first need to initialize pygame modules as shown below.
1 |
pygame.init() |
pygame.init() will attempt to initialize all the pygame modules for you. Not all pygame modules need to be initialized, but this will automatically initialize the ones that do.
Displaying Game Objects:
After initializing pygame modules, it’s time to display the game window. For that, we need to initialize its dimensions(width and height). Here I have used 500 x 500, but you can choose yours.
1 2 3 4 5 6 |
display_width = 500 display_height = 500 display = pygame.display.set_mode((display_width,display_height)) window_color= (200,200,200) display.fill(window_color) pygame.display.update() |
display.fill(window_color) will fill white color into game window and pygame.display.update() allows only a portion of the screen to be updated, instead of the entire area. If no argument is passed, it updates the entire Surface area.
This will create a game window as shown below.
Now it’s time to display snake and apple. Here I have used red color for snake and an image for apple. At the start of each game, we want snake’s starting position to be fixed while apple can take any random location. Starting length of the snake is 3 units where each unit is a 10×10 block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
red = (255,0,0) black = (0,0,0) apple_image = pygame.image.load('apple.jpg') snake_head = [250,250] snake_position = [[250,250],[240,250],[230,250]] apple_position = [random.randrange(1,50)*10,random.randrange(1,50)*10]<strong> def display_snake(snake_position): for position in snake_position: pygame.draw.rect(display,red,pygame.Rect(position[0],position[1],10,10)) def display_apple(display,apple_position, apple): display.blit(apple,(apple_position[0], apple_position[1])) </strong> |
pygame.draw.rect() will draw a rectangle corresponding to given arguments which will represent our snake and display.blit() will show the image of an apple.
This will create a game window as shown below.
The next thing is to decide at what frame rate we want to play our game. This is done using pygame.time.Clock() that creates a “clock” object. Now whenever clock.tick() is called and passed with some number, then it will limit the run time speed of the game. As an example, if clock.tick(20) is called, then the program will never run at more than 20 frames per second.
1 2 |
clock = pygame.time.Clock() clock.tick(20) |
Game Logic:
Now it’s time to define game rules. As you know, there must be some rules which makes a game playable.
Rule 1: If the snake collapses with itself or with boundaries, game over.
1 2 3 4 5 6 7 8 9 10 11 12 |
def collision_with_boundaries(snake_head): if snake_head[0]>=500 or snake_head[0]<0 or snake_head[1]>=500 or snake_head[1]<0 : return 1 else: return 0 def collision_with_self(snake_position): snake_head = snake_position[0] if snake_head in snake_position[1:]: return 1 else: return 0 |
Rule 2: Moving the snake to a new position
In our game, the snake will continue to move in one direction until a button is pressed. To move the snake, we need to add one unit to the head and remove one unit from the tail.
1 2 |
snake_position.insert(0,list(snake_head)) snake_position.pop() |
Another case is when a button is pressed to move in a direction(left, right, up or down). Also, the Snake cannot move backward.
1 2 3 4 5 6 7 8 9 10 11 |
if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and prev_button_direction != 1: button_direction = 0 elif event.key == pygame.K_RIGHT and prev_button_direction != 0: button_direction = 1 elif event.key == pygame.K_UP and prev_button_direction != 2: button_direction = 3 elif event.key == pygame.K_DOWN and prev_button_direction != 3: button_direction = 2 else: button_direction = button_direction |
After seeing which direction button is pressed, we need to change our snakes head position.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if button_direction == 1: snake_head[0] += 10 elif button_direction == 0: snake_head[0] -= 10 elif button_direction == 2: snake_head[1] += 10 elif button_direction == 3: snake_head[1] -= 10 else: pass snake_position.insert(0,list(snake_head)) snake_position.pop() |
Rule 3. If the snake eats an apple, the apple moves to a new position and snake length increases.
When the snake eats an apple, we increase our snake’s length and improve the score. To increase snake size, we add one unit at snake’s head. Also, we need to create another apple at random location to proceed the game.
1 2 3 4 5 6 7 8 |
def collision_with_apple(apple_position, score): apple_position = [random.randrange(1,50)*10,random.randrange(1,50)*10] score += 1 return apple_position, score if snake_head == apple_position: apple_position, score = collision_with_apple(apple_position, score) snake_position.insert(0,list(snake_head)) |
Displaying Final Score:
After the game is over, we want to display the final score. Here, I have defined a function ‘display_final_score’, which takes final score and text to be displayed as its arguments to display in the game window.
1 2 3 4 5 6 7 8 |
def display_final_score(display_text, final_score): largeText = pygame.font.Font('freesansbold.ttf',35) TextSurf = largeText.render(display_text, True, black) TextRect = TextSurf.get_rect() TextRect.center = ((display_width/2),(display_height/2)) display.blit(TextSurf, TextRect) pygame.display.update() time.sleep(2) |
This will display our final score as shown below.
Finally, our snake game is created, now it’s time to play it.
Now, you might have got some feeling about creating games using pygame. Hope you enjoy reading.
If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.
when you displayed the 3 snakes on screen you gave positions the wouldnt form a rectangle(250,250,240,250). could you explain that part a bit more please?
(250,250) are the (x, y) coordinates. To draw the rectangle using these coordinates, I have used pygame.draw.rect() function which draws a 10×10 rectangle starting from this x-y position. Similarly, we will draw rectangles for (240,250), (230,250) and for every position. Please refer display_snake() function defined above. Hope this helps.
can this be made without the numpy library
dont you need to call the functions though?
here, i have explained only main points. See the whole code here https://github.com/TheAILearner/Snake-Game-with-Pygame where play_game function calls the display_snake(). Hope this helps.
Hi,
Great tutorial.
I have also created a snake gamewith pygames. https://github.com/sjain3097/snake_game
this a git link to the repository in case someone need any help feel free to contact me
Hi,
In your github code, you are creating a current_direction_vector variable under def is_direction_blocked. Can you please explain why you need that, even though the game works smoothly without it.
Thanks