Category: Fun & Experiments
Tags: Fun & Experiments, Games
Hello fellow coding adventurers! Ever wanted to make your own game but thought it was too complicated? Well, think again! Today, we’re going to dive into the exciting world of game development by creating a classic: the Snake game, using a beginner-friendly Python library called Pygame.
Get ready to bring a simple idea to life with just a few lines of code. This tutorial is designed for absolute beginners, so don’t worry if you’re new to some concepts. We’ll explain everything step-by-step!
What is Pygame?
Before we jump into coding, let’s talk about Pygame.
- Pygame: Pygame is a set of Python modules designed for writing video games. It provides functionalities for graphics, sound, user input, and more. Think of it as a toolbox that helps you draw things on the screen, play sounds, and react to keyboard presses or mouse clicks, making game development much easier.
It’s widely used by hobbyists and indie developers because it’s relatively easy to learn and incredibly powerful for 2D games.
Setting Up Your Environment
First things first, you need to make sure you have Python installed on your computer. If you don’t, head over to python.org and download the latest version.
Once Python is ready, we need to install Pygame. Open your command prompt (Windows) or terminal (macOS/Linux) and type the following command:
pip install pygame
- pip:
pipis Python’s package installer. It’s like an app store for Python, allowing you to easily download and install libraries (collections of code) that other people have made, like Pygame.
If the installation is successful, you’re all set to start coding!
Game Plan: What We’ll Build
Our Snake game will have these core features:
- Game Window: A simple window where our game will play out.
- Snake: A moving “snake” that grows longer as it eats food.
- Food: A target for the snake to eat, appearing randomly.
- Movement: You’ll control the snake’s direction using arrow keys.
- Collision Detection: The game will end if the snake hits the wall or itself.
- Score: Keep track of how much food the snake has eaten.
Let’s Start Coding!
Open your favorite code editor (like VS Code, Sublime Text, or even a simple text editor) and create a new Python file, for example, snake_game.py.
Step 1: Initialize Pygame and Set Up the Screen
Every Pygame program starts with initialization. We’ll also set up our game window’s size and title.
import pygame
import random # We'll need this for the food placement later
pygame.init()
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("My Simple Snake Game!")
WHITE = (255, 255, 255) # Max red, green, blue = white
BLACK = (0, 0, 0) # No red, green, blue = black
GREEN = (0, 255, 0) # Max green
RED = (255, 0, 0) # Max red
clock = pygame.time.Clock()
Step 2: Define Game Variables
Now, let’s define variables for our snake, food, and game mechanics.
snake_block = 10 # Size of one snake segment (10 pixels by 10 pixels)
snake_speed = 15 # How fast the snake moves (frames per second)
x1 = screen_width / 2 # Starting x-coordinate, in the middle of the screen
y1 = screen_height / 2 # Starting y-coordinate, in the middle of the screen
snake_list = [] # This list will store the (x, y) coordinates of each segment of our snake
length_of_snake = 1 # The initial length of the snake
x1_change = 0
y1_change = 0
food_x = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
game_over = False # Becomes True when the player decides to quit the entire application
game_close = False # Becomes True when the snake crashes, prompting a "Game Over" screen
score = 0 # Player's score
Step 3: Helper Functions to Draw and Display
We’ll create a few functions to make our main game loop cleaner.
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_block, snake_block])
# pygame.draw.rect(): Draws a rectangle on the screen.
# Arguments: (surface, color, [x_pos, y_pos, width, height])
def display_score(score):
font = pygame.font.SysFont("comicsansms", 25) # Choose a font (comicsansms) and size (25)
value = font.render("Your Score: " + str(score), True, WHITE)
# font.render(): Creates a new Surface (an image) with the rendered text.
# Arguments: (text, antialias, color). Antialias makes the text smoother.
screen.blit(value, [0, 0]) # Draw the text on the screen at position (0,0) (top-left corner)
# screen.blit(): Draws one image (our text surface) onto another (our game screen).
def message(msg, color):
font = pygame.font.SysFont("comicsansms", 50) # Larger font for the main message
mesg = font.render(msg, True, color)
# Calculate position to center the message on the screen
mesg_rect = mesg.get_rect(center=(screen_width / 2, screen_height / 2))
screen.blit(mesg, mesg_rect)
Step 4: The Main Game Loop
This is the heart of our game. It continuously checks for events, updates game logic, and draws everything on the screen.
while not game_over:
# Loop for the "Game Over" screen
while game_close:
screen.fill(BLACK) # Clear the screen with black
message("You Lost! Press Q-Quit or C-Play Again", RED)
display_score(score) # Show final score
pygame.display.update() # Update the display to show the game over message
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q: # If 'Q' is pressed
game_over = True # End the main game loop
game_close = False # Exit the game over loop
if event.key == pygame.K_c: # If 'C' is pressed
# Reset game variables to play again
x1 = screen_width / 2
y1 = screen_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
food_x = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
score = 0
game_close = False # Exit the game over loop and start new game
if event.type == pygame.QUIT: # If the user clicks the window close button
game_over = True
game_close = False
# Loop for active gameplay
for event in pygame.event.get():
if event.type == pygame.QUIT: # If user closes the window
game_over = True
if event.type == pygame.KEYDOWN:
# pygame.KEYDOWN: An event type that occurs when a key is pressed down.
# event.key: A constant representing which key was pressed (e.g., pygame.K_LEFT for the left arrow key).
if event.key == pygame.K_LEFT:
x1_change = -snake_block # Move left by one snake block
y1_change = 0 # No vertical movement
elif event.key == pygame.K_RIGHT:
x1_change = snake_block # Move right
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block # Move up
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block # Move down
x1_change = 0
# Collision with boundaries (game over if snake hits the wall)
if x1 >= screen_width or x1 < 0 or y1 >= screen_height or y1 < 0:
game_close = True
# Update snake's position based on its current direction
x1 += x1_change
y1 += y1_change
# Clear the screen for the new frame
screen.fill(BLACK)
# Draw the food
pygame.draw.rect(screen, RED, [food_x, food_y, snake_block, snake_block])
# Add the current head position to the snake's body list
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
# Remove the oldest segment if the snake is longer than its current length
if len(snake_list) > length_of_snake:
del snake_list[0]
# Collision with self (game over if snake hits its own body)
for x in snake_list[:-1]: # Check all segments except the current head
if x == snake_head:
game_close = True
# Draw the entire snake and the score
draw_snake(snake_block, snake_list)
display_score(score)
# Update the full display surface to the screen to show all changes
pygame.display.update()
# pygame.display.update(): This updates the entire screen to show what we've drawn since the last update.
# Without this, you wouldn't see anything!
# Check if the snake has eaten the food
if x1 == food_x and y1 == food_y:
# Generate new food position
food_x = round(random.randrange(0, screen_width - snake_block) / 10.0) * 10.0
food_y = round(random.randrange(0, screen_height - snake_block) / 10.0) * 10.0
length_of_snake += 1 # Make the snake grow
score += 10 # Increase score
# Control game speed
clock.tick(snake_speed)
# clock.tick(): This pauses the game for a short time to ensure it doesn't run faster than our desired `snake_speed` frames per second.
pygame.quit()
quit() # Exit the Python script
Congratulations, You’ve Made a Game!
You’ve just created your very own Snake game! It might look like a lot of code, but we broke it down into understandable chunks. Each part plays a crucial role in bringing the game to life.
By following this tutorial, you’ve learned about:
- Initializing Pygame and setting up a display window.
- Handling user input from the keyboard.
- Drawing shapes (rectangles for snake and food).
- Implementing game logic like movement and collision detection.
- Managing game state and displaying a score.
- Controlling game speed with
pygame.time.Clock().
This is just the beginning! Game development is a fantastic journey of creativity and problem-solving.
Next Steps and Improvements
Want to make your game even better? Here are some ideas:
- Different Levels: Increase snake speed or make the food disappear faster.
- Obstacles: Add stationary blocks that the snake must avoid.
- Sounds: Add sounds for eating food or game over.
- Better Graphics: Replace simple rectangles with images (sprites).
- Start Screen: Create a welcome screen before the game begins.
Experiment, have fun, and keep building!
Leave a Reply
You must be logged in to post a comment.