2017-12-02 9 views
0

pygame에서 Pong을 다시 만들고자하며 점수를 기준으로 그물의 색을 빨강 또는 초록으로 변경하려고했습니다. 다른 사람이 점수를 매길 때까지 누군가 점수를 얻은 후에 빨간색 또는 녹색으로 유지할 수 있지만, 3 초 후에 다시 그물 색을 검은 색으로 변경하고 싶습니다. 나는 time.sleep (3)을 사용하여 시도했지만, 내가 그랬을 때마다 그물은 검은 색으로 남을 것이다. `이상적으로Pygame을 사용하여 time.sleep을 사용하여 x 초 동안 기다리지 말고 코드를 실행하지 않음

elif pong.hitedge_right:  
     game_net.color = (255,0,0)  
     time.sleep(3)  
     scoreboard.sc1 +=1 
     print(scoreboard.sc1) 
     pong.centerx = int(screensize[0] * 0.5) 
     pong.centery = int(screensize[1] * 0.5) 

     scoreboard.text = scoreboard.font.render('{0}  {1}'.formatscoreboard.sc1,scoreboard.sc2), True, (255, 255, 255)) 

     pong.direction = [random.choice(directions),random.choice(directions2)] 
     pong.speedx = 2 
     pong.speedy = 3 

     pong.hitedge_right = False 
     running+=1 
     game_net.color=(0,0,0) 

, 그 다음, 3 초 동안 빨간색으로 점수 판을 업데이트하고 공을 다시 시작하지만, 대신에 모든 게 일시 정지는 곧바로 블랙에 그물 색상을 변경으로 건너 뜁니다한다. 나는 이것을하는 더 좋은 방법이 있다고 믿는다. 또는 어쩌면 나는 time.sleep을 완전히 잘못 사용하고있다. 그러나 이것을 고치는 방법을 모른다.

+0

틱 최소한의 작업 예제를 제공하는 것이 가능합니까? 조각? 언뜻보기에 코드가 제게 적합합니다. –

+0

''time.sleep()'은 prorgam에서 항상 수행하는 mainloop을 멈추기 때문에 사용할 수 없습니다. mainloop을 실행해야하고 현재 시간을 확인하고 3 초 후에이 부분을 실행해야합니다. 'pygame.time.get_ticks()'를 사용하면 현재 시간을 알 수 있습니다. – furas

답변

1

다른 요소를 업데이트하는 mainloop이 중지되므로 PyGame (또는 GUI 프레임 워크)에서 sleep()을 사용할 수 없습니다.

변수에서 현재 시간을 기억하고 나중에 루프를 사용하여 현재 시간과 비교하여 3 초 남았는지 확인해야합니다. 아니면 3 초 후에 해고 될 자체 EVENT를 만들어야합니다.이 이벤트는 for event에서 확인해야합니다.

그것은 내가 그 시간을 사용


처럼 보일 수있는 방법만을 보여줄 수있는 코드에 더 많은 변화를해야 할 수도 있습니다은/

# create before mainloop with default value 
update_later = None 


elif pong.hitedge_right:  
    game_net.color = (255,0,0)  
    update_later = pygame.time.get_ticks() + 3000 # 3000ms = 3s 


# somewhere in loop 
if update_later is not None and pygame.time.get_ticks() >= update_later: 
    # turn it off 
    update_later = None 

    scoreboard.sc1 +=1 
    print(scoreboard.sc1) 
    # ... rest ... 

사용 이벤트

# create before mainloop with default value 
UPDATE_LATER = pygame.USEREVENT + 1 

elif pong.hitedge_right:  
    game_net.color = (255,0,0)  
    pygame.time.set_timer(UPDATE_LATER, 3000) # 3000ms = 3s 

# inside `for `event` loop 
if event.type == UPDATE_LATER: 
    # turn it off 
    pygame.time.set_timer(UPDATE_LATER, 0) 

    scoreboard.sc1 +=1 
    print(scoreboard.sc1) 
    # ... rest ... 
+0

BTW : examples [time-execute-function] (https://github.com/furas/python-examples/tree/master/pygame/time-execute-function) 및 [clock] (https : // github. co.kr/furas/python-examples/tree/master/pygame/clock) – furas