Certainly! Below is a simple implementation of the classic Snake game using Python and the Pygame library.
Prerequisites:
Before running the code, make sure you have Pygame installed. You can install it using pip:
pip install pygame
Snake Game Code:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# Create the screen object
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# Clock to control the game's frame rate
clock = pygame.time.Clock()
# Define colors
WHITE = (255, 255, 255)
RED = (200, 0, 0)
GREEN = (0, 180, 0)
BLACK = (0, 0, 0)
# Snake settings
SNAKE_SIZE = 20
SNAKE_SPEED = 15
# Define the font for score display
font = pygame.font.SysFont('arial', 25)
def draw_snake(snake_body):
for block in snake_body:
pygame.draw.rect(screen, GREEN, [block[0], block[1], SNAKE_SIZE, SNAKE_SIZE])
def show_score(score):
value = font.render("Score: " + str(score), True, WHITE)
screen.blit(value, [0, 0])
def game_loop():
game_over = False
game_close = False
# Starting position of the snake
x = SCREEN_WIDTH / 2
y = SCREEN_HEIGHT / 2
# Movement variables
x_change = 0
y_change = 0
# Snake body and length
snake_body = []
snake_length = 1
# Food position
food_x = round(random.randrange(0, SCREEN_WIDTH - SNAKE_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - SNAKE_SIZE) / 20.0) * 20.0
while not game_over:
while game_close:
screen.fill(BLACK)
message = font.render("Game Over! Press C - Play Again or Q - Quit", True, RED)
screen.blit(message, [SCREEN_WIDTH / 6, SCREEN_HEIGHT / 3])
show_score(snake_length - 1)
pygame.display.update()
# Event handling for game over state
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()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Event handling for game state
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -SNAKE_SIZE
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = SNAKE_SIZE
y_change = 0
elif event.key == pygame.K_UP:
y_change = -SNAKE_SIZE
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = SNAKE_SIZE
x_change = 0
# Update snake position
x += x_change
y += y_change
# Boundaries collision detection
if x >= SCREEN_WIDTH or x < 0 or y >= SCREEN_HEIGHT or y < 0:
game_close = True
screen.fill(BLACK)
pygame.draw.rect(screen, RED, [food_x, food_y, SNAKE_SIZE, SNAKE_SIZE])
# Snake movement
snake_head = [x, y]
snake_body.append(snake_head)
if len(snake_body) > snake_length:
del snake_body[0]
# Self collision detection
for block in snake_body[:-1]:
if block == snake_head:
game_close = True
draw_snake(snake_body)
show_score(snake_length - 1)
pygame.display.update()
# Food consumption
if x == food_x and y == food_y:
food_x = round(random.randrange(0, SCREEN_WIDTH - SNAKE_SIZE) / 20.0) * 20.0
food_y = round(random.randrange(0, SCREEN_HEIGHT - SNAKE_SIZE) / 20.0) * 20.0
snake_length += 1
clock.tick(SNAKE_SPEED)
pygame.quit()
sys.exit()
if __name__ == "__main__":
game_loop()
Instructions:
-
Run the Code:
- Save the code in a file named
snake_game.py.
- Run the script using the command
python snake_game.py.
-
Controls:
- Use the arrow keys to move the snake up, down, left, or right.
-
Gameplay:
- Collect the red food squares to grow longer.
- Avoid running into the walls or the snake's own body.
- The score is displayed at the top left corner.
-
Game Over:
- When the game is over, you can press:
- C to play again.
- Q to quit the game.
Explanation:
Customization:
- Adjust Speed: Modify the
SNAKE_SPEED variable to increase or decrease the game's difficulty.
- Change Colors: Tweak the RGB values in the color definitions to customize the game's appearance.
Have Fun!