def dfs(board): mem = {hash_board(board)} # count = 1 # max_goal = sum(board[0]) stack = [[board, []]] while stack: board, solution = stack.pop(-1) # count += 1 # if count % 10000 == 0: # print(count, max_goal, len(mem)) # print_board(board) for b, move in list(valid_moves(board))[::-1]: if hash_board(b) in mem: continue if sum(b[0]) == 230: print(b[0]) return solution + [(move, b)] mem.add(hash_board(b)) # max_goal = max(sum(b[0]), max_goal) stack.append([b, solution + [(move, b)]])
def search(self, board, depth, player_num, heuristic): if player_num == 1: opp_num = 2 else: opp_num = 1 # Check if leaf if depth == 0 or len(board.valid_moves()) == 0 or board.check_win(player_num)[0] or board.check_win(opp_num)[0]: return heuristic(board, player_num) # Get all possible board states from the given board possible_moves = [] for col in board.valid_moves(): board_copy = copy.deepcopy(board) board_copy.add(col, player_num) possible_moves.append(board_copy) # Run search recursively h = float("-inf") for move in possible_moves: h = max(h, -self.search(move, depth - 1, opp_num, heuristic)) return h
def minimax(self, board, depth, player_num, heuristic): # Set player values if player_num == 1: opp_num = 2 else: opp_num = 1 # Start search for each valid move possible_moves = [float("-inf") for i in range(board.x_max)] for col in board.valid_moves(): board_copy = copy.deepcopy(board) board_copy.add(col, player_num) possible_moves[col] = -self.search(board_copy, depth - 1, opp_num, heuristic) # Take the move with the highest value h = max(possible_moves) move = possible_moves.index(h) print (move, h) return (move, h)
def random(self, board): moves = board.valid_moves() return random.choice(moves)