如何在pygame中为敌人的攻击增加冷却时间?

2024-10-03 23:25:13 发布

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

我已经尝试使用threading.timer来解决这个问题,但似乎无法让它为我想做的事情工作。没有错误消息。要么它甚至不会从玩家的生命值中减去,要么它会立即耗尽生命值,破坏整点,而time.sleep会冻结整个程序

这是我无法正常工作的代码

from threading import Timer
import pygame

playerhealth = ['<3', '<3', '<3', '<3', '<3'] # just a list of player health symbolized by hearts

running = True
while running:
    def removehealth():    
        playerhealth.__delitem__(-1) # deletes the last item in the list of hearts


    t = Timer(1, removehealth)
    t.start()

    # id display the hearts on screen down here

Tags: oftheimport消息错误玩家事情running
2条回答

您可以使用模块time并等待一定的秒数

import time

start = time.time() # gets current time

while running:
    if time.time() - start > 1: # if its been 1 second
        removehealth()
        start = time.time()

还要删除列表中的最后一项,您可以执行del playerhealth[-1]

使用pygame的方法是使用^{}重复创建^{}。e、 g:

milliseconds_delay = 1000 # 1 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, milliseconds_delay)

在pygame中,可以定义客户事件。每个事件都需要一个唯一的id。用户事件的id必须介于pygame.USEREVENT(24)和pygame.NUMEVENTS(32)之间。在本例中pygame.USEREVENT+1是计时器事件的事件id,它消耗运行状况

在事件循环中发生事件时移除心脏:

running = True
while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == timer_event:
            del playerhealth[-1]

通过将0传递给时间参数(pygame.time.set_timer(timer_event, 0)),可以停止计时器事件

相关问题 更多 >