yszaxka 2023-06-14 22:12 采纳率: 100%
浏览 94
已结题

AttributeError: Game object has no attribute run 怎么办

python马里奥游戏

# 游戏主要入口
import pygame
from source import tools, setup
def main():
    game = tools.Game()
    game.run()
if __name__ == '__main__':
   main()
# 工具和游戏主控
import os

import pygame
import pygame
import random

class Game:
    def __init__(self):
        self.screen = pygame.display.get_surface()
        self.clock = pygame.time.Clock()

        def run(self):
            while True:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.display.quit()
                    elif event.type == pygame.KEYDOWN:
                        self.keys = pygame.key.get_pressed()
                    elif event.type == pygame.KEYUP:
                        self.keys = pygame.key.get_pressed()
                self.screen.fill((random.randint(0,255),random.randint(0,255),random.randint(0,255))) # 随机出一种颜色
                pygame.display.update()
                self.clock.tick(60)  # 每秒钟60帧

这两个代码分别是两个python file里面的,代码是正确的,但是会显示以下错误,我怎样都解决不了
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\fbyzb\PycharmProjects\SuperMario\main.py", line 14, in
main()
File "C:\Users\fbyzb\PycharmProjects\SuperMario\main.py", line 9, in main
game.run()
^^^^^^^^
AttributeError: 'Game' object has no attribute 'run'

Process finished with exit code 1

  • 写回答

2条回答 默认 最新

  • 失棉的羊 . 2023-06-15 01:14
    关注

    这段代码中出现了一个错误。错误信息是"AttributeError: Game object has no attribute run",意思是Game对象没有run属性。

    这个错误是因为在Game类中定义了一个run方法,但是该方法被放置在了init方法内部,导致无法访问到。要解决这个错误,需要将run方法移动到init方法的外部。

    修正后的代码如下:

    class Game:
        def __init__(self):
            self.screen = pygame.display.get_surface()
            self.clock = pygame.time.Clock()
    
        def run(self):
            while True:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.display.quit()
                    elif event.type == pygame.KEYDOWN:
                        self.keys = pygame.key.get_pressed()
                    elif event.type == pygame.KEYUP:
                        self.keys = pygame.key.get_pressed()
                self.screen.fill((random.randint(0,255),random.randint(0,255),random.randint(0,255))) # 随机出一种颜色
                pygame.display.update()
                self.clock.tick(60)  # 每秒钟60帧
    

    将run方法移动到init方法的外部后,再次运行代码应该就不会出现该错误了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 6月23日
  • 已采纳回答 6月15日
  • 创建了问题 6月14日