问题在于,当我以崇高的文字构建此代码时,它给我输出为AttributeError:“设置”对象没有属性“ screen_width”。这是一个错误。我不知道该如何解决?尽管我已经在堆栈溢出中进行了搜索,但是这些答案并不能解决这个问题。有人可以通过这段代码并确定如何解决此问题来帮助我吗?
这是我的alieninvasion.py
代码:
import sys
import pygame
from settings import Settings
def run_game():
#Intiialize game and create a screen object
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
#start the main loop for the game
while True:
#redraw the screen during each pass though the loop
screen.fill(ai_settings.bg_color)
# Watch for Keyboard and mouse events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# make th emost recently drawn screen visible
pygame.display.flip()
run_game()
这是我的setting.py
代码
class Settings():
"""A class to store all the settings for Aliean Invasion """
def __init__(self):
"""Initialize the game settings"""
#screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
这是我得到的回报。
Traceback (most recent call last):
File "AlienInvasion.py", line 34, in <module>
run_game()
File "AlienInvasion.py", line 15, in run_game
(ai_settings.screen_width, ai_settings.screen_height))
AttributeError: 'Settings' object has no attribute 'screen_width'
我希望找出我看不到的简单错误。
答案 0 :(得分:1)
您的“设置”类别没有screen_width
,您应该使用ai.screen_width
。
答案 1 :(得分:0)
这应该是正确的代码:
alieninvasion.py
:
#!/usr/bin/env python
import sys
import pygame
from setting import Settings
def run_game():
# Initialize game and create a screen object
pygame.init()
ai_settings = Settings()
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Invasion")
# start the main loop for the game
while True:
# redraw the screen during each pass though the loop
screen.fill(ai_settings.bg_color)
# Watch for Keyboard and mouse events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# make the most recently drawn screen visible
pygame.display.flip()
run_game()
setting.py
:
class Settings:
"""A class to store all the settings for Alien Invasion """
def __init__(self):
"""Initialize the game settings"""
# screen settings
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 8
在alieninvasion.py
中,您缩进了pygame.display.flip()
。缩进相同数量的while True
语句将导致此行不可访问。我在代码中做了一些更改,以供参考以及一些错字。
在大多数其他编程语言中,缩进仅用于帮助使代码看起来更漂亮。但是在Python中,需要指出语句属于哪个代码块。
答案 2 :(得分:0)
要解决( AttributeError:'Settings'对象没有属性'screen_width'),您必须在 类设置 中输入以下内容self.ai_screen_width = 1200,然后在您放置的 alieninvasion.py 中,screen = pygame.display.set_mode((ai_settings。ai_screen_width,ai_settings.ai_screen_height))
注意:对不起,我的英语不好意思。