Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
AttributeError
#1
I am getting an error in my code that I am just stumped on.
Here is the code for the main file:
import sys

import pygame

from settings import Settings

class AlienInvasion:
    """Overall class to manage game assets and behavior"""

    def __init__(self):
        """Initialize the game, and create game resources"""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        # Set the background color
        self.bg_color = (230, 230, 230)

        

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            # 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()

            #Redraw the screen during each pass through the loop
            self.screen.fill(self.settings.bg_color)

if __name__ == '__main__':
    # Make a game instance, and run the game
    ai = AlienInvasion()
    ai.run_game()
And here is the code from the settings class I was trying to import:
class Settings:
    """A class to store all settings for alien invasion"""

    def __init__(self):
        """Initialize the game's settings"""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color(230, 230, 230)
The error I get is
AttributeError: 'Settings' object has no attribute 'bg_color'
I don't understand why I am getting this error because i made the attribute self.bg_color in the Settings class.
If anyone could help with the code or explain to me why I am getting this error I would appreciate it.
Thanks!
Reply
#2
Maybe you need to add an argument to your init?

__init__(self, arg1, ...)
Reply
#3
The error is in Settings. Your settings class tries to call a method that isn't defined, at least not in the code you posted.
    def __init__(self):
        """Initialize the game's settings"""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color(230, 230, 230)  # Where is this method defined?
Maybe you meant to do this?
self.bg_color = (230, 230, 230)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020