[Python] 纯文本查看 复制代码 import pygame
import random
import sys
# 初始化 Pygame
pygame.init()
# 屏幕宽高和帧率
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 400
FPS = 60
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 创建游戏屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("跑酷游戏")
# 字体
font = pygame.font.Font(None, 36)
# 玩家类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = (100, SCREEN_HEIGHT - 75)
self.velocity = 0
self.is_jumping = False
def update(self):
# 重力作用
self.velocity += 1
if self.velocity > 10:
self.velocity = 10
self.rect.y += self.velocity
# 防止掉出地面
if self.rect.bottom > SCREEN_HEIGHT - 50:
self.rect.bottom = SCREEN_HEIGHT - 50
self.is_jumping = False
def jump(self):
if not self.is_jumping:
self.velocity = -15
self.is_jumping = True
# 障碍物类
class Obstacle(pygame.sprite.Sprite):
def __init__(self, x, y, width, height):
super().__init__()
self.image = pygame.Surface((width, height))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self):
self.rect.x -= 5
if self.rect.right < 0:
self.kill()
# 初始化玩家和障碍物组
player = Player()
all_sprites = pygame.sprite.Group()
all_sprites.add(player)
obstacles = pygame.sprite.Group()
# 生成障碍物事件
ADD_OBSTACLE = pygame.USEREVENT + 1
pygame.time.set_timer(ADD_OBSTACLE, 1500)
# 分数
score = 0
# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.jump()
if event.type == ADD_OBSTACLE:
obstacle = Obstacle(SCREEN_WIDTH, SCREEN_HEIGHT - 70, 50, 50)
all_sprites.add(obstacle)
obstacles.add(obstacle)
# 更新
all_sprites.update()
# 碰撞检测
if pygame.sprite.spritecollideany(player, obstacles):
running = False
# 绘制
screen.fill(WHITE)
all_sprites.draw(screen)
# 更新分数
score += 1
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(FPS)
# 游戏结束
pygame.quit()
sys.exit()
|