1

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 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

4 Comments

thank you master!, i will re-edit my code like this,[but my code wasn't bad either:)]
@Django You can simplify one line. Change pygame.draw.rect(self.game.display, (color), pygame.Rect(rect)) to pygame.draw.rect(self.game.display, color, rect). Try to write many small classes instead of one large class (God-Object)
Actually I can't refactor the code like this, I already have a character class and required operations. i do this in the loop of the character class ,thanks for replying anyway
@Django Anyway, you can create a self.rect attribute. So you don't have to pass it to the methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.