在Python中更新函数内部的局部变量

时间:2020-03-13 05:33:58

标签: 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。我知道这是因为对于play_round函数的每次迭代play_game函数中的for循环将p1_scorep2_score的值重置为零,但我不知道如何阻止这种情况的发生。任何建议将不胜感激。 program output

1 个答案:

答案 0 :(得分:0)

问题在于p1_Scorep2_Scoreplay_round中的 local 变量。因此,每次调用此函数时,都会得到这些变量的 new 实例。而且,您总是设置

p1_Score = 0
p2_Score = 0
play_round

。因此,在函数结束时,任何分数都不会大于1。

要对此进行补救,请使用self.p1_Scoreself.p2_Score使这些变量成为实例变量,并将0初始化移动到游戏类的__init__函数中。或者,将得分设为Player类的类变量。