Python Turtle Snake Game

In this Python turtle Snake Game tutorial, we will learn about how to make a snake game using Python turtle. With the help of a turtle, we can easily make a snake game.

The snake game was developed by Gremlin Industries and published in October 1976.

The snake game is a very interesting game and the snake in the snake game is controlled using the four directions if the snakehead hits the wall and hits itself then the game will be over with the score.

In the snake game, the main aim is to collect the food. If snakes collect maximum food then the game score will be maximum.

Python Turtle Snake Game

Block of Code:

In this python turtle snake game block of code, we will import all the modules into the program from which we can make a snake game.

Turtle: It is used to create different shapes, designs, and pictures.

Time: It is used for counting the number of seconds.

Random: It is used to generate the random numbers

# import required modules
from turtle import *
import turtle as tur
import time
import random

Block of code:

In the following Python turtle snake game block of code, we are creating a window screen and after that, we give the title to the window and after this, we give the background color to the window.

  • tur.Screen() is used to create the window screen.
  • ws.title(“Pythontpoint”) is used to give the title to the window.
  • ws.bgcolor(“cyan”) is used to give the background color to the window.
  • ws.setup(width=700, height=600) is used to set the screen with and height.
  • ws.tracer(0) is used to update the screen updates.
# Creating a window screen
ws = tur.Screen()
ws.title("Pythontpoint")
ws.bgcolor("cyan")
ws.setup(width=700, height=600)
ws.tracer(0)

Block of code:

In this block of code, we will create the snakehead and give the circle shape to the head of the snake.

  • hd.shape(“circle”) s used to give the shape to the head.
  • hd.color(“black”) is used to give the color to the snakehead.
  • hd.penup() is used to sop the drawing.
# head of the snake
hd = tur.Turtle()
hd.shape("circle")
hd.color("black")
hd.penup()
hd.goto(0, 0)
hd.direction = "Stop"

Check this code in the Repository from Github and you can also fork this code.

Github User Name: PythonT-Point

Block of code:

In this Python turtle snake game block of code, we will create the food for the snake this food is eaten by the snake and the score is displayed on the screen.

  • foodsh.speed(0) is used to change the speed of the turtle.
  • foodsh.shape(shpes) is used to give the shape of the food.
  • foodsh.color(colrs) is used to give the color to the food.
# food in the game
foodsh = tur.Turtle()
colrs = random.choice(['red', 'orange', 'yellow'])
shpes = random.choice(['square', 'triangle', 'circle'])
foodsh.speed(0)
foodsh.shape(shpes)
foodsh.color(colrs)
foodsh.penup()
foodsh.goto(0, 100)

Block of code:

In this Python turtle block of code, we will change the speed of the snake and also give the color to the snake.

  • tur.Turtle() is used to create different shapes, designs, and pictures.
  • pen.speed(0) is used to change the speed of the snake.
  • pen.color(“red”) is used to give the color to the snake.
  • pen.write(“Score : 0 High Score : 0″, align=”center”, font=(“Times New Roman”, 24, “bold”)) is used to write the text on the screen.
pen = tur.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("red")
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Score : 0  High Score : 0", align="center",
          font=("Times New Roman", 24, "bold"))

Block of code:

In this block of code, we will assign the key directions to the snake from which the snake moves up, down, left, and right.

  • ws.onkeypress(gp, “d”) is used to press the d key to star the snake movement.
  • ws.onkeypress(movedown, “c”) is used to press the c key to move the downward direction.
  • ws.onkeypress(moveleft, “x”) is used to press the x key to move the snake in the left direction.
  • ws.onkeypress(moveright, “v”) is used to press the x key to move the snake in the right direction.
# assigning key directions
def gp():
    if hd.direction != "down":
        hd.direction = "up"
 
 
def movedown():
    if hd.direction != "up":
        hd.direction = "down"
 
 
def moveleft():
    if hd.direction != "right":
        hd.direction = "left"
def moveright():
    if hd.direction != "left":
        hd.direction = "right"
 
 
def move():
    if hd.direction == "up":
        y = hd.ycor()
        hd.sety(y+20)
    if hd.direction == "down":
        y = hd.ycor()
        hd.sety(y-20)
    if hd.direction == "left":
        x = hd.xcor()
        hd.setx(x-20)
    if hd.direction == "right":
        x = hd.xcor()
        hd.setx(x+20)
 
 
         
ws.listen()
ws.onkeypress(gp, "d")
ws.onkeypress(movedown, "c")
ws.onkeypress(moveleft, "x")
ws.onkeypress(moveright, "v")
 
segments = []

Read:

Python Turtle Spiraling Shape

Python Turtle Write

Python Turtle Circle Mania

Block of code:

In this block of code, we will start playing the snake game the main aim is to collect the food. If snakes collect maximum food then the game score will be maximum.

# Main Gameplay
while True:
    ws.update()
    if hd.xcor() > 290 or hd.xcor() < -290 or hd.ycor() > 290 or hd.ycor() < -290:
        time.sleep(1)
        hd.goto(0, 0)
        hd.direction = "Stop"
        colors = random.choice(['red', 'blue', 'green'])
        shapes = random.choice(['square', 'circle'])
        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(
            score, high_score), align="center", font=("candara", 24, "bold"))
    if hd.distance(foodsh) < 20:
        x = random.randint(-270, 270)
        y = random.randint(-270, 270)
        foodsh.goto(x, y)
     # Adding segment
        newsegmnt = tur.Turtle()
        newsegmnt.speed(0)
        newsegmnt.shape("circle")
        newsegmnt.color("orange")  # tail colour
        newsegmnt.penup()
        segments.append(newsegmnt)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(
            score, high_score), align="center", font=("candara", 24, "bold"))
    # Checking for hd collisions with body segments
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x, y)
    if len(segments) > 0:
        x = hd.xcor()
        y = hd.ycor()
        segments[0].goto(x, y)
    move()
    for segment in segments:
        if segment.distance(hd) < 20:
            time.sleep(1)
            hd.goto(0, 0)
            hd.direction = "stop"
            colors = random.choice(['red', 'orange', 'yellow'])
            shapes = random.choice(['square', 'circle'])
            for segment in segments:
                segment.goto(1000, 1000)
            segment.clear()
 
            score = 0
            delay = 0.1
            pen.clear()
            pen.write("Score : {} High Score : {} ".format(
                score, high_score), align="center", font=("candara", 24, "bold"))
    time.sleep(delay)
 
ws.mainloop()
 

Code:

# import required modules
from turtle import *
import turtle as tur
import time
import random
 
delay = 0.1
score = 0
high_score = 0
 
 
 
# Creating a window screen
ws = tur.Screen()
ws.title("Pythontpoint")
ws.bgcolor("cyan")
ws.setup(width=700, height=600)
ws.tracer(0)
 
# head of the snake
hd = tur.Turtle()
hd.shape("circle")
hd.color("black")
hd.penup()
hd.goto(0, 0)
hd.direction = "Stop"
 
# food in the game
foodsh = tur.Turtle()
colrs = random.choice(['red', 'orange', 'yellow'])
shpes = random.choice(['square', 'triangle', 'circle'])
foodsh.speed(0)
foodsh.shape(shpes)
foodsh.color(colrs)
foodsh.penup()
foodsh.goto(0, 100)
 
pen = tur.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("red")
pen.penup()
pen.hideturtle()
pen.goto(0, 250)
pen.write("Score : 0  High Score : 0", align="center",
          font=("Times New Roman", 24, "bold"))
 
 
 
# assigning key directions
def gp():
    if hd.direction != "down":
        hd.direction = "up"
 
 
def movedown():
    if hd.direction != "up":
        hd.direction = "down"
 
 
def moveleft():
    if hd.direction != "right":
        hd.direction = "left"
 
 
def moveright():
    if hd.direction != "left":
        hd.direction = "right"
 
 
def move():
    if hd.direction == "up":
        y = hd.ycor()
        hd.sety(y+20)
    if hd.direction == "down":
        y = hd.ycor()
        hd.sety(y-20)
    if hd.direction == "left":
        x = hd.xcor()
        hd.setx(x-20)
    if hd.direction == "right":
        x = hd.xcor()
        hd.setx(x+20)
 
 
         
ws.listen()
ws.onkeypress(gp, "d")
ws.onkeypress(movedown, "c")
ws.onkeypress(moveleft, "x")
ws.onkeypress(moveright, "v")
 
segments = []
 
 
 
# Main Gameplay
while True:
    ws.update()
    if hd.xcor() > 290 or hd.xcor() < -290 or hd.ycor() > 290 or hd.ycor() < -290:
        time.sleep(1)
        hd.goto(0, 0)
        hd.direction = "Stop"
        colors = random.choice(['red', 'blue', 'green'])
        shapes = random.choice(['square', 'circle'])
        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()
        score = 0
        delay = 0.1
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(
            score, high_score), align="center", font=("candara", 24, "bold"))
    if hd.distance(foodsh) < 20:
        x = random.randint(-270, 270)
        y = random.randint(-270, 270)
        foodsh.goto(x, y)
 
        # Adding segment
        newsegmnt = tur.Turtle()
        newsegmnt.speed(0)
        newsegmnt.shape("circle")
        newsegmnt.color("orange")  # tail colour
        newsegmnt.penup()
        segments.append(newsegmnt)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen.clear()
        pen.write("Score : {} High Score : {} ".format(
            score, high_score), align="center", font=("candara", 24, "bold"))
    # Checking for hd collisions with body segments
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x, y)
    if len(segments) > 0:
        x = hd.xcor()
        y = hd.ycor()
        segments[0].goto(x, y)
    move()
    for segment in segments:
        if segment.distance(hd) < 20:
            time.sleep(1)
            hd.goto(0, 0)
            hd.direction = "stop"
            colors = random.choice(['red', 'orange', 'yellow'])
            shapes = random.choice(['square', 'circle'])
            for segment in segments:
                segment.goto(1000, 1000)
            segment.clear()
 
            score = 0
            delay = 0.1
            pen.clear()
            pen.write("Score : {} High Score : {} ".format(
                score, high_score), align="center", font=("candara", 24, "bold"))
    time.sleep(delay)
 
ws.mainloop()

Output:

After running the above code, we will get the following output in which we can see that the snake is in the circle form and the food is in the square form as shown on the screen.

Python Turtle Snake Game
Python Turtle Snake Game

After playing the game the score is shown on the screen how many times the snake eat the food without colliding with the wall is shown on the screen.

Python Turtle snake game output
Python Turtle snake game output

1 thought on “Python Turtle Snake Game”

Leave a Comment