You need to enable JavaScript to run this app. 为什么我每次尝试让Pygame精灵跳跃时程序都会崩溃?
优惠活动
大模型
产品
解决方案
定价
更多

为什么我每次尝试让Pygame精灵跳跃时程序都会崩溃?

问题原因及修复方案

核心崩溃原因

按下跳跃键后游戏直接关闭是因为调用jump()函数时触发了Python参数不匹配异常,程序直接终止:

  • 你定义的全局jump函数要求传入self参数,但你在按键检测逻辑中调用jump()时没有传入任何参数,运行到此处就会抛出TypeError直接结束程序。

其他逻辑错误

除了崩溃问题,你的跳跃逻辑本身也存在多处错误:

  • jump是玩家角色的行为,应该作为方法定义在Player类内部,不应该单独定义为全局函数
  • 跳跃需要修改角色的Y轴坐标(上下方向),你当前写的修改X轴坐标逻辑完全不对
  • 你写的self.rect.x =+ 50是错误语法,等价于self.rect.x = +50,不是你想的累加操作(正确累加语法是+=)
  • 你在jump函数内定义的局部变量x没有任何作用,不会修改角色的坐标属性

修正后完整代码

import pygame
import random
import time

GRAY = (192, 192, 192)
RED  = (255,   0,   0)

class Player(pygame.sprite.Sprite):
    def __init__(self, color, x, y, width, height):
        super().__init__()
        self.color = color
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        # 新增跳跃相关属性
        self.is_jump = False
        self.jump_speed = 10
        self.gravity = 0.5
        self.initial_y = y

    def update(self):
        self.rect.x += 5
        if self.rect.x >= 950:
            self.rect.x = 0
        # 处理跳跃物理逻辑
        if self.is_jump:
            self.rect.y -= self.jump_speed
            self.jump_speed -= self.gravity
            # 落到地面后重置跳跃状态
            if self.rect.y >= self.initial_y:
                self.rect.y = self.initial_y
                self.is_jump = False
                self.jump_speed = 10

    # 跳跃方法挪到类内部
    def jump(self):
        if not self.is_jump: # 防止空中二次跳跃
            self.is_jump = True


color_line = (0,0,0)

pygame.init()
screen = pygame.display.set_mode([1000, 500])

all_sprites_list = pygame.sprite.Group()

player_width  = 50
player_height = 50

player = Player(RED, 50, 413, 50, 50)
all_sprites_list.add(player)

clock = pygame.time.Clock()

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] or keys[pygame.K_w] or keys[pygame.K_SPACE]:
        player.jump() # 调用玩家实例的jump方法

    all_sprites_list.update()

    screen.fill((255, 255, 255))
    pygame.draw.line(screen, color_line, (0, 500), (1000, 500), 75)
    all_sprites_list.draw(screen)
    pygame.display.flip()

    clock.tick(30)
    
pygame.quit()

内容的提问来源于stack exchange,提问作者Pixeled

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 19:45:02