2017-02-12 73 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

我該如何接受?完成了!謝謝 –