2019-08-15 17:28:31

I'm trying to create a rapper for pygame's keyboard to make life easier when I do key logic. Here's my code:

import pygame, pygame.locals as pl
pygame.init()
pygame.display.set_mode((600, 600))
pygame.display.set_caption("Testing stuff.")
x = 0
y = 0
def main():
 while 1:
  keyloop()
  pygame.time.wait(2)

def keyloop():
 global x
 global y
 if key_pressed(pl.K_UP):
  y += 1
  print(y)
 elif key_pressed(pl.K_RIGHT):
  x += 1
  print(x)

def key_pressed(key):
 for event in pygame.event.get():
  if event.type == pygame.KEYDOWN and event.key == key: return True
 return False

main()

The issue here is, when you run this, only the up arrow works. I understand why this happens (I loop through the events and clear them when I check for the up arrow being pressed) but is there any way to fix this problem? It would be really nice if I can just do key_pressed() and key_down() which works beautifully because it's a list.
I can't use key_down for pressing keys because it triggers multiple times, and having a timer for each key doesn't seem like the right solution.
I also didn't include key_down because it's not used.

2019-08-15 17:51:37

Pygame works much, much better with event-based input, rather than polling. If you really want to use polling, you'd be better off keeping your own list of pressed/released keys and updating them every frame.
A single list could handle that, if you use ints with different values for pressed / down / up / released. I'd go with 1 bit for down/up, and one for the state in the previous frame, but whatever works.

看過來!
"If you want utopia but reality gives you Lovecraft, you don't give up, you carve your utopia out of the corpses of dead gods."
MaxAngor wrote:
    George... Don't do that.