我如何让一个物体在一段时间后消失在pygame中



我正在尝试使用pygame在python中制作一个简单的射击游戏。我的游戏逻辑很简单,一个目标在随机位置出现三秒,然后消失,在这个时间限制内,我们必须将指针移向目标并击中空间。如果他们机器人的坐标匹配,那么我们就得了一分。这是代码

import pygame, sys, time, random
from pygame.locals import *
pygame.init()
disp = pygame.display
win = disp.set_mode((450, 450))
disp.set_caption("Shooter")
#-----------------------------------------------------------------------------------------#
pointer = pygame.image.load('sprites/sprite0.png')
target = pygame.image.load('sprites/sprite1.png')
ptrx = 225
ptry = 225
locx = random.randint(0, 29)
locy = random.randint(0, 29)
points = 0
shot = False
green = (000, 255, 000)
array = [0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150,
165, 180, 195, 210, 225, 240, 255, 270, 285, 300,
310, 330, 345, 360, 375, 390, 105, 420, 435]
score = 0
#-----------------------------------------------------------------------------------------#
def showTargetInRandomLoaction():
global locx
global locy
global array
win.blit(target, (array[locx], array[locy]))
# Here's the problem
def shoot():
global shot
shot = True
checkIfBulletHasHitTheTarget()

def checkIfBulletHasHitTheTarget():
global score
if shot == True:
bulletPos = (ptrx, ptry)
targPos = (array[locx], array[locy])
if bulletPos == targPos:
print("target hit success !")
score += 1
print(f"Your Score - {score}")
return True
else:
print("target hit uncess !")
return False

def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
win.fill(green)
global ptrx
global ptry
global shot
global array
showTargetInRandomLoaction()
key = pygame.key.get_pressed()
left = key[pygame.K_LEFT]
right=  key[pygame.K_RIGHT]
up = key[pygame.K_UP]
down = key[pygame.K_DOWN]
space = key[pygame.K_SPACE]
win.blit(pointer, (ptrx, ptry))
if left and ptrx >= 0:
ptrx -= 15
if right and ptrx <= 435:
ptrx += 15
if up and ptry >= 0:
ptry -= 15
if down and ptry <= 435:
ptry += 15
if space:
shot = True
shoot()
disp.update()
#----------------------------------------------------------------------------------------#
if __name__ == '__main__':
main()

我建议使用计时器事件。使用pygame.time.set_timer()可以重复创建USEREVENT。例如:

time_delay = 3000 # 3 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, time_delay)

注意,在pygame中可以定义客户事件。每个事件都需要一个唯一的id。用户事件的id必须在pygame.USEREVENT(24(和pygame.NUMEVENTS(32(之间。在这种情况下,pygame.USEREVENT+1是计时器事件的事件id。

获取事件循环中的事件,并在timer_event发生时定义新的随机位置:

def main():
global locx, locy
time_delay = 3000 # 3 seconds
timer_event = pygame.USEREVENT + 1
pygame.time.set_timer(timer_event, time_delay)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == timer_event:
locx = random.randint(0, 29)
locy = random.randint(0, 29)
# [...]

最新更新