How to efficiently hold a key in Pygame?

前端 未结 7 1694
谎友^
谎友^ 2020-12-11 07:10

I\'ve found two related questions:

  • Pygame hold key down causes an infinite loop
  • pygame - on hold button down

But I want to be specific. H

相关标签:
7条回答
  • 2020-12-11 07:44

    Don't mix up event.get() and key.get_pressed().


    If you press or release a key, and event is put into the event queue, which you query with event.get(). Do this if you're actually interested if a key was pressed down physically or released (these are the actual keyboard events. Note that KEYDOWN get's added multiple time to the queue depending on the key-repeat settings).

    Also, there's no need to query the state of all keys while handling a KEYDOWN event, since you already know which key is pressed down by checking event.key


    If you're interested in if a key is hold down (and ignoring the key-repeat, which you probably want), then you should simply use key.get_pressed(). Using a bunch of flags is just unnecessary and will clutter up your code.

    So your code could simplified to:

    while not done: 
        keys = key.get_pressed() 
        if keys[K_DOWN]: 
            print "DOWN" 
        for e in event.get(): 
            pass # proceed other events. 
                 # always call event.get() or event.poll() in the main loop
    
    0 讨论(0)
提交回复
热议问题