Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

python - PyGame press two buttons at the same time

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...