1
votes

I am currently working on a game where I wish to give the player an option of four characters to play. Here is my current code to do this:

running = 1
charactersChoice = ['char.png', 'char2.png', 'char3.png', 'char4.png']
choice = ''

while choice == '':
    screen.fill((47, 79, 79))
    screen.blit(pygame.image.load(charactersChoice[0]), (100,100))
    screen.blit(pygame.image.load(charactersChoice[1]), (700,100))
    screen.blit(pygame.image.load(charactersChoice[2]), (100,600))
    screen.blit(pygame.image.load(charactersChoice[3]), (700,600))

    keys = pygame.key.get_pressed()

    #Choose character

    if keys[pygame.K_1]:
        choice = charactersChoice[0]

    if keys[pygame.K_2]:
        choice = charactersChoice[1]

    if keys[pygame.K_3]:
        choice = charactersChoice[2]

    if keys[pygame.K_4]:
        choice = charactersChoice[3]


    pygame.display.flip()


while running == 1:
#rest of code for game here

As you can see, I blit the four different character profiles onto the screen and then check if the player has pressed the keys 1-4 to select their option. After selecting their option, it should move onto the main loop. Currently, if I press the key '1' while the code is running, it will not change the variable choice to what is intended.

Hope I have explained my problem well enough.

1
Try printing out the evaluation of the if statements. See if they are returning true like they should. Also, try printing out keys. - Micheal O'Dwyer
@ShadowMitia I have used pygame.key.get_pressed() again later on in the program but changing this has no impact on the issue. - Mattattack
Have you tried calling pygame.event.pump() before calling get_pressed()? - ShadowMitia
@MichealO'Dwyer printing out the if statements always returns '0' - Mattattack

1 Answers

3
votes

You have to call pygame.event.pump() at least once before using pygame.key.get_pressed() so that pygame can check what keys have been pressed.