如何让代码问另一个问题并存储最后一个问题

how to make code ask another question and store last one

我在学校做一个项目,要求我在 python 中做一个音乐测验,它读取一个文件,显示歌曲每个单词的首字母和艺术家(例如 Dave F F) .在我的文件中,我有一个包含 10 首歌曲名称的列表,其中 python 随机获取一行并进行显示。它必须来自一个文件(我的是记事本) 用户必须有 2 次机会猜出歌曲的名称,如果他们不这样做,那么游戏就结束了。我遇到的问题是我无法让我的代码问另一个问题,并存储最后一个问题,这样它就不会再问了(例如,如果第一个问题是 Dave 和 F F,我希望它不再出现) .如果能向我展示如何让 python 显示排行榜,我将不胜感激。答案可以是经过改进的完整代码,因为我不擅长缩进和将代码放在正确的位置。

我已经给了用户 2 次正确播放歌曲的机会,如果他们不正确,程序就会结束,但不会循环到开头。

import random

with open("songlist.txt", "r") as songs_file:
    with open("artistlist.txt", "r") as artists_file:
        songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
                             for (song, artist) in zip(songs_file,     artists_file)]

random_song, random_artist = random.choice(songs_and_artists)
songs_intials = "".join(item[0].upper() for item in random_song.split())


print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)


nb_tries_left = 3
guess = input("Guess the name of the song! ")
nb_tries_left -= 1

finished = False
while not finished:
    answer_found = (guess == random_song)
    if not answer_found:
        guess = input("Nope! Try again! ")
        nb_tries_left -= 1
    elif answer_found:
        print("The songs' initials are", songs_intials, "and the name of the artist is", random_artist)

    finished = (answer_found or nb_tries_left <= 0) 

if answer_found:

歌曲首字母为LT,歌手姓名为Fredo 猜歌名!像那样 歌曲的首字母是 LT,艺术家的名字是 Fredo 做得好!

Python 然后就没有再问了,不知道会不会又是那个问题。

故意弄错会输出这个:

The songs' initials are CS and the name of the artist is 50 Cent
Guess the name of the song! candysong
Nope! Try again! carpetshop
Nope! Try again! coolsong
Sorry, you've had two chances. Come back soon!
>>> 

首先你想获得 2 首独特的歌曲。为此,您可以使用 random.sample。对于您的用例,它是

indexes = random.sample(range(len(songs_and_artists)), 2) # 2 random songs (sampling without replacement)
# song 1
random_song, random_artist = songs_and_artists[indexes[0]]
# song 2
random_song, random_artist = songs_and_artists[indexes[1]]

此外,我建议您将代码放入函数中,并在每首选定的歌曲中使用它。

为了在每场比赛中提出不止一个问题,您必须这样做:

with open("songlist.txt", "r") as songs_file:
        with open("artistlist.txt", "r") as artists_file:
            songs_and_artists = [(song.rstrip('\n'), artist.rstrip('\n'))
                            for (song, artist) in zip(songs_file,     artists_file)]

def getSongAndArtist():
    randomIndex = random.randrange(0, len(songs_and_artists))
    return songs_and_artists.pop(randomIndex)


while(len(songs_and_artists) > 0):
    random_song, random_artist = getSongAndArtist()
    #play game with the song

您将歌曲列表保存在 python 列表中,并在每轮随机弹出一首,只要您有更多歌曲可以播放。

对于排行榜,您必须在开始游戏之前询问用户名并保存用户名列表及其分数,然后选择排名靠前的用户名。你还应该弄清楚如何给用户评分