How to Make a Snake Game in Python

The snake game is a classic video game that has entertained gamers across generations. In this popular game, the player uses the arrow keys to maneuver a growing snake around the screen to eat food pellets. The longer the snake gets without running into the screen edges or its own body, the higher the score.

Python‘s built-in turtle graphics module provides an easy way to recreate this iconic game. By following this beginner-friendly Python snake game tutorial, you‘ll learn fundamentals like:

  • Using turtle graphics to display game elements
  • Handling keyboard input to control game actions
  • Implementing collision checks and scoring systems
  • Building gameplay loops and logic flows

These core concepts can be applied to making all kinds of arcade games, so completing this project will give you a great foundation in Python game development. Let‘s get started!

Getting Set Up

First, you‘ll need to install Python on your computer if you don‘t already have it. I recommend the latest Python 3 release which you can download from python.org.

Once setup, launch IDLE which is the standard Python integrated development environment. You can also work in an editor like Visual Studio Code or PyCharm.

Next, let‘s import the modules we need:

import turtle
import random
import time
  • turtle: Provides the graphics functionality we need to display shapes and draw the game screen
  • random: Generates random numbers for spawn food placement
  • time: Allows tracking time elapsed for game speed

Initializing the Screen

The turtle module gives us access to a virtual canvas onto which we can start placing the game elements. Let‘s initialize that now:

screen = turtle.Screen()
screen.setup(600, 600)
screen.title("Snake Game")
screen.bgcolor("green")

Here we create the screen as a 600 x 600 pixel window, set a title, and apply a green background color.

Next let‘s create our main snake character:

snake = turtle.Turtle() 
snake.shape("square")
snake.color("black")  
snake.penup()
snake.goto(0, 0)

The snake turtle shape defaults to an arrow so we change it to a square. After moving the pen up so no lines are drawn when it moves, we reposition the snake to the center of the screen.

Let‘s also create the snake‘s initial food target:

food = turtle.Turtle()
food.shape("circle")
food.color("red")   
food.penup()
food.speed(0)     
food.goto(100, 0)

We make this turtle a red circle, hide the animation with speed(0) for smooth movement, disable line drawing, and send it to the coordinates (100, 0).

Controlling Snack Movement

In the actual snake game, the player uses the arrow keys to turn the snake left, right, up and down. Let‘s enable that by mapping key presses to snake direction changes.

First we need functions to set each direction:

def go_up():
    snake.direction = "up"   

def go_down():
    snake.direction = "down"

def go_left():
    snake.direction = "left"

def go_right():
    snake.direction = "right"

Then we can listen for specific keys and call the appropriate function:

screen.listen()
screen.onkeypress(go_up, "Up")
screen.onkeypress(go_down, "Down")
screen.onkeypress(go_left, "Left") 
screen.onkeypress(go_right, "Right")

Now when the player presses up, down, left or arrow on the keyboard, it will set snake.direction to the matching value.

To actually make the snake move continuously, we need a function like:

def move():
    if snake.direction == "up":
        y = snake.ycor()  
        snake.sety(y + 20)

    if snake.direction == "down":
        y = snake.ycor()
        snake.sety(y - 20)

    if snake.direction == "left":
        x = snake.xcor()
        snake.setx(x - 20)

    if snake.direction == "right":
        x = snake.xcor()
        snake.setx(x + 20) 

This gets the current x and y coordinates, adds/subtracts 20 pixels depending on the direction, and resets the position. Calling move() repeatedly will then slide the snake forward on each keypress.

Implementing Gameplay

We have the basic snake moving around an empty screen. Now let‘s actually turn it into a game by adding gameplay logic.

Main Game Loop

We need an infinite loop that handles repeating tasks like:

  • Listening for player input
  • Moving the snake
  • Updating scores, speed etc.
  • Checking for win/loss conditions

Here is a simplified game loop:

while True:

    screen.update()

    move()

    # Check collisions
    # Check if snake ate food

    # Game over conditions

Wrapping the whole flow inside while True keeps it running continuously so that gameplay is smooth rather than fragmented.

Collision Detection

An important mechanic is detecting when the snake hits the screen edges or its own body. To check for this:

if snake.xcor() > 280 or snake.xcor() < -280:
    game_over()

if snake.ycor() > 280 or snake.ycor() < -280:
    game_over()   

The screen coordinates run from -300 to 300 so we stop 4 pixels short of the max values. When either condition matches, we can trigger a game over function.

To detect collisions with itself, we must store each segment as the snake grows, then check if the head touches any of them:

segments = []

if head.distance(segment) < 20: 
    game_over()

Spawning Food

To place the food pellet at a random free location when eaten:

x = random.randint(-280, 280)
y = random.randint(-280, 280)

food.goto(x, y)

By generating random x and y values inside the playing area we can automatically repopulate food without it appearing inside the snake.

Scoring System

Let‘s add a scoring display and rules for points:

score = 0
high_score = 0

pen = turtle.Turtle()  

pen.speed(0)    
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 250)  

pen.write("Score: {}  High Score: {}".format(score, high_score), 
          align="center", font=("Courier", 24, "normal")) 

# When food eaten
score += 1  
if score > high_score:
    high_score = score

    pen.clear()   
    pen.write("Score: {} High Score: {}".format(score, high_score), 
              align="center", font=("Courier", 24, "normal")) 

This tracks both the current and highest ever score, updating the display when necessary. We simply increment the score every time the snake eats food.

With the scoring rules in place, the core snake game mechanics are all set! There are many ways you could continue enhancing it:

  • Add menus and UI screens
  • Allow choosing speed and difficulty
  • Have snake grow when eating instead of just scoring
  • Support two player mode
  • Add sound effects and visuals

The full code for this snake game tutorial is available on GitHub here.

I hope you enjoyed learning how to code a functional snake game in Python using the built-in turtle module! Let me know about any other fun projects you end up building.