Create a Snake-Game using Turtle in Python

Last Updated : 18 Feb, 2026

The Snake Game is a classic arcade game first released in 1976 by Gremlin Industries and published by Sega. The goal is simple to control the snake using arrow keys, collect food to grow longer and avoid hitting the walls or yourself. We’ll build this game in Python using the following modules:

  • Turtle: A built-in Python library that provides a virtual canvas for drawing shapes and animations.
  • Time: Used to control game speed.
  • Random: Helps generate random positions for food on the screen.

Steps to Implement Snake Game

Step 1: Setup Modules, Window, Snake, Food and Scoreboard

In this step, we initialize the game environment and create the main objects required for the Snake Game.

  • Modules: Import turtle for graphics, random for food position and appearance, and time for controlling game speed.
  • Game Variables: Initialize delay to control snake speed, score to track current points, high_score to store the highest score, and run to control the main game loop safely.
  • Window: Create a 600×600 game window with a light blue background (#add8e6) and disable automatic animation using tracer(0) for smooth manual updates.
  • Snake Head: Create a white square turtle positioned at the center (0, 0) and set its initial direction to "Stop".
  • Food: Create a turtle with random shape and color and place it at position (0, 100).
  • Scoreboard: Create a hidden turtle to display the current score and high score at the top of the window.
Python
import turtle as t
import random
import time

d = 0.1
s = 0
hs = 0
run = True

# screen
sc = t.Screen()
sc.title("Snake Game")
sc.bgcolor("#add8e6")
sc.setup(width=600, height=600)
sc.tracer(0)

# snake head
h = t.Turtle()
h.shape("square")
h.color("white")
h.penup()
h.goto(0, 0)
h.direction = "Stop"

# food
f = t.Turtle()
f.shape(random.choice(["circle", "square", "triangle"]))
f.color(random.choice(["red", "green", "black"]))
f.penup()
f.goto(0, 100)

# scoreboard
p = t.Turtle()
p.hideturtle()
p.penup()
p.goto(0, 250)
p.write("Score : 0  High Score : 0", align="center", font=("candara", 24, "bold"))

Step 2: Define Snake Movement and Keyboard Controls

In this step, we create functions to control the snake’s direction and movement using keyboard keys.

Direction Functions: These functions change the snake’s direction when an arrow key is pressed. Each function also prevents the snake from moving in the opposite direction instantly to avoid self-collision.

  1. up() changes direction to "up" if the snake is not moving down
  2. down() changes direction to "down" if the snake is not moving up
  3. left() changes direction to "left" if the snake is not moving right
  4. right() changes direction to "right" if the snake is not moving left

Move Function: This function moves the snake head by 20 pixels in the current direction.

Key Binding: The sc.listen() function enables keyboard input and sc.onkeypress() connects arrow keys to their respective direction functions.

Python
def up():
    if h.direction != "down":
        h.direction = "up"

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

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

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

def move():

    if h.direction == "up":
        h.sety(h.ycor() + 20)

    elif h.direction == "down":
        h.sety(h.ycor() - 20)

    elif h.direction == "left":
        h.setx(h.xcor() - 20)

    elif h.direction == "right":
        h.setx(h.xcor() + 20)

sc.listen()

sc.onkeypress(up, "Up")
sc.onkeypress(down, "Down")
sc.onkeypress(left, "Left")
sc.onkeypress(right, "Right")

Step 3: Implement Main Game Loop and Game Logic

In this step, we create the main loop that runs the game continuously, handles collisions, updates the score and moves the snake.

  • Main Loop: Runs continuously using the run variable and updates the screen.
  • Wall Collision: If the snake hits the boundary, the snake resets to the center, body clears, and score resets.
  • Food Collision: When the snake touches the food, the food moves to a new random position, a new body segment is added, and the score increases.
  • Body Movement: Each body segment follows the position of the segment in front of it.
  • Self Collision: If the snake hits its own body, the game resets.
  • Speed Control: time.sleep(d) controls the game speed.
  • Error Handling: try-except prevents errors when the window is closed.
Python
seg = []

while run:
    try:
        sc.update()

        # wall collision
        if abs(h.xcor()) > 290 or abs(h.ycor()) > 290:
            time.sleep(1)
            h.goto(0, 0)
            h.direction = "Stop"

            for segment in seg:
                segment.goto(1000, 1000)
            seg.clear()

            s = 0
            d = 0.1
            p.clear()

            p.write(f"Score : {s}  High Score : {hs}", align="center", font=("candara", 24, "bold"))

        # food collision
        if h.distance(f) < 20:
            f.goto(random.randint(-270, 270), random.randint(-270, 270))
            new_seg = t.Turtle()
            new_seg.shape("square")
            new_seg.color("orange")
            new_seg.penup()
            seg.append(new_seg)
            d -= 0.001
            s += 10

            if s > hs:
                hs = s
            p.clear()
            p.write(f"Score : {s}  High Score : {hs}", align="center", font=("candara", 24, "bold"))

        # move body
        for i in range(len(seg) - 1, 0, -1):
            x = seg[i - 1].xcor()
            y = seg[i - 1].ycor()
            seg[i].goto(x, y)

        if seg:
            seg[0].goto(h.xcor(), h.ycor())
        move()

        # self collision
        for segment in seg:
            if segment.distance(h) < 20:
                time.sleep(1)
                h.goto(0, 0)
                h.direction = "Stop"

                for segment in seg:
                    segment.goto(1000, 1000)
                seg.clear()

                s = 0
                d = 0.1
                p.clear()
                p.write(f"Score : {s}  High Score : {hs}", align="center", font=("candara", 24, "bold"))

        time.sleep(d)
        
    except t.Terminator:
        run = False

Output

The game window opens showing the snake, food and score and the snake moves based on arrow key input while the score updates during gameplay.

Comment