创建基础游戏框架
import pygame # 初始化游戏 pygame.init() # 设置窗口 screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("我的平台游戏") # 游戏主循环 running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # 填充背景色 screen.fill((0, 128, 255)) # 天空蓝 # 更新显示 pygame.display.flip() pygame.quit()
实现角色控制
class Player:
def __init__(self):
self.x = 100
self.y = 500
self.width = 40
self.height = 60
self.color = (255, 0, 0)
self.velocity_y = 0
self.gravity = 0.8
self.jump_power = -15
self.on_ground = True
def jump(self):
if self.on_ground:
self.velocity_y = self.jump_power
self.on_ground = False
def update(self):
# 应用重力
self.velocity_y += self.gravity
self.y += self.velocity_y
# 地面检测(简单版)
if self.y >= 540:
self.y = 540
self.velocity_y = 0
self.on_ground = True
def draw(self):
pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
添加平台(和人物位置一定要比较):
platforms = [
pygame.Rect(0, 540, 800, 40), # 地面
pygame.Rect(200, 400, 150, 20),
pygame.Rect(400, 300, 150, 20),
pygame.Rect(600, 200, 150, 20)
]
# 绘制平台
for platform in platforms:
pygame.draw.rect(screen, (139, 69, 19), platform)
输入用户处理:
# 在游戏循环中添加
keys = pygame.key.get_pressed()
player = Player()
if keys[pygame.K_SPACE]:
player.jump()
player.update()
将上述代码片段组合后,你将获得:
- 可左右移动的角色(需添加移动代码)
- 基础跳跃功能
- 静态平台
- 实时画面渲染