Untitled
import pygame import sys import random import time # Initialize Pygame pygame.init() # Set up some constants WIDTH, HEIGHT = 800, 600 BLOCK_SIZE = 20 FPS = 10 # Set up some colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) # Set up the display screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Set up the font font = pygame.font.Font(None, 36) # Set up the clock clock = pygame.time.Clock() class SnakeGame: def __init__(self): self.snake = [(200, 200), (220, 200), (240, 200)] self.direction = 'RIGHT' self.apple = self.generate_apple() def generate_apple(self): while True: 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 self.snake: return (x, y) def draw_snake(self): for pos in self.snake: pygame.draw.rect(screen, GREEN, (pos[0], pos[1], BLOCK_SIZE, BLOCK_SIZE)) def draw_apple(self): pygame.draw.rect(screen, RED, (self.apple[0], self.apple[1], BLOCK_SIZE, BLOCK_SIZE)) def update_snake(self): head = self.snake[-1] if self.direction == 'RIGHT': new_head = (head[0] + BLOCK_SIZE, head[1]) elif self.direction == 'LEFT': new_head = (head[0] - BLOCK_SIZE, head[1]) elif self.direction == 'UP': new_head = (head[0], head[1] - BLOCK_SIZE) elif self.direction == 'DOWN': new_head = (head[0], head[1] + BLOCK_SIZE) self.snake.append(new_head) if self.snake[-1] == self.apple: self.apple = self.generate_apple() else: self.snake.pop(0) def check_collision(self): head = self.snake[-1] if (head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT or head in self.snake[:-1]): return True return False def play(self): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and self.direction != 'DOWN': self.direction = 'UP' elif event.key == pygame.K_DOWN and self.direction != 'UP': self.direction = 'DOWN' elif event.key == pygame.K_LEFT and self.direction != 'RIGHT': self.direction = 'LEFT' elif event.key == pygame.K_RIGHT and self.direction != 'LEFT': self.direction = 'RIGHT' screen.fill(BLACK) self.draw_snake() self.draw_apple() self.update_snake() if self.check_collision(): text = font.render("Game Over!", True, WHITE) screen.blit(text, (WIDTH // 2 - text.get_width() // 2, HEIGHT // 2 - text.get_height() // 2)) pygame.display.flip() time.sleep(2) break pygame.display.flip() clock.tick(FPS) if __name__ == "__main__": game = SnakeGame() game.play()
Leave a Comment