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

Pygame射击游戏报错:TypeError: 参数1必须是pygame.surface.Surface而非None

Pygame太空射击游戏发射激光时崩溃:TypeError: argument 1 must be pygame.surface.Surface, not None

问题现象

运行基于Pygame开发的太空射击游戏,按下空格键发射激光时游戏直接崩溃,抛出错误:

TypeError: argument 1 must be pygame.surface.Surface, not None

错误追踪指向Laser类初始化时调用pygame.mask.from_surface()传入了None值。

问题根源

排查发现PlayerShip类存在变量名拼写错误:

  • 初始化时将激光图像赋值给了self.lazer_img(拼写为lazer)
  • 但shoot方法中引用的是self.laser_img(拼写为laser)
    这导致self.laser_img未被正确赋值,始终为None,传递给Laser类后触发错误。

修复方案

修正PlayerShip类中的变量名拼写,确保赋值和引用一致:

  1. 如果保留初始化时的self.lazer_img,则将shoot方法中的self.laser_img改为self.lazer_img
  2. 或者统一修正为self.laser_img,确保初始化和调用时变量名完全一致

示例修正代码:

class PlayerShip:
    def __init__(self):
        # 修正变量名为laser_img,和shoot方法保持一致
        self.laser_img = pygame.image.load("laser.png").convert_alpha()
    
    def shoot(self):
        # 现在引用的是正确赋值的self.laser_img
        laser = Laser(self.x, self.y, self.laser_img)
        self.lasers.append(laser)

内容的提问来源于stack exchange,提问作者İrem Cemre Özdemir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 07:43:11