Python Code for Snake Game

In this tutorial, we will create a classic Snake Game using Python and object-oriented programming. The game is divided into separate files to keep the code clean and professional.

We will use Python’s built-in turtle module, so no extra game library is required.

Create a Virtual Environment

First, create a project folder and open it with Visual Studio Code or any IDE. Go to the terminal and write the following code to create a virtual environment:

python -m venv venv

Activate the virtual environment using the following code:

venv\Scripts\activate

Now, within the project folder, create a new file named: snake.py and paste the following code into it:

from turtle import Turtle

# Starting positions for the first three snake segments
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]

# Distance the snake moves each step
MOVE_DISTANCE = 20

# Direction constants
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0

class Snake:
    def __init__(self):
        # Store all snake body segments
        self.segments = []

        # Create the starting snake body
        self.create_snake()

        # The first segment is the snake head
        self.head = self.segments[0]

    def create_snake(self):
        # Create snake segments at the starting positions
        for position in STARTING_POSITIONS:
            self.add_segment(position)

    def add_segment(self, position):
        # Create a new square segment
        new_segment = Turtle(shape="square")
        new_segment.color("white")
        new_segment.penup()
        new_segment.goto(position)

        # Add the segment to the snake body
        self.segments.append(new_segment)

    def extend(self):
        # Add a new segment at the position of the last segment
        self.add_segment(self.segments[-1].position())

    def move(self):
        # Move each segment to the position of the segment before it
        for seg_num in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)

        # Move the snake head forward
        self.head.forward(MOVE_DISTANCE)

    def up(self):
        # Prevent the snake from moving directly downward
        if self.head.heading() != DOWN:
            self.head.setheading(UP)

    def down(self):
        # Prevent the snake from moving directly upward
        if self.head.heading() != UP:
            self.head.setheading(DOWN)

    def left(self):
        # Prevent the snake from moving directly right
        if self.head.heading() != RIGHT:
            self.head.setheading(LEFT)

    def right(self):
        # Prevent the snake from moving directly left
        if self.head.heading() != LEFT:
            self.head.setheading(RIGHT)

Create food.py and paste the following code into it:

from turtle import Turtle
import random


class Food(Turtle):
    def __init__(self):
        super().__init__()

        # Create food as a small circle
        self.shape("circle")
        self.penup()
        self.shapesize(0.5, 0.5)
        self.color("blue")
        self.speed("fastest")

        # Place food at a random position
        self.refresh()

    def refresh(self):
        # Generate random x and y coordinates inside the screen
        random_x = random.randint(-280, 280)
        random_y = random.randint(-280, 280)

        # Move food to the random position
        self.goto(random_x, random_y)

Now, create scoreboard.py and paste the following code:

from turtle import Turtle

# Text alignment and font settings
ALIGNMENT = "center"
FONT = ("Courier", 24, "normal")

class Scoreboard(Turtle):
    def __init__(self):
        super().__init__()

        # Starting score
        self.score = 0

        # Scoreboard style
        self.color("white")
        self.penup()
        self.goto(0, 270)
        self.hideturtle()

        # Display initial score
        self.update_scoreboard()

    def update_scoreboard(self):
        # Write the current score on the screen
        self.write(f"Score: {self.score}", align=ALIGNMENT, font=FONT)

    def game_over(self):
        # Display game over message
        self.goto(0, 0)
        self.write("GAME OVER", align=ALIGNMENT, font=FONT)

    def increase_score(self):
        # Increase score when snake eats food
        self.score += 1

        # Clear old score and write updated score
        self.clear()
        self.update_scoreboard()

Now we will create our main file for operation. We can name it main.py. Copy the following code and paste it into main.py:

from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

# 1. Creating snake body

snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with food
    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scoreboard.increase_score()

    # Detect collision with wall
    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
        game_is_on = False
        scoreboard.game_over()

    # Detect collision with tail
    for segment in snake.segments:
        if segment == snake.head:
            pass
        elif snake.head.distance(segment) < 10:
            game_is_on = False
            scoreboard.game_over()

screen.exitonclick()

How to run the code

Open main.py in any IDE, run the code. If you wrote the code properly, the game should be playing after a few seconds.

Get the codes on GitHub.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top