Let’s learn how to make a simple Snake game in Python with Pygame. When the snake eats food, it will grow longer. But be careful, if it hits the wall or itself, the game will stop.
Pygame helps us show things on the screen and control how the game works. It’s a fun and easy way to start learning game coding, even if you’re just starting out!
Let’s see how to Set Up Pygame :
Before starting the snake game in Python using Pygame, you must install Pygame in your system. Type the command below in your terminal.
pip install pygame
If this does not work then try this one–
"py -m pip install -U pygame --user"
Snake Game in Python with Pygame Source Code
import pygame
import time
import random
# Initialize pygame
pygame.init()
# Game window dimensions
WIDTH, HEIGHT = 600, 400
# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (213, 50, 80)
BLACK = (0, 0, 0)
# Snake block size
BLOCK_SIZE = 10
# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Clock for controlling game speed
clock = pygame.time.Clock()
SNAKE_SPEED = 15
# Font
font = pygame.font.SysFont("bahnschrift", 25)
def draw_snake(snake_body):
for block in snake_body:
pygame.draw.rect(screen, GREEN, [block[0], block[1], BLOCK_SIZE, BLOCK_SIZE])
def display_message(msg, color, x, y):
text = font.render(msg, True, color)
screen.blit(text, [x, y])
def game_loop():
game_over = False
game_close = False
x, y = WIDTH // 2, HEIGHT // 2
x_change, y_change = 0, 0
snake_body = []
snake_length = 1
food_x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
food_y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
while not game_over:
while game_close:
screen.fill(BLACK)
display_message("Game Over! Press Q-Quit or C-Play Again", RED, WIDTH // 6, HEIGHT // 3)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -BLOCK_SIZE
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = BLOCK_SIZE
y_change = 0
elif event.key == pygame.K_UP:
y_change = -BLOCK_SIZE
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = BLOCK_SIZE
x_change = 0
# Check boundaries
if x >= WIDTH or x < 0 or y >= HEIGHT or y < 0:
game_close = True
x += x_change
y += y_change
screen.fill(BLACK)
pygame.draw.rect(screen, RED, [food_x, food_y, BLOCK_SIZE, BLOCK_SIZE])
snake_body.append([x, y])
if len(snake_body) > snake_length:
del snake_body[0]
# Check collision with itself
for block in snake_body[:-1]:
if block == [x, y]:
game_close = True
draw_snake(snake_body)
pygame.display.update()
# Eating food
if x == food_x and y == food_y:
food_x = random.randrange(0, WIDTH - BLOCK_SIZE, BLOCK_SIZE)
food_y = random.randrange(0, HEIGHT - BLOCK_SIZE, BLOCK_SIZE)
snake_length += 1
clock.tick(SNAKE_SPEED)
pygame.quit()
quit()
game_loop()
Top Logics You Must Know there in Code:
1. Snake Moves with Arrow Keys
The snake starts in the middle of the screen and moves when you press arrow keys. Press left, it goes left. Press down, it goes down. Each keypress changes the snake’s direction.
2. Snake Eats Food to Grow
A red square (food) shows up in random places. If the snake touches it, it eats it. When that happens, the snake becomes longer by 1 block, and a new food appears.
3. Game Over on Crash
The game ends if:
The snake hits the wall (goes out of screen), the snake hits itself (bites its own body)
When that happens, a “Game Over” message shows, and you can press Q to quit or C to play again.
4. Snake is a List of Blocks
The snake is made from many little squares (blocks). These blocks are stored in a list. The list grows every time the snake eats food, and the screen updates to show the new length.
5. Game Runs in a Loop
The whole game runs inside a while loop. This loop keeps checking:
- Did you press a key?
- Did the snake eat food?
- Did it hit something?
The screen updates over and over using clock.tick(), which controls how fast the snake moves.
Conclusion:
And that’s it! You’ve just built a fun Snake game in Python with Pygame. Now you can try adding your features, like new levels or different speeds. Keep practicing, and you’ll get better at making games in no time!
Thanks for visiting codehelping.com. For more Python projects, visit here.