简体   繁体   English

Python琐事游戏

[英]Python trivia game

I want to make a trivia game using 2 arrays or lists. 我想使用2个数组或列表制作一个琐事游戏。 How do you link items from one list to another? 如何将项目从一个列表链接到另一个列表? I have this code: 我有以下代码:

import random

mylist = ['A','B','C']
answer = ['1','2','3']
value = random.choice(mylist)
print (value)
input()
mylist.remove(value)
value = random.choice(mylist)
mylist.remove(value)
print (value)
input()
value = random.choice(mylist)
print(value)
mylist.remove(value)

I know how to randomly choose a variable from mylist (the questions) but how do I represent A as 1 and have the user input 1 for it to be correct? 我知道如何从mylist (问题)中随机选择一个变量,但是我如何将A表示为1并让用户输入1以使其正确呢?

How do I link one list to another and make a trivia game? 如何将一个列表链接到另一个列表并制作琐事游戏? It needs to ask a question and then the user inputs answer. 它需要提出一个问题,然后用户输入答案。 If correct, they get a point and after 4 questions it asks them if they want to play again and then 4 new questions for 3 rounds and there has to be a score kept of how many they got right. 如果是正确的话,他们会得到一个分数,并在问了四个问题后询问他们是否要再次比赛,然后问三个回合中有四个新问题,并且必须记分他们正确的分数。

This program is right on the borderline between being acceptable as a list/dict of lists and being better off written with classes. 该程序正处于可接受的列表/字典列表和更好的用类编写之间的边界。 If there's any possibility that it will grow, you'd probably want to reorganize it as an object oriented program (OOP), like this: 如果有增长的可能,您可能希望将其重组为面向对象程序(OOP),如下所示:

import sys
import random

class Question(object):
    def __init__(self, question, answer, options):
        self.question = question
        self.answer = answer
        self.options = options

    def ask(self):
        print self.question + "?"
        for n, option in enumerate(self.options):
            print "%d) %s" % (n + 1, option)

        response = int(sys.stdin.readline().strip())   # answers are integers
        if response == self.answer:
            print "CORRECT"
        else:
            print "wrong"

questions = [
    Question("How many legs on a horse", 4, ["one", "two", "three", "four", "five"]),
    Question("How many wheels on a bicycle", 2, ["one", "two", "three", "twenty-six"]),

    # more verbose formatting
    Question(question="What colour is a swan in Australia",
             answer=1,
             options=["black", "white", "pink"]),    # the last one can have a comma, too
    ]

random.shuffle(questions)    # randomizes the order of the questions

for question in questions:
    question.ask()

That puts the logic of how the data structure is used closer to where the data structure is defined. 这使如何使用数据结构的逻辑更接近于定义数据结构的位置。 Also (addressing your original question), it's easy to associate questions with answers because they're no longer in separate lists. 另外(解决您的原始问题),将问题与答案相关联也很容易,因为它们不再位于单独的列表中。

There's no incentive not to do this because Python doesn't require much extra work to make a class. 没有动机不这样做,因为Python不需要太多额外的工作就可以创建一个类。 This is approximately the same length as the dict-of-lists solution (on which it was based), and is arguably easier to read, closer to you had in mind before you sat down to start programming. 这与列表字典解决方案(基于它的解决方案)大致相同的长度,并且可以说更易于阅读,离您坐下来开始编程之前就更近了。 I often use classes even in four-line programs: OOP doesn't have to be a big deal. 即使在四行程序中,我也经常使用类:OOP没什么大不了的。

Edit: You can manipulate the list of class instances the same way you'd manipulate a list of integers or strings. 编辑:您可以像处理整数或字符串列表一样地操作类实例列表。 For example, 例如,

del questions[0]

removes the first item from the list, 从列表中删除第一项,

questions.append(Question("What is a new question", 1, ["This is."]))

adds a new question to the end of the list, pop lets you use the list as a stack, etc. (See a Python tutorial for more.) If you want to remove specific questions using list's remove method, rather than removing it by index (what del does), then you'll need to tell Python what it means for two questions to be the same. 在列表末尾添加一个新问题,使用pop可以将列表用作堆栈,等等。(有关更多信息,请参见Python教程。)如果要使用列表的remove方法删除特定问题,而不是通过索引删除它( del做了什么),那么您需要告诉Python两个相同的问题意味着什么。

Try adding these two methods to the class: 尝试将两个方法添加到类中:

    def __eq__(self, other):
        return self.question == other.question

    def __repr__(self):
        return "<Question: %s? at %0x>" % (self.question, id(self))

The first defines two Question instances to be equal if their question strings are the same. 如果它们的问题字符串相同,则第一个将两个Question实例定义为相等。 You could extend the definition by also requiring their answers to be the same, but you get the idea. 您可以通过要求它们的答案相同来扩展定义,但是您明白了。 It allows you to do this: 它允许您执行以下操作:

questions.remove(Question("How many legs on a horse", 0, []))

to remove the legs-on-a-horse question. 消除马腿问题。

The second pretty-prints the question objects on the Python command-line, so that you can see what you're doing when you experiment with these commands. 第二篇在Python命令行上漂亮地打印了问题对象,以便您在试验这些命令时可以看到自己在做什么。 The best way to learn is by trial-and-error, and this makes trial-and-error more productive. 最好的学习方法是通过反复试验,这使反复试验更具生产力。

Use an array of arrays. 使用数组数组。

One array per question 每个问题一个数组

In each array the first element is the question, the second the index of the correct answer and the remainder are the possible answer options 在每个数组中,第一个元素是问题,第二个元素是正确答案的索引,其余元素是可能的答案选项

I have not randomized the questions as you can already do this 我尚未将问题随机化,因为您已经可以这样做

import sys

questions=[
  ['How many legs on a horse',4, 1, 2, 3, 4 ,5],
  ['How many wheels on a bicycle',2,'one','two','three','twenty six'],
  ['What colour is a swan in Australia',1, 'black', 'white', 'pink']
  ]

for ask in questions:
    print ask[0]+'?'
    n = 1
    for options in ask[2:]:
        print "%d) %s" % (n,options)
        n = n + 1
    response = sys.stdin.readline().strip()
    if int(response) == ask[1]:
        print "CORRECT"
    else:
        print "wrong"

Alternatively, in line with suggestion below in comments (thanks Don) use a dict. 或者,根据下面注释中的建议(感谢Don)使用dict。

import sys

questions = [
  {
  'question': 'How many legs on a horse',
  'answer': 4,
  'options': [1, 2, 3, 4, 5]},
  {
   'question': 'How many wheels on a bicycle',
   'answer': 2,
   'options': ['one', 'two', 'three', 'twenty six']},

  {
   'question': 'What colour is a swan in Australia',
   'answer': 1,
   'options': ['black', 'white', 'pink']}
  ]

for ask in questions:
    print ask['question'] + '?'
    n = 1
    for options in ask['options']:
        print "%d) %s" % (n, options)
        n = n + 1
    response = sys.stdin.readline().strip()
    if int(response) == ask['answer']:
        print "CORRECT"
    else:
        print "wrong"

hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM