我试图在一个也非常简单的抽认卡游戏中添加一个非常简单的得分函数,但我无法使游戏记住包含得分的变量的值(它始终将其重置为0)。分数显然取决于用户的诚实度(这很好),猜测单词时必须按下“ Y”。
DataFrame
一些注意事项: 我知道现在代码中仅实现了积极的分数,但我认为最好是逐步进行并首先进行工作。
答案 0 :(得分:2)
每次在def add_score()
中将变量初始化为0
。另外,它是一个局部变量,这意味着您只能在函数add_score()
中引用它。这意味着每次退出该函数时,该变量都会被完全删除。
您需要创建一个全局变量,即在游戏开始时且在函数外部将其初始化为0。然后在add_score
内部,您只需引用全局变量并增加它,而无需每次都对其进行初始化:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
global pos_score
pos_score += 1
print(pos_score)
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
请注意,我跳过了不相关的功能。但是,通常这样更改变量的范围被认为是不好的做法。您应该做的是拥有一个类(对于本示例而言有点太复杂了)或返回要从add_score
添加的值并将该值添加到主循环中。这将是代码:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
#global pos_score
#pos_score += 1
#print(pos_score)
return 1
return 0
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
pos_score += add_score()
print(pos_score)
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')