Select, move and deselect a card from Solitaire game pygame
Problem Description:
I want to select a card with the mouse (the card changes to another image of a card with orange edges), move it (or not) and later deselect the card clicking again, returning it to the original image of the card (without orange edges).
I made the two first steps, but I can’t find a way to deselect the card.
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
if event.type==pygame.MOUSEBUTTONDOWN:
if event.button==1 and mouse_rect.colliderect(card_rect):
card = pygame.image.load("1c2.png").convert_alpha()
card = pygame.transform.scale(card, (99, 100))
if event.button == 1 and not mouse_rect.colliderect(card_rect):
n = pygame.mouse.get_pos()
x = n[0]
y = n[1]
card_rect.centerx = x
card_rect.centery = y
if event.button==1 and mouse_rect.colliderect(card_rect) and card_rect.width==99:
card = pygame.image.load("1c.png").convert_alpha()
card = pygame.transform.scale(card, (100, 100))
Original image:1c.png
Image selected (with orange edges):1c2.png
I try to change a little the width of the card when you select it, and after using that in the last conditional that you can see above.
I also tried (in the last conditional too):
if event.button==1 and mouse_rect.colliderect(card_rect) and card==pygame.image.load("1c2.png").convert_alpha():
card = pygame.image.load("1c.png").convert_alpha()
card = pygame.transform.scale(card, (100, 100))
What can I do to fix it?
Thanks!
Wrong result: The card stays at the selected image (card with orange borders).
Solution – 1
Do not load the images in the application loop. Load the images before the application loop. Use a Boolean variable (card_selected
) to indicate if the map is selected. Invert the state when clicking on the card (card_selected = not card_selected
):
card_1 = pygame.image.load("1c.png").convert_alpha()
card_1 = pygame.transform.scale(card_1, (100, 100))
card_2 = pygame.image.load("1c2.png").convert_alpha()
card_2 = pygame.transform.scale(card_2, (100, 100))
card = card_1
card_selected = False
# [...]
run = True
while run:
for event in pygame.event.get():
if event.type==pygame.QUIT:
run = False
if event.type==pygame.MOUSEBUTTONDOWN:
if event.button == 1 and card_rect.collidepoint(event.pos):
card_selected = not card_selected
card = card_2 if card_selected else card_1
# [...]
pygame.quit()
sys.exit()
Do not forget to clear the display in every frame. The entire scene must be redrawn in each frame.