I've been trying to create a simple game in which zombies (represented by purple circles) are attacking a treasure.
Here's my code:
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)
However, I want to make it so that every two seconds that a zombie has collided with the treasure, it takes one away from treasure_health
, is there any way I can achieve this?
Thanks in advance.
Use pygame.time.get_ticks()
to measure time. This function measures the time since the game started in milliseconds. Once a collision is detected, calculate the time the zombie will take the next treasure:
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
# [...]