如何每两秒矩形碰撞带走健康?

How do I take away health for every two seconds of rectangle collision?

我一直在尝试创建一个简单的游戏,让僵尸(用紫色圆圈表示)攻击宝藏。

这是我的代码:

import pygame
from sys import exit
from random import randint

pygame.init()

clock = pygame.time.Clock()

screen_width = 1000
screen_height = 660
screen = pygame.display.set_mode((screen_width, screen_height))

# Treasure
treasure_health = 15
treasure_health_text = pygame.font.SysFont('comicsans', 30)
treasure = pygame.image.load(r"filename")
treasure_surf = pygame.transform.scale(treasure, (60, 60))
treasure_rect = treasure_surf.get_rect(center = (500, 330))

# Zombie
zombie_vel = 1
zombie = pygame.image.load(r"filename")
zombie_surf = pygame.transform.scale(zombie, (30, 25))
zombie_rect = zombie_surf.get_rect(center = (randint(0, 1000), randint(0, 600)))

while True:

    screen.fill('DarkGreen')
    screen.blit(treasure_surf, treasure_rect)
    screen.blit(zombie_surf, zombie_rect)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    if zombie_rect.centerx < 500:
        zombie_rect.centerx += zombie_vel

    if zombie_rect.centerx > 500:
        zombie_rect.centerx -= zombie_vel

    if zombie_rect.centery < 330:
        zombie_rect.centery += zombie_vel

    if zombie_rect.centery > 330:
        zombie_rect.centery -= zombie_vel

    if zombie_rect.colliderect(treasure_rect):
        zombie_vel = 0
        # print(treasure_health)


    # Health
    treasure_health_surf = treasure_health_text.render(
        'Treasure Health: ' + str(treasure_health), False, ('Black'))
    treasure_health_rect = treasure_health_surf.get_rect(midleft = (0, 600))
    screen.blit(treasure_health_surf, treasure_health_rect)    

    pygame.display.update()
    clock.tick(60)

但是,我想做到每两秒僵尸与宝物相撞,它就会从treasure_health中拿走一个,有什么办法可以实现吗?

提前致谢。

使用pygame.time.get_ticks()来测量时间。此函数测量自游戏开始以来的时间(以毫秒为单位)。一旦检测到碰撞,计算僵尸拿走下一个宝物的时间:

zombie_time = 0
while True:
    current_time = pygame.time.get_ticks()

    # [...]

    if zombie_rect.colliderect(treasure_rect):
        zombie_vel = 0

        if zombie_time < current_time:
            zombie_time = current_time + 2000 # 2 seconds from now on
            if treasure_health > 0:
                treasure_health -= 1

    # [...]