def train(self, player=Player('X'), board=Board(), previous_key=None, previous_move=None): memory_key = Model.MEMORY_KEY.format(player.char, board.key) if memory_key not in self.memory.keys(): self.memory[memory_key] = { 'weights': [0, 0, 0, 0, 0, 0, 0, 0, 0], 'childs': [], 'previous_key': previous_key, 'previous_move': previous_move } self._set_all_related(memory_key) for index in range(9): _board = Board(board.key) done, winner = _board.add(player, index) if done: if winner: self._set_weight( memory_key, index, 3.0 if winner.char == 'X' else -2.0 if winner.char == 'O' else -1.0) if winner is False: self.train( player=Player('X' if player.char == 'O' else 'O'), board=_board, previous_key=memory_key, previous_move=index) if not previous_key: self._cleanup()