为什么我的游戏在使用 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,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)
black = (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()