Spaces:
Sleeping
Sleeping
| import pygame | |
| import random | |
| def snake_game(): | |
| pygame.init() | |
| # Screen dimensions | |
| width, height = 600, 400 | |
| screen = pygame.display.set_mode((width, height)) | |
| clock = pygame.time.Clock() | |
| # Colors | |
| white = (255, 255, 255) | |
| black = (0, 0, 0) | |
| red = (213, 50, 80) | |
| green = (0, 255, 0) | |
| # Snake attributes | |
| snake_block = 10 | |
| snake_speed = 15 | |
| # Initialize snake and food positions | |
| snake = [(100, 50)] | |
| food = (random.randrange(0, width, snake_block), random.randrange(0, height, snake_block)) | |
| direction = (0, 0) | |
| running = True | |
| while running: | |
| for event in pygame.event.get(): | |
| if event.type == pygame.QUIT: | |
| running = False | |
| if event.type == pygame.KEYDOWN: | |
| if event.key == pygame.K_UP: | |
| direction = (0, -snake_block) | |
| elif event.key == pygame.K_DOWN: | |
| direction = (0, snake_block) | |
| elif event.key == pygame.K_LEFT: | |
| direction = (-snake_block, 0) | |
| elif event.key == pygame.K_RIGHT: | |
| direction = (snake_block, 0) | |
| # Move snake | |
| head = (snake[0][0] + direction[0], snake[0][1] + direction[1]) | |
| snake.insert(0, head) | |
| if head == food: | |
| food = (random.randrange(0, width, snake_block), random.randrange(0, height, snake_block)) | |
| else: | |
| snake.pop() | |
| # Check for collisions | |
| if head[0] < 0 or head[1] < 0 or head[0] >= width or head[1] >= height or head in snake[1:]: | |
| running = False | |
| # Render screen | |
| screen.fill(black) | |
| for segment in snake: | |
| pygame.draw.rect(screen, green, [segment[0], segment[1], snake_block, snake_block]) | |
| pygame.draw.rect(screen, red, [food[0], food[1], snake_block, snake_block]) | |
| pygame.display.update() | |
| clock.tick(snake_speed) | |
| pygame.quit() | |