我正在尝试创建这个游戏的猜测歌曲,但它将不允许我有超过一首歌曲,即使我改变了范围,我还想知道如何添加代码来做评分,为猜测写的歌曲。在
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
您需要将
random.randint
范围更改为random.randint(0,len(song.readlines())-1)
,以便从所有列出的歌曲中选择一个随机索引,并对艺术家执行相同的操作。更好的方法是使用
random.choice
从列表中选择一个随机元素。for range
range(0,1)
将导致循环只运行一次,相应地更新范围您可以使用
with
关键字自动关闭文件,而不是显式关闭它。因此,根据以上更改,修复的代码可能看起来像
相关问题 更多 >
编程相关推荐