import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 200
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置游戏标题
pygame.display.set_caption('Google Dino')
# 加载跳跃音效
jump_sound = pygame.mixer.Sound('jump.wav')
# 加载障碍物图像
cactus_img = pygame.image.load('cactus.png')
bird_img = pygame.image.load('bird.png')
# 定义 Dino 类
class Dino(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.image.load('dino.png')
self.rect = self.image.get_rect()
self.rect.x = 50
self.rect.y = SCREEN_HEIGHT - 70
self.jump_speed = 10
self.gravity = 1
def jump(self):
self.rect.y -= self.jump_speed
def update(self):
self.rect.y += self.gravity
if self.rect.y >= SCREEN_HEIGHT - 70:
self.rect.y = SCREEN_HEIGHT - 70
# 定义障碍物类
class Obstacle(pygame.sprite.Sprite):
def __init__(self, img):
super().__init__()
self.image = img
self.rect = self.image.get_rect()
self.rect.x = SCREEN_WIDTH
self.rect.y = SCREEN_HEIGHT - 90
def update(self):
self.rect.x -= 5
# 创建 Dino 对象
dino = Dino()
# 创建障碍物组
obstacle_group = pygame.sprite.Group()
# 设置游戏帧率
clock = pygame.time.Clock()
# 初始化分数和难度
score = 0
difficulty = 1
# 游戏主循环
running = True
while running:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and dino.rect.y == SCREEN_HEIGHT - 70:
dino.jump()
jump_sound.play()
# 更新 Dino 对象
dino.update()
# 创建障碍物
if random.randint(1, 100) <= difficulty:
obstacle_type = random.randint(1, 2)
if obstacle_type == 1:
obstacle = Obstacle(cactus_img)
else:
obstacle = Obstacle(bird_img)
obstacle_group.add(obstacle)
# 更新障碍物
for obstacle in obstacle_group:
obstacle.update()
if obstacle.rect.x <= -50:
obstacle_group.remove(obstacle)
score += 1
if score % 10 == 0:
difficulty += 1
# 检测碰撞
if pygame.sprite.spritecollide(dino, obstacle_group, False):
running = False
# 绘制游戏画面
screen.fill(WHITE)
pygame.draw.rect(screen, BLACK, [0, SCREEN_HEIGHT - 70, SCREEN_WIDTH, 2])
screen.blit(dino.image, dino.rect)
obstacle_group.draw(screen)
# 绘制分数
font = pygame.font.Font(None, 36)
text = font.render('Score: ' + str(score), True, RED)
screen.blit(text, [SCREEN_WIDTH - 120, 10])
# 更新游戏画面
pygame.display.update()
# 控制游戏帧率
clock.tick(30)
# 结束 Pygame
pygame.quit()
请注意,在运行此游戏之前,您需要准备一些图像和音频文件,并将其命名为 dino.png
、cactus.png
、bird.png
和 jump.wav
。