我正在做一种轰炸机,我正在尝试使炸弹在一段时间后爆炸。抱歉,这个问题已经存在。我一直在寻找任何答案,但没有找到。
这应该像:
我把炸弹放在某处
2.炸弹等待5秒
3.炸弹爆炸
我不知道如何给5秒之前爆炸。
class bomb(object):
def __init__(self, aposX, aposY, bombRange = 5):
self.posX = aposX
self.posY = aposY
self.bombRange = bombRange
self.timeToExplode = 5000
pygame.draw.circle(ventana,(200,0,0),(self.posX,self.posY),20)
def update(self):
pygame.draw.circle(ventana,(200,0,0),(self.posX,self.posY),20)
#Here should wait 5 seconds and then call the explde method
self.explode()
def explode(self):
pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX+20+(40*self.bombRange),self.posY),40)
pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX-20-(40*self.bombRange),self.posY),40)
pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX,self.posY+20+(40*self.bombRange)),40)
pygame.draw.line(ventana,(200,0,0),(self.posX,self.posY),(self.posX,self.posY-20-(40*self.bombRange)),40)
希望您能为我提供帮助。
最佳答案
这是dt
变体的一个小例子。我将dt
传递给update
方法,在其中使用它来减少timer属性。在主循环中,如果计时器低于0,我只是画出爆炸线。要删除实例,我将爆炸的炸弹放入一个集合中,该集合从包含所有炸弹实例的bomb_set
中减去。
import pygame
class Bomb(object):
def __init__(self, aposX, aposY, bombRange=5):
self.posX = aposX
self.posY = aposY
self.bombRange = bombRange
self.timeToExplode = 3000
def update(self, dt):
# Subtract the passed time `dt` from the timer each frame.
self.timeToExplode -= dt
def explode(self, screen):
pygame.draw.line(screen,(200,0,0),(self.posX,self.posY),(self.posX+20+(40*self.bombRange),self.posY),40)
pygame.draw.line(screen,(200,0,0),(self.posX,self.posY),(self.posX-20-(40*self.bombRange),self.posY),40)
pygame.draw.line(screen,(200,0,0),(self.posX,self.posY),(self.posX,self.posY+20+(40*self.bombRange)),40)
pygame.draw.line(screen,(200,0,0),(self.posX,self.posY),(self.posX,self.posY-20-(40*self.bombRange)),40)
def draw(self, screen):
pygame.draw.circle(screen,(200,0,0),(self.posX,self.posY),20)
def main():
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
bomb_set = set() # This set holds the bomb instances.
done = False
while not done:
# Get the passed time since last clock.tick call.
dt = clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
bomb_set.add(Bomb(*event.pos))
# Game logic.
to_remove = set()
# Update bombs. Pass the `dt` to the bomb instances.
for bomb in bomb_set:
bomb.update(dt)
# Add old bombs to the to_remove set.
if bomb.timeToExplode <= -3000:
to_remove.add(bomb)
# Remove bombs fromt the bomb_set.
if to_remove:
bomb_set -= to_remove
# Draw everything.
screen.fill((30, 30, 30))
for bomb in bomb_set:
bomb.draw(screen)
# I'm just drawing the explosion lines each
# frame when the time is below 0.
if bomb.timeToExplode <= 0:
bomb.explode(screen)
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
main()
pygame.quit()
关于python - 给时间炸弹在pygame上爆炸,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46861059/