給我一個python的貪吃蛇遊戲 這裡給你一個用 pygame 寫的簡單 Python 貪吃蛇遊戲 🐍 (先確保你有安裝 pygame:pip install pygame) import pygame import random # 初始化 pygame.init() # 視窗大小 WIDTH, HEIGHT = 600, 400 BLOCK_SIZE = 20 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("貪吃蛇") clock = pygame.time.Clock() font = pygame.font.SysFont(None, 35) # 顏色 WHITE = (255, 255, 255) GREEN = (0, 200, 0) RED = (200, 0, 0) BLACK = (0, 0, 0) def draw_snake(snake): for block in snake: pygame.draw.rect(screen, GREEN, (*block, BLOCK_SIZE, BLOCK_SIZE)) def show_score(score): text = font.render(f"Score: {score}", True, WHITE) screen.blit(text, [10, 10]) def game(): snake = [[100, 100]] direction = "RIGHT" food = [random.randrange(0, WIDTH, BLOCK_SIZE), random.randrange(0, HEIGHT, BLOCK_SIZE)] score = 0 running = True while running: screen.fill(BLACK) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and direction != "DOWN": direction = "UP" elif event.key == pygame.K_DOWN and direction != "UP": direction = "DOWN" elif event.key == pygame.K_LEFT and direction != "RIGHT": direction = "LEFT" elif event.key == pygame.K_RIGHT and direction != "LEFT": direction = "RIGHT" # 移動蛇 head = snake[0].copy() if direction == "UP": head[1] -= BLOCK_SIZE elif direction == "DOWN": head[1] += BLOCK_SIZE elif direction == "LEFT": head[0] -= BLOCK_SIZE elif direction == "RIGHT": head[0] += BLOCK_SIZE # 撞牆 if head[0] < 0 or head[0] >= WIDTH or head[1] < 0 or head[1] >= HEIGHT: running = False # 撞自己 if head in snake: running = False snake.insert(0, head) # 吃食物 if head == food: food = [random.randrange(0, WIDTH, BLOCK_SIZE), random.randrange(0, HEIGHT, BLOCK_SIZE)] score += 1 else: snake.pop() # 畫食物 pygame.draw.rect(screen, RED, (*food, BLOCK_SIZE, BLOCK_SIZE)) draw_snake(snake) show_score(score) pygame.display.update() clock.tick(10) pygame.quit() if __name__ == "__main__": game()