You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Python Pygame游戏中精灵无法正常跳跃的代码问题

问题定位

  • 跳跃逻辑仅在按下空格的瞬间执行1次,跳跃作为逐帧动画需要在主循环内持续调用才能完成完整动作
  • 计算得到的跳跃高度完全没有同步到Player精灵的坐标属性,精灵位置不会发生变化
  • 窗口关闭QUIT事件的判断被写到了按键按下KEYDOWN的分支内,导致点击窗口叉号无法正常退出游戏
  • 未限制空中二次跳跃,多次按空格会导致跳跃逻辑异常
  • 可选优化:原代码引用的自定义字体不存在时会直接报错,可调整为默认字体避免启动失败

修复后可运行代码

from pygame.locals import *
import pygame
import os
import random

WIDTH = 800
HEIGHT = 600
FPS = 60
usr_y = 400

# 定义颜色
GREEN = (75, 0, 130)
BLUE = (255, 20, 147)

# 初始化游戏和窗口
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Mini-games by Latypov Vildan 10'a' Class")
clock = pygame.time.Clock()
# 取消注释下方代码自行替换icon路径
# icon = pygame.image.load('icon.png')
# pygame.display.set_icon(icon)


class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 40))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH - 360
        self.rect.centery = HEIGHT - 200

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -8
        if keystate[pygame.K_RIGHT]:
            self.speedx = 8
        self.rect.x += self.speedx
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0
        

all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)


def print_text(message, x, y, font_color = (0, 0, 0), font_type = None, font_size = 30):
    font_type = pygame.font.Font(font_type, font_size)
    text = font_type.render(message, True, font_color)
    screen.blit(text, (x, y))

jump = False
counter = 30

def make():
    global usr_y, counter, jump
    if counter >= -30:
        usr_y -= counter / 2.5
        counter -= 1
    else:
        counter = 30
        jump = False
        usr_y = 400 # 重置回初始地面高度,避免坐标偏移
    

# 游戏主循环
running = True
while running:
    clock.tick(FPS)
    # 事件处理
    for event in pygame.event.get(): 
        if event.type == QUIT:
            running = False
        if event.type == KEYDOWN:    
            if event.key == K_ESCAPE:
                running = False
            elif event.key == K_SPACE:
                if not jump: # 禁止空中二次跳跃,可删除实现多段跳
                    jump = True
    
    # 执行跳跃逻辑
    if jump:
        make()
    # 同步跳跃坐标到精灵
    player.rect.centery = usr_y

    # 更新精灵
    all_sprites.update()
    # 渲染
    screen.fill(BLUE)
    all_sprites.draw(screen)
    print_text('Hi', 250, 250)
    pygame.display.flip()

pygame.quit()

内容的提问来源于stack exchange,提问作者Вильдан Латыпов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 13:06:11