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

如何修复Game对象无run_game_loop属性的AttributeError问题

解决AttributeError: 'Game' object has no attribute 'run_game_loop'问题

报错信息

Traceback (most recent call last):
  File "c:\Users\james\OneDrive\Desktop\crossy rpg game\main.py", line 7, in <module>
    game.run_game_loop()
    ^^^^^^^^^^^^^^^^^^
AttributeError: 'Game' object has no attribute 'run_game_loop'
PS C:\Users\james\OneDrive\Desktop\crossy rpg game>

问题原因

你的game.py里,draw_objects和run_game_loop两个方法没有缩进,它们不属于Game类的成员方法,而是类外部的独立函数。所以当你创建Game实例后调用run_game_loop()时,Python找不到这个属性。

修复步骤

把draw_objects和run_game_loop方法缩进,放到Game类的内部,和__init__方法保持同级缩进(通常为4个空格)。

修复后的game.py代码:

import pygame
class Game:
    def __init__(self):
        self.width = 1850
        self.height = 1000
        self.white_color = (255, 255, 255)
        self.red_color = (255,0,0)
        self.green_color = (0,255,0)
        self.blue_color = (0,0,255)
        self.game_window = pygame.display.set_mode((self.width,self.height))
        self.clock = pygame.time.Clock()
        background_image = pygame.image.load('assets/background.png')
        self.background = pygame.transform.scale(background_image, (self.width,self.height))
        tresure_image = pygame.image.load('assets/tresure.jpg')
        self.tresure_image = pygame.transform.scale(tresure_image, (100,100))  
    def draw_objects(self):
        self.game_window.fill(self.white_color)
        self.game_window.blit(self.background, (0,0))
        self.game_window.blit(self.tresure_image, (900,50))
        pygame.display.update()
    def run_game_loop(self):
        while True:
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    return
            self.draw_objects()
            self.clock.tick(60)

验证

修改后重新运行main.py,即可正常启动游戏循环,不会再出现属性错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 16:05:01