整数变量不起作用,即使我在它们上使用全局变量也没有回来,我甚至试过返回它并没有用。经过多次尝试错误测试和解决问题的尝试后,我找到了问题的根源,但我不知道如何解决它。因为这段代码很长(714)我不会提出全部内容。相反,我会提出所需的内容。
def plrcheck():
global pwr
global typ
if prsna in [sf1, sf2, sf3, sa1, sa2, sa3, sw1, sw2, sw3, se1, se2, se3]:
pwr = 5
elif prsna in [sf4, sf5, sa4, sa5, se4, se5, sw4, sw5]:
pwr = 8
elif prsna in [sf6, sa6, sw6, se6]:
pwr = 11
if prsna in [sf1, sf2, sf3, sf4, sf5, sf6]:
typ = 'Fire'
elif prsna in [sw1, sw2, sw3, sw4, sw5, sw6]:
typ = 'Water'
elif prsna in [sa1, sa2, sa3, sa4, sa5, sa6]:
typ = 'Air'
elif prsna in [se1, se2, se3, se4, se5, se6]:
typ = 'Earth'
pygame.display.flip()
def oppcheck():
global optyp
global oppwr
if opp in [sf1, sf2, sf3, sa1, sa2, sa3, sw1, sw2, sw3, se1, se2, se3]:
oppwr = 5
elif opp in [sf4, sf5, sa4, sa5, se4, se5, sw4, sw5]:
oppwr = 8
elif opp in [sf6, sa6, sw6, se6]:
oppwr = 11
if opp in [sf1, sf2, sf3, sf4, sf5, sf6]:
optyp = 'Fire'
elif opp in [sw1, sw2, sw3, sw4, sw5, sw6]:
optyp = 'Water'
elif opp in [sa1, sa2, sa3, sa4, sa5, sa6]:
optyp = 'Air'
elif opp in [se1, se2, se3, se4, se5, se6]:
optyp = 'Earth'
pygame.display.flip()
def atkchk(x):
plrcheck()
oppcheck()
if x == 'opponent':
if optyp == 'Air':
if typ == 'Earth':
oppwr += 2
elif optyp == 'Water':
if typ == 'Fire':
oppwr += 2
elif optyp == 'Fire':
if typ == 'Air':
oppwr += 2
elif optyp == 'Earth':
if typ == 'Water':
oppwr += 2
elif x == 'player':
if typ == 'Air':
if optyp == 'Earth':
pwr += 2
elif typ == 'Water':
if optyp == 'Fire':
pwr += 2
elif typ == 'Fire':
if optyp == 'Air':
pwr += 2
elif typ == 'Earth':
if optyp == 'Water':
pwr += 2
while pwr - oppwr < 0:
discard = int(math.fabs(pwr-oppwr)/2)+1
#Selection Process of Discarding for Player
while pwr - oppwr > -1:
discard = int(math.fabs(pwr-oppwr)/2)+1
#Selection process of discarding for opponent
win()
def game():
while matchLoop:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_x:
plrcheck()
oppcheck()
atkchk('player')
问题出现在[atkchk(x)],它会忘记[pwr和oppwr]变量,即使它外面仍在工作。顺便说一句,这应该不需要pygame知识,只需简单的python知识即可。我已经分配了所有其他变量,但这不是问题的一部分(直到我在[atkchk(x)]中添加它才完全正常工作,并且我已将其缩小到我之前所说的内容。无论如何你知道要解决这个问题吗?
答案 0 :(得分:1)
在函数顶部添加对这些变量的全局引用,如
def atkchk(x):
global pwr
global oppwr
Python允许您使用与全局变量同名的本地范围变量。这可能会有点混乱。如果您没有告诉函数您打算使用已定义的全局作用域pwr
和oppwr
,那么对这些名称的任何赋值都将创建一个同名的本地作用域变量,从而有效地隐藏全局函数中的变量。
查看此帖子的答案:Use of Global Keyword in Python
第二个和第三个答案谈论你遇到的问题。