貪吃蛇游戲
# 貪吃蛇游戲
import pygame, random
# 初始化游戲
pygame.init()
# 創(chuàng)建游戲窗口
screen = pygame.display.set_mode((800, 600))
# 設(shè)置游戲窗口標(biāo)題
pygame.display.set_caption("貪吃蛇游戲")
# 設(shè)置游戲背景顏色
screen.fill((0, 0, 0))
# 設(shè)置游戲速度
speed = 5
# 設(shè)置貪吃蛇顏色
snake_color = (255, 255, 255)
# 設(shè)置食物顏色
food_color = (255, 0, 0)
# 設(shè)置障礙物顏色
obstacle_color = (255, 255, 255)
# 設(shè)置游戲字體
font = pygame.font.Font("simhei.ttf", 24)
# 定義貪吃蛇的移動(dòng)方向
# 0 - 向上
# 1 - 向下
# 2 - 向左
# 3 - 向右
direction = 0
# 定義貪吃蛇的身體列表
snake_body = [[200, 200], [210, 200], [220, 200]]
# 定義障礙物列表
obstacles = []
# 定義游戲分?jǐn)?shù)
score = 0
# 定義游戲結(jié)束標(biāo)志
game_over = False
# 生成障礙物
for i in range(20):
? ? obstacles.append([random.randint(0, 800), random.randint(0, 600)])
# 生成食物
food = [random.randint(0, 800), random.randint(0, 600)]
# 游戲主循環(huán)
while not game_over:
? ? # 檢查事件
? ? for event in pygame.event.get():
? ? ? ? # 檢查是否退出游戲
? ? ? ? if event.type == pygame.QUIT:
? ? ? ? ? ? game_over = True
? ? ? ? # 檢查鍵盤事件
? ? ? ? if event.type == pygame.KEYDOWN:
? ? ? ? ? ? # 檢查是否按下上下左右鍵
? ? ? ? ? ? if event.key == pygame.K_UP and direction != 1:
? ? ? ? ? ? ? ? direction = 0
? ? ? ? ? ? elif event