简体   繁体   English

pygame 按键按下时继续循环

[英]pygame continue loop when key pressed

I'm trying to make my timer keep adding when we click e but Im not sure why I have to hold e for the timer to keep adding up my timer name is (tons) is there a way I could keep adding my timer when we click e instead of stopping when we are not clicking e anymore I tried the 'if event.type == pygame.K_e' but its the same thing I have to hold e我试图让我的计时器在我们单击 e 时继续添加,但我不知道为什么我必须按住 e 让计时器继续添加我的计时器名称是(吨)有没有一种方法可以在我们继续添加我的计时器时当我们不再单击 e 时,单击 e 而不是停止我尝试了“if event.type == pygame.K_e”,但我必须按住 e

        if keys[pygame.K_e]: # if we click e then it should keep adding tons
            tons += 1
            print(tons)

game loop V游戏循环 V

run = True
while run:
    # Making game run with fps
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    
# telling what to do when we say the word 'key'
    keys = pygame.key.get_pressed()

            
    if hit:
        if keys[pygame.K_e]: # if we click e then it should keep adding tons
            tons += 1
            print(tons)
            
        if tons > 10:
            playerman.direction = "att"
            if health2 > -21:
                health2 -= 0.3
            else:
                playerman.direction = "Idle"
                hit = False
                
            if tons > 30:
                tons = 0
                playerman.direction = "Idle"

but Im not sure why I have to hold e for the timer to keep adding up但我不知道为什么我必须按住 e 让计时器继续累加

Because that's how you coded it.因为这就是你编码它的方式。 Look at your code:看看你的代码:

 if keys[pygame.K_e]: # if we click e then it should keep adding tons
    tons += 1

tons gets incremented if and only if e is pressed.当且仅当按下e时, tons才会增加。

is there a way I could keep adding my timer when we click e instead of stopping when we are not clicking e anymore有没有一种方法可以在我们单击 e 时继续添加我的计时器,而不是在我们不再单击 e 时停止

Just set a flag instead, something like this:只需设置一个标志,如下所示:

pressed_e = False
run = True
while run:
    for event in pygame.event.get():
        ...
        if event.type == pygame.KEYDOWN and event.key == pygame.K_e:
            pressed_e = True

    if pressed_e: # if we click e then it should keep adding tons
        tons += 1
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM