I have this error with pygame , when i try to run code from Python Crash Course (Exception has occurred: AttributeError )

Viewed 78

I am trying to make a project from the book Python Crash course. I made everything exactly as the code snippets from the book shows but i constantly get the following error :

Exception has occurred: AttributeError 'Settings' object has no attribute 'screenWidth' File "D:\Visual Studio Code projects\Sudoku game\window.py", line 12, in run_game (igSettings.screenWidth, igSettings.screenHeight)) File "D:\Visual Studio Code projects\Sudoku game\window.py", line 28, in run_game()

This is the code for my Sudoku file:

import sys
import pygame

from settings import Settings

def run_game():
    pygame.init()

    igSettings = Settings()

    screen = pygame.display.set_mode(
        (igSettings.screenWidth, igSettings.screenHeight))
    pygame.display.set_caption("Sudoku")

    while True:

        screen.fill(igSettings.bgColor) 

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0) 



        pygame.display.flip()


run_game()

And this is the code from my Settings file:

class Settings():

    def set(self):

        self.screenWidth = 1200
        self.screenHeight = 800   
        self.bgColor = (0.235,0)

I coulden't find a solution online

2 Answers

You need to call set on the object igSettings to set attributes of the object.

igSettings = Settings()
igSettings.set()

Or simply make them class attributes, you access them directly now.

class Settings:
    screenWidth = 1200
    screenHeight = 800
    bgColor = (0.235,0)

Now you don't even need to call set. You can look more about how classes work in python.

Instead of the method set, create a constructor (__init__), in the class Settings:

class Settings():

    def __init__(self):

        self.screenWidth = 1200
        self.screenHeight = 800   
        self.bgColor = (0, 235, 0)

Note, you cannot choose the name of the constructor. The name has to be exactly __init__. See Class Objects.
The constructor is automatically invoked, when an instance of the class is constructed:

igSettings = Settings()

Further more there is a typo, when the attribute `` is declared (. -> ,):

self.bgColor = (0.235,0)

self.bgColor = (0,235,0)
Related