如何在while循环中使用字典?

亚当·布雷斯林

我正在尝试制作一个琐事游戏,这是我迄今为止的代码。我在增加此游戏的玩家分数时遇到问题。我正在使用 while 循环来尝试增加玩家的分数,如果玩家 1 的问题错了,那么轮到玩家 2 了,但我不知道如何在两者之间切换。我有一个“答案”变量,玩家将在其中输入值。在这个 while 循环中,我试图说当“答案”等于正确答案时;我希望您执行以下操作,当“答案”不等于答案时,请执行以下操作。我试图从我的答案字典中获取相应的值,但我不知道如何获取它。“answers [key]”给了我一个错误,我需要输入其他内容。

player_1_points = 0
player_1 = input("Enter in your name Player 1: ")

player_2_points = 0
player_2 = input("Enter in your name Player 2: ")

questions = {'one' : 'What is the tallest mountain in the world?'}

choices = {'a' : 'A. Mount Everest', 'b' : 'B. Mount St. Helens', 'c' : 'C. Mount Vesuvius', 'd' : 'D. K2'}

answers = {1 : {'Answer': 'A'}}

print(questions['one'])

print(choices['a'], choices['b'], choices['c'], choices['d'])

answer = str(input("Answer is: "))


while answer == answers[key] :
  if player_1 == answer :
    player_1_points += 1
    print("Correct Answer!")
    print(player_1, player_1_points)
    print(player_2, player_2_points)
    
  elif player_2 == answer :
    player_2_points += 1
    print("Correct Answer!")
    print(player_1, player_1_points)
    print(player_2, player_2_points)
  
while answer != answer[key] :
  if player_1 != answer :
    print("Incorrect, Player 2's Turn")
    print(answer)

  elif player_2 != answer :
    print("Incorrect, Player 1's turn")
    print(answer)
贵族骑士

抱歉,我更改了您的代码。

player_1_points = 0
player_1 = input("Enter in your name Player 1: ")

player_2_points = 0
player_2 = input("Enter in your name Player 2: ")

# now questions is a list of dictionaries
questions = [
    {
        'question': 'What is the tallest mountain in the world?',
        'option a': 'A. Mount Everest',
        'option b': 'B. Mount St. Helens',
        'option c': 'C. Mount Vesuvius',
        'option d': 'D. K2',
        'answer': 'A. Mount Everest'
    }
]

# you can add more questions to above list of questions


# loop through list of questions 
for question in questions:
    print(question['question'])
    print(question['option a'])
    print(question['option b'])
    print(question['option c'])
    print(question['option d'])

    # ask player 1 to enter their answer
    player_1_answer = input("Enter you answer Player 1 : ")
    if player_1_answer == question['answer']: 
        print('Correct Answer!')
        player_1_points += 1
    else:
        print('Incorrect Answer!')

    # ask player 2 to enter their answer
    player_2_answer = input("Enter you answer Player 2 : ")
    if player_2_answer == question['answer']:
        print('Correct Answer!')
        player_2_points += 1
    else:
        print('Incorrect Answer!')

# print scores for each player at the end
print(player_1, player_1_points)
print(player_2, player_2_points)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章