开发者社区> 问答> 正文

我想创建一个问答游戏,从列表中选择随机问题而无需重复

此代码可让2个玩家从列表中回答一个随机问题,然后比较他们的得分。

问题:

  1. Questions keep repeating because of ` randint ` , tried using ` random.shuffle ` — no luck.
  2. If I input an answer that is on the answer list on different questions it still printing "correct" maybe because of this code ` if guess.lower() == answers[a].lower(): ` .
  3. I can't make it work that if an answer is wrong it will print "wrong". I tried adding this code and it works, but if I input the correct answer it still returns "wrong".

    elif guess.lower() != answers[a].lower(): print("Wrong!") break

我的代码

from random import randint
print("====== Quiz  Game ======")
print("")
questions = [
             "What star is in the center of the solar system?:",
             "What is the 3rd planet of the solar system?:",
             "What can be broken, but is never held?:",
             "What part of the body you use to smell?:",
             "How many days in one year?:",
             "How many letters in the alphabet?:",
             "Rival of Intel?:",
             "No.8 element on periodic element?:",
             "What is the galaxy that contains our solar system?:",
             "What animal is the king of the jungle?:"
             ]
answers = [
           "Sun",
           "Earth",
           "Promise",
           "Nose",
           "365",
           "26",
           "AMD",
           "Oxygen",
           "Milky Way",
           "Lion"
           ]

p1score = 0
p2score = 0
def playerOne():
    global p1score
    for i in range(5):
        q = randint(0,9)
        guess = input(questions[q])
        for a in range(len(answers)):
            if guess.lower() == answers[a].lower():
                print("Correct!")
                p1score += 1
                break
            else:
                continue
    print("Your score is:",p1score)
    print("")

def playerTwo():
    global p2score
    for i in range(5):
        q = randint(0,9)
        guess = input(questions[q])
        for a in range(len(answers)):
            if guess.lower() == answers[a].lower():
                print("Correct!")
                p2score += 1
                break
            else:
                continue
    print("Your score is:",p2score)
    print("")

def quiz():
    global p1score
    global p2score
    print("======Student no.1======")
    playerOne()
    print("======Student no.2======")
    playerTwo()
    if p1score > p2score:
        print("Student 1 has the highest score!")
    elif p1score < p2score:
        print("Student 2 has the highest score!")
    elif p1score == p2score:
        print("Students are tied!")
    else:
        print("Invalid")

quiz()

问题1和2的图像

问题3的图片

问题来源:stackoverflow

展开
收起
is大龙 2020-03-25 00:13:47 630 0
1 条回答
写回答
取消 提交回答
  • 您应该将问题和答案放在一起,然后可以使用random.shuffle(list)来创建具有随机顺序的项目的列表。然后您可以对-loop使用普通的`来获取问题和答案-它们​​将以随机顺序出现,并且不会重复出现。

    您可以一起提问和回答,因此没有问题可以检查用户输入的正确答案。

    import random
    
    data = [
      ["What star is in the center of the solar system?:", "Sun"],
      ["What is the 3rd planet of the solar system?:","Earth"],
      ["What can be broken, but is never held?:", "Promise"],
      ["What part of the body you use to smell?:", "Nose"],
      ["How many days in one year?:","365"],
      ["How many letters in the alphabet?:", "26"],
      ["Rival of Intel?:", "AMD"],
      ["No.8 element on periodic element?:", "Oxygen"],
      ["What is the galaxy that contains our solar system?:","Milky Way"],
      ["What animal is the king of the jungle?:",  "Lion"],
    ]
    
    random.shuffle(data) # run only once 
    
    for item in data:
        print('question:', item[0])
        print('  answer:', item[1])
        print('---')
    
      • BTW:*您也可以这样写循环 for question, answer in data: print('question:', question) print(' answer:', answer) print('---')
    • *编辑:*工作代码 import random

      data = [ ["What star is in the center of the solar system?:", "Sun"], ["What is the 3rd planet of the solar system?:","Earth"], ["What can be broken, but is never held?:", "Promise"], ["What part of the body you use to smell?:", "Nose"], ["How many days in one year?:","365"], ["How many letters in the alphabet?:", "26"], ["Rival of Intel?:", "AMD"], ["No.8 element on periodic element?:", "Oxygen"], ["What is the galaxy that contains our solar system?:","Milky Way"], ["What animal is the king of the jungle?:", "Lion"], ]

      TODO: read data from text file or CSV file

      def player(number, data): score = 0

      print("====== Student no.", number, "======")
      
      for question, answer in data:
          guess = input(question)
          if guess.lower() == answer.lower():
              print("Correct!\n")
              score += 1
          else:
              print("Wrong\n")
      
      print("Your score is: ", score, "\n")
      
      return score
      

      --- main ---

      random.shuffle(data) # run only once score1 = player(1, data) #score1 = player(1, data[:5])

      random.shuffle(data) # next player will have questions in different order score2 = player(2, data) #score1 = player(2, data[:5])

      #score3 = player(3, data) # you can have more players (but you could use list for scores) #score4 = player(4, data) # you can have more players (but you could use list for scores)

      best_score, best_player = max([score1, 1], [score2, 2], [score3, 3], [score4, 4])

      results_in_order = sort( [[score1, 1], [score2, 2], [score3, 3], [score4, 4]], reverse=True )

      if score1 > score2: print("Student 1 has the highest score!") elif score1 < score1: print("Student 2 has the highest score!") else: print("Students are tied!")

    回答来源:stackoverflow

    2020-03-25 00:13:57
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
4个迭代,从批量交...1573957773.pdf 立即下载
用计算和数据去改变整个世界 立即下载
《解决方案A4折页-游戏_复制》 立即下载