The snake game is one of the most popular Python game projects, and it teaches a great idea: the snake is just a list of positions. Each tick, a new head is added in the direction you're moving and the tail is removed, unless you just ate food, in which case the snake grows.
Play the browser version first (arrow keys, WASD or swipe). The Python version below uses the built-in turtle module, so it runs on any computer with Python and needs no extra installs.
Play Snake
This is a browser copy of the game so you can play it here. The Python version below opens its own window on your computer (how to run it).
How to play
- Steer with the arrow keys or W A S D (swipe on a phone).
- Eat the food to grow and score a point.
- Hitting a wall or your own body ends the game.
The complete Snake code
Here is the whole program (90 lines). Save it as snake.py and run it with Python 3: the turtle window opens and the game starts.
import random
import turtle
STEP = 20 # size of one grid square in pixels
LIMIT = 280 # the walls are at -280 and 280
screen = turtle.Screen()
screen.setup(620, 620)
screen.bgcolor("black")
screen.title("Snake")
screen.tracer(0) # we redraw the screen ourselves
pen = turtle.Turtle()
pen.hideturtle()
pen.penup()
snake = [(0, 0), (-20, 0), (-40, 0)] # head first
direction = (STEP, 0)
food = (100, 100)
score = 0
def move(head, direction):
return (head[0] + direction[0], head[1] + direction[1])
def hits_wall(head):
return abs(head[0]) > LIMIT or abs(head[1]) > LIMIT
def new_food():
while True:
spot = (random.randint(-14, 14) * STEP, random.randint(-14, 14) * STEP)
if spot not in snake:
return spot
def square(x, y, color):
pen.goto(x - 9, y - 9)
pen.color(color)
pen.begin_fill()
for _ in range(4):
pen.forward(18)
pen.left(90)
pen.end_fill()
def draw():
pen.clear()
square(food[0], food[1], "red")
for x, y in snake:
square(x, y, "lime")
pen.goto(-280, 290)
pen.color("white")
pen.write(f"Score: {score}", font=("Arial", 14, "bold"))
screen.update()
def turn(dx, dy):
global direction
if (dx, dy) != (-direction[0], -direction[1]): # no reversing into yourself
direction = (dx, dy)
def tick():
global food, score
head = move(snake[0], direction)
if hits_wall(head) or head in snake:
pen.goto(0, 0)
pen.color("white")
pen.write(f"Game over! Score: {score}", align="center", font=("Arial", 24, "bold"))
screen.update()
return
snake.insert(0, head)
if head == food:
score += 1
food = new_food()
else:
snake.pop()
draw()
screen.ontimer(tick, 120)
screen.listen()
screen.onkey(lambda: turn(0, STEP), "Up")
screen.onkey(lambda: turn(0, -STEP), "Down")
screen.onkey(lambda: turn(-STEP, 0), "Left")
screen.onkey(lambda: turn(STEP, 0), "Right")
tick()
screen.mainloop()How the Snake game works, step by step
01The snake is a list of (x, y) tuples
The first tuple is the head. Moving means adding a new head in front and popping the last tuple off the tail, so the body follows the head for free.
snake = [(0, 0), (-20, 0), (-40, 0)] # head first02Move one grid square
The direction is a tuple too, like (20, 0) for right. Adding it to the head gives the next square. A tiny function makes this testable.
def move(head, direction):
return (head[0] + direction[0], head[1] + direction[1])03Grow by not popping
Every tick we insert the new head. If the head landed on the food we keep the tail (the snake grows) and pick new food; otherwise we pop() the tail so the length stays the same.
snake.insert(0, head)
if head == food:
score += 1
food = new_food()
else:
snake.pop()04Detect crashes
The game ends when the new head is outside the walls or already in the body list. head in snake checks every body square at once.
if hits_wall(head) or head in snake:
# game over05Run the game loop with a timer
screen.ontimer(tick, 120) calls tick again in 120 milliseconds, which is the game's speed. screen.tracer(0) plus screen.update() stops flicker by drawing each frame in one go.
screen.ontimer(tick, 120)What you'll learn
- Lists of tuples as game state
insert()andpop()on lists- Keyboard events with
onkey() - A timer-based game loop with
ontimer() globalvariables inside event handlers
Python concepts in this game:
Snake coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Move the head
Write move(head, direction): both are (x, y) tuples. Return the new head position as a tuple.
Hint
Add the x parts together and the y parts together: (head[0] + direction[0], head[1] + direction[1]).
Show a solution
def move(head, direction):
return (head[0] + direction[0], head[1] + direction[1])
print(move((0, 0), (20, 0)))One step of the snake
Write step(snake, direction, food). Add the new head to the front of the list. If the head is on the food, keep the tail (grow) and return True; otherwise remove the tail and return False.
Hint
snake.insert(0, head) adds to the front and snake.pop() removes the last item.
Show a solution
def step(snake, direction, food):
head = (snake[0][0] + direction[0], snake[0][1] + direction[1])
snake.insert(0, head)
if head == food:
return True
snake.pop()
return False
body = [(0, 0), (-20, 0)]
print(step(body, (20, 0), (20, 0)), body)Game over?
Write crashed(head, snake): return True if the head is outside -280...280 on either axis, or if the head is already in the snake list.
Hint
abs() lets one test cover both walls on an axis: abs(head[0]) > LIMIT.
Show a solution
LIMIT = 280
def crashed(head, snake):
if abs(head[0]) > LIMIT or abs(head[1]) > LIMIT:
return True
return head in snake
print(crashed((300, 0), [(280, 0)]))Make it your own
Once your challenges pass, try one of these upgrades:
- Speed up a little every time the snake eats.
- Save the high score to a file with <code>open()</code>.
- Add a wrap-around mode where walls send you to the other side.
- Rebuild it with pygame for smoother graphics.
Frequently asked questions
How do I run the Python snake game?
Copy the code into a file called snake.py and run python snake.py. It only uses the turtle and random modules, which come with Python, so there is nothing to install.
Why does this snake game use turtle and not pygame?
turtle ships with Python, so beginners can run it straight away. The game logic (the list of positions, moving, growing and crashing) is exactly the same in pygame.
How does the snake grow in Python?
Each tick a new head is inserted at the front of the list. Normally the tail is popped off, but when the head reaches the food the tail is kept, so the list gets one item longer.