如何修复“猜歌游戏” python

时间:2019-05-08 11:07:35

标签: python

我正在尝试创建一个用于猜歌曲的游戏,但是即使我更改了范围,它也不允许我播放超过一首歌曲,我也想知道如何添加代码来猜测乐曲。

import random

for x in range(0,1):
    randNum = int(random.randint(0,1))

    song = open("Songs.txt", "r")
    songname = str(song.readlines()[randNum])
    print(songname[0])
    song.close()

    artist = open("Artists.txt", "r")
    artistname = artist.readlines()[randNum]
    print(artistname[0])
    artist.close()
    y = 0

    songGuess = input("What is the song called?")
    while(y<=2):
        if songGuess == songname:
            print("Answer correct!")
            break
        else:
            y = y + 1
            songguess = input("Incorrect! Try again:")

        if y == 2:
            print("GAME OVER")
            break

1 个答案:

答案 0 :(得分:0)

  • 您需要将random.randint的范围更改为random.randint(0,len(song.readlines())-1),以便从所有列出的歌曲中选择随机索引,并对歌手做同样的事情。

  • 更好的方法是使用random.choice从列表中选择一个随机元素。

  • 您对范围range(0,1)的使用将使您的循环仅运行一次,并相应地更新范围

  • 您可以使用with关键字自动关闭文件,而不必显式关闭文件。

因此,根据上述更改,固定代码可能看起来像

import random

num_attempts = 10
#Run loop for num_attempts times
for x in range(0, num_attempts):

    songname = ''
    artistname = ''
    #Use with to open file
    with open('Songs.txt') as song:
        #Read all songs into a list
        songs = song.readlines()
        #Choose a random song
        songname = random.choice(songs)
        print(songname)

    with open('Artists.txt') as artist:
        # Read all artists into a list
        artists = artist.readlines()
        # Choose a random artist
        artistname = random.choice(artists)
        print(artistname)

    y = 0

    #Play your game
    songGuess = input("What is the song called?")
    while(y<=2):
        if songGuess == songname:
            print("Answer correct!")
            break
        else:
            y = y + 1
            songguess = input("Incorrect! Try again:")

        if y == 2:
            print("GAME OVER")
            break