【问题标题】:I would like to create a quiz game that picks random question from list without repetition我想创建一个问答游戏,从列表中选择随机问题而不重复
【发布时间】:2020-06-20 08:24:42
【问题描述】:

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

问题:

  1. 由于randint,问题不断重复,尝试使用random.shuffle — 不成功。
  2. 如果我输入的答案在不同问题的答案列表中,它仍会打印“正确” 可能是因为这个代码if guess.lower() == answers[a].lower():
  3. 我不能让它工作,如果答案是错误的,它会打印“错误”。 我尝试添加此代码并且它有效,但如果我输入正确答案,它仍然返回“错误”。
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()

Image of Problem no.1 and 2

Image of Problem no.3

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读Why is "Can someone help me?" not an actual question?
  • 我会这样做,创建一个空列表 seen_questions 并将问题附加到列表中,因此每次随机选择一个问题时,请检查 seen_questions 如果问题已经被选中,则首先打印出问题。制作一个问题和答案字典,其中键=问题,值=答案。
  • 您可以在开始时使用random.shuffle(list) - 以随机顺序获取元素 - 稍后仅使用for-loop 从这个随机列表中获取问题。但是您必须将问题和答案放在一个列表中 - 将它们混在一起。

标签: python python-3.x list python-2.7 random


【解决方案1】:

9。编写一个简单的问答游戏,其中包含十个问题的列表和这些问题的答案列表。

游戏应该给玩家四个随机选择的问题来回答。它应该

逐一提问,并告诉玩家问题是否正确

错了。最后它应该打印出他们正确的四分之几。

question_prompts = [

["What color are apples?\n(a)Red/Green\n(b)Orange \n(c)Violet/Green\n(d)Black/Orange", "a"],

["What color are bananas?\n(a)Red/Green\n(b)Yellow \n(b)Orange \n(a)Violet/Green", 'b'],

["What Month is Christmas?\n(a)September \n(b)December \n(c)October \n(d)November", 'b'],

["What color are Rice?\n(a)Red/Green\n(b)Yellow\n(c)Red/Green\n(d)Yellow", 'b'],

["What animal can run faster than Lion?\n(a)Man\n(b)Dear\n(c)Red/Green\n(d)Yellow", 'b'],
     
["How many continents in the World ?\n(a) Seven\n(b) Nine\n(c)Red/Green\n(d)Yellow", 'a'],

["How many colors rainbow has?\n(a)Seven\n(b)Five\n(c)Red/Green\n(d)Yellow", 'a'],

["What is my name?\n(a) Nick\n(b)Chioma\n(c)Tiger\n(d)Greatness", 'a'],

["What year did Pandemic occur?\n(a)2020\n(b)2019\n(c)2021\n(d)2023", 'a'],

["How old is the earth approximately?\n(a)6b years\n(b)6.4b years\n(c)6b years\n(d)6.4b years", 'b']


]

count = 0


sample = sample(question_prompts, 4)

for i, j in sample:

    print(i)

    answer = input("Enter your answer: ").lower()

    if answer == j:

        count += 1

        print("Right, Your score: ", count)

        print('')

    else:

        print("Wrong, correct answer is: ", j)

        print()

print("You got", count, "out of", len(sample), "questions")

这对我有用。

【讨论】:

  • 如果您有新问题,请点击 按钮提出问题。如果有助于提供上下文,请包含指向此问题的链接。 - From Review
【解决方案2】:

您应该将问题和答案放在一起,然后您可以使用random.shuffle(list) 以随机顺序创建包含项目的列表。然后您可以使用普通的for-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('---')

顺便说一句:你也可以这样写循环

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!")

【讨论】:

  • 感谢您几乎完成所有工作的帮助,我仍在比较并尝试了解您的代码如何使其正常工作,顺便说一句,我是 python 新手,感谢您提供新知识.
  • 是否可以设定你只需要回答多少个问题,例如我只需要 5 个问题而不回答 10 个问题,例如 sample.random 的工作原理
  • for item in data[:5] ?
  • 或者您可以更改函数 def player(number, data) 以便运行 player(1, data[:5])player(2, data[5:]) - 所以玩家 1 获得前 5 个问题,玩家 2 获得其他 5 个问题。只需一个shuffle 即可为每个玩家使用不同的问题。
  • 删除其他random.shuffle后现在可以使用了
猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-06
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多