1

I created a small example to explain:

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()

I wanted to create this so the block does not move every clock tick and rather move, then wait half a second, and then move once again. I wasn't exactly sure how to delay within a loop, so I simply used pygame.time.wait, however this caused my game to freeze upon start up (when I decided to run the code). Why does this keep happening?

J.C.
  • 25
  • 6

1 Answers1

1

You can not wait inside the application loop. pygame.time.wait halts the loop and makes the application irresponsible.
Use pygame.time.get_ticks() to return the number of milliseconds since pygame.init() was called. Calculate the point in time when the block needs to be move. When the time is reached, move the block and calculate the time when the block has to be moved again:

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()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174