我正在尝试编写一个游戏,该游戏显示歌曲的首字母和歌手,并要求用户两次尝试猜测歌曲。但是,当我尝试验证答案正确(始终是正确的)时,它仍然说错了。
我的代码如下:
import random
for x in range(0, 13):
randNum = int(random.randint(0, 13))
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)
artist.close()
songGuess = input("What is the song called?")
for x in range(0,1):
if songGuess == songname:
print("Answer correct!")
else:
songguess = input("Incorrect! Try again:")
x = x + 1
if x == 2:
print("GAME OVER")
break
x = x+1
if x == 13:
break
quiz()
应该发生的情况是,当仅给出歌曲名称和艺术家的首字母时,用户应该尝试两次来猜测歌曲的名称,如果在游戏结束前无法猜出歌曲,则应该结束
答案 0 :(得分:0)
尝试这个。代替for循环,而是使用while循环。
通常,当您有计数器时,最好使用while
循环。因此,在这种情况下,由于您要检查变量以运行一小部分代码y
次,因此while
循环是最好的。
import random
for x in range(0, 13):
randNum = int(random.randint(0, 13))
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)
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
quiz()
答案 1 :(得分:0)
我将按以下方式重写代码,但是可以使用许多不同的变体。
import random
# Set these to whatever makes sense for your use case.
max_turns = 5
max_guesses = 2
# Load these from wherever you want. This is just some dumb testing data.
songs = load_songs() # you'll need to write some code to do this
artists = load_artists() # you'll need to write some code to do this
for turn_counter in range(max_turns):
# Pick a random song:
randNum = int(random.randint(0, 11))
song_name = songs[randNum]
artistname = artists[randNum]
print()
print(song_name[0])
print(artistname)
# Prompt for a guess:
song_guess = input("What is the song called?\n> ")
# Let the user guess until they hit the max tries:
guess_counter = 0
correct_guess = False
while True:
if song_guess == song_name:
correct_guess = True
break
guess_counter += 1
if guess_counter>=max_guesses:
break
# Song wasn't guessed correctly and we haven't hit
# the max guesses yet, so try again:
song_guess = input("Incorrect! Try again:\n> ")
# We're out of the while loop, so either the song was guessed
# correctly, or we hit the max number of guesses. Find out which:
if correct_guess:
print("Answer correct!")
else:
print("GAME OVER")
break