[Python] How to pass a screen as a parameter in python

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I've been writing some code for moving cards around and putting them in decks, hopefully so that soon I can start working on programming an actual card game. I have 2 classes so far, Card and Deck, and they each have a method called Render whose job is, when called, to draw the card on the screen.

    This is how I initialized the screen:

    screen = pygame.display.set_mode((1280, 720))


    This is how the Render method is coded (it's virtually identical for both classes):

    def Render(self):

    pygame.draw.rect(screen, self.color, self.rect_obj)


    Here's an example of how I'm calling it:

    for deck in decks:
    deck.Render()

    for card in active_cards:
    card.Render()


    This code works just fine. But I want to move those classes into a different file to clean up the main file, and in order to do this I need to be able to pass the screen into this method somehow since it obviously isn't defined in the other file. I'd prefer to do this rather than just hard-coding the render into the main loop itself. Here's the version of the code that I attempted, but it didn't work:

    Render method defined in separate file:

    def Render(self, screen):

    pygame.draw.rect(screen, self.color, self.rect_obj)


    Example call (after importing the other file):

    for deck in decks:
    deck.Render(screen)

    for card in active_cards:
    card.Render(screen)


    This code doesn't work. The window simply starts up, freezes, and then crashes. I don't get an actual error in the console. What's going on? What's the best way to accomplish what I'm trying to accomplish?

    Continue reading...

Compartilhe esta Página