1

I keep getting this error. Here's the full traceback.

Traceback (most recent call last): File "C:/Users/Luc/PycharmProjects/game_practice/game.py", line 23, in <module> run_game() File "C:/Users/Luc/PycharmProjects/game_practice/game.py", line 13, in run_game player = Player(ai_settings, screen) File "C:\Users\Luc\PycharmProjects\game_practice\player.py", line 8, in __init__ self.rect.centerx = screen.rect.left AttributeError: 'pygame.Surface' object has no attribute 'rect' 

Here's the code for the "Player" file that's having an issue:

class Player: def __init__(self, ai_settings, screen): self.screen = screen self.screen_rect = screen.get_rect() self.rect = pygame.Rect((0, 0), (ai_settings.player_width, ai_settings.player_height)) self.rect.centerx = screen.rect.left self.rect.centery = screen.rect.ai_settings.screen_height / 2 self.color = ai_settings.player_color def draw_player(self): pygame.draw.rect(self.screen, self.color, self.rect) 

When I comment these two lines:

self.rect.centerx = screen.rect.left self.rect.centery = screen.rect.ai_settings.screen_height / 2 

The program runs with the rectangle initialized at (0,0) like its supposed to, so I am not really sure why the object has an attribute error when I include the other lines.

0

1 Answer 1

2

The screen is a pygame.Surface which has no rect attribute, but you can get a rect with the size of the surface by calling screen.get_rect() what you already do in this line:

self.screen_rect = screen.get_rect() 

Now you just have to use your self.screen_rect instead of screen.rect and your code should work.

# To place the player at the midleft. self.rect.midleft = self.screen_rect.midleft 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.