我在做一个简单的小游戏。下面的内容提示用户并以交互方式显示一个问题。在
我想加入一个“得分”功能。每当我试图在我的Question
类中初始化一个“count”为0或类似值,并以value
中存储的值为增量,count
将保持为0。我有麻烦了。理想情况下,我希望在用户回答每个问题后打印分数。如果正确,将self.value
加到count
中,否则减去。在
import random
class Question(object):
def __init__(self, question, answer, value):
self.question = question
self.answer = answer
self.value = value
def ask(self):
print (self.question + "?")
count = 0
response = input().strip()
if response in self.answer:
x = random.randint(0,3)
print (positives[x])
print ("Answer is" + " " + self.answer)
else:
y = random.randint(0,3)
print (negatives[y])
print ("Answer is" + " " + self.answer)
question_answer_value_tuples = [('This author made a University of Virginia law professor the protagonist of his 2002 novel "The Summons"',
'(John) Grisham']
#there are a few hundred of these. This is an example that I read into Question. List of tuples I made from a jeopardy dataset.
positives = ["Correct!", "Nice Job", "Smooth", "Smarty"]
negatives = ["Wrong!", "Think Again", "Incorrect", "So Sorry" ]
questions = []
for (q,a,v) in question_answer_value_tuples:
questions.append(Question(q,a,v))
print ("Press any key for a new question, or 'quit' to quit. Enjoy!")
for question in questions:
print ("Continue?")
choice = input()
if choice in ["quit", "no", "exit", "escape", "leave"]:
break
question.ask()
我想加一些东西
^{pr2}$我想我在处理局部/全局变量时遇到了麻烦。在
每次你叫“询问”你都会将计数重置为0。count也是一个局部变量,因为它只在ask()中定义。您需要使count成为类的成员并将其初始化为0。然后可以像其他类变量一样使用它。参见下面的代码。在
但是我不满意你的逻辑,把你的分数包括在你的问题类-因为分数涉及很多问题,所以它需要在你的类中或类外进行全局定义,所以当你调用你的方法ask时,它应该返回答案是真是假还是值,就像这样
^{pr2}$然后你做以下事情
相关问题 更多 >
编程相关推荐