2017-02-12 35 views
0

我在做一个简单的琐事游戏。我在下面提示用户并以交互方式显示问题。根据条件从运行总量中增加或减少一个变量

我想添加一个“分数”功能。每当我尝试初始化“count”为0或类似的内容时,我的Question类,并增加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() 

我想添加类似

count = 0 
if response in self.answer: 
    count += self.value 
else: 
    count -= self.value 
print (count) 

我觉得我在与局部/全局变量的麻烦。

+1

如果你可以有计数作为类,即一部分的单人游戏的事'self.count = 0' 或者,如果你想使用全局, – Nullman

+0

感谢声明为全球'全球count',我认为以下方法最适合我的需求和理解! –

回答

0

每次调用“ask”时,都会将count重置为0.此外count也是局部变量,因为它只在ask()中定义。您需要计算该类的成员并将其初始化为0.然后,您可以像使用其他类变量一样使用它。见下面的代码。

def __init__(self, question, answer, value): 
self.question = question 
self.answer = answer 
self.value = value 
self.count=0 

def ask(self): 
print (self.question + "?") 
response = input().strip() 
if response in self.answer: 
    x = random.randint(0,3) 
    print (positives[x]) 
    print ("Answer is" + " " + self.answer) 
    self.count += self.value 


... etc 

但我不满意自己的,包括你的分数你的问题类中的逻辑 - 因为比分涉及到许多问题,因此将需要以全局在你的班上或外部类的定义,因此当你打电话给你的方法要求它应该返回是否回答是否为真或假的值,如下所示

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) 
    return self.value 
    else: 
    y = random.randint(0,3) 
    return 0 

然后你做下面的事情;

score=0 
for question in questions: 
    print ("Continue?") 
    choice = input() 
    if choice in ["quit", "no", "exit", "escape", "leave"]: 
    break 
    score+=question.ask() 
+0

所以我这样做 –

+0

嗨user32329如果这个或任何答案已解决您的问题,请考虑通过点击复选标记来接受它。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 –

+0

我该如何接受?完成了!谢谢 –

相关问题