按下一个键时,将变量仅增加一个

时间:2019-06-21 09:41:27

标签: python pygame

我有一个可变状态计数器,我想在按下键a时将其减1,而在按下d键时将其加1。

我想出了一个启发:按下一个键时仅增加一个,但是我的代码无法按预期工作,当我将was_pressed变量重置为false时,状态计数器开始增加自己。

running = True
state_counter = 0
number_of_states = 0
was_pressed = False

import pygame

while running:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
        # The user closed the window or pressed escape
        running = False

        if event.type == KEYDOWN and event.key==K_a:
            if not was_pressed:
                state_counter -= 1
                print("state_counter %d times"%state_counter)
                was_pressed = True
            else:
                was_pressed = False

        elif event.type == KEYDOWN and event.key == K_d:
            if not was_pressed:
                state_counter += 1
                print("state_counter %d times"%state_counter)
                was_pressed = True
            else:
                was_pressed = False
pygame.quit()
print('Done!, state counter is: ', state_counter)

问题是我需要变量同时增加和减少(与所提到的问题有所不同),当然我需要每次按下键时都要更改变量(可能是前一种情况)问题,但我无法实现。)我也不能time.sleep(),因为我不想让程序进入睡眠状态。

任何帮助表示感谢,非常感谢。

2 个答案:

答案 0 :(得分:1)

KEYDOWN事件仅在按下键时发生一次。按住键时不会连续出现。因此,不需要was_pressed状态:

while running:
    for event in pygame.event.get():
        if event.type == QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            # The user closed the window or pressed escape
            running = False

        if event.type == KEYDOWN and event.key==K_a:
            state_counter -= 1
            print("state_counter %d times"%state_counter)

        elif event.type == KEYDOWN and event.key == K_d:
            state_counter += 1
            print("state_counter %d times"%state_counter)

答案 1 :(得分:1)

import pyautogui
import pygame
Number_of_Presses = 0
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
       if event.key == pygame.K_a:
            Number_of_Presses -= 1
            print (Number_of_Presses)
    if event.type == pygame.KEYDOWN:
       if event.key == pygame.K_d:
            Number_of_Presses += 1
            print (Number_of_Presses)