PyGame同时按下两个按钮

PyGame同时按下两个按钮

本文介绍了PyGame同时按下两个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这个:

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?

推荐答案

键盘事件(例如 pygame.KEYDOWN )仅在按下按钮时发生一次.
使用 pygame.key.get_pressed() 来不断评估按钮的状态.例如:

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

这篇关于PyGame同时按下两个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 19:00