2017-11-14 1 views
2

게임에서 경과 한 시간을 기준으로 점수를 원합니다. 이렇게하려면 두 개의 루프를 동시에 실행하고 싶습니다. 게임 루프와 점수 루프는 1.5 초마다 점수에 1을 더합니다. 프로그램을 실행하면 점수가 표시되지 않습니다. 멀티 스레딩을 제대로 사용하고 있습니까? 이것이 최선의 방법인가요? 간단하게 관련 코드 만 게시했습니다. 감사!게임 루프가 파이썬에서 실행되는 동안 게임 점수를 표시하는 멀티 스레딩?

def text_objects(text, font): 
    textSurface = font.render(text, True, black) 
    return textSurface, textSurface.get_rect() 

def displayScore(text): 
    while(True): 
     textStyle = pygame.font.Font('freesansbold.ttf', 25) 
     # pop up window defining window and textRect to align text properly 
     textWindow, textRect = text_objects(text, textStyle) 
     textRect.center = ((display_width/2)), ((display_height/2)) 
     gameDisplay.blit(textWindow, textRect) 
     pygame.display.update() 
     time.sleep(1.5) 
     text = int(text) 
     text +=1 
     text = str(text) 

def gameStart(): 

    x_change = 0 
    y_change = 0 
    x = (display_width * 0.39) 
    y = (display_height * 0.7) 
    car_width = 200 
    x_brick = (display_width * random.uniform(.05, .95)) 
    y_brick = display_height - 925 

    # exception for the game crashing and the game loop 
    gameExit = False 

    while not gameExit: 

    # capturing user actions 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      pygame.quit() 
      quit() 

     # key-down events for car movements 
     if event.type == pygame.KEYDOWN: 
      if event.key == pygame.K_LEFT: 
       x_change = -5 
      elif event.key == pygame.K_RIGHT: 
       x_change = 5 
      elif event.key == pygame.K_UP: 
       y_change = -5 
      elif event.key == pygame.K_DOWN: 
       y_change = 5 

     # cancelling out key-up events 
     if event.type == pygame.KEYUP: 
      if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 
       x_change = 0 
      if event.key == pygame.K_UP or event.key == pygame.K_DOWN: 
       y_change = 0 


    # crash conditions 
    if x > display_width - car_width or x < 0: 
     crash() 
    if y > display_height - 175 or y < 0 - 10: 
     crash() 


    # updating car movements 
    x += x_change 
    y += y_change 

    # generating display 
    gameDisplay.fill(white) 
    car(x, y) 
    brick(x_brick, y_brick) 

    # moving the brick 
    y_brick += brick_speed 

    # updates for parameter given or entire surface 
    pygame.display.update() 

    # frames per second, the more frames per second the faster and smoother things move, taxing on processing speed 
    clock.tick(60) 


t1 = Thread(target=gameStart()) 
t2 = Thread(target=displayScore('0')) 
t1.start() 
t2.start() 

편집 :이와 함께 종료 .. 당신은 _thread을 사용할 수

import time 

score = 0 

def timer(oldsec): 
    currentsec = time.time() 
    if abs(currentsec - oldsec > 3): 
     return True 
    else: 
     False 


oldsec = time.time() # what time is it now 

while True: 
    if timer(oldsec) == True: 
     score += 1 
     oldsec = time.time() 
     print (score) 
+1

아니요, 올바르게 수행하지 않습니다. 실제로 (절차 적 세계 세대와 같이) 별도의 스레드에서 완료하는 데 시간을 요하는 작업 만 수행하면됩니다. 또한 꽤 많은 다른 GUI/렌더링 라이브러리와 마찬가지로 Pygame은 다중 스레드를 지원하지 않습니다. 즉, 메인 이벤트 루프 스레드 이외의 스레드에서 화면에 아무 것도 렌더링 할 수 없습니다. – EvilTak

+0

좋아, 설명해 주셔서 감사합니다. 동시에 두 개의 루프를 실행하는 방법에 대한 제안이 있습니까? –

+1

매 1.5 초마다 점수를 업데이트 할 목적으로 두 번째 루프를 실행하려면하지 마십시오. 최종 점수 업데이트 이후 1.5 초가 지났는지 단순히 확인하여 업데이트 루프에서이 작업을 수행 할 수 있습니다. 있다면 점수를 업데이트하고 그렇지 않으면 점수를 업데이트하십시오. 이상적으로 이것을'Timer' 또는'TimedEvent' 클래스로 추상화 시키면'x' 초마다 메소드를 호출하고 이벤트 루프가 실행될 때마다'x' 초가 경과했는지 확인합니다. – EvilTak

답변

0

.

from _thread import * 

count = 0 

def Your_other_loop(): 
    global count 
    while True: 
     #Do loop stuff 



def loop(): 
    global count 
    while True: 
     print(count) 

start_new_thread(Your_other_loop,()) 
loop()