I would like to know if i can remove an image when button is clicked in pygame

Viewed 42

I am trying to remove the image when I click 1 key.

import pygame
import pygame.freetype
import random

# Intialise pygame
pygame.init()
pygame.font.init()

screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)  # Fullscreen

Cards

cards = (pygame.image.load('image/london.png'), pygame.image.load('image/america.png'))

def card():
    screen.blit(card_size[0], (100, 40))
    screen.blit(card_size[1], (330, 40))

Game loop

loop of the program starts here

running = True
while running:
    screen.fill((255, 194, 102))  # RGB
    for event in pygame.event.get(): # Event handler
        if event.type == pygame.QUIT:
            running = False

Here I have tried to remove item from the list but is didn't work.

    if event.type == pygame.KEYDOWN:
        if event.key == ord('1'):
            cards.remove()
        if event.key == ord('2'):
            print('gone')

card()
pygame.display.update()
1 Answers

Removing an image means not to draw the image. There are different solutions.


Solution 1:

Draw the images in a loop:

cards = [
    pygame.image.load('image/london.png'), 
    pygame.image.load('image/america.png')]
def card():
    for i in range(len(cards)):
        screen.blit(cards[i], (100 + i*230, 40))

pop an image when a key is pressed:

while running:
    # [...]

    for event in pygame.event.get():
        # [...]

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1 and len(cards) > 0:
                cards.pop(0)
            if event.key == pygame.K_2 and len(cards) > 1:
                cards.pop(1)

Solution 2:

Add a list that indicates if an image needs to be drawn:

cards_active = [True, True]
def card():
    for i in range(len(cards)):
        if cards_active[i]:
            screen.blit(cards[i], (100 + i*230, 40))

Toggle the state in the list when a key is pressed:

while running:
    # [...]

    for event in pygame.event.get():
        # [...]

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_1 and len(cards) > 0:
                cards_active[0] = not cards_active[0]
            if event.key == pygame.K_2 and len(cards) > 1:
                cards_active[1] = not cards_active[1]
Related