AttributeError: у объекта «Настройки» нет атрибута «screen_width»?Как решить эту проблему? - PullRequest
0 голосов
/ 10 октября 2018

Проблема в том, что когда я строю этот код в возвышенном тексте;это дает мне вывод как AttributeError: у объекта 'Settings' нет атрибута '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'

Я с нетерпением жду, чтобы узнать, какую простую ошибку я не вижу.

Ответы [ 2 ]

0 голосов
/ 03 мая 2019

Это должен быть правильный код:

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 это требуется для указания того, к какому блоку кода принадлежит оператор.

0 голосов
/ 10 октября 2018

Ваш класс настроек не имеет screen_width, вы должны использовать ai.screen_width.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...