如何修复这个游戏循环函数问题
我的问题是,当我运行我的代码时,它显示了这个错误:
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: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:import pygame
从游戏模块导入 Game
pygame.init()
game = Game()
game.run_game_loop()
pygame.quit()
quit()
我试过交换变量和其他方法,但要么没有效果,要么情况更糟。
1 个回答
-1
这里的问题是,draw_objects
和 run_game_loop
这两个函数的缩进不正确,导致 Python 解释器认为它们并不是 Game
类的一部分。
比如,在下面的代码中(取自 这里),
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self, x):
self.add(x)
self.add(x)
我们正确地缩进了 add
和 addtwice
方法。想了解更多关于 Python 中缩进的信息,可以查看 这里。
所以,解决你问题的方法就是正确缩进 draw_objects
和 run_game_loop
这两个函数。
补充:
我在这里给你部分解决方案,因为我的回答似乎有点让人困惑,
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)
注意到 draw_objects
函数现在每行都增加了 4 个空格吗?这个缩进告诉 Python 解释器,这个函数实际上是属于 Game
类的方法。对 run_game_loop
函数做同样的处理,你的问题就应该能解决了。我鼓励你试试这个方法,然后重新运行你的代码。