If you are one who enjoys playing the snake game, I am sure you will find this article interesting.
In this article, I will teach you how to come up with a simple snake game that even a beginner in Python would find easy to develop.
There exists a number of ways to create this game and one includes the use of Python’s PyGame library which is a Python library we use to create games.
The other way is by the use of the turtle library. This module comes pre-installed with Python and it provides a virtual canvas for users to create shapes and pictures.
Therefore, this article will use the turtle library to implement our simple snake game which is beginner-friendly especially for novice Python developers.
In addition to this module, we will also use two other modules namely;
- Time module – This method will allow us to keep track of the number of seconds that have elapsed since the previous time.
- Random module – It generates numbers randomly in Python.
Other basic tools you will need to use include a text editor of your choice. I will use VSCode in this article. Of course, you will need to install Python 3 on your machine if you do not have it already. You may also use the Geekflare Compiler.
This should be fun!
How the snake game works
The ultimate goal of this game is for the player to achieve the highest score by controlling the snake to collect the food the screen displays.
The player controls the snake using four direction keys that are relative to the direction the snake is moving towards. Should the snake hit a block or itself, the player loses the game.
The following steps we will follow to implement this game.
- Importing into our programs the pre-installed modules (turtle, time, and random).
- Creating the game’s screen display using the turtle module.
- Setting the keys for the snake’s moving direction around the screen.
- The gameplay implementation.
Create a snakegame.py file in which we will add the implementation code.
Importing the modules
This bit of the code will import the turtle, time, and random modules that are by default pre-installed in Python. Additionally, we will then set default values for the player’s initial score, the highest score the player will attain, and the time of delay taken by the player in every move. The time module is used here to calculate the time of delay.
Add the following bit of code to your snakegame.py file.
import turtle
import random
import time
player_score = 0
highest_score = 0
delay_time = 0.1
Creating the game’s screen display
The turtle module we import here will allow us to create a virtual canvas that will be the game’s window screen. From here, we can create the snake’s body and the food the snake will collect. Our screen will also display the player’s tracked score.
Add this code to the Python file.
# window screen created
wind = turtle.Screen()
wind.title("Snake Maze🐍")
wind.bgcolor("red")
# The screen size
wind.setup(width=600, height=600)
# creating the snake
snake = turtle.Turtle()
snake.shape("square")
snake.color("black")
snake.penup()
snake.goto(0, 0)
snake.direction = "Stop"
# creating the food
snake_food = turtle.Turtle()
shapes = random.choice('triangle','circle')
snake_food.shape(shapes)
snake_food.color("blue")
snake_food.speed(0)
snake_food.penup()
snake_food.goto(0, 100)
pen = turtle.Turtle()
pen.speed(0)
pen.shape('square')
pen.color('white')
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Your_score: 0 Highest_Score : 0", align="center",
font=("Arial", 24, "normal"))
turtle.mainloop()
The code snippet above starts with initializing the turtle screen and passes a title and a background color to the screen. After defining the window size of our screen, we draw the shape of the snake on the virtual canvas.
The penup() method simply picks up the turtle’s pen so that a line is not drawn as the turtle moves. The goto(x,y) method contains coordinate positions that move the turtle to an absolute position.
We then create the food that the snake collects. We will want to display the player’s score every time the snake collects the food and the highest score the player reaches during the game. Therefore, we use the pen.write() method to implement this. The hideturtle() hides the turtle icon from the screen on the header section that this text is written.
It is important to add the turtle.mainloop() at the end of your code, which will display the screen longer to allow you the user to do something on the screen.
Run the file and you should have the following output:
Setting up the direction keys for the snake
Here, we will set up specific keys that will guide the direction the snake will be moving on the screen. We will use the ‘L’ for left, ‘R’ for right, ‘U’ for up, ‘D’ for down. We will implement these directions using the turtle’s direction function that we will call on the snake.
Add the following code snippet to your code.
# Assigning directions def moveleft(): if snake.direction != "right": snake.direction = "left" def moveright(): if snake.direction != "left": snake.direction = "right" def moveup(): if snake.direction != "down": snake.direction = "up" def movedown(): if snake.direction != "up": snake.direction = "down" def move(): if snake.direction == "up": coord_y = snake.ycor() snake.sety(coord_y+20) if snake.direction == "down": coord_y = snake.ycor() snake.sety(coord_y-20) if snake.direction == "right": coord_x = snake.xcor() snake.setx(coord_x+20) if snake.direction == "left": coord_x = snake.xcor() snake.setx(coord_x-20) wind.listen() wind.onkeypress(moveleft, 'L') wind.onkeypress(moveright, 'R') wind.onkeypress(moveup, 'U') wind.onkeypress(movedown, 'D')
The move() function above sets the movement of the snake in the defined position within a precise coordinate value.
The listen() function is an event listener that calls on the methods that move the snake to a particular direction when the player presses the key.
The snake game gameplay implementation
After laying down the basic outlook of our snake game, we will have to make the game real-time.
This will involve the following:
- Growing the snake’s length every time it collects the food by preferably using a different color.
- Incrementing the player’s score each time the snake collects the food and tracking the highest score.
- The player is able to control the snake from colliding with the wall or its own body.
- The game restarts when the snake collides.
- The player’s score is reset to zero when the game restarts, while the screen retains the player’s highest score.
Add the rest of this code to your python file.
segments = []
#Implementing the gameplay
while True:
wind.update()
if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290:
time.sleep(1)
snake.goto(0, 0)
snake.direction = "Stop"
snake.shape("square")
snake.color("green")
for segment in segments:
segment.goto(1000, 1000)
segments.clear()
player_score = 0
delay_time = 0.1
pen.clear()
pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))
if snake.distance(snake_food) < 20:
coord_x = random.randint(-270, 270)
coord_y = random.randint(-270, 270)
snake_food.goto(coord_x, coord_y)
# Adding segment
added_segment = turtle.Turtle()
added_segment.speed(0)
added_segment.shape("square")
added_segment.color("white")
added_segment.penup()
segments.append(added_segment)
delay_time -= 0.001
player_score += 5
if player_score > highest_score:
highest_score = player_score
pen.clear()
pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))
# checking for collisions
for i in range(len(segments)-1, 0, -1):
coord_x = segments[i-1].xcor()
coord_y = segments[i-1].ycor()
segments[i].goto(coord_x, coord_y)
if len(segments) > 0:
coord_x = snake.xcor()
coord_y = snake.ycor()
segments[0].goto(coord_x, coord_y)
move()
for segment in segments:
if segment.distance(snake) < 20:
time.sleep(1)
snake.goto(0, 0)
snake.direction = "stop"
snake.color('white')
snake.shape('square')
for segment in segments:
segment.goto(1000, 1000)
segment.clear()
player_score = 0
delay_time = 0.1
pen.clear()
pen.write("Player's_score: {} Highest_score: {}".format(player_score, highest_score), align="center", font=("Arial", 24, "normal"))
time.sleep(delay_time)
turtle.mainloop()
In the above code snippet, we set a random position for the snake’s food within the screen. Every time the snake collects this food, its body segment increases with a different color; white, in this case, to distinguish its growth.
After the snake collects the food without colliding, the food is set at a random position within the 270 coordinate range of the screen size. Every time the snake collects food, the player’s score increments by 5. When the snake collides, the player’s score is set to 0 while the screen retains its highest score.
Now return the Python file and you should see your turtle screen looking like this:
Conclusion 🐍
Using the turtle library is one fun and easy way to create the snake game as we have seen in this article. Alternatively, you could implement the same using the PyGame library. You can check out the PyGame tutorial here and see how you could implement the game differently.
You may also try out a number guessing game in Python or how to get JSON data in Python.
Enjoy coding!