如何在 Python 中的 if/elif 语句中添加和更新变量?



除了(current_space)没有更新(current_space+=rolled_dice)之外,一切都有效。它只是更新为 (rolled_dice) 值。 是什么原因造成的,是否有更好的做法可以在这里实施。喜欢上课?

from random import randint
finish_line = 20
player_1 = raw_input('Enter player 1 name: ')
player_2 = raw_input('Enter player 2 name: ')    
print('nWelcome ' + player_1 + ' and ' + player_2)
print('nLet's Play!n')

def roll_1():
current_space1 = int()
#print(current_space1)
roll_dice = raw_input(player_1 + ' roll dice? y or n: ')
if roll_dice == 'y':
rolled_dice = (randint(1,6))
print(player_1 + ' ' + 'rolled a ' + str(rolled_dice))
if current_space1 != finish_line:
current_space1 += rolled_dice
#print(current_space1)
roll_2()
elif current_space1 == finish_line:
print('You are the winner ' + player_1 + '!')
elif roll_dice == 'n':
print('Thanks for playing')
else:
print('Invalid entry')

def roll_2():
current_space2 = int()
roll_dice = raw_input(player_2 + ' roll dice? y or n: ')
if roll_dice == 'y':
rolled_dice = (randint(1,6))
print(player_2 + ' ' + 'rolled a ' + str(rolled_dice))
if current_space2 != finish_line:
current_space2 += rolled_dice
roll_1()
elif current_space2 == finish_line:
print('You are the winner ' + player_2 + '!')
elif roll_dice == 'n':
print('Thanks for playing')
else:
print('Invalid entry')
roll_1() 

current_space1current_space2都是局部变量 - 它们是在函数进入时创建和初始化的,并且仅在函数上下文中可用,一旦您离开函数或进入另一个函数,它们就不可用。如果您希望它们在函数外部可用(并在多个函数调用中递增),则需要全局声明它们:

finish_line = 20
player_1 = raw_input('Enter player 1 name: ')
player_2 = raw_input('Enter player 2 name: ')
current_space1 = 0
current_space2 = 0
# ...
def roll1():
global current_space1  # instead of current_space1 = int()
# rest of the function ...
def roll2():
global current_space2  # instead of current_space2 = int()
# rest of the function ...

话虽如此,使用全局变量不被认为是一种好的做法。例如,请参阅这篇文章及其答案。

current_space1current_space2分别是函数roll_1roll_2局部变量。这些变量实际上按行递增... += rolled_dice但在下一行中,您将重新调用该函数,该函数又具有自己的范围,其中current_space开头为零。这将持续到您达到最大递归深度。

相反,您可以global这些变量,并使用global关键字对其进行标记。

另一种方法是创建一个Player

class Player:
def __init__(self):
self.current_space = 0

并且仅将一个roll函数与两个作为参数传递给该roll函数的Player实例一起使用。然后,您将递增player.current_space += rolled_dice

例如:

def roll(active_player, passive_player):
...
if active_player.current_space != finish_line:
active_player.current_space += rolled_dice
roll(passive_player, active_player)

顺便说一句,当您检查玩家是否达到目标时,您可能还需要重新考虑,因为在您的示例中,您首先要求滚动,然后玩家可以从之前已经获得的分数中获胜。

最新更新