这是我的代码的一部分:
def dice_game():
dice_window = Tk()
dice_window.geometry('450x450')
player1_score = 0
player2_score = 0
def player1_turn():
player1_num1 = random.randint(1, 6)
player1_num2 = random.randint(1, 6)
player1_score = player1_num1 + player1_num2
player1_total = player1_num1 + player1_num2
if (player1_total % 2) == 0:
player1_score = player1_score + 10
else:
player1_score = player1_score - 5
player1_result = Label(dice_window, text = ( "Player 1 got", player1_num1, "and", player1_num2, "and their total score is:", player1_score))
player1_result.pack()
for x in range(1, 6):
player1_turn()
我尝试将循环放在player1_turn()函数和dice_game()函数中,但结果始终相同。我如何保持2位玩家的得分而无需在本节每次循环5次后重置它们?
答案 0 :(得分:1)
由于您是在player1_score
函数主体内分配player2_score
和player1_turn()
,因此它使player1_score & player2_score
是函数player1_turn()
的局部变量。
因此,如果您使用的是python3
,则可以使用player1_score
关键字明确地将player2_score
和nonlocal
定义为非局部变量。
代码将如下所示。
def dice_game():
dice_window = Tk()
dice_window.geometry('450x450')
player1_score = 0
player2_score = 0
def player1_turn():
nonlocal player1_score, player2_score
player1_num1 = random.randint(1, 6)
player1_num2 = random.randint(1, 6)
player1_score = player1_num1 + player1_num2
player1_total = player1_num1 + player1_num2
if (player1_total % 2) == 0:
player1_score = player1_score + 10
else:
player1_score = player1_score - 5
player1_result = Label(dice_window, text = ( "Player 1 got", player1_num1, "and", player1_num2, "and their total score is:", player1_score))
player1_result.pack()
for x in range(1, 6):
player1_turn()
# END
对于python 2,有一种解决方法,您可以将player1_score & player2_score
存储在score = {'player1_score': 0, 'player2_score': 0}
这样的字典中
答案 1 :(得分:1)
让我们分解一下。我可以看到player1_turn()
是嵌套的,因为您想访问dice_window
。但是有更好的方法!
首先分离功能。 player1_turn
需要一个骰子窗口,看起来您想要保存的东西是player1_score
,因此我们将其返回。
def player1_turn(dice_window):
player1_num1 = random.randint(1, 6)
player1_num2 = random.randint(1, 6)
player1_score = player1_num1 + player1_num2
player1_total = player1_num1 + player1_num2
if (player1_total % 2) == 0:
player1_score = player1_score + 10
else:
player1_score = player1_score - 5
player1_result = Label(dice_window, text = ( "Player 1 got", player1_num1, "and", player1_num2, "and their total score is:", player1_score))
player1_result.pack()
return player1_score
现在进入游戏:
def dice_game():
dice_window = Tk()
dice_window.geometry('450x450')
# we're not using x, so we should make it clear that this is a loop of 5
scores = []
total = 0
for x in range(5):
player1_score = player1_turn(dice_window)
# now what to do with the score?
scores.append(player1_score) # save it?
print(player1_score) # print it?
total += player1_score # add it up
print(scores)
print(total)
答案 2 :(得分:0)
好吧,原样的代码在dice_game()函数中包含了for循环。 如您所见,您正在将该函数的分数声明为零。因此,要调用for循环,您需要调用dice_game(),它将得分再次重置为零。
也许您应该尝试在函数dice_game()之外使用for循环,最后,分数将被保留。或者您可以接受声明
player1_score = 0
player2_score = 0
在函数外部,作为全局变量。