You need to enable JavaScript to run this app. Python音乐猜歌游戏实现分数达10时触发胜利提示功能求助
优惠活动
大模型
产品
解决方案
定价
更多

Python音乐猜歌游戏实现分数达10时触发胜利提示功能求助

代码问题梳理与修复方案

首先梳理原有代码的核心问题:

  • 循环逻辑优先级错误:原有代码优先判断答错次数是否满2次,全程没有检查答对分数是否达到10的阈值,导致即便答对10题也不会触发胜利逻辑
  • 胜利判断逻辑完全写反:原有代码写的while score != 10会在分数未达到10的时候反复打印胜利提示,和需求完全相反
  • 存在冗余函数调用:login函数中调用完game之后又调用ransong属于无效操作,歌曲列表已经提前读取完成
  • 无答对达标即时终止逻辑:原有代码即便答对满10题,也会继续要求用户输入,直到答错满2次才会终止程序
修复后完整代码
import random

print("Welcome to my quiz. The task is to name 10 of Juice Wrld's songs. You get two wrong answers, and if you pass that margin you lose. Good luck!")
    
def login():
    file = open("musicpass.txt", "r")
    password = file.read()
    userguess = input("Enter password for access: ")
    if password == userguess:
        print("Access Granted!")
        game(song)
    else:
        print("Access Denied!")
        login()

def ransong():
    with open("musicsongs.txt", "r") as file:
        content= file.read()
        words = content.splitlines()
    return words

def game(songlist):
    wrong_guess = 0
    score = 0
    # 循环条件:答错次数未到上限且未答对10题
    while wrong_guess < 2 and score < 10:
        usguess1 = input("Enter your choice here: ")
        if usguess1 in songlist:
            print("Correct!")
            score += 1
            # 答对后立刻判断是否达到胜利条件
            if score == 10:
                print("You win")
                print(f"Your final score is: {score}")
                return
        else:
            wrong_guess += 1
            if wrong_guess < 2:
                print(f"Incorrect, one more guess allowed")
    # 跳出循环说明答错次数达到上限
    print("Incorrect, game over")
    print(f"Your score is: {score}")
    print("Incorrect, no more guesses left.")

def main():
    login()

song = ransong()
main()

内容的提问来源于stack exchange,提问作者zobr0toN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 12:24:04