import pygame import random # Initialize pygame pygame.init() # Screen settings WIDTH, HEIGHT = 600, 400 BLOCK_SIZE = 20 # Snake and food block size screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Snake Game") # Colors WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) BLACK = (0, 0, 0) # Snake settings snake = [(100, 100), (80, 100), (60, 100)] # Initial snake position direction = (BLOCK_SIZE, 0) # Moving right initially # Food settings num_food_items = 1150 # Increased to 50 food items food_items = [] # Function to generate food def generate_food(): while True: #Added loop to prevent food spawning on the snake x = random.randint(0, (WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE y = random.randint(0, (HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE if (x,y) not in snake: return (x, y) # Initially populate food items for _ in range(num_food_items): food_items.append(generate_food()) # Game loop settings clock = pygame.time.Clock() running = True def draw_snake(): for block in snake: pygame.draw.rect(screen, GREEN, (*block, BLOCK_SIZE, BLOCK_SIZE)) def draw_food(): for food in food_items: pygame.draw.rect(screen, RED, (*food, BLOCK_SIZE, BLOCK_SIZE)) while running: screen.fill(BLACK) # 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 and direction != (0, BLOCK_SIZE): direction = (0, -BLOCK_SIZE) elif event.key == pygame.K_DOWN and direction != (0, -BLOCK_SIZE): direction = (0, BLOCK_SIZE) elif event.key == pygame.K_LEFT and direction != (BLOCK_SIZE, 0): direction = (-BLOCK_SIZE, 0) elif event.key == pygame.K_RIGHT and direction != (-BLOCK_SIZE, 0): direction = (BLOCK_SIZE, 0) # Move snake new_head = (snake[0][0] + direction[0], snake[0][1] + direction[1]) # Check collisions if (new_head in snake or # Hitting itself new_head[0] < 0 or new_head[0] >= WIDTH or # Hitting walls new_head[1] < 0 or new_head[1] >= HEIGHT): running = False # Game Over # Add new head to snake snake.insert(0, new_head) # Check if snake eats food food_eaten = None for food in food_items: if new_head == food: food_eaten = food break if food_eaten: food_items.remove(food_eaten) # Remove the eaten food # Add a new food item food_items.append(generate_food()) else: snake.pop() # Remove last part if no food eaten draw_snake() draw_food() pygame.display.update() clock.tick(10) # Game speed pygame.quit()