python全免费教程制作平台跳越游戏小白新手入门必看(二)

创建基础游戏框架

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()

将上述代码片段组合后,你将获得:

  • 可左右移动的角色(需添加移动代码)
  • 基础跳跃功能
  • 静态平台
  • 实时画面渲染
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值