PyGame press two buttons at the same time

人走茶凉 提交于 2021-02-13 17:40:57

问题


I wrote this:

import pygame

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            print "A"
        if event.key == pygame.K_RIGHT:
            print "B"
        if event.key == pygame.K_LEFT:
            print "C"

Why can't I press two buttons at the same time?


回答1:


The keyboard events (e.g. pygame.KEYDOWN) occure only once when a button is pressed.
Use pygame.key.get_pressed() to continuously evaluate the states of the buttons. e.g.:

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

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        print "A"
    if keys[pygame.K_RIGHT]:
        print "B"
    if keys[pygame.K_LEFT]:
        print "C"

Or if you would rather get a list:

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

    keys = pygame.key.get_pressed()
    if any(keys):
        kmap = {pygame.K_UP : "A", pygame.K_RIGHT : "B", pygame.K_LEFT : "C"}
        sl = [kmap[key] for key in kmap if keys[key]]
        print sl



回答2:


Try this:

import pygame

finish = False
while not finish:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            finish = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                print "A"
            if event.key == pygame.K_RIGHT:
                print "B"
            if event.key == pygame.K_LEFT:
                print "C"

In your version you're iterating over pygame.event.get() and you evaluate only the last event in the for loop (apart from the quit logic), meaning you only evaluate the last keypress. Move the code into the loop and you can evaluate all the events.

If you want to detect multiple keypresses then use pygame.key.get_pressed()

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

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        print("C")    
    if keys[pygame.K_RIGHT]:
        print("B")
    if keys[pygame.K_UP]:
        print("A")


来源:https://stackoverflow.com/questions/59181962/pygame-press-two-buttons-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!