如何在Pygame中设置延迟/冷却时间?

时间:2019-08-10 06:09:13

标签: python pygame timedelay

我正在为一个学校项目制作游戏,它正在复制任天堂的《 Punch-Out》!游戏(拳击游戏)。

我使用变量leftright来确定程序使用的图像,例如left = True表示我使用左道奇图像,right = True表示我使用右道奇图像。当两个变量均为False时,它将使用站立或“空闲”图像。

到目前为止,我可以使角色向左或向右闪避,但是我无法让他们回到中立位置并在按下按钮后将图像变回直立位置。

我尝试将py.time.delay()放在我想要延迟的点之间,但到目前为止,它没有用。

这是我的代码:

import pygame as py

py.init()
window = py.display.set_mode((1000,600))

#Variables
x = 350
y = 250
height = 20
width =5
left = False
right = False

normIdle = py.image.load('p1idle.png')

dodgeLeft = py.image.load('p1DodgeLeft.png')

dodgeRight = py.image.load('p1DodgeRight.png')

#Dodging/ Image changing
def redrawgamewindow():
    if left:
        window.blit(dodgeLeft, (x,y))

    elif right:
        window.blit(dodgeRight, (x,y))
    else:
        window.blit(normIdle, (x,y))

    py.display.update()

#Main Loop
run = True
while run:
    #py.time.delay(300)

    for event in py.event.get():
        if event.type == py.QUIT:
            run = False

    keys = py.key.get_pressed()
    if keys[py.K_LEFT]:
        left = True
        right = False
        x -= 20
        py.time.delay(300)
        left = False
        right = False
        x += 20

    if keys[py.K_RIGHT]:
        left = False
        right = True
        x += 20
        py.time.delay(300)
        left = False
        right = False
        x -= 20

    redrawgamewindow()

    window.fill((0,0,0))
py.quit()

我希望角色能够躲避并停留几毫秒,然后自动回到站立图像中的原始位置。

1 个答案:

答案 0 :(得分:0)

我能够通过在主循环之前进行一些小的修改来使代码工作:

DispatchQueue.main.async {
    tableView.reloadData()
}

我删除了x + = / x-=命令,因为它们仅在发送延迟之前和之后才更改。我可以看到一旦您的游戏变得更加复杂,将可以使用它们,但是对于这个问题,它们还没有用。

此外,作为次要样式,要摆脱一个变量,您还可以使用# first, before the main loop draw the game window with Idle. This didn't show up before because you were going into the loop and redrawing idle. But now that we check to see if you are redrawing idle, it is probably a good idea to initialize things with redrawgamewindow(). redrawgamewindow() #Main Loop run = True while run: #py.time.delay(300) for event in py.event.get(): if event.type == py.QUIT: run = False # this is a variable to see if the user did something that would change the graphics redraw_my_char = False keys = py.key.get_pressed() if keys[py.K_LEFT]: left = True right = False redraw_my_char = True #note that this does not prevent button mashing e.g. right and left at once. You if keys[py.K_RIGHT]: left = False right = True redraw_my_char = True if redraw_my_char: # you could say if did Left or Right, but I assume you'll be implementing punching, so it would probably be easier just to track one variable, redraw_my_char # draw left or right redrawgamewindow() py.time.delay(300) left = False right = False # with left or right reset, draw again redrawgamewindow() window.fill((0,0,0)) py.quit()

相关问题