Introduction
Video games are one of the funniest things. It can reduce the feeling of boredom created by overwork.
In this tutorial, I will show how to create a Snake Game in Python using the Turtle Module. I will guide you step-by-step to build this simple project. So, don't worry and keep reading.
☛Visit Also: Apple Catcher Game in Python - PyGame Projects
Project Details
I've used the Python Turtle module to build this game. It is very easy to use and understandable. Users have to use the four arrow keys to control the movement of the snake around the screen and make it eat food.
Each food will give the user two points and make the snake longer and faster. If the head of the snake hits the wall, the game will be over.
Requirements and Installation
Use pip3 instead of pip for Linux.
☛Install Turtle: pip install PythonTurtle
How the Game works
This project uses two turtles for the two main characters of this game: One is the Hungry Snake and another one is the food of the Snake. The game follows these simple steps.
Steps:
1. Create and set the properties for the snake and food turtle.
2. Set the starting values for these variables: Snake Size, Snake Speed, and The Score.
3. Now move the Snake forward.
4. Check if the Snake has eaten the food or not. If 'NO' then jump to step 6, otherwise, follow the next one.
5. It means the snake has eaten the food. Now increase the size and speed of the snake, and update the current score by adding two, then follow the next step.
6. Now check if the Snake touches the Wall or not. If 'YES', follow the next step otherwise, jump back to step 3.
7. Display 'Game Over'.
Let's get to the main topic. Start coding to give the Snake a new life.
1. Import the Modules
Start writing the python code for snake game by importing the turtle and the random module. The third and fourth line is for window color and window title respectively.
import random
import turtle as t
t.bgcolor('yellow')
t.title('Snake Game')
2. Create a Turtle for the Hungry Snake
This code will create a turtle for the snake and set its color, speed, and shape. snake.penup() is for disabling the turtle from drawing anything on the screen. snake.hideturtle() will hide the turtle from the screen.
snake = t.Turtle()
snake.shape('square')
snake.color('red')
snake.speed(0)
snake.penup()
snake.hideturtle()
3. Food for the Snake
It will create an another turtle for the food.
food = t.Turtle()
food.color('green')
food.shape('square')
food.speed(0)
food.penup()
food.hideturtle()
4. Add Some Text on the Screen
Now add a welcoming message. It will show before the game starts, telling 'Press SPACE to Start'. The second code is for displaying the scores at the right corner of the window.
welcome_text = t.Turtle()
welcome_text.write('Press SPACE to Start', align='center', font=('Helvetica', 20, 'bold'))
welcome_text.hideturtle()
score_text = t.Turtle()
score_text.hideturtle()
Our Turtle has set. Let's write the code to make the hungry snake have the food.
To facilitate copying, I have written the whole code in this way. But to better understand the code, start at point 9: "Start the Game".
5. Game Over
After the snake starts moving if it crosses the boundary then, this part of the code will show a message: "Game Over!".
def game_over():
snake.color('yellow')
food.color('yellow')
t.penup()
t.hideturtle()
t.write('GAME OVER!', align='center', font=('Helvetica', 40, 'bold'))
6. The Boundary
The boundary() function measures the actual position of each wall. Then, it compares the coordinates of the snake with the coordinate of the walls. If the program finds the snake has crossed the boundary then, it will return a boolean value: 'True' otherwise, 'False'.
def boundary():
left_wall = -t.window_width() / 2
right_wall = t.window_width() / 2
top_wall = t.window_height() / 2
bottom_wall = -t.window_height() / 2
(x, y) = snake.pos()
boundary = (x<=left_wall or x>=right_wall or y<=bottom_wall or y>=top_wall)
return boundary
Let's understand how the code measures the coordinate of the boundaries.
The entire screen is 400 wide. So, the right wall is half of the entire width from the center, i.e, 200. The logic for the left wall is the same but, (center - right wall), i.e, 0-200= (-200).
The same logic for the top and bottom with the left and right respectively.
7. Display the Score
The display_score() function gets called when the Snake eats the food. It updates the current score by updating the previous one in the top right corner of the window.
def display_score(current_score):
score_text.clear()
score_text.penup()
x = (t.window_width() / 2) - 50
y = (t.window_height() / 2) - 50
score_text.setpos(x, y)
score_text.write(str(current_score), align='right',
font=('Helvetica', 30, 'bold'))
8. Place Food
When the Snake will reach the food, this function will get called. It will place the food in a new random position between -150 and 150.
def place_food():
# Hide Turtle
food.ht()
food.setx(random.randint(-150, 150))
food.sety(random.randint(-150, 150))
# Show Turtle
food.st()
9. Start the Game
I've divided this part of the code into two segments. The first segment sets up some variables such as snake speed, score, snake length, etc. Next, it calls the 'display_score' and 'place_food' functions, described at points 7 and 8 respectively.
The second segment declares an infinite loop for moving the snake slightly until it crosses the boundary. In every iteration, the code checks if the snake has eaten the food or not. If YES then, the speed and length of the snake will increase also with the score, and the food will be placed in the other place randomly.
def start_game():
score = 0
# Clear the Starting Screen
welcome_text.clear()
snake_speed = 1
snake_length = 2
snake.shapesize(1, snake_length, 1)
snake.showturtle()
display_score(score)
place_food()
The Second Part
place_food()
while True:
snake.forward(snake_speed)
# The snake eats the food when it is less than 30 pixels away
if snake.distance(food) < 30:
place_food()
snake_length += 0.5
snake.shapesize(1, snake_length, 1)
snake_speed += 0.4
score += 2
display_score(score)
if boundary():
game_over()
break
10. Controller Functions
We did so many things to feed the Hungry Snake but didn't do anything to control the snake movement from our keyboard. Now it's time to do that task otherwise the snake will crash with the wall:-).
Here we have four functions for the four arrow keys of our keyboard. Whenever one of the arrow keys will be pressed, the respective function will be called that are given below.
def go_left():
if snake.heading() == 90 or snake.heading() == 270:
# The head of the snake is being set at a 180 degree angle.
snake.setheading(180)
def go_right():
if snake.heading() == 90 or snake.heading() == 270:
snake.setheading(0)
def go_up():
if snake.heading() == 0 or snake.heading() == 180:
snake.setheading(90)
def go_down():
if snake.heading() == 0 or snake.heading() == 180:
snake.setheading(270)
11. Listening the Key Presses
We reached almost the end of the code. Now it's time to listen to the KeyPress. Add this code at the very end of your main program.
t.onkey(start_game, 'space')
t.onkey(go_up, 'Up')
t.onkey(go_right, 'Right')
t.onkey(go_down, 'Down')
t.onkey(go_left, 'Left')
t.listen()
t.mainloop()
Yes! We've done. Now, You're able play this game.
🔹Visit Also: Make Your own Quiz Game in Python - with CSV file
Conclusion
In this tutorial, You've learned to create a snake game in python. We used the Python Turtle module to build this project. I've divided the entire code into several parts for Your convenience to get the logic of the project better.
You can rebuild the game by changing the snake speed, color, etc. Do it and share it with me. If You've any queries related to this topic, let me know in the comment section.
Thanks for reading!💙