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

音乐猜谜游戏开发及歌曲标题首字母显示功能调试求助

代码调试方案

问题根源

你的代码存在两个核心问题:

  1. 分割逻辑错误:用split(" ",1)分割艺术家和歌曲名,会把艺术家名字里的空格当成分割点(比如Michael Jackson Billie Jean会被拆成艺术家Michael、歌曲名Jackson Billie Jean),完全不符合需求。
  2. 遍历逻辑错误:for x in song_title是遍历歌曲名的每个字符而非每个单词,导致每个字符的首字母(即字符本身)和艺术家重复打印,输出混乱。

修正步骤

第一步:统一歌曲文件格式

先把songs.txt的每行改成艺术家|歌曲名格式(比如Michael Jackson|Billie Jean、Eminem|Cleaning Out My Closet),避免艺术家名字带空格时分割出错。

第二步:修正分割与首字母提取代码

import random 

# 读取歌曲文件并随机选一首
with open("songs.txt", "r") as select:
    song = random.choice(select.readlines()).strip()  # 去掉换行符

# 分割艺术家和歌曲名
artist, song_title = song.split("|")

# 提取歌曲名每个单词的首字母并格式化
title_initials = [word[0].upper() for word in song_title.split()]
initials_display = "  ".join(title_initials)

# 按要求输出
print(f"{artist} {initials_display}")

运行后会输出类似Michael Jackson B J的结果,符合需求。


完整音乐猜谜游戏开发指导

1. 授权玩家验证

创建authorized_users.txt,每行存用户名:密码(比如alice:123456、bob:abcdef),验证逻辑如下:

def authenticate_user():
    print("请输入授权信息")
    username = input("用户名: ").strip()
    password = input("密码: ").strip()
    
    with open("authorized_users.txt", "r") as f:
        for line in f:
            stored_user, stored_pwd = line.strip().split(":")
            if stored_user == username and stored_pwd == password:
                print("验证通过!开始游戏")
                return username
    print("未授权用户,游戏结束")
    exit()

2. 歌曲文件管理

保持songs.txt的艺术家|歌曲名格式,确保每行数据准确无空行。

3. 随机选歌与首字母展示

封装成函数复用:

def get_random_song():
    with open("songs.txt", "r") as f:
        songs = [line.strip() for line in f if line.strip()]
    song = random.choice(songs)
    artist, song_title = song.split("|")
    # 提取首字母并格式化
    initials = "  ".join([word[0].upper() for word in song_title.split()])
    return artist, song_title, initials

4. 猜谜逻辑与计分

def play_round(artist, song_title, initials):
    print(f"\n提示:{artist} {initials}")
    score = 0
    # 第一次猜测
    guess1 = input("第一次猜测歌曲名: ").strip().lower()
    if guess1 == song_title.lower():
        score += 3
        print(f"猜对了!得3分")
        return score
    # 第二次猜测
    guess2 = input("猜错了,第二次猜测: ").strip().lower()
    if guess2 == song_title.lower():
        score += 1
        print(f"猜对了!得1分")
        return score
    # 两次都错,游戏结束
    print(f"两次都猜错了,正确答案是{song_title}")
    return -1

5. 得分存储与排行榜

存储得分

def save_score(username, total_score):
    with open("scores.txt", "a") as f:
        f.write(f"{username}:{total_score}\n")

展示前五得分

def show_top_scores():
    print("\n=== 得分排行榜前五 ===")
    scores = []
    try:
        with open("scores.txt", "r") as f:
            for line in f:
                user, score = line.strip().split(":")
                scores.append((-int(score), user, int(score)))  # 负号用于升序排序取前5
        # 按分数降序排序
        scores.sort()
        top_five = scores[:5]
        for idx, (_, user, score) in enumerate(top_five, 1):
            print(f"{idx}. {user}: {score}分")
    except FileNotFoundError:
        print("暂无得分记录")

6. 游戏主流程

def main():
    username = authenticate_user()
    total_score = 0
    while True:
        artist, song_title, initials = get_random_song()
        round_score = play_round(artist, song_title, initials)
        if round_score == -1:
            break
        total_score += round_score
        print(f"当前总得分: {total_score}")
    
    print(f"\n游戏结束!你的总得分是{total_score}")
    save_score(username, total_score)
    show_top_scores()

if __name__ == "__main__":
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:52:31