import pygame
import random
# 初始化 Pygame 库
pygame.init()
# 定义游戏窗口大小
WIDTH = 600
HEIGHT = 400
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# 设置游戏标题
pygame.display.set_caption("向前冲")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义小球类
class Ball(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((30, 30))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = 50
self.rect.y = HEIGHT // 2
self.speed = 1
def update(self):
# 移动小球
self.rect.x += self.speed
# 定义障碍物类
class Obstacle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50, random.randint(50, 200)))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = WIDTH
self.rect.y = HEIGHT - self.image.get_height()
def update(self):
# 移动障碍物
self.rect.x -= 5
# 定义宝石类
class Gem(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((20, 20))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = WIDTH
self.rect.y = random.randint(50, HEIGHT - 50)
def update(self):
# 移动宝石
self.rect.x -= 5
# 创建游戏精灵组
all_sprites = pygame.sprite.Group()
# 创建障碍物精灵组
obstacles = pygame.sprite.Group()
# 创建宝石精灵组
gems = pygame.sprite.Group()
# 创建小球
ball = Ball()
all_sprites.add(ball)
# 定义分数
score = 0
# 游戏主循环
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_UP]:
ball.rect.y -= ball.speed
elif keys[pygame.K_DOWN]:
ball.rect.y += ball.speed
# 每隔一段时间创建一个新的障碍物和宝石
if random.randint(0, 100) < 5:
obstacle = Obstacle()
obstacles.add(obstacle)
all_sprites.add(obstacle)
if random.randint(0, 100) < 10:
gem = Gem()
gems.add(gem)
all_sprites.add(gem)
# 更新游戏精灵
all_sprites.update()
# 检查小球是否碰到了障碍物
hits = pygame.sprite.spritecollide(ball, obstacles, False)
if hits:
running = False
# 检查小球是否收集到了宝石
gems_hits = pygame.sprite.spritecollide(ball, gems, True)
for gem in gems_hits:
score += 10
# 填充屏幕背景色
screen.fill(BLACK)
# 绘制分数
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), True, WHITE)
screen.blit(score_text, (10, 10))
# 绘制所有游戏精灵
all_sprites.draw(screen)
# 更新屏幕
pygame.display.flip()
# 限制游戏每秒钟的帧数
clock = pygame.time.Clock()
clock.tick(60)
#退出游戏
pygame.quit()