当按键时,pygame继续循环

2024-09-29 00:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

当我们点击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)

游戏循环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"

Tags: runeventiftypeitkeyspygame计时器
1条回答
网友
1楼 · 发布于 2024-09-29 00:11:57

but Im not sure why I have to hold e for the timer to keep adding up

因为你就是这样编码的。看看你的代码:

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

tons在且仅在按下e时递增

is there a way I could keep adding my timer when we click e instead of stopping when we are not clicking e anymore

只需设置一个标志,如下所示:

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
    ...

相关问题 更多 >