python - 为什么我的游戏在使用 pygame.time.wait 或 pygame.time.delay 时会死机?
问题描述
我创建了一个小例子来解释:
import pygame
pygame.init()
class Player(pygame.sprite.Sprite):
def __init__(self, color):
super().__init__()
self.image = pygame.Surface([25, 25])
self.image.fill(color)
self.color = color
self.rect = self.image.get_rect()
class Block(pygame.sprite.Sprite):
def __init__(self, color):
super().__init__()
self.image = pygame.Surface([25, 25])
self.image.fill(color)
self.color = color
self.rect = self.image.get_rect()
def update(self):
self.rect.y +=5
pygame.time.wait(500)
# Color
red = (255, 0, 0)
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode([500,500])
# Sprite List
sprite_list = pygame.sprite.Group()
block_list = pygame.sprite.Group()
# Player
player = Player(red)
player.rect.x = 250
player.rect.y = 250
sprite_list.add(player)
# Block
block = Block(black)
block.rect.x = 250
block.rect.y = 0
block_list.add(block)
sprite_list.add(block)
notDone = True
clock = pygame.time.Clock()
while notDone:
for event in pygame.event.get():
if event.type == pygame.QUIT:
notDone = False
sprite_list.update()
block_collide = pygame.sprite.spritecollide(player, block_list, False)
for block in block_collide:
print("Collision")
notDone = False
screen.fill(white)
sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
我想创建它,这样block
它就不会在每个时钟滴答声中移动,而是移动,然后等待半秒,然后再次移动。我不确定如何在循环中延迟,所以我只是使用了pygame.time.wait
,但这导致我的游戏在启动时冻结(当我决定运行代码时)。为什么这种情况不断发生?
解决方案
您不能在应用程序循环内等待。pygame.time.wait
停止循环并使应用程序不负责任。
用于pygame.time.get_ticks()
返回自pygame.init()
调用以来的毫秒数。计算块需要移动的时间点。到达时间后,移动块并计算块必须再次移动的时间:
next_block_move_time = 0
while notDone:
# [...]
# sprite_list.update() <--- DELETE
current_time = pygame.time.get_ticks()
if current_time > next_block_move_time:
# set next move time
next_block_move_time = current_time + 500 # 500 milliseconds = 0.5 seconds
# move blocks
block_list .update()
推荐阅读
- javascript - 是否可以在警报框中获取网站设置的 http 标头?
- apache-kafka - 具有多个分区的 kafka 主题和具有多个队列侦听器的 ActiveMQ 有什么区别
- autodesk-forge - 加载多个模型时如何在查看器中通过 dbid 选择?
- vba - 从工作表函数传递范围时获取单元格内部颜色失败
- javascript - 关于匿名函数的概念和javascript中的调用
- node.js - docker 容器未启动 - 产生 Java enoent 错误
- javascript - Firebase 帐户创建尝试使用变量设置其他信息,然后获取该信息
- hadoop - 将任意本地 jar 发送到 YARN 容器类路径
- ios - 从当前视图而不是 RootView 导航到 ViewModel
- python - 2 通过 python 的命令行和 "if __name__ == "__main__":" 输入