import pygame import random # Initialize Pygame pygame.init() # Set up the screen WIDTH, HEIGHT = 600, 400 CELL_SIZE = 20 GRID_WIDTH, GRID_HEIGHT = WIDTH // CELL_SIZE, HEIGHT // CELL_SIZE screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Snake Game") # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) # Snake class class Snake: def __init__(self): self.body = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)] self.direction = (1, 0) def move(self): head = self.body[0] x, y = head dx, dy = self.direction new_head = ((x + dx) % GRID_WIDTH, (y + dy) % GRID_HEIGHT) if new_head in self.body[1:]: return False # Snake collided with itself self.body.insert(0, new_head) return True def grow(self): self.body.append(self.body[-1]) def draw(self): for segment in self.body: pygame.draw.rect(screen, GREEN, (segment[0] * CELL_SIZE, segment[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)) def change_direction(self, direction): if direction == "UP" and self.direction != (0, 1): self.direction = (0, -1) elif direction == "DOWN" and self.direction != (0, -1): self.direction = (0, 1) elif direction == "LEFT" and self.direction != (1, 0): self.direction = (-1, 0) elif direction == "RIGHT" and self.direction != (-1, 0): self.direction = (1, 0) # Food class class Food: def __init__(self): self.position = self.new_position() def new_position(self): return random.randint(0, GRID_WIDTH-1), random.randint(0, GRID_HEIGHT-1) def draw(self): pygame.draw.rect(screen, RED, (self.position[0] * CELL_SIZE, self.position[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE)) # Game loop def main(): snake = Snake() food = Food() clock = pygame.time.Clock() running = True while running: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.change_direction("UP") elif event.key == pygame.K_DOWN: snake.change_direction("DOWN") elif event.key == pygame.K_LEFT: snake.change_direction("LEFT") elif event.key == pygame.K_RIGHT: snake.change_direction("RIGHT") # Move snake if not snake.move(): running = False # Game over if snake collided with itself # Check if snake ate food if snake.body[0] == food.position: snake.grow() food.position = food.new_position() # Draw everything screen.fill(BLACK) snake.draw() food.draw() pygame.display.flip() # Cap the frame rate clock.tick(10) pygame.quit() if __name__ == "__main__": main()