[英]my code does not repeat when I guess the first answer wrong but then enter the correct answer
This is basically a guessing game where a file with data has random names of songs chosen from it and the player has to guess them with only the artist and first letter of each word of the song title given.这基本上是一个猜谜游戏,其中包含数据的文件具有从中选择的随机歌曲名称,玩家必须仅凭艺术家和给出的歌曲标题的每个单词的首字母来猜测它们。 However when the player guesses wrongly at first and then correct the code just stops instead of asking for a new answer and picking a new song.
然而,当玩家一开始猜错然后更正代码时,代码就会停止,而不是要求新的答案并选择一首新歌。 How can this be fixed?
如何解决这个问题? Any suggestions would be appreciated.
任何建议,将不胜感激。 Also how can data in a file be sorted into a hierarchy and then displayed in that hierarchy?
此外,如何将文件中的数据分类到层次结构中,然后在该层次结构中显示?
import random
score = 0
#player details
username = input("Please enter a username:")
password = input("Please enter a password:")
#player authentication
player_usr = input("Enter your username")
player_pass = input("Enter your password")
if player_usr == username:
if player_pass == password:
start = True
else:
print("Acces denied. Wrong details.")
start = False
else:
print("Acces denied. Wrong details")
start = False
#main game loop
while start == True:
t = True
while t == True:
lines = open("music").read().splitlines()
myline =random.choice(lines) #choosing from file
chosensong = myline
artist = chosensong.rsplit(",", 1)[1]
print(artist) #getting artist name
song = chosensong.rsplit(",",1)[0]
for word in song.split():
print(word[0]) #getting letters of song name
t = False
target = chosensong.rsplit(",",1)[0]
guess = None
guesses = 0
answer = input("Enter guess:")
guess = answer.lower()
# points and authentcation of answer
while guesses != 2:
if guess == target:
if guesses == 0:
score = score + 3
print("you were correct")
break
else:
score = score + 1
print("you were right")
break
else:
print("please try again")
guesses = guesses + 1
answer = input("Enter guess:")
guess = answer.lower()
start = False
print(score)
You probably won't have a single user, so I modified your login logic to allow multiple users.您可能没有一个用户,所以我修改了您的登录逻辑以允许多个用户。 This code contains a
logins
dictionary, where the keys are usernames, and values are passwords.此代码包含一个
logins
字典,其中键是用户名,值是密码。 When the user enters their username and password, you need to check当用户输入他们的用户名和密码时,您需要检查
logins
contain the key that is the given username? logins
是否包含作为给定用户名的密钥?#player details
logins = {"admin": "admin", "lab_gaming": "abcd0123", "new_user": "password"}
while True:
try:
# Get auth details from user
player_usr = input("Enter your username")
player_pass = input("Enter your password")
# Check if auth details are in the logins dict
assert logins[player_usr] == player_pass
except (KeyError, AssertionError):
# If the player_usr doesn't exist, then a KeyError is thrown
# If the player_usr exists but the password is wrong, an AssertionError is thrown by the assert line
print("Invalid login details")
else:
# else is run if the try block completes without an error
# If no error, auth succeeded, so break out of the while True loop
break
Next, let's read the song list.接下来,我们来看看歌单。 This needs to be done only one time because presumably the song list won't change every time you play the game.
这只需要做一次,因为大概每次玩游戏时歌曲列表都不会改变。
# Read the file containing songs ONCE, since there's no need to read it multiple times per game
# If this is a csv file, consider using the csv module to read it
song_list = []
with open("music.txt") as f:
for line in f:
song_details = line.strip().lower().rsplit(",", 1)
song_list.append(song_details)
# Now song_list is a list of lists. Each element of song_list is another list, which contains the song name and artist.
Next, we can start the game.接下来,我们可以开始游戏了。 Let's define a variable
play
which will tell us whether the user wants to play another game.让我们定义一个变量
play
来告诉我们用户是否想玩另一个游戏。 By default, this is true.默认情况下,这是真的。 Let's also initialize
score
to zero.让我们也将
score
初始化为零。
play = True
score = 0
Now, you need to keep playing while the play
variable is true.现在,您需要在
play
变量为真时继续播放。 In each game, you randomly select a song at the start.在每场比赛中,你随机 select 一首歌曲开始。 You can do this without reading the entire file, because remember we read the file already.
您可以在不读取整个文件的情况下执行此操作,因为请记住我们已经读取了该文件。
I modified your code that prints the song hint slightly.我修改了稍微打印歌曲提示的代码。
Next, we start the turns
loop.接下来,我们开始
turns
循环。 Remember, the while loop can take any condition, so we're going to loop while turns < 3
.请记住,while 循环可以接受任何条件,因此我们将循环 while
turns < 3
。 (Of course, we initialized turns = 0
before we start this loop). (当然,我们在开始这个循环之前初始化了
turns = 0
)。
Inside this loop, we can ask the user for their guess, and if the guess is correct, add to their score and break out of the inner loop.在这个循环中,我们可以询问用户的猜测,如果猜测正确,则添加到他们的分数并跳出内部循环。 If their guess is wrong, increment
turns
and continue the loop.如果他们的猜测是错误的,则增量
turns
并继续循环。 Remember, we already check turns < 3
, so we don't need yet another check here.请记住,我们已经检查了
turns < 3
,所以我们不需要在这里再次检查。
Now you're finally out of the inner loop.现在你终于脱离了内循环。 This means the game ended due to a correct guess, or the user ran out of turns.
这意味着游戏因正确猜测而结束,或者用户用尽了回合。 In either case, you can ask them if they want to play another game, and set the value of
play
accordingly.无论哪种情况,您都可以询问他们是否想玩另一个游戏,并相应地设置
play
的价值。 If play
is set to False
, then the loop will automatically end.如果
play
设置为False
,则循环将自动结束。
while play: # No need to == True, because that's what a boolean comparison does
# Randomly select a song/artist combo, then automatically unpack them into separate variables
selected_song, selected_artist = random.choice(lines)
# Print selected artist
print(f"Artist: {selected_artist}")
# Select the first character of each word in the song
# Then join all of them with a space in between
song_clue = " ".join(word[0] for word in selected_song.split())
# Print song clue
print(f"Song: {song_clue}")
turns = 0
while turns < 3: # This automatically stops your turn when turns >= 3
guess = input("Enter guess: ").lower()
if guess == selected_song:
print("You were correct!")
if turns == 0:
score += 3
else:
score += 1
break # This breaks the inner while loop
else:
print("Please try again.")
turns += 1
# Now you're out of the inner loop, so you can ask the user if they want to play again
play = input("Play again (y/n)? ").lower() == 'y'
print(f"Your score was {score}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.