私は単純なトリビアゲームを作っています。以下では、ユーザーにプロンプトを表示し、インタラクティブな方法で質問を表示します。条件に基づいて実行中の合計から変数を加算または減算する
「スコア」機能を追加します。私が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()
私はローカル/グローバル変数とのトラブルを抱えていると思う
count = 0
if response in self.answer:
count += self.value
else:
count -= self.value
print (count)
のようなものを追加したいです。
その場合は、クラスすなわちの一部としてカウント数を持つことができ、シングルプレイヤーの事 'self.count = 0 ' か、グローバル使用したい場合は、グローバル'グローバルcount'として – Nullman
おかげで、それを宣言し、I下記の方法が私のニーズと理解に最も適していると思います! –