Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.2 kB
0
Indexable
Never
import pygame
import sys
import random

# Initialize Pygame
pygame.init()

# Set up the display
width, height = 600, 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

# Set up the snake
snake_size = 20
snake_color = (0, 255, 0)  # Green
snake_speed = 15
snake = [[100, 50], [90, 50], [80, 50]]  # Initial positions of the snake segments

# Set up the food
food_size = 20
food_color = (255, 0, 0)  # Red
food_position = [random.randrange(1, (width//food_size)) * food_size,
                  random.randrange(1, (height//food_size)) * food_size]

# Set up the game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        snake[0][1] -= snake_size
    if keys[pygame.K_DOWN]:
        snake[0][1] += snake_size
    if keys[pygame.K_LEFT]:
        snake[0][0] -= snake_size
    if keys[pygame.K_RIGHT]:
        snake[0][0] += snake_size

    # Move the snake
    for i in range(len(snake) - 1, 0, -1):
        snake[i] = list(snake[i - 1])

    # Check for collision with food
    if snake[0] == food_position:
        snake.append([0, 0])
        food_position = [random.randrange(1, (width//food_size)) * food_size,
                          random.randrange(1, (height//food_size)) * food_size]

    # Check for collision with walls
    if snake[0][0] < 0 or snake[0][0] >= width or snake[0][1] < 0 or snake[0][1] >= height:
        pygame.quit()
        sys.exit()

    # Check for collision with itself
    for segment in snake[1:]:
        if snake[0] == segment:
            pygame.quit()
            sys.exit()

    # Fill the screen with a white background
    screen.fill((255, 255, 255))

    # Draw the snake
    for segment in snake:
        pygame.draw.rect(screen, snake_color, pygame.Rect(segment[0], segment[1], snake_size, snake_size))

    # Draw the food
    pygame.draw.rect(screen, food_color, pygame.Rect(food_position[0], food_position[1], food_size, food_size))

    # Update the display
    pygame.display.flip()

    # Control the game speed
    pygame.time.Clock().tick(snake_speed)

Leave a Comment