Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
90: Building a Simple Snake Game with Turtle
By now, you've got a handle on the core logic of Python, but I've always found that the best way to solidify those concepts is to build something visual. Today, we're using the turtle module. It's a bit old-school, but it's built right into Python and it's fantastic for understanding coordinate systems and game loops without needing to install heavy libraries like Pygame.
Setting up the Arena
First, we need a window. In turtle, the Screen object acts as our game board. I like to set a fixed window size so the game doesn't jump around when it starts. We'll also set the background to black to give it that classic arcade feel.
import turtle
import time
import random
# Setup the screen
win = turtle.Screen()
win.title("Snake Game")
win.bgcolor("black")
win.setup(width=600, height=600)
win.tracer(0) # Turns off screen updates for smoother animation
Defining the Snake and its Movement
I'm treating the snake's head as a separate turtle object. We need to define a move() function that shifts the head forward based on its current heading. To handle the controls, we'll use win.listen() and bind the arrow keys to functions that change the head's direction.
head = turtle.Turtle()
head.shape("square")
head.color("white")
head.penup()
head.goto(0,0)
head.direction = "stop"
def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
def go_up():
if head.direction != "down":
head.direction = "up"
# ... (similar functions for go_down, go_left, go_right)
win.listen()
win.onkeypress(go_up, "Up")
# Bind other keys here...
Spawning Food and Growing the Body
For the food, we just need another turtle that jumps to a random coordinate whenever the snake "collides" with it. To make the snake grow, I'm using a list to keep track of the body segments. Each time the snake eats, we append a new turtle object to that list.
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
segments = []
# Inside the game loop:
if head.distance(food) < 20:
# Move food to random spot
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y)
# Add a segment
new_segment = turtle.Turtle()
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
The "Frozen Screen" Mistake
Here is where I usually trip up the first time I build this. You'll notice I called win.tracer(0) at the start. This tells Python not to animate every single movement of the turtle, which prevents that annoying "stutter" as the snake moves. However, when I first ran my game loop, the screen stayed completely blank. I spent five minutes wondering why my logic was broken, only to realize that when you turn off the tracer, you're responsible for manually refreshing the screen.
If you don't call win.update() inside your while loop, you're essentially drawing on a canvas that's hidden from the user. It's a classic "gotcha."
while True:
win.update() # This is the missing piece!
time.sleep(0.1)
move()
# Move the segments in reverse order
for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y)
if len(segments) > 0:
x = head.xcor()
y = head.ycor()
segments[0].goto(x, y)
Collision Detection
Finally, we need the game to actually end. I'm checking if the head's x or y coordinates exceed 290 (since our window is 600 wide). I also loop through the segments list; if the head's distance to any segment is too small, it's game over. It's a simple distance check, but it's effective enough for a project like this.
📋 Practical Task
Implementing a Live Scoreboard for the Snake Game
Your task is to add a scoring system to the Snake game we just built. Follow these requirements:
- Create a new turtle object specifically for the scoreboard.
- Use the
.write()method to display the current score in the top-center of the screen. - Ensure the scoreboard is hidden (using
.hideturtle()) so only the text is visible. - Update the score and refresh the text on the screen every time the snake collides with the food.
- Reset the score to 0 when the snake hits a wall or its own tail.
There are no comments for now.