Absolutely! Below is a simple implementation of the classic Snake game in Python using the popular pygame library. The snake collects apples, grows longer, and the game ends if it collides with itself or the wall.
First, make sure you have pygame installed:
pip install pygame
Snake Game in Python (with Pygame)
import pygame
import random
import sys
# Initialize pygame
pygame.init()
# Game constants
WIDTH, HEIGHT = 600, 400
CELL_SIZE = 20
FPS = 10
# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
# Set up display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Snake Game')
# Clock
clock = pygame.time.Clock()
# Font
font = pygame.font.SysFont('Arial', 25)
def draw_snake(snake):
for segment in snake:
pygame.draw.rect(screen, GREEN, (*segment, CELL_SIZE, CELL_SIZE))
def draw_apple(position):
pygame.draw.rect(screen, RED, (*position, CELL_SIZE, CELL_SIZE))
def random_position():
x = random.randint(0, (WIDTH - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
y = random.randint(0, (HEIGHT - CELL_SIZE) // CELL_SIZE) * CELL_SIZE
return (x, y)
def main():
# Initial snake and apple
snake = [(WIDTH // 2, HEIGHT // 2)]
direction = (0, 0)
apple = random_position()
score = 0
running = True
while running:
screen.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 direction != (0, CELL_SIZE):
direction = (0, -CELL_SIZE)
elif event.key == pygame.K_DOWN and direction != (0, -CELL_SIZE):
direction = (0, CELL_SIZE)
elif event.key == pygame.K_LEFT and direction != (CELL_SIZE, 0):
direction = (-CELL_SIZE, 0)
elif event.key == pygame.K_RIGHT and direction != (-CELL_SIZE, 0):
direction = (CELL_SIZE, 0)
if direction != (0, 0):
# Move snake
new_head = (snake[0][0] + direction[0], snake[0][1] + direction[1])
snake.insert(0, new_head)
# Check for apple collision
if new_head == apple:
score += 1
apple = random_position()
# Make sure apple doesn't spawn on the snake
while apple in snake:
apple = random_position()
else:
snake.pop() # Remove tail
# Check for collisions
if (
new_head[0] < 0 or new_head[0] >= WIDTH or
new_head[1] < 0 or new_head[1] >= HEIGHT or
new_head in snake[1:]
):
# Game over
text = font.render(f'Game Over! Score: {score}', True, WHITE)
screen.blit(text, (WIDTH // 2 - text.get_width() // 2, HEIGHT // 2 - text.get_height() // 2))
pygame.display.flip()
pygame.time.wait(2000)
running = False
continue
draw_snake(snake)
draw_apple(apple)
# Draw score
score_text = font.render(f'Score: {score}', True, WHITE)
screen.blit(score_text, (5, 5))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()
How to play:
- Use the arrow keys to control the snake.
- Eat the red apples to grow longer.
- Avoid running into the walls or yourself.
Let me know if you want to add more features (like high scores, increasing speed, etc.)!