import pygame # Import the Pygame library for game development import random # Import the random module for generating random numbers # Initialize Pygame pygame.init() # Initialize the Pygame library # Set up the screen WIDTH, HEIGHT = 600, 400 # Defines the width and height of the game window GRID_SIZE = 20 # Defines the size of each grid cell GRID_WIDTH, GRID_HEIGHT = WIDTH // GRID_SIZE, HEIGHT // GRID_SIZE # Calculates the number of grid cells screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Create the game window with the specified dimensions pygame.display.set_caption("Snake Game") # Set the title of the game window # Define colors using RGB values WHITE = (255, 255, 255) # Defines the color white GREEN = (0, 255, 0) # Defines the color green RED = (255, 0, 0) # Defines the color red BLACK = (0, 0, 0) # Defines the color black PINK = (255, 192, 203) # Defines the color pink PURPLE = (128, 0, 128) # Defines the color purple ORANGE = (255, 165, 0) # Defines the color orange # Snake class class Snake: def __init__(self): self.length = 1 # Initial length of the snake self.positions = [((WIDTH / 2), (HEIGHT / 2))] # Initial position of the snake's head self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) # Initial direction of the snake self.color = GREEN # Color of the snake def get_head_position(self): return self.positions[0] # Get the position of the snake's head def turn(self, point): if self.length > 1 and (point[0]*-1, point[1]*-1) == self.direction: return # Prevents the snake from turning back on itself else: self.direction = point # Change the direction of the snake def move(self): cur = self.get_head_position() x, y = self.direction new = (((cur[0] + (x*GRID_SIZE)) % WIDTH), (cur[1] + (y*GRID_SIZE)) % HEIGHT) if len(self.positions) > 2 and new in self.positions[2:]: self.reset() # Resets the game if snake collides with itself return -1 else: self.positions.insert(0, new) # Move the snake's head to the new position if len(self.positions) > self.length: self.positions.pop() # Remove the last segment of the snake if it's longer than its length return 0 def reset(self): self.length = 1 # Reset the length of the snake self.positions = [((WIDTH / 2), (HEIGHT / 2))] # Reset the position of the snake's head self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) # Reset the direction of the snake def draw(self, surface): for p in self.positions: r = pygame.Rect((p[0], p[1]), (GRID_SIZE, GRID_SIZE)) pygame.draw.rect(surface, self.color, r) # Draw the snake on the game surface pygame.draw.rect(surface, WHITE, r, 1) # Draw the border of the snake segments def handle_keys(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # Quit the game if the window is closed elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.turn(UP) # Turn the snake upwards elif event.key == pygame.K_DOWN: self.turn(DOWN) # Turn the snake downwards elif event.key == pygame.K_LEFT: self.turn(LEFT) # Turn the snake to the left elif event.key == pygame.K_RIGHT: self.turn(RIGHT) # Turn the snake to the right # Food class class Food: def __init__(self): self.position = (0, 0) # Initial position of the food self.color = RED # Color of the food self.randomize_position() # Set a random position for the food def randomize_position(self): self.position = (random.randint(0, GRID_WIDTH-1) * GRID_SIZE, random.randint(0, GRID_HEIGHT-1) * GRID_SIZE) # Set a random position for the food within the grid def draw(self, surface): r = pygame.Rect((self.position[0], self.position[1]), (GRID_SIZE, GRID_SIZE)) pygame.draw.rect(surface, self.color, r) # Draw the food on the game surface pygame.draw.rect(surface, WHITE, r, 1) # Draw the border of the food # Directions UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0) def main(): clock = pygame.time.Clock() # Create a clock object to control the frame rate snake = Snake() # Create an instance of the Snake class food = Food() # Create an instance of the Food class score = 0 # Initialize the score to zero while True: # Main game loop screen.fill(BLACK) # Fill the game window with Black color snake.handle_keys() # Handle user input for controlling the snake result = snake.move() # Move the snake if result == -1: score = 0 # Reset the score if the snake collides with itself if snake.get_head_position() == food.position: snake.length += 1 # Increase the length of the snake if it eats the food score += 1 # Increase the score food.randomize_position() # Move the food to a random position snake.draw(screen) # Draw the snake on the game surface food.draw(screen) # Draw the food on the game surface # Displaying score font = pygame.font.SysFont(None, 25) # Create a font object text = font.render(f"Score: {score}", True, WHITE) # Render the text displaying the score screen.blit(text, (10, 10)) # Draw the text on the game surface pygame.display.update() # Update the display clock.tick(10) # Control the frame rate if __name__ == "__main__": main() # Start the game