def ai(): """ Find best next move """ turn = deepcopy(session['turn']) game = deepcopy(session['board']) moves = [] print('Moves left:', empty_moves(game)) minimax(game, turn, moves) print('Best moves: ', moves) if turn == 'X': best_moves_ordered = sorted(moves, key=lambda x: list(x.values()), reverse=True) if len(moves) >= 0: for item in best_moves_ordered[0].keys(): session['best_move'] = item if turn == 'O': best_moves_ordered = sorted(moves, key=lambda x: list(x.values())) if len(moves) >= 0: for item in best_moves_ordered[0].keys(): session['best_move'] = item print('Best moves ordered: ', best_moves_ordered) print('Best move BOX: ', session['best_move']) return redirect(url_for('index'))
def getAIMove(data, definedDepth, maxDepth): #avoid aliasing the board that would cause massive problem board = copy.deepcopy(data.board.board) if data.isExpectimax: bestScore, bestMove = expectimax(board, data.rows, data.cols, data.baseNum, definedDepth, maxDepth) elif data.isMinimax: bestScore, bestMove = minimax(board, data.rows, data.cols, data.baseNum, definedDepth, maxDepth, False) #RL is off elif data.isRL: bestScore, bestMove = minimax(board, data.rows, data.cols, data.baseNum, definedDepth, maxDepth, True) #RL is on #print(bestScore, bestMove) if bestScore == -np.inf: data.isGameOver = True if bestMove == "Left": data.board.moveLeft() elif bestMove == "Right": data.board.moveRight() elif bestMove == "Up": data.board.moveUp() elif bestMove == "Down": data.board.moveDown() if data.isEvilMode: data.board.evilAIMove() else: data.board.placeRandomNumber()
def test_minimax_empty_board(self): '''Minimax scores for X and O for empty board. set fields of board: [ ][ ][ ] [ ][ ][ ] [ ][ ][ ] ''' self.assertEqual( minimax(self.board, Field.CROSS, Field.CIRCLE, 0, False), 0) self.assertEqual( minimax(self.board, Field.CROSS, Field.CIRCLE, 0, True), 0)
def test_minimax_not_win(self): '''Minimax scores for X and O - third move. set fields of board: [O][ ][ ] [ ][X][ ] [ ][ ][ ] ''' self.board[0] = Field.CIRCLE self.board[4] = Field.CROSS self.assertEqual( minimax(self.board, Field.CROSS, Field.CIRCLE, 0, False), 0) self.assertEqual( minimax(self.board, Field.CROSS, Field.CIRCLE, 0, True), 0)
def test_minimax_win(self): '''Minimax scores for X and O for win X or O. set fields of board: [O][ ][X] [O][X][ ] [ ][ ][O] ''' self.board[0] = Field.CIRCLE self.board[2] = Field.CROSS self.board[3] = Field.CIRCLE self.board[4] = Field.CROSS self.board[8] = Field.CIRCLE self.assertEqual( minimax(self.board, Field.CIRCLE, Field.CROSS, 0, False), -10) self.assertEqual( minimax(self.board, Field.CIRCLE, Field.CROSS, 0, True), 10)
def runAI(color): t1 = time.time() ai_move = ai.minimax(0, color, model.board, float("-inf"), float("inf")) print(ai_move.weight) t2 = time.time() print(t2-t1) #model.ttable.save() model.ttable.hashtable = {} ai_move.apply(model.board) redraw() return ai_move
def test_minimax_draw_game(self): '''Minimax scores for X and O for draw game - not empty field. set fields of board: [X][O][X] [O][X][X] [O][X][O] ''' self.board[0] = Field.CROSS self.board[1] = Field.CIRCLE self.board[2] = Field.CROSS self.board[3] = Field.CIRCLE self.board[4] = Field.CROSS self.board[5] = Field.CROSS self.board[6] = Field.CIRCLE self.board[7] = Field.CROSS self.board[8] = Field.CIRCLE self.assertEqual( minimax(self.board, Field.CROSS, Field.CIRCLE, 0, False), 0) self.assertEqual( minimax(self.board, Field.CROSS, Field.CIRCLE, 0, True), 0)
def main(): # single or 2-player mode mode = input("2-player mode? (Y/N): ") if mode.lower() == 'y': board = Board() while True: board.print_board() p1_move = int(input("Player 1, enter the column for your move: ")) board.move(PLAYER1_PIECE, p1_move - 1) if board.game_won(PLAYER1_PIECE): board.print_board() print("Game Over: Player 1 Wins") break board.print_board() print("-" * 45) p2_move = int(input("Player 2, Enter the column for your move: ")) board.move(PLAYER2_PIECE, p2_move - 1) if board.game_won(PLAYER2_PIECE): board.print_board() print("Game Over: Player 2 Wins") break print("-" * 45) # playing AI else: game_over = False board = Board() while not game_over: board.print_board() turn = 0 if turn == PLAYER1: p1_move = int(input("Player 1, enter the column for your move: ")) board.move(PLAYER1_PIECE, p1_move - 1) if board.game_won(PLAYER1_PIECE): board.print_board() print("Game Over: You Win!") game_over = True board.print_board() print("-" * 45) turn += 1 turn = turn % 2 if turn == AI and not game_over: col = minimax(board, 5, -math.inf, math.inf, True)[0] print(col, board.is_valid_location(col)) if board.is_valid_location(col): board.move(AI_PIECE, col) if board.game_won(AI_PIECE): board.print_board() print("Game Over: You lost.") game_over = True board.print_board() print("-" * 45) turn += 1 turn = turn % 2
def runAI(color): t1 = time.time() ai_move = ai.minimax(0, color, model.board, float("-inf"), float("inf")) if ai_move is None: raise Exception("No Possible Moves") # print(ai_move.weight) t2 = time.time() # print(t2-t1) model.ttable.hashtable = {} alphabet = ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'] old_x = ai_move.checker.x old_y = ai_move.checker.y new_x = ai_move.piece.x / 62.5 new_y = ai_move.piece.y / 62.5 print("Your Move --> " + alphabet[old_x] + str(old_y+1) + " to " + alphabet[int(new_x)] + str(int(new_y+1))) ai_move.apply(model.board) redraw(win2) return ai_move
def main(): board_size = 3 board = Board(board_size) player1, player2 = board.pieces print("TIC TAC TOE\nP1 is '" + player1 + "' \nP2 is '" + player2 + "'") while (True): board.draw() # Ask p1 p1_move = input("Player 1 where do you want to place your " + player1 + "? i.e 2,3:\n") p1_move = list(map(int, p1_move.split())) board.add_move(player1, p1_move[0], p1_move[1]) board.draw() winner = check_board(board) if (winner == player1 or winner == player2): print(winner + " won!") break elif (winner == cnsts.DRAW): print('Draw!') break # Ask p2 print("Player 2 plays...\n") score_res = minimax(board, board.pieces[1]) p2_move = score_res[0] board.add_move(player2, p2_move[0], p2_move[1]) # check board winner = check_board(board) if (winner == player1 or winner == player2): print(winner + " won!") break elif (winner == cnsts.DRAW): print('Draw!') break # end game or not board.draw()
def play(): user = None board = ai.initial() ai_turn = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(background_color) # start game if user is None: # title title = largeFont.render("Play Tic-Tac-Toe", True, (255, 255, 255)) title_rect = title.get_rect() title_rect.center = ((width / 2), (height / 3)) screen.blit(title, title_rect) # buttons X_button = pygame.Rect((width / 8), (height / 2), width / 4, 50) X_text = regularFont.render("Play X", True, gray) X_rect = X_text.get_rect() X_rect.center = X_button.center pygame.draw.rect(screen, black, X_button) screen.blit(X_text, X_rect) O_button = pygame.Rect(5 * (width / 8), (height / 2), width / 4, 50) O_text = regularFont.render("Play O", True, gray) O_rect = O_text.get_rect() O_rect.center = O_button.center pygame.draw.rect(screen, black, O_button) screen.blit(O_text, O_rect) # Check for user choice if pygame.mouse.get_pressed()[0]: mouse_pos = pygame.mouse.get_pos() if X_button.collidepoint(mouse_pos): time.sleep(0.5) user = ai.X elif O_button.collidepoint(mouse_pos): time.sleep(0.5) user = ai.O else: # game board tile_size = 80 tile_origin = (width / 2 - (1.5 * tile_size), height / 2 - (1.5 * tile_size)) # make board tiles = [] for i in range(3): row = [] for j in range(3): rect = pygame.Rect(tile_origin[0] + j * tile_size, tile_origin[1] + i * tile_size, tile_size, tile_size) pygame.draw.rect(screen, black, rect, 3) if board[i][j] is not None: color = black if board[i][j] == ai.O: color = gray else: color = black character = regularFont.render(board[i][j], True, color) characterRect = character.get_rect() characterRect.center = rect.center screen.blit(character, characterRect) row.append(rect) tiles.append(row) end_game = ai.terminal(board) player = ai.player(board) # draw title if end_game: # if game has ended winningPlayer = ai.winner(board) if winningPlayer is None: title = f"Game Over: Tie" else: title = f"Game Over: {winningPlayer} wins" elif user == player: # player's turn title = f"Play as {user}" else: # ai's turn title = f"AI is thinking..." title = largeFont.render(title, True, title_color) titleRect = title.get_rect() titleRect.center = ((width / 2), 30) screen.blit(title, titleRect) # AI's turn if user != player and not end_game: if ai_turn: time.sleep(0.5) move = ai.minimax(board) board = ai.result(board, move) ai_turn = False else: ai_turn = True # Player's turn if pygame.mouse.get_pressed( )[0] and user == player and not end_game: mouse = pygame.mouse.get_pos() for i in range(3): for j in range(3): if board[i][j] == ai.EMPTY and tiles[i][ j].collidepoint(mouse): board = ai.result(board, (i, j)) if end_game: againButton = pygame.Rect(width / 3, height - 65, width / 3, 50) againText = regularFont.render("Play Again", True, title_color) againRect = againText.get_rect() againRect.center = againButton.center pygame.draw.rect(screen, gray, againButton) screen.blit(againText, againRect) if pygame.mouse.get_pressed()[0]: mouse = pygame.mouse.get_pos() if againButton.collidepoint(mouse): time.sleep(0.3) user = None board = ai.initial() ai_turn = False pygame.display.flip()
def test_minimax(self): # Own Test board1 = chess.Board() pawn = board1.get_piece(chess.locate("e2")) knight = board1.get_piece(chess.locate("g8")) board1.move_piece(pawn, chess.locate("e4")) board1.move_piece(knight, chess.locate("f6")) _, move = ai.minimax(board1, 3, 1) self.assertEqual( move, chess.Move(board1.get_piece(chess.locate("f6")), chess.locate("e4"))) _, move = ai.minimax_with_pruning(board1, 3, 1, alpha=-1000, beta=1000) self.assertEqual( move, chess.Move(board1.get_piece(chess.locate("f6")), chess.locate("e4"))) _, move = ai.minimax(board1, 3, 0) _, move = ai.minimax_with_pruning(board1, 0, 3, alpha=-1000, beta=1000) board1.move_piece(board1.get_piece(chess.locate("f1")), chess.locate("a6")) _, move = ai.minimax(board1, 3, 1) self.assertEqual( move, chess.Move(board1.get_piece(chess.locate("b8")), chess.locate("a6"))) board1.move_piece(board1.get_piece(chess.locate("b8")), chess.locate("a6")) print(board1.compute_score(1)) print(move) # Puzzle 68960 from lichess.org board3 = Board(empty=True) board3.add_piece(locate_piece(ROOK, WHITE, locate("d1"))) board3.add_piece(locate_piece(ROOK, WHITE, locate("f1"))) board3.add_piece(locate_piece(KING, WHITE, locate("g1"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("b2"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("c2"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("a3"))) board3.add_piece(locate_piece(KNIGHT, BLACK, locate("e3"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("h3"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("c4"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("g4"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("b5"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("e5"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("f5"))) board3.add_piece(locate_piece(BISHOP, BLACK, locate("a6"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("b6"))) board3.add_piece(locate_piece(KNIGHT, WHITE, locate("d6"))) board3.add_piece(locate_piece(KNIGHT, WHITE, locate("e7"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("f7"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("g7"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("h7"))) board3.add_piece(locate_piece(ROOK, BLACK, locate("a8"))) board3.add_piece(locate_piece(KNIGHT, BLACK, locate("b8"))) board3.add_piece(locate_piece(ROOK, BLACK, locate("f8"))) board3.add_piece(locate_piece(KING, BLACK, locate("h8"))) print(board3) ai.minimax(board3, 4, WHITE) # Puzzle 68960 from lichess.org board3 = Board(empty=True) board3.add_piece(locate_piece(ROOK, WHITE, locate("d1"))) board3.add_piece(locate_piece(ROOK, WHITE, locate("f1"))) board3.add_piece(locate_piece(KING, WHITE, locate("g1"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("b2"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("c2"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("a3"))) board3.add_piece(locate_piece(KNIGHT, BLACK, locate("e3"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("h3"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("c4"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("g4"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("b5"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("e5"))) board3.add_piece(locate_piece(PAWN, WHITE, locate("f5"))) board3.add_piece(locate_piece(BISHOP, BLACK, locate("a6"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("b6"))) board3.add_piece(locate_piece(KNIGHT, WHITE, locate("d6"))) board3.add_piece(locate_piece(KNIGHT, WHITE, locate("e7"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("f7"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("g7"))) board3.add_piece(locate_piece(PAWN, BLACK, locate("h7"))) board3.add_piece(locate_piece(ROOK, BLACK, locate("a8"))) board3.add_piece(locate_piece(KNIGHT, BLACK, locate("b8"))) board3.add_piece(locate_piece(ROOK, BLACK, locate("f8"))) board3.add_piece(locate_piece(KING, BLACK, locate("h8"))) print(board3) board3.move_piece(locate_piece(ROOK, WHITE, locate("d1")), locate("d2")) print(board3) for move, board in board3.get_moves(BLACK): print(move) print(ai.minimax(board3, 3, BLACK)) print(BLACK)
if currentTurn == AI: aiTurn = None aiCoordsToChoose = [] for coord in planetCoords: chosenNumberProps = [] if ulamNumber.ulamNumbers(planetValues[coord]): chosenNumberProps.append(CONDITION_ULAM) if primeNumber.primeNumber(planetValues[coord]): chosenNumberProps.append(CONDITION_PRIME) if happyNumbers.happyNumbers(planetValues[coord]): chosenNumberProps.append(CONDITION_HAPPY) if currentCondition in chosenNumberProps: aiCoordsToChoose.append(coord) if currentIter != 2: a = time.time() aiTurn = ai.minimax(planetCoords, planetRadiuses, planetValues, planetOwner, 1) print(time.time() - a) # aiTurn = aiTurn[1] while True: if len(aiTurn[0]) == 0: aiTurn = None break index = ai.selectProper(aiTurn[0], AI) properProfit = aiTurn[0][index] properNode = aiTurn[1][index] if properNode in aiCoordsToChoose: if properNode is not None or len(aiTurn[0]): aiTurn = properNode break del aiTurn[0][index]
g_move_num += 1 g_valid_moves = get_valid_moves(g_board, cur_color) # Check if game is finished if len(g_valid_moves) == 0: if len(get_valid_moves(g_board, enemy_color(cur_color))) == 0: finish_game(g_board) break else: print('Currnet player have no more moves available') cur_color = enemy_color(cur_color) continue # Get choice if agent[cur_color] == "Naive": print("Naive AI Move") ai.start(g_move_num) valid_move = ai.naive(g_valid_moves) elif agent[cur_color] == "Minimax": print("Minimax AI Move") ai.start(g_move_num) print("color: ", cur_color) valid_move = ai.minimax(g_board, cur_color) else: print("Player Move") othello_board.refresh_board(g_board, g_valid_moves, cur_color) # valid_move = get_choice(g_valid_moves, cur_color) othello_board.start_listening(g_valid_moves, cur_color) valid_move = othello_board.get_choice() make_move(g_board, valid_move, cur_color) cur_color = enemy_color(cur_color)
screen.blit(label, (40, 10)) game_over = True #check for tie elif 0 not in board[ROW_COUNT - 1]: label = myfont.render("It's a tie!", 1, ORANGE) screen.blit(label, (40, 10)) game_over = True turn = AI draw_board(board) # AI Moves if turn == AI and not game_over: #run MiniMax algorithm to determine move heur, col = ai.minimax(np.flip(board, 0), AI, 4, -math.inf, math.inf) #move is the column if is_valid_location(board, col): #drop if valid location pygame.time.wait(500) row = get_next_open_row(board, col) drop_piece(board, row, col, AI) #check if AI has won if winning_move(board, AI): label = myfont.render("AI wins!!", 1, YELLOW) screen.blit(label, (40, 10)) game_over = True #check if player has won elif 0 not in board[ROW_COUNT - 1]: label = myfont.render("It's a tie!", 1, ORANGE)