Pygame:为什么代码从来没有到达第二次打印?



我正在用pygame制作一个小游戏,其中一艘船撞小行星,我想使用布尔值作为防碰撞设备,我的意思是防碰撞将始终为假,除非有碰撞,然后它应该是True a不允许任何碰撞发生,1秒后防碰撞将返回false。这个想法是为了避免在动画已经开始的时候出现爆炸动画和生命损失。我认为逻辑是正确的,但我似乎无法使它工作。我总是能得到第一个指纹,但没有第二个。奇怪的是,它在vsc调试器中正常工作,但这是我可以达到第二次打印并将值更改为正常的唯一方法。为什么?

current_time = 0
while running :
#[...]
current_time = pygame.time.get_ticks() 
#[...]
if self.player.estado == self.player.Estado.volando:
#comprobar colisión

colisiones = pygame.sprite.spritecollide(self.player, self.asteroides, True, pygame.sprite.collide_circle)
anticolision = False
for colision in colisiones:

if colision and not anticolision:
anticolision_time = pygame.time.get_ticks()
anticolision = True 
print("anticolision true")                        
expl = Explosion(colision.rect.center)
self.explosionSound.play()
self.all_sprites.add(expl)                  
self.vidas -= 1
espera = (anticolision_time - current_time)/ 1000
if espera > 1:
print("anticolision false")
anticolision = False

else:
pass
if self.vidas == 0:     
self.gameOver()
running= False

我会在if测试上面添加print语句,所以看看espera的值是多少。

解决方法是:(anticolision_time - current_time )/ 1000

使其工作,因为anticolision_time将会更大:)祝你好运!

>>> import time
>>> current = time.time()
>>>
>>>
>>>
>>> anti_time = time.time()
>>>
>>> current - anti_time
-5.687999963760376

如你所见,你的变量current_time有点误导人,你需要将其重命名为start_time以使其更清晰

在您的实现中,current_time始终等于anticolision_time

pygame.time.get_ticks()的返回值只有在使用pygame.time.delay延迟一段时间后才会改变。在某些系统上,您还需要处理事件(参见pygame.event.pump)。

最新更新