def minimax(state, depth, alpha, beta, maximizingPlayer, current_board): if is_game_over(current_board) or depth == 0 or len( state.__dict__['children']) == 0: return state tree = state.fill( current_board, maximizingPlayer, depth - 1) # crear el árbol de nodos llenos con scores y movements if maximizingPlayer: maxEval = NEGATIVE_INF for child in tree: evaluation = minimax(child, depth - 1, alpha, beta, True, current_board) maxEval = max(maxEval, evaluation.get_score()) alpha = max(alpha, evaluation.get_score()) if beta <= alpha: break child.set_move(maxEval, evaluation.__dict__['movement']) return child else: minEval = POSITIVE_INF for child in tree: evaluation = minimax(child, depth - 1, alpha, beta, False, current_board) minEval = min(minEval, evaluation.get_score()) beta = min(beta, evaluation.get_score()) if beta <= alpha: break child.set_move(minEval, evaluation.__dict__['movement']) return child
def try_newgame(tweet): """ Process a single attempted new game. :param tweet: The tweet to be processed as new game. :type tweet: Tweepy.Status, dict :return: The resulting new game, or None if no new game made. :rtype: None, ConnectFourGame """ if tweet.in_reply_to_status_id is None: # not reply to another tweet if tweet.text.split(" ")[1] == "new": # second word is 'new' user1 = tweet.user.screen_name # TWO PLAYER GAME if len(tweet.entities[u'user_mentions']) > 1: user2 = tweet.entities[u'user_mentions'][1][u'screen_name'] newgame = ConnectFourGame.new_game(get_next_game_id(), user1, user2, int(tweet.id_str)) log("Created two player game: " + newgame.game_to_string()) return newgame # ONE PLAYER GAME if tweet.text.split(" ")[2] == "singleplayer": user2 = " mimimax_ai_alpha" newgame = ConnectFourGame.new_game(get_next_game_id(), user1, user2, int(tweet.id_str)) newgame.play_turn(int(tweet.id_str), minimax(newgame, 3)) log("Created one player game: " + newgame.game_to_string()) return newgame
def oneMoveGame(currentGame, depth): if currentGame.pieceCount == 42: # Is the board full already? print 'BOARD FULL\n\nGame Over!\n' sys.exit(0) #currentGame.aiPlay() # Make a move (only random is implemented) search_Tree = minimax(currentGame, depth) move = search_Tree.makeDecision() result = currentGame.playPiece(move) GameOperations(currentGame, move) currentGame.gameFile.close() # not sure if this should be here or not
def play(self, board): print("{} move : ".format(self.name)) tempBoard = copy.deepcopy(board) node = Node(self.level, 1, board, self.color) dropColNum = minimax(node, self.level, 1) tempBoard.Update(dropColNum%board.getHeight(), self.color) #for child in node.children: # if child.getValue() == dropColNum: # board = child.getBoard() # break return tempBoard
def testMinimax_Game(): #max_depth = 5 moves = 1 verbose = True list_depth = [] list_size = [] list_count = [] list_finalScore = [] list_Obs_BF = [] list_Exp_BF = [] list_nc = [] size_board = [(2, 1), (3, 1), (3, 2), (4, 2), (5, 3), (6, 4)] maxdepth = [1, 2, 3, 4, 5, 6, 7, 8] f = open('output_exper_grad_Minimax3.txt', 'w') for i in maxdepth: #alg = lambda game, state: minimax(game, state, max_depth=i) f.write(f'Depth is {i}\n') for size, count in size_board: mg = MancalaGame(size, count) initstate = mg.initial() list_depth.append(i) list_size.append(size) list_count.append(count) fs, _, nc = minimax(mg, initstate, max_depth=i) optimal_bf, effective_bf = branchFactorCalculation(nc, i) list_finalScore.append(fs) list_Obs_BF.append(optimal_bf) list_Exp_BF.append(effective_bf) list_nc.append(nc) #utilityScore,nc = palyGrad(mg, alg, moves=moves, verbose=False) #fs = play_minimax_ab(mg, max_depth=i, moves=moves, verbose=True) f.write(f'Size of board Size: {size} Count: {count}\n') f.write(f'Final Score is: {fs}\n') f.write(f'Node Count is: {nc}\n') f.write(f'Branch factor using formula (N+1)/d is: {optimal_bf}\n') f.write( f'Branch factor effective using formula newton is : {effective_bf}\n' ) pdData = pd.DataFrame(np.column_stack([ list_depth, list_size, list_count, list_finalScore, list_nc, list_Obs_BF, list_Exp_BF ]), columns=[ 'Depth', 'Size', 'Count', 'FinalScore', 'Node Count', 'Observer_BF', 'Exp_BF' ]) writer = pd.ExcelWriter('MinimimaxBF.xlsx', engine='xlsxwriter') pdData.to_excel(writer, 'Sheet1') writer.save()
def try_playturn(tweet, doc): """ Process a single tweet as an attempted move on an open game. :param tweet: The tweet to be processed as an attempted move on an open game. :type tweet: Tweepy.Status, dict :param doc: The database item storing the game onto which the turn is played. :type doc: dict :return: The resulting game after the move is played, or None if move not played. :rtype: ConnectFourGame, None """ game = ConnectFourGame.game_from_string(doc["game"]) active_user = game.user2 if game.user1_is_playing == 1: active_user = game.user1 move_index = 2 if game.user1 == game.user2 or game.user2 == " mimimax_ai_alpha": move_index = 1 tweet_text = tweet.text.split(" ") if len(tweet_text) >= move_index + 1: column_played = tweet_text[move_index] if any(column_played == s for s in ["1", "2", "3", "4", "5", "6", "7"]): if (tweet.user.screen_name == active_user) & game.can_play( int(column_played)): # PLAY TURN game.play_turn(int(tweet.id_str), int(column_played)) log(active_user + " played a " + column_played + " resulting in game: " + game.game_to_string()) if game.user2 == ' mimimax_ai_alpha': ai_move = minimax(game, 3) game.play_turn(int(tweet.id_str), ai_move) log("mimimax_ai_v1 played a " + str(ai_move) + " resulting in game: " + game.game_to_string()) return game
def interactiveGame(currentGame, depth): # Fill me in while not currentGame.pieceCount == 42: if currentGame.currentTurn == 1: user_Move = input("Enter the column [1-7] where you would like to play : ") if not 0 < user_Move < 8: print "Invalid column number!" continue if not currentGame.playPiece(user_Move - 1): print "This column is full!" continue try: currentGame.gameFile = open("humanplayer.txt", "w") except: sys.exit("error opening the file") GameOperations(currentGame, user_Move - 1) elif not currentGame.pieceCount == 42: search_Tree = minimax(currentGame, depth) move = search_Tree.makeDecision() result = currentGame.playPiece(move) try: currentGame.gameFile = open("computerplayer.txt", "w") except: sys.exit("Error opening file") GameOperations(currentGame, move) currentGame.gameFile.close() # not sure if this should be here or not if currentGame.player1Score > currentGame.player2Score: print "Player 1 wins" elif currentGame.player2Score > currentGame.player1Score: print "Computer wins" else: print "Draw"
def play(data): print(data) CURRENT_GAME_ID = data['game_id'] PLAYER_TURN_ID = data['player_turn_id'] av_pos = get_available_positions(data['board']) movement = [] if len(av_pos) == 1: movement = av_pos[0] else: maximizingPlayer = True if PLAYER_TURN_ID == 1 else False root = Node() root.create_children(TREE_DEPTH) alg = minimax(root, TREE_DEPTH, NEGATIVE_INF, POSITIVE_INF, maximizingPlayer, data['board']) movement = alg.__dict__['movement'] print("Movement made: " + str(movement), '\n') sio.emit( 'play', { 'tournament_id': TOURNAMENT_ID, 'player_turn_id': PLAYER_TURN_ID, 'game_id': CURRENT_GAME_ID, 'movement': movement })
def playminimax(lis): currentColor = 1 nextColor = 2 movesRemaining = 1 while AnyMove(lis, currentColor) == True: templis = deepcopy(lis) minimaxe = minimax(templis, currentColor, movesRemaining) doMove(lis, minimaxe) (currentColor, nextColor) = (nextColor, currentColor) print("coins remaining:", currentColor, "=", countt(lis, currentColor)) print(nextColor, "=", countt(lis, nextColor)) movesRemaining = movesRemaining - 1 if movesRemaining == 0: return (lis, countt(lis, 1), countt(lis, 2)) return (lis, countt(lis, 1), countt(lis, 2))
path, states = astar_search(graph.getVertex('S'), 'G', graph) print("Q1.2 -- A* Search:") print("States Expanded:[", end='') for state, weight in states.items(): print("'", state, "', ", end="", sep="") print("\b\b]\nPath Returned: [", end='') for state, time in path.items(): print("'", state.getName(), "', ", end="", sep='') print("\b\b]\n") ####################3 ## Q3: Adversarial Search ## 1: values = [3, 10, 2, 9, 10, 7, 5, 9, 2, 5, 6, 4, 2, 7, 9, 1] treeDepth = math.log(len(values), 2) value, path = minimax(0, 0, True, values, treeDepth, []) print("Q3.1 -- Adversarial Search with Minimax") print("Output Path: ", path) print("Output Value: ", value, "\n") ## 3: valueab = minimaxab(values, 0, True, treeDepth, 0, [], 10000, -10000) print("Q3.3 -- Adversarial Search with Minimax & Alpha-Beta Pruning") print("Output Value: ", valueab)
def get_move(self): return minimax(self._board, self._depth, self._major, self._heuristic)[1]
def ai_vs_ai(board, player_turn, depth=5, evaluation_function1=3, evaluation_function2=3): game_over = False rounds = 0 turn = player_turn decision_times0 = [] decision_times1 = [] while not game_over: if len(board.get_valid_locations()) == 0: label = pygame.font.SysFont("monospace", 24).render("DRAW!", 0, board.white) board.screen.blit(label, (40, 10)) pygame.display.update() game_over = True if turn == 0 and not game_over: start_time0 = time.time() # if rounds == 0 or rounds == 1: # column = random.randint(0, 6) # else: #column, minimax_score = minimax_alpha_beta(board, depth, -math.inf, math.inf, True, 1, evaluation_function1) column, minimax_score = minimax(board, depth, True, 1, evaluation_function1) if board.is_empty(column): pygame.time.wait(500) row = board.get_next_row(column) board.place_piece(row, column, 1) if board.check_win(1): label = pygame.font.SysFont("monospace", 24).render( "Red (AI) wins!", 1, board.red) board.screen.blit(label, (40, 10)) pygame.display.update() game_over = True end_time0 = time.time() decision_time = end_time0 - start_time0 decision_times0.append(decision_time) print('Red (AI) decision time (seconds):', decision_time) board.print_board() board.draw_board(1, 2) rounds += 1 turn += 1 turn = turn % 2 if turn == 1 and not game_over: start_time1 = time.time() # if rounds == 0 or rounds == 1: # column = random.randint(0, 6) # else: #column, minimax_score = minimax_alpha_beta(board, depth, -math.inf, math.inf, True, 2, evaluation_function2) column, minimax_score = minimax(board, depth, True, 2, evaluation_function2) if board.is_empty(column): pygame.time.wait(500) row = board.get_next_row(column) board.place_piece(row, column, 2) if board.check_win(2): label = pygame.font.SysFont("monospace", 24).render( "Yellow (AI) wins!", 2, board.yellow) board.screen.blit(label, (40, 10)) pygame.display.update() game_over = True end_time1 = time.time() decision_time1 = end_time1 - start_time1 decision_times1.append(decision_time1) print('Yellow (AI) decision time (seconds):', decision_time1) board.print_board() board.draw_board(1, 2) rounds += 1 turn += 1 turn = turn % 2 if game_over: pygame.time.wait(5000) print('Average decision time of Red (AI) (seconds) :', sum(decision_times0) / len(decision_times0)) print('Average decision time of Yellow (AI) (seconds) :', sum(decision_times1) / len(decision_times1))
def human_vs_ai(board, player_turn, depth=4, evaluation_function=3): game_over = False turn = player_turn decision_times0 = [] decision_times1 = [] while not game_over: if len(board.get_valid_locations()) == 0: label = pygame.font.SysFont("monospace", 24).render("DRAW!", 0, board.white) board.screen.blit(label, (40, 10)) pygame.display.update() game_over = True for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEMOTION: pygame.draw.rect(board.screen, board.gray, (0, 0, board.width, board.square_size)) position_x = event.pos[0] if turn == 0: pygame.draw.circle( board.screen, board.red, (position_x, int(board.square_size / 2)), board.radius) else: pygame.draw.circle( board.screen, board.yellow, (position_x, int(board.square_size / 2)), board.radius) pygame.display.update() if event.type == pygame.MOUSEBUTTONDOWN: print('------------------------------') pygame.draw.rect(board.screen, board.gray, (0, 0, board.width, board.square_size)) position_x = event.pos[0] column = int(math.floor(position_x / board.square_size)) if turn == 0: if board.is_empty(column): row = board.get_next_row(column) board.place_piece(row, column, 1) if board.check_win(1): label = pygame.font.SysFont("monospace", 24).render( "Red wins!", 1, board.red) board.screen.blit(label, (40, 10)) game_over = True board.print_board() board.draw_board(1, 2) turn += 1 turn = turn % 2 if turn == 1 and not game_over: start_time0 = time.time() #column, minimax_score = minimax_alpha_beta(board, depth, -math.inf, math.inf, True, 2, evaluation_function) column, minimax_score = minimax(board, depth, True, 1, evaluation_function) if board.is_empty(column): pygame.time.wait(500) row = board.get_next_row(column) board.place_piece(row, column, 2) if board.check_win(2): label = pygame.font.SysFont("monospace", 24).render( "Yellow (AI) wins!", 2, board.yellow) board.screen.blit(label, (40, 10)) game_over = True end_time0 = time.time() decision_time = end_time0 - start_time0 decision_times0.append(decision_time) print('(AI) decision time (seconds):', decision_time) board.print_board() board.draw_board(1, 2) turn += 1 turn = turn % 2 if game_over: print('Average decision time of (AI) (seconds) :', sum(decision_times0) / len(decision_times0)) pygame.time.wait(3000)
def minimaxMoveFunction(state): _, move = minimax(state, 9, -inf, inf) return move