How to set coordinates for sprites in group
Question:
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)
Answers:
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
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)
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