Python, correct way to pass variables between functions

Viewed 66

I'm trying to make a game in python using the pygame module.

def draw_character(self, color, box):
    rect = pygame.Rect(box)
    pygame.draw.rect(self.game.display, (color), pygame.Rect(rect))
    return rect

and in the draw_character function preserves the collision shape of the character

move function:

def move(self, rect):
   if rect.bottom >= self.game.DISPLAY_H:
        print("work")

and finally I call the function like this

self.move(self.draw_character((221,171,177), (self.f1, self.f2, 60, 60)))

Is there another way I can call the rect variable or am I already doing this correctly

1 Answers

Add a Character class and make the rectangle (rect) and the color an attribute of the class:

class Character:
    def __init__(rect, color, game):
        self.rect = rect
        self.color = color
        self.game = game

    def move(self):
        if self.rect.bottom >= self.game.DISPLAY_H:
            print("work")
   
    def draw(self):
        pygame.draw.rect(self.game.display, self.color, self.rect)

Create an instance of the class Character. Move and draw the character in the application loop:

character = Character((221,171,177), (self.f1, self.f2, 60, 60))

while True:

    # [...]

    character.move()
    character.draw()
Related