Python Snake Game – Create a Snake Game using Turtle

Remember the snake game in the feature phones? All of us would have played this game at least once in our childhood. Wouldn’t it be interesting to build your own snake game? In this Python project by TechVidvan, you will be able to learn to develop a Snake game in Python. So, get ready to play your game!

What is a Snake Game?

Snake game is one of the classic arcade games that are popular among people. In this game, the player controls the movement of the snake aiming to collect food or fruits. The snake can be moved in all four directions and each food collected increases the score. The game stops when the snake collides with the walls or itself.

Python Snake Game – Project Details

This game will be built in Python using three simple modules, namely, turtle, time and random.

1. Turtle helps in giving the game a window and also helps to create different shapes for snakes, food, etc., and control them.

2. Time module is used here to count the number of seconds elapsed.

3. Random modules help in the generation of random numbers that can be used to place the food at random locations for the snake to collect.

Download Snake Game Python Program

Please download the full Python source code for building the snake game: Snake Game Python Project

Prerequisites for Python Snake Game

You can use any one of the editors/ applications where you can run Python code. All the modules, Turtle, Time, and Random are pre-installed. So, there is no need to install any packages.

Steps to build Snake Game Project in Python

Before going to the implementation part, let’s first briefly discuss the steps to be followed:

1. Creating a window screen for the game

2. Writing functions for controlling the movement of the snake

3. Locating the food at random locations

4. Incrementing the score on collecting food or ending the game on a collision

This game runs in an infinite loop. Every time the snake moves, the state is checked for food collection or collision. And appropriate actions are taken. Using a turtle, we can set the color and shape of the food and snake of our choice.

We will now implement this logic in Python step by step.

1. Initializing the Project Components

Let’s first import the required modules, i.e. turtle, random, and time. And then create the required variables that store delay, the scores, and the list to store the snake segments.

import turtle
import random
import time

delay=0.1
score = 0
high_score = 0
segments = []

2. Creating Screen and Other components

The next step is to create a window for the game, setting borders. Then creating the components that represent the snake and the food. Also, a board to show the present score and the highest score.

# Creating the window and setting height and width
wn = turtle.Screen()
wn.title("TechVidan's Snake Game")
wn.bgcolor("black")
wn.setup(width=700, height=700)
wn.tracer(0)

#Creating a border for the game
turtle.speed(5)
turtle.pensize(4)
turtle.penup()
turtle.goto(-310,250)
turtle.pendown()
turtle.color('black')
turtle.forward(600)
turtle.right(90)
turtle.forward(500)
turtle.right(90)
turtle.forward(600)
turtle.right(90)
turtle.forward(500)
turtle.penup()
turtle.hideturtle()

# Creating head of the snake
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "Stop"


#Creating food in the game
food = turtle.Turtle()
food_color = random.choice(['yellow', 'green', 'tomato'])
food_shape = random.choice([ 'triangle', 'circle','square'])
food.speed(0)
food.shape(food_shape)
food.color(food_color)
food.penup()
food.goto(20, 20)

#Creating space to show score and high score
scoreBoard = turtle.Turtle()
scoreBoard.speed(0)
scoreBoard.shape("square")
scoreBoard.color("white")
scoreBoard.penup()
scoreBoard.hideturtle()
scoreBoard.goto(0, 250)
scoreBoard.write("Score : 0 High Score : 0", align="center",
  font=("Courier", 25, "bold"))

Here,

a. penup() stops drawing the turtle pen.

b. speed() sets the speed with 0 being fastest, 10 being fast, 6 being normal, 3 being slow, and 1 being slowest. If no argument is given, it returns the current speed.

c. color() sets the pen color and fill color.

d. shape() –sets the shape to the turtle object.

e. hideturtle() makes the turtle invisible.

f. goto() moves the turtle to the given position.

3. Adding movement functions for the snake

Before going to the main part, there is another step that is required to be done. That is, to create functions that control the movement of the snake by pressing the respective keys on the keyboard.

# assigning key directions
def move_up():
 if head.direction != "down":
  head.direction = "up"


def move_down():
 if head.direction != "up":
  head.direction = "down"


def move_left():
 if head.direction != "right":
  head.direction = "left"


def move_right():
 if head.direction != "left":
  head.direction = "right"


def move():
 if head.direction == "up":
  y = head.ycor()
  head.sety(y+20)
 if head.direction == "down":
  y = head.ycor()
  head.sety(y-20)
 if head.direction == "left":
  x = head.xcor()
  head.setx(x-20)
 if head.direction == "right":
  x = head.xcor()
  head.setx(x+20)


wn.listen() # This listens to the key press
#If any one of up, down, left or right key pressed, one of the below actions take place
wn.onkeypress(move_up, "Up")
wn.onkeypress(move_down, "Down")
wn.onkeypress(move_left, "Left")
wn.onkeypress(move_right, "Right")

One important thing to be noticed in the functions is the if conditions. If the snake is moving up, it is not possible to change the direction to down. Before this, it needs to either move to the right or left. Remember? The same applies here too, to all four directions.

4. The main while loop controlling the game

We are in the last step, but an important step that controls the whole game. As discussed previously, we use a while loop that runs infinitely till the conditions are met that ends the game.

The movement of the snake is done by changing the coordinates of each segment to the coordinates of the previous segment.

Here we have three possible cases, other than the movement of the snake in one of the four directions. These are:

A. The snake collects food, the distance between the snake and the food is less than the threshold. In this case, we need to

  • Increment the score
  • Change the position of the food
  • Add a new segment to the snake

B. Collision with the walls, when the distance of the snake from the wall is less than the threshold set. Then, we end the game by

  • Clearing the screen
  • Showing that game is over and the final score

C. Collision with the body, when the distance between the head of the snake and one of the segments is less than the threshold. In this case also, we end the game.

# Main Game
while True: #Running an infinite till the collision occurs and then the game ends
wn.update()

 #Ending the game on collision with any of the walls
 if head.xcor() > 280 or head.xcor() < -300 or head.ycor() > 240 or head.ycor() < -240:
  time.sleep(1) #This reduces the speed of snake
  wn.clear()
  wn.bgcolor('blue')
  scoreBoard.goto(0,0)
  scoreBoard.write("GAME OVER\n Your Score is : {}".format(
score), align="center", font=("Courier", 30, "bold"))

#If snake collects food
if head.distance(food) < 20:
 #increasing score and updating the high_score if required
 score += 10
if score > high_score:
 high_score = score
scoreBoard.clear()
scoreBoard.write("Score : {} High Score : {} ".format(
score, high_score), align="center", font=("Courier", 25, "bold"))

#creating food at random location
x_cord = random.randint(-290, 270)
y_cord = random.randint(-240, 240)
food_color = random.choice(['yellow', 'green', 'tomato'])
food_shape = random.choice([ 'triangle', 'circle','square'])
food.speed(0)
food.shape(food_shape)
food.color(food_color)
food.goto(x_cord, y_cord)

# Adding a new segment to the snake
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("white smoke") # giving a new color to the tail
new_segment.penup()
segments.append(new_segment) #adding the segment to the list


# Moving the snake
for i in range(len(segments)-1, 0, -1):
 x = segments[i-1].xcor()
 y = segments[i-1].ycor()
 segments[i].goto(x, y)
if len(segments) > 0:
 x = head.xcor()
 y = head.ycor()
 segments[0].goto(x, y)
move()

#Checking for collision with the body
 for segment in segments:
  if segment.distance(head) < 20:
   time.sleep(1)
   wn.clear()
   wn.bgcolor('blue')
   scoreBoard.goto(0,0)
   scoreBoard.write("\t\tGAME OVER\n Your Score is : {}".format(
   score), align="center", font=("Courier", 30, "bold"))

 time.sleep(delay)

turtle.Terminator()

Now we are all set to play the game. Run the program written above by saving it as SnakeGame.py.

Python Snake Game Output

python snake game output

Summary

In this Python project, we have successfully built the Snake game. For this purpose, we used the turtle, time, and random modules which are available in the standard library. We learned to control the movement of the snake, place the food at a random location and find the state of the snake. And based on the state we increment score on food collection or end game on collision. Hoping that you enjoyed making this project. Looking forward to seeing you again on some other project!