如何修复“猜谜游戏”Python

2024-10-03 19:25:06 发布

您现在位置: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

Tags: txtcloseinputifsongartistrandomopen
1条回答
网友
1楼 · 发布于 2024-10-03 19:25:06
  • 您需要将random.randint范围更改为random.randint(0,len(song.readlines())-1),以便从所有列出的歌曲中选择一个随机索引,并对艺术家执行相同的操作。

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

  • for rangerange(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

相关问题 更多 >