繁体   English   中英

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

[英]how to make code ask another question and store last one

我在学校做一个项目,要求我用python进行音乐测验,读取文件,显示歌曲和歌手(例如Dave FF)每个单词的首字母。 在我的文件中,我列出了10首歌曲的名称,其中python获取一条随机行并进行显示。 它必须来自文件(我的是记事本)。用户必须有2次机会猜测歌曲的名称,如果没有,则游戏结束。 我遇到的问题是我无法让我的代码问另一个问题,并存储最后一个被问到的位置,这样它就不会再问它了(例如,如果第一个问题是Dave和FF,我希望它不再出现) 。 如果向我展示了如何让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 Guess,歌曲的名字! 就像那首歌的首字母是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列表中,然后在每轮随机弹出一首,只要您有更多的歌曲可以播放。

对于排行榜,您必须在启动游戏之前要求用户名,并保存用户名及其分数列表,然后选择排名靠前的用户名。 您还应该弄清楚如何给用户打分

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM