- 19th Nov 2023
- 12:50 pm
This code creates a simple Snake game where the player controls the snake's direction using the arrow keys. The snake grows when it eats the food (red block) and the game ends if the snake collides with itself or the game window boundaries.
import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 600, 400
BLOCK_SIZE = 20
FPS = 10
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Create the game window
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Snake and food variables
snake = [(WIDTH // 2, HEIGHT // 2)]
snake_direction = "RIGHT"
food = (random.randint(0, (WIDTH-BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE,
random.randint(0, (HEIGHT-BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE)
# Game loop
clock = pygame.time.Clock()
running = True
while running:
win.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != "DOWN":
snake_direction = "UP"
elif event.key == pygame.K_DOWN and snake_direction != "UP":
snake_direction = "DOWN"
elif event.key == pygame.K_LEFT and snake_direction != "RIGHT":
snake_direction = "LEFT"
elif event.key == pygame.K_RIGHT and snake_direction != "LEFT":
snake_direction = "RIGHT"
# Move the snake
head = (snake[0][0], snake[0][1])
if snake_direction == "UP":
head = (head[0], head[1] - BLOCK_SIZE)
elif snake_direction == "DOWN":
head = (head[0], head[1] + BLOCK_SIZE)
elif snake_direction == "LEFT":
head = (head[0] - BLOCK_SIZE, head[1])
elif snake_direction == "RIGHT":
head = (head[0] + BLOCK_SIZE, head[1])
snake.insert(0, head)
# Check for collision with food
if head == food:
food = (random.randint(0, (WIDTH-BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE,
random.randint(0, (HEIGHT-BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE)
else:
snake.pop()
# Check for collision with walls or itself
if (head[0] < 0 or head[0] >= WIDTH or
head[1] < 0 or head[1] >= HEIGHT or
head in snake[1:]):
running = False
# Draw snake
for segment in snake:
pygame.draw.rect(win, GREEN, (segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE))
# Draw food
pygame.draw.rect(win, RED, (food[0], food[1], BLOCK_SIZE, BLOCK_SIZE))
# Update display
pygame.display.flip()
clock.tick(FPS)
# Quit Pygame
pygame.quit()
About The Author - Shaoni Gupta
Seasoned programmer with 6 years of experience in designing, developing, and deploying software solutions. Strong problem-solving skills coupled with the ability to collaborate effectively in multidisciplinary teams. Continuously learning and adapting to new technologies and methodologies to drive innovation and deliver high-quality, user-centric solutions.