import pygame
import random
pygame.init()
# 设置游戏窗口的大小
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("Dodge the Obstacle")
# 设置游戏时钟
clock = pygame.time.Clock()
# 加载游戏素材
player_image = pygame.image.load("player.png").convert_alpha()
obstacle_image = pygame.image.load("obstacle.png").convert_alpha()
# 定义游戏变量
player_x = width // 2
player_y = height - 100
player_speed = 5
obstacle_x = random.randint(0, width - obstacle_image.get_width())
obstacle_y = 0
obstacle_speed = 3
score = 0
font = pygame.font.SysFont(None, 50)
# 游戏循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 处理玩家输入
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= player_speed
if keys[pygame.K_RIGHT] and player_x < width - player_image.get_width():
player_x += player_speed
# 更新游戏状态
obstacle_y += obstacle_speed
if obstacle_y > height:
obstacle_x = random.randint(0, width - obstacle_image.get_width())
obstacle_y = 0
score += 1
obstacle_speed += 0.1
# 处理游戏碰撞
player_rect = pygame.Rect(player_x, player_y, player_image.get_width(), player_image.get_height())
obstacle_rect = pygame.Rect(obstacle_x, obstacle_y, obstacle_image.get_width(), obstacle_image.get_height())
if player_rect.colliderect(obstacle_rect):
running = False
# 渲染游戏画面
screen.fill((255, 255, 255))
screen.blit(player_image, (player_x, player_y))
screen.blit(obstacle_image, (obstacle_x, obstacle_y))
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 游戏结束
pygame.quit()
注意:在运行这段代码之前,需要确保已经安装了 Pygame 并且准备好了用于游戏的素材图片。