0

My code is:

keys = pygame.key.get_pressed()
  if keys[pygame.K_1]:
    if money >= worker_cost:
      money -= worker_cost
      workers += 1
      worker_cost = round(worker_cost*1.1, 2)

So I am trying to make a game in pygame, but when I put this in to detect when the user wants to buy something, it won't detect that I pressed anything. I have tried putting print commands inside the if loop to see if the loop starts, but it doesn't. Any tips would be appreciated

Cole
  • 1
  • there is no loop in your code, have you tried checking if it registers the press at all (put `print` in the `if keys[pygame.K_1]:` block (outer one), maybe the second condition is not met?)? do you call `pygame.event.get()` anywhere in the main loop? it has to be called – Matiiss Nov 14 '21 at 17:58

1 Answers1

0

Use the keyboard events instead of pygame.key.get_pressed().

pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a key and get continuous movement.

The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action:

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

        if event.type == pg.KEYDOWN:
            if event.key == pg.K_1:

                # do action
                if money >= worker_cost:
                    money -= worker_cost
                    workers += 1
                    worker_cost = round(worker_cost*1.1, 2) 

    # [...]
Rabbid76
  • 202,892
  • 27
  • 131
  • 174