Python无法调用函数

时间:2018-12-02 13:00:50

标签: python python-3.x function class

我正在用python开发石头剪刀布,但被卡住了。 我做了一个在(石头,剪刀和剪刀)之间循环的课程,我希望计算机知道它是先前的游戏。 例如(第一轮电脑玩石头,下一轮电脑应该玩纸)
但我不知道如何调用学习功能使其工作

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

def move(self):
    return 'rock'

def learn(self, my_move, their_move):
    self.my_move = my_move
    self.their_move = their_move

def beats(one, two):
return ((one == 'rock' and two == 'scissors') or
        (one == 'scissors' and two == 'paper') or
        (one == 'paper' and two == 'rock'))

class Game:
def __init__(self, p1, p2):
    self.p1 = p1
    self.p2 = p2

def play_round(self):
    move1 = input("Pick something!\n")
    move2 = self.p2.move()
    print(f"Player 1: {move1}  Player 2: {move2}")
    self.p1.learn(move1, move2)
    self.p2.learn(move2, move1)
    if beats(move1, move2):
        self.p1.score += 1
        print ("You win")
        print ("Human score = " + str(self.p1.score) + " "  + "Computer score = " + str(self.p2.score) ) 
    elif beats(move2,move1):
        self.p2.score += 1
        print ("Computer wins")
        print ("Human score = " + str(self.p1.score) + " "  + "Computer score = " + str(self.p2.score) ) 
    else:
        print ("Draw")
        print ("Human score = " + str(self.p1.score) + " "  + "Computer score = " + str(self.p2.score) )

def play_game(self):
    print("Game start!")
    for round in range(3):
        print(f"Round {round}:")
        self.play_round()
    print("Game over!")

class human_player(Player):
def move(self):
   return input("Pick something!\n")

class randomplayer(Player):
def move(self):
    return random.choice(moves)

class repeat(Player):
def move(self):
    return 'rock'

class cycleplayer(Player):
def move(self):
    # calling my_move from the Player class
    if self.learn.my_move == "rock" or "paper" or "scissors" :
        return 'rock'

    elif  self.their_move == 'rock':
        return "paper"   

    elif self.their_move == 'paper':
        return "scissors"  

    elif self.their_move == 'scissors':
        return "rock"

if HumanPlayer_choice == "cycle" :
game = Game(Player(), cycleplayer())
game.play_game()

这是我遇到的错误。

  

发生异常:AttributeError'function'对象没有   属性“ my_move”

我知道我需要利用带有学习功能的init函数来使其工作,但是我不确定如何。

2 个答案:

答案 0 :(得分:3)

问题出在这条线上:

if self.learn.my_move == "rock" or "paper" or "scissors" :

learn函数没有名为my_move的属性。你的意思可能是

if self.my_move == "rock" or self.my_move == "paper" or self.my_move == "scissors" :

请注意,您必须在self.my_move =="paper"之前添加"scissors";否则,其评估方式如下:

if (self.my_move == "rock") or ("paper") or ("scissors"):

并且由于非空字符串始终被评估为True,因此这种if情况变得毫无用处。


如@DmitryErohin所述,有一种更好的方法可以实现,而无需重复自己:

if (self.my_move in ("rock", "paper", "scissors")):

这不那么冗长,可读性更强

答案 1 :(得分:0)

据我所知,您的代码中存在一些问题。请根据您的代码查看以下示例。我无法遵循某些逻辑,因此它可能无法完全按照您的要求运行。建议:

  • 因为您只想存储cycle_player动作的前一动作,所以将其存储在Cycle对象(实例)中而不是Player上
  • 随着move方法的变化,它的实现特定于子类(例如human_player,random_player,cycle_player)
  • 某些方法比静态方法要好,而不是在每个实例方法中都重新创建

    import random
    
    class Player:
        def __init__(self):
            self.score = 0
    
    class Game:
        def __init__(self, p1, p2):
            self.p1 = p1
            self.p2 = p2
    
        @staticmethod
        def check_result(a, b): #Return win, draw, loose for a over b
            if (a == b):
                return 'draw'
            if (a == 'rock' and b == 'scissors') or (a == 'scissors' and b == 'paper') or (a == 'paper' and b == 'rock'):
                return 'win'
            return 'loose'
    
        def play_round(self):
            #move1 = input("Pick something!\n")
            move1 = self.p1.move()
            move2 = self.p2.move()
            print(f"Player 1: {move1}  Player 2: {move2}")
            result = Game.check_result(move1, move2) # a over b
            if result == 'win':
                self.p1.score += 1
                print ("You win")
            elif result == 'loose':
                self.p2.score += 1
                print ("Computer wins")
            else:
                print ("Draw")
            print ("Human score = " + str(self.p1.score) + " "  + "Computer score = " + str(self.p2.score))
    
        def play_game(self):
            print("Game start!")
            for round in range(3):
                print(f"Round {round + 1}:")
                self.play_round()
            print("Game over!")
    
    class human_player(Player):
        def move(self):
            return input("Pick something!\n") #TODO validate input
    
    class random_player(Player): #Option in game for computer to make random moves
        def move(self):
            return random.choice(["scissors","paper","rock"])
    
    class repeat_player(Player): #Option
        def move(self):
            return 'rock'
    
    class cycle_player(Player):
        def __init__(self):
            self.previous_move = None
            super().__init__()
    
        def move(self):
            # calling my_move from the Player class
            if self.previous_move is None :
                next_move = 'rock'
            elif  self.previous_move == 'rock':
                next_move = "paper"
            elif self.previous_move == 'paper':
                next_move = "scissors"  
            elif self.previous_move == 'scissors':
                next_move = "rock"
            self.previous_move = next_move
            return next_move
    
    #game = Game(human_player(), random_player())
    #game = Game(human_player(), repeat_player())
    game = Game(human_player(), cycle_player())
    game.play_game()