3

I'm learning OOP and I have a few questions. When the initiliazer is called, is the code automatically processed? Cause if that's the case, I don't understand why my game isn't drawing the rectangle i ask it to draw in the init part of the player class. I'm very new to OOP and as such I'm not sure of what I'm doing, to some extent. Here's my code:

import pygame

white = (255, 255, 255)
black = (0, 0, 0)

class Game():
    width = 800
    height = 600
    screen = pygame.display.set_mode((width, height))
    def __init__(self):
        pass
    def fill_screen(self, color):
        self.color = color
        self.screen.fill(self.color)

class Player(pygame.sprite.Sprite):
    lead_x = 800/2
    lead_y = 600/2
    velocity = 0.002
    block_size = 10
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])

    def move_player_x_left(self):
        self.lead_x += -self.velocity

    def move_player_x_right(self):
        self.lead_x += self.velocity

    def move_player_y_up(self):
        self.lead_y += -self.velocity

    def move_player_y_down(self):
        self.lead_y += self.velocity

game = Game()
player = Player()

exitGame = False
while not exitGame:
    game.fill_screen(white)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitGame = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                player.move_player_y_up()
            if event.key == pygame.K_s:
                player.move_player_y_down()
            if event.key == pygame.K_d:
                player.move_player_x_right()
            if event.key == pygame.K_a:
                player.move_player_x_left()
    pygame.display.update()
pygame.quit()
quit()
Lol Lol
  • 155
  • 1
  • 9

1 Answers1

2

You are constantly filling the screen with white in your mainloop. The Player class only draws on __init__. This means that the rect is drawn for a split second and then covered over by white.

Your assumption about the code in __init__ automatically being called is correct. These methods with double underscores are called by python in special cases, they are called magic methods. You can find a list of them here.

def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    # The rect drawing part was moved from here.
def update(self):
    # You were previously assigning this to a variable, this wasn't necessary.
    pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])

You will need to call the new update method in the mainloop after you fill the screen.

while True:
    game.fill_screen(white)
    player.update()
mustachioed
  • 533
  • 3
  • 18