As a data analyst and Python enthusiast, few coding projects excite me more than creating a fully-functional snake game from scratch. These classic arcade games combine logic, problem-solving, and simple graphics programming in a fun, engaging way – making them a favorite introductory project for new coders.
In this comprehensive guide, we‘ll code a snake game in Python step-by-step, covering key concepts like functions, loops, event handling, and data structures. Follow along to gain practical skills you can apply to future Python projects. Let‘s slither into some snake game development!
A Nostalgic Blast From the Past
For many 90s kids like myself, snake games bring back fond memories of feeding quarters into arcade machines, struggling to top your high score. Though snake mechanics seem simple now, at the time it was revolutionary technology!
The first known snake game, Blockade, was developed in 1976. Players had to maneuver segments of a line to box in opponents. Then in 1978 came Snake – the game that truly popularized the genre. Here, a single snake ate dots to grow longer while avoiding walls and its own body.
Soon snake games slithered into the digital era on PCs and early cell phones. Even today‘s youth remain enthralled, swiping their fingers to guide snakes on smartphones and tablets.
So what makes these games so timelessly appealing? A few key elements:
- Simplicity – Easy to learn, challenging to master
- Progression – Feelings of growth and accomplishment
- Risk vs. Reward – Higher stakes as snake grows bigger
- Replayability – Quick to restart and try beating your high score
By coding a snake game yourself, you can understand what makes them so engaging while honing useful Python skills. Let‘s break it down step-by-step!
Snake Game Overview
For those new to snake games, here‘s a quick overview:
The player uses arrow keys to move a "snake" around the screen. As the snake finds and eats food, it grows longer. The goal is to grow as big as possible without hitting the screen boundaries or the snake‘s own body. Each collision ends the game.
Some key elements we‘ll need are:
- Snake – Player‘s avatar, grows when eating
- Food – Collectible dots for snake to eat
- Screen edges – End game if snake hits them
- Scoring – Track length of snake/food eaten
- Collision detection – End game if snake hits itself
- Difficulty increase – Speed up snake over time
With some basic Python concepts, we can code all of this ourselves! Let‘s look at how.
Import Required Modules
Python comes packed with modules containing reusable functions to simplify development. For our snake game, we primarily need 3:
- Turtle – Provides graphics/drawing functionality
- Time – Allows tracking time/frames
- Random – Generates random numbers
Turtle will handle our graphics, Time helps with game speed, and Random places food randomly. To access functions from these modules:
import turtle
import time
import random
Now let‘s initialize our game screen using Turtle!
Initialize the Game Screen with Turtle
Turtle allows us to easily set up a graphics window in Python. We can treat it as a blank canvas to draw the different elements of our game.
First we‘ll create the screen itself, set the dimensions, and give it a title:
screen = turtle.Screen()
screen.setup(width=600, height=600)
screen.title("Snake Game")
This creates a 600×600 pixel window with the title "Snake Game". Next let‘s add a background color using RGB values:
screen.bgcolor("green")
We now have a dedicated window ready for gameplay! Time to add the snake.
Coding the Snake with Turtle Objects
The snake will be the player‘s avatar, starting small but growing by eating food. To represent the snake, we‘ll create a Turtle object:
snake = turtle.Turtle()
Turtles have built-in methods for moving, drawing, changing colors, etc. This makes them perfect for representing our snake.
Next let‘s set the snake‘s shape, color, and initial movement direction:
snake.shape("square")
snake.color("black")
snake.direction = "stop"
The square shape and black color form the initial snake head. We set the direction to "stop" until arrow keys tell it which way to move.
Handling Snake Movement with Functions
To move our snake, we need functions to handle each press of the arrow keys. We‘ll track which direction the snake is headed and update its position accordingly.
First a move() function to handle movement:
def move():
if snake.direction == "up":
# Move up by increasing y coord
y = snake.ycor()
y += 20
snake.sety(y)
# Handle other directions
...
And functions to change direction on keypresses:
def go_up():
if snake.direction != "down":
snake.direction = "up"
def go_down():
if snake.direction != "up":
snake.direction = "down"
# Handle other directions
...
We ensure the snake can‘t move backwards into itself by preventing 180 degree turns.
Tracking Keypress Events to Move Snake
Now we need to call those snake movement functions when an arrow key is pressed.
Turtle‘s onkey() method allows detecting keypresses and calling functions in response:
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_down, "Down")
# ...
By tying this together with a main game loop, we can move the snake around the screen with arrow keys!
Building the Snake Body
So far we‘re moving just the snake‘s head. Let‘s add body segments so the snake gets longer when eating food.
We‘ll store each segment as a Turtle object in a list:
segments = []
# Add initial body segment
segment = turtle.Turtle()
segment.shape("square")
segment.color("grey")
segments.append(segment)
When moving, we‘ll cycle through the body segments from tail to head, moving each to the position of the one in front of it:
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
This produces the classic snake animation as it slithers forward.
Spawning Food Objects at Random Locations
As the snake explores, it needs to find food scattered across the screen. We‘ll randomly generate food using the random module:
import random
# Create food
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.speed(0)
food.penup()
food.goto(random.randint(-280, 280), random.randint(-280, 280))
By placing food at random x,y coordinates, it will appear in unpredictable locations for the snake to seek out.
Detecting Collisions to End Game
What‘s a snake game without colliding into walls or your own ever-growing body? Let‘s code collision detection.
We can check border collisions easily with the screen dimensions:
# Check border collision
if (snake.xcor() > 280 or snake.xcor() < -280 or
snake.ycor() > 280 or snake.ycor() < -280):
game_over()
For self-collision, we check if any body segment is too close:
# Check for head hitting body
for segment in segments:
if segment.distance(snake) < 10:
game_over()
When a collision occurs, we can call game_over() to reset the game.
Increasing Difficulty by Speeding Up Snake
No good snake game stays slow and steady forever. Let‘s incrementally speed up the snake to increase difficulty over time.
We‘ll use a speed variable that increases when eating:
speed = 10
if snake.distance(food) < 15:
# Snake ate food
speed += 1
And in the movement function, we‘ll tie speed to the snake‘s animation delay:
# Higher speed = shorter delay
snake.delay(150/speed)
Now players have a small window at the start to learn controls before frantically trying to outpace the snake. The tension ramps up perfectly!
Showing Game Over and Resetting
When the snake collides, we need to pause the game, display "Game Over", and reset the snake to play again.
Here‘s one way to implement it:
def game_over():
# Hide snake
snake.hideturtle()
# Clear screen
screen.clear()
# Show game over text
style = ("Arial", 30, "bold")
pen.write("Game Over", align="center", font=style)
# Reset snake and food
snake.showturtle()
snake.direction = "stop"
snake.goto(0,0)
food.goto(random.randint(-280, 280), random.randint(-280, 280))
Now players can restart and beat their high score!
Expanding the Game with New Features
While we‘ve coded a solid, playable snake game, there‘s always room for improvement. Some ideas to try:
- Add a scoreboard
- Vary food sizes
- Obstacles like rocks
- Sound effects
- Multiple snakes
- Power-ups
- Difficulty settings
- Multiplayer over network
The great thing about Python is if you can think it, you can code it! Starting with a simple snake game teaches you the foundations to create almost anything you can imagine.
I hope this guide gets you started bringing these nostalgic games to life while improving your programming skills. Soon you‘ll be a Python snake charmer! Let me know if you have any other questions.
Happy coding!