2016-12-03 25 views
0

我遇到了麻煩。當它應該大於0時,它不會將當前分數保存爲高分。我希望代碼保存分數,然後當我再次玩時,高分被更新。所有相關的代碼如下。謝謝:)我是新來的Python/pygame的爲什麼我的高分在Pygame上節省?

def highScores(high_score): 
    intro = True 
    while intro == True: 
     for event in pygame.event.get(): 
      if event.type == pygame.QUIT: 
       pygame.quit() 
       quit() 

    gameDisplay.fill(black) 
    font1 = pygame.font.SysFont('gillsans', 35, bold = True) 
    font2 = pygame.font.SysFont('gillsans', 20) 
    title = font1.render("High Score", True, white) 
    gameDisplay.blit(title, (200,100)) 
    first = font2.render("Your high score is: "+str(high_score), True, white) 
    gameDisplay.blit(first, (70,200)) 

    pygame.draw.rect(gameDisplay, white, (350, 400, 100, 45)) 
    button("Back",350, 400, 100, 45,"back") 
    pygame.display.update() 

def highScore(count): 
    high_score = get_high_score(count) 
    smallText = pygame.font.SysFont('gillsans',30) 
    text = smallText.render("High Score: "+str(high_score), True, white) 
    gameDisplay.blit(text, (420,0)) 

def get_high_score(count): 
    high_score = count 
    try: 
     high_score_file = open("high_score.txt", "r") 
     high_score = int(high_score_file.read()) 
     #high_score_file.close() 
     #return high_score 
    except: 
     pass 
    if count >= high_score: 
     return high_score 
     save_high_score() 

def save_high_score(count): 
    try: 
     high_score_file = open("high_score.txt", "w") 
     high_score_file.write(str(count)) 
     #high_score_file.close() 
     #return high_score 
    except: 
     pass 
    if count >= high_score: 
     return high_score 
     save_high_score() 
+2

在'def get_high_score(count):'它看起來像你正在返回,在你執行'save_high_score()'之前,你應該在執行時包含參數'count'。即'save_high_score(count)'。在你的代碼中放一些'print'命令來顯示你正在執行什麼以及什麼時候執行。 –

+0

不要使用裸「except」,因爲它會隱藏每一個可能的錯誤,並使得您的程序非常難以調試。總是指定您希望的異常,例如「IOError:',然後爲用戶打印一條消息。另外,儘量縮短'try'子句的長度。 – skrx

回答

1

get_high_score,你是返回保存前:

return high_score 
    save_high_score() 

你可以只扭轉兩種說法:

save_high_score() 
    return high_score 

如果您真的需要在save_high_score中調用save_high_score,你將不得不重構你的代碼。這樣做會做一個無意的遞歸。

相關問題