import pygame import random # 初始化 pygame pygame.init() # 色彩定義 WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLACK = (0, 0, 0) # 螢幕大小 SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 # 蛇和食物大小 BLOCK_SIZE = 20 # 設定螢幕 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('貪食蛇遊戲') clock = pygame.time.Clock() font = pygame.font.SysFont(None, 25) def draw_snake(snake_list): for x in snake_list: pygame.draw.rect(screen, GREEN, [x[0], x[1], BLOCK_SIZE, BLOCK_SIZE]) def message(msg, color): mesg = font.render(msg, True, color) screen.blit(mesg, [SCREEN_WIDTH/6, SCREEN_HEIGHT/3]) def gameLoop(): game_over = False game_close = False x1 = SCREEN_WIDTH / 2 y1 = SCREEN_HEIGHT / 2 x1_change = 0 y1_change = 0 snake_list = [] snake_length = 1 foodx = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / 10.0) * 10.0 foody = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0 while not game_over: while game_close == True: screen.fill(WHITE) message("你輸了!按 Q 退出或 R 重新開始", RED) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_r: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -BLOCK_SIZE y1_change = 0 elif event.key == pygame.K_RIGHT: x1_change = BLOCK_SIZE y1_change = 0 elif event.key == pygame.K_UP: y1_change = -BLOCK_SIZE x1_change = 0 elif event.key == pygame.K_DOWN: y1_change = BLOCK_SIZE x1_change = 0 if x1 >= SCREEN_WIDTH or x1 < 0 or y1 >= SCREEN_HEIGHT or y1 < 0: game_close = True x1 += x1_change y1 += y1_change screen.fill(WHITE) pygame.draw.rect(screen, RED, [foodx, foody, BLOCK_SIZE, BLOCK_SIZE]) snake_head = [] snake_head.append(x1) snake_head.append(y1) snake_list.append(snake_head) if len(snake_list) > snake_length: del snake_list[0] for x in snake_list[:-1]: if x == snake_head: game_close = True draw_snake(snake_list) pygame.display.update() if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, SCREEN_WIDTH - BLOCK_SIZE) / 10.0) * 10.0 foody = round(random.randrange(0, SCREEN_HEIGHT - BLOCK_SIZE) / 10.0) * 10.0 snake_length += 1 clock.tick(15) pygame.quit() quit() gameLoop() python snake_game.py