下面是一個簡單的Python貪吃蛇游戲的代碼示例:
import pygame
import random
# 游戲窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 蛇身尺寸
SNAKE_SIZE = 20
# 初始化pygame
pygame.init()
# 創建游戲窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("貪吃蛇游戲")
# 蛇頭初始位置
snake_x = WINDOW_WIDTH // 2
snake_y = WINDOW_HEIGHT // 2
# 蛇身初始長度
snake_length = 1
snake_body = [[snake_x, snake_y]]
# 食物初始位置
food_x = random.randint(0, (WINDOW_WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
food_y = random.randint(0, (WINDOW_HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
# 設置游戲時鐘
clock = pygame.time.Clock()
# 游戲結束標志
game_over = False
# 游戲循環
while not game_over:
# 處理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 獲取按鍵輸入
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
snake_y -= SNAKE_SIZE
elif keys[pygame.K_DOWN]:
snake_y += SNAKE_SIZE
elif keys[pygame.K_LEFT]:
snake_x -= SNAKE_SIZE
elif keys[pygame.K_RIGHT]:
snake_x += SNAKE_SIZE
# 判斷是否吃到食物
if snake_x == food_x and snake_y == food_y:
snake_length += 1
food_x = random.randint(0, (WINDOW_WIDTH - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
food_y = random.randint(0, (WINDOW_HEIGHT - SNAKE_SIZE) // SNAKE_SIZE) * SNAKE_SIZE
# 更新蛇身
snake_body.append([snake_x, snake_y])
if len(snake_body) > snake_length:
del snake_body[0]
# 判斷游戲是否結束
if snake_x < 0 or snake_x >= WINDOW_WIDTH or snake_y < 0 or snake_y >= WINDOW_HEIGHT or [snake_x, snake_y] in snake_body[:-1]:
game_over = True
# 渲染游戲界面
window.fill((0, 0, 0))
for body_part in snake_body:
pygame.draw.rect(window, (0, 255, 0), (body_part[0], body_part[1], SNAKE_SIZE, SNAKE_SIZE))
pygame.draw.rect(window, (255, 0, 0), (food_x, food_y, SNAKE_SIZE, SNAKE_SIZE))
pygame.display.update()
# 控制游戲更新頻率
clock.tick(10)
# 退出游戲
pygame.quit()
這只是一個簡單的貪吃蛇游戲代碼示例,你可以根據自己的需求進行修改和擴展。