Displaying random image from list every time button is clicked PyGame

Viewed 97

How I can display random image from list every time button is clicked in Pygame? I want it to work in a way that if user clicks the button, random image is displayed. If the user clicks the button again, the random image is replaced with new random image.

Here is a part of the code I have written already:

card_list = ["image1.png", "image2.png", "image3.png", "image4.png"]

random_card = random.choice(card_list)
card_img = pygame.image.load(random_card)
card_img = pygame.transform.scale(card_img, (200, 350))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if l_button.collidepoint(event.pos):
                    print("LOWER")
                    screen.blit(card_img, (100,100))
                    
                elif h_button.collidepoint(event.pos):
                    print("HIGHER")

    #lower button
    l_button = pygame.Rect(400, 350, 200, 100)
    pygame.draw.rect(screen, button_color, l_button)
    screen.blit(lower_text, (450, 380))

    #higher button
    h_button = pygame.Rect(400, 150, 200, 100)
    pygame.draw.rect(screen, button_color, h_button)
    screen.blit(higher_text, (450, 180))

Now it only displays the image once, if the button is clicked another time the image don't change. How can I fix that?

1 Answers

Everything that is drawn in the event loop is only visible for a single frame. If you want to draw the picture permanently, you need to draw it in the application loop. Init card_img with None. Draw the image in the application loop and choose a new image when the button is clicked:

card_list = ["image1.png", "image2.png", "image3.png", "image4.png"]
card_images = []
for filename in card_list:
    img = pygame.image.load(filename)
    card_images.append(pygame.transform.scale(img, (200, 350)))
card_img = None

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if l_button.collidepoint(event.pos):
                    print("LOWER")
                    card_img = random.choice(card_images)
                    
                elif h_button.collidepoint(event.pos):
                    print("HIGHER")

    if card_img != None:
        screen.blit(card_img, (100,100))

    #lower button
    l_button = pygame.Rect(400, 350, 200, 100)
    pygame.draw.rect(screen, button_color, l_button)
    screen.blit(lower_text, (450, 380))

    #higher button
    h_button = pygame.Rect(400, 150, 200, 100)
    pygame.draw.rect(screen, button_color, h_button)
    screen.blit(higher_text, (450, 180))
Related