풍선이 3 초마다 폭발해야하는이 게임이 있지만 폭발은 약 1 초 동안 지연되어야합니다 (지금은 거의 즉각적입니다). 3 초마다 풍선을 가지고 있지만 지연 부분에 문제가 있습니다. 내가 잠을 자거나 기다리면, 내가 계속하는 다른 모든 애니메이션이 멈추고, 그것은 내가 원하는 것이 아닙니다. 누군가는 어떤 조언을 가지고 있습니까?다른 모든 기능을 지연시키지 않고 파이 게임에서 이벤트를 지연시키는 방법은 무엇입니까?
0
A
답변
0
pygame.time.get_ticks()
은 현재 시간을 밀리 초 단위로 나타냅니다.
당신은 설정할 수 있습니다 (3S의 =의 3000ms)
next_baloon = pygame.time.get_ticks() + 3*1000
하고 당신이 풍선을
if next_baloon <= pygame.time.get_ticks():
start_ballon()
next_baloon = pygame.time.get_ticks() + 3*1000
next_explosion = pygame.time.get_ticks() + 1*1000
if next_explosion <= pygame.time.get_ticks():
explode_ballon()
0
여기에 완벽한 예입니다을 시작하는 시간이 있는지 확인해야 모든 루프있다. 객체 지향 프로그래밍, 파이 게임 스프라이트 및 스프라이트 그룹을 사용하는 것이 좋습니다. 이 스프라이트에는 timer
속성이 있으며 각 프레임의 델타 시간 인 dt
만큼 감소합니다. 풍선의 시간이 끝나면 포함 된 스프라이트 그룹 balloon.kill()
에서 제거되고 대신 폭발 인스턴스가 추가됩니다. 폭발은 또한 타이머가 있고 그 자체가 타이머 0
아래에있을 때 self.kill()
을 제거합니다. 풍선을 더 추가하려면 마우스 단추를 누르십시오.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
# Images. Balloon = blue, explosion = orange.
BALLOON_IMAGE = pg.Surface((50, 50), pg.SRCALPHA)
pg.draw.circle(BALLOON_IMAGE, pg.Color('steelblue2'), (25, 25), 25)
EXPLOSION_IMAGE = pg.Surface((80, 80), pg.SRCALPHA)
pg.draw.circle(EXPLOSION_IMAGE, pg.Color('sienna1'), (40, 40), 40)
class Balloon(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = BALLOON_IMAGE
self.rect = self.image.get_rect(center=pos)
self.timer = 3
def update(self, dt):
self.timer -= dt
class Explosion(pg.sprite.Sprite):
def __init__(self, pos):
super().__init__()
self.image = EXPLOSION_IMAGE
self.rect = self.image.get_rect(center=pos)
self.timer = 1
def update(self, dt):
self.timer -= dt
if self.timer <= 0:
self.kill()
balloons = pg.sprite.Group(Balloon((300, 300)))
all_sprites = pg.sprite.Group(balloons)
done = False
while not done:
dt = clock.tick(30)/1000
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
balloon = Balloon(event.pos)
balloons.add(balloon)
all_sprites.add(balloon)
all_sprites.update(dt)
for balloon in balloons:
if balloon.timer <= 0:
balloon.kill()
all_sprites.add(Explosion(balloon.rect.center))
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
+0
[프로그램 아케이드 게임] (http://programarcadegames.com/index.php?chapter=introduction_to_sprites&lang=en#section_13)의 12 장 및 13 장에서는 클래스, 스프라이트 스프라이트 그룹은 아직 모르는 경우 작동합니다. – skrx
타이머를 구현해야합니다. https://stackoverflow.com/q/30720665/6220679 – skrx