Both are useful in different situations, so pick whichever you need. The main difference between methods 1 and 2, is that 1 runs the code when you press the key, and method 2 runs the code while the key is pressed. The get_key() function uses a try, except statement, because if you havent pressed the key yet, it will give an error when you try to get it from the dictionary. What this allows you to do is run a piece of code repeatedly while the key is held down. An uppercase 'A' is reported as 65 by all events. For example, a lowercase 'a' will be reported as 65 by keydown and keyup, but as 97 by keypress. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. This is useful because it allows to to track holding down a key. The keyup event is fired when a key is released. What it does is keep track of which keys are actually being pressed, and not just when they got presses. left False while k: keys () for event in (): if event.type pygame.QUIT: k False if event.type pygame.KEYDOWN: if event.key pygame.KLEFT: left True if event.type pygame.KEYUP: if event.key pygame.KLEFT: left False (10) if keyspygame.KRIGHT and x < 460: x x. The second method for detecting keypresses is almost the same, but you can use it in more situations. # do something when the spacebar is pressed What the code will do is detect a keypress event and it will see if it is the correct key, and if so, then it activates the code. The first way you can detect keypresses is to activate when the key is pressed down. I’ve used pygame before, and there are a few ways you can detect keypresses.
0 Comments
Leave a Reply. |