Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set coordinates for sprites in group

I’m working in a card game in pygame the question is how can i set the coordinates for cards sprites in the group to let the draw function draws each 13 cards in different row like Heart cards in row one and diamond cards in row two ….
I’ve done the first row and stuck in finding the correct math formula to do that

def get_cards_row_number(screen):
    c = Card(screen, card_type['Diamond'], card_value['7'])
    card_width = c.rect.width
    card_heigt = c.rect.height
    screen_w = screen.get_rect().width
    screen_h = screen.get_rect().height
    available_space_x = screen_w-card_width
    number_cards = int(available_space_x/(card_width))
    return number_cards


def draw_hand(screen, cards):
    # Draw a player cards.
    # cards param is a sprite Group
    c = Card(screen, card_type['Diamond'], card_value['7'])
    card_width = c.rect.width
    card_heigt = c.rect.height
    for t in card_type:
        for v in card_value:
            c = Card(screen, t, v)
            cards.add(c)

    j = card_width

    for i, c in enumerate(cards):
        c.rect.x = j
        j += card_width+5 # plus 5 to put some space between each card

    cards.draw(screen)

image of game screen

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to define the cards per row (e.g. 13) and calculate the row and column using the // (floor division) operator and % (modulo) operator (the modulo operator computes the remainder of an integral division).

cards_per_row = 13

for i, c in enumerate(cards):
    row = i // cards_per_row 
    column = i % cards_per_row  

    c.rect.x = 10 + (card_width + 5) * column
    c.rect.y = 10 + (card_heigt + 5) * row 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading