简体   繁体   English

当我猜第一个答案错误但随后输入正确答案时,我的代码不会重复

[英]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当用户输入他们的用户名和密码时,您需要检查

  1. Does logins contain the key that is the given username? logins是否包含作为给定用户名的密钥?
  2. Is the value at that key equal to the given password?该键的值是否等于给定的密码?
#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.

相关问题 我究竟做错了什么? 我的代码告诉我猜测不正确,当它正确时 - What am I doing wrong? My code tells me the guess is incorrect, when it is correct Python:为什么我的代码一直告诉我答案是错误的,而事实并非如此? - Python: why does my code keep telling me the answer is wrong when its not? 我正在尝试简化我的代码,但答案是错误的 - I'm trying simplify my code but the answer is wrong 当用户回答错误时,如何使我的代码不生成新的整数? - How do I make my code not generate new integers when the user gets the answer wrong? Caesar Cipher:为什么在用作测试的打印值之间有正确的答案时,我的程序为什么返回错误答案? - Caesar Cipher: why does my program returns the wrong answer, when between the printed values used as tests there is the correct one? Python 2.7 代码没有给出正确答案 - Python 2.7 code does not give correct answer 我的python程序说答案是不正确的? - My python program is saying the answer is not correct when it is? 我在我的块中添加了一行代码,虽然我得到的答案是正确的,但我不明白那条简单的行是做什么的 - I added a line of code to my block, although the answer I get is correct I don't understand what that simple line does 我的Python类在我调用时无法正确回答 - My Python class does not answer right when I call it Advent of Code 2022 第 8 天,第 1 部分。我的答案与预期的答案不符,但我得到的样本是正确的。 迷失方向 - Advent of Code 2022 Day 8, Part 1. My answer is not matching the answer expected, but I am getting the sample correct. Lost on where to go
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM