[英]Updating local variables inside a function in Python
我正在學習 python 並即將完成一個程序,在兩個玩家之間運行三輪石頭剪刀布游戲,並在每輪結束時更新玩家分數並將其顯示在屏幕上:
import random
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
moves = ['rock', 'paper', 'scissors']
"""#!/usr/bin/env python3
import random
"""This program plays a game of Rock, Paper, Scissors between two Players,
and reports both Player's scores each round."""
moves = ['rock', 'paper', 'scissors']
"""The Player class is the parent class for all of the Players
in this game"""
class Player:
def move(self):
return 'rock'
def learn(self, my_move, their_move):
pass
def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
(one == 'scissors' and two == 'paper') or
(one == 'paper' and two == 'rock'))
class RandomPlayer(Player):
def move(self):
return random.choice(moves)
class Game:
def __init__(self, p1, p2):
self.p1 = p1
self.p2 = p2
def keep_p1_score(self, p1_Score):
return p1_Score
def play_round(self):
move1 = self.p1.move()
move2 = self.p2.move()
p1_Score = 0
p2_Score = 0
print(f"Player One played: {move1} Player Two played: {move2}")
if beats(move1, move2) == True:
print('**Player One wins**')
p1_Score += 1
elif beats(move2, move1) == True:
print('**Player Two wins**')
p2_Score += 1
else:
print('**TIE**')
print(f'Score: Player One: {p1_Score} Player Two: {p2_Score}')
self.p1.learn(move1, move2)
self.p2.learn(move2, move1)
def play_game(self):
print("Game start!")
for round in range(3):
print(f"Round {round + 1}:")
self.play_round()
print("Game over!")
if __name__ == '__main__':
game = Game(RandomPlayer(), RandomPlayer())
game.play_game()
問題是當我運行代碼時,它不會更新玩家分數。 正如您在輸出的這張圖片中看到的,即使玩家 2 贏得了第二輪和第三輪,他在第三輪結束時的得分仍然是 1 而不是 2。我知道這是因為對於內部 for 循環中play_round
函數的每次迭代play_game
函數p1_score
和p2_score
的值重置為零,但我不知道如何阻止這種情況發生。 任何建議將不勝感激。 程序輸出
問題是, p1_Score
和p2_Score
是局部變量play_round
。 所以每次你調用這個函數時,你都會得到這些變量的一個新實例。 此外,你總是設置
p1_Score = 0
p2_Score = 0
在play_round
。 因此,在函數結束時,任何分數都不會大於 1。
為了解決這個問題,使用self.p1_Score
和self.p2_Score
使這些變量成為實例變量,並將 0 初始化移動到游戲類的__init__
函數中。 或者,將分數Player
類的類變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.