You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python猜歌代码以禁止用户重复提交同一正确答案?

猜歌小游戏重复提交刷分漏洞修复方案

核心实现逻辑是新增已答对歌曲的记录容器,每次用户提交答案时做重复校验,只有首次答对的有效歌曲才会累计分数。

具体修改点

  • 在game函数初始化变量时,新增空集合correct_songs = set(),集合的去重特性刚好适配校验需求,查询效率也更高
  • 调整答案校验逻辑,原来仅判断答案是否在歌单里,现在新增重复校验:只有答案在歌单且未在correct_songs中存在时,才判定为有效正确答案
  • 有效答对后除了分数加1,还要把当前答案加入correct_songs集合,避免后续重复提交计分
  • 可新增重复提交的友好提示,优化用户体验

修改后的核心game函数代码

def game(song):
    songlist = song
    guess = 0
    score = 0
    correct_songs = set() # 新增:存储已答对的歌曲
    while guess != 2:
        if score == 10:
            print("Well done, you win!")
            break
            
        usguess1 = input("Enter your choice here: ")
        if usguess1 in songlist:
            if usguess1 not in correct_songs: # 新增:校验是否已经答对过
                print("Correct!")
                score = score + 1
                correct_songs.add(usguess1) # 新增:加入已答对集合
            else:
                print("这首歌你已经答对过了,不重复计分哦")
        else:
            print("Incorrect, one more guess allowed")
            guess = guess + 1
    else:
        print("Your score is:",score)
        print("Incorrect, no more guesses left.")

完整修改后代码

import random
score = 0
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(): #defines the function
    file = open("musicpass.txt", "r")
    password = file.read()
    userguess = input("Enter password for access: ")
    if password == userguess:
        print("Access Granted!")
        game(song)
        ransong()
    else:
        print("Access Denied!")
        login()

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


def game(song):
    songlist = song
    guess = 0
    score = 0
    correct_songs = set() # 新增:存储已答对的歌曲
    while guess != 2:
        if score == 10:
            print("Well done, you win!")
            break
            
        usguess1 = input("Enter your choice here: ")
        if usguess1 in songlist:
            if usguess1 not in correct_songs: # 新增:校验是否已经答对过
                print("Correct!")
                score = score + 1
                correct_songs.add(usguess1) # 新增:加入已答对集合
            else:
                print("这首歌你已经答对过了,不重复计分哦")
        else:
            print("Incorrect, one more guess allowed")
            guess = guess + 1
    else:
        print("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 13:54:06