Ejemplo n.º 1
0
def start(board, steps=100, size=20):
    for i in range(1, steps + 1):
        os.system('clear')
        print('step:', i, '/', steps)
        print_board(board, size)
        time.sleep(0.1)
        board = constrain(advance(board), size)
Ejemplo n.º 2
0
    def test_en_passant(self):
        board = get_mock(7)
        print_board(board)

        assert_equal(board.en_passant, (6, 2))
        assert_equal(board.evaluation_params()['material'], [12, 8])
        assert_equal(board.evaluation_params()['activeness'], [24, 21])
        assert_true(board.pieces[(6, 3)] == ('pawn', WHITE))
        cnt = 0
        for move in board.get_board_moves(
                capture_sort_key=Board.sort_take_by_value):
            revert_info = board.make_move(move)
            if revert_info is None:
                continue

            if cnt == 0:
                assert_equal(move['piece'], 'pawn')
                assert_equal(move['new_position'], (6, 2))
                assert_equal(move['captured_piece'], 'pawn')
                assert_equal(board.evaluation_params()['material'], [11, 8])
                assert_equal(board.evaluation_params()['activeness'], [22, 21])
                assert_true((6, 3) not in board.pieces)
            cnt += 1

            board.revert_move(revert_info)

        assert_true(board.pieces[(6, 3)] == ('pawn', WHITE))
Ejemplo n.º 3
0
    def test_print(self, capsys):
        board = generate_board(4)

        print_board(4, board)

        captured = capsys.readouterr()
        assert captured.out == " 0 0 0 0\n 0 0 0 0\n 0 0 0 0\n 0 0 0 0\n"
Ejemplo n.º 4
0
def main():

    board_size = 5
    game = goboard.GameState.new_game(board_size)

    # temperature == c in w + c*sqrt(log N / n)
    # higher temperatures are more volatile,
    # lower temperaures create a more focused search
    temperature = 1.5

    bots = {
        gotypes.Player.black: mcts.MCTSAgent(3, temperature),
        gotypes.Player.white: mcts.MCTSAgent(3, temperature),
    }

    while not game.is_over():

        time.sleep(0.3)  #

        print(chr(27) + "[2J")
        print_board(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)

        game = game.apply_move(bot_move)
Ejemplo n.º 5
0
    def __str__(self):
        """
            to string, will be invoked when printing the node
        """

        state_board = {}

        for p in self.state["players"]:
            state_board[p] = "*p*"

        for l in self.state["goals"]:
            if l in state_board:
                state_board[l] = state_board[l] + "*g*"
            else:
                state_board[l] = "*g*"

        for o in self.state["blocks"]:
            if o in state_board:
                state_board[o] = state_board[o] + "*b*"
            else:
                state_board[o] = "*b*"

        utils.print_board(state_board,
                          message=self.transition_action +
                          str(self.heuristic(self.state)),
                          debug=True)

        return self.transition_action
Ejemplo n.º 6
0
def game():

    # Count of the left ships
    ai_ships_left = len(FLEET)
    player_ships_left = len(FLEET)

    # Variables for storing AI move state
    last_hit_row = UNKNOWN
    last_hit_col = UNKNOWN
    ai_target_ship = None
    ai_hits = []

    # Variables for storing player move state
    player_target_ship = None
    player_hits = []

    # Add random ships to boards
    player_board.place_random_ships()
    ai_board.place_random_ships()

    print_board(ai_board, ai_guesses, SIZE)

    print('Battleships')
    print_board(player_board, player_guesses, SIZE)

    while ai_ships_left and player_ships_left:
        # Player turn
        ai_ships_left = player_turn(ai_ships_left, player_target_ship,
                                    player_hits)
        # AI turn
        player_ships_left = ai_turn(last_hit_row, last_hit_col,
                                    player_ships_left, ai_target_ship, ai_hits)
Ejemplo n.º 7
0
def main():
    # Handles command line args
    if len(sys.argv) != 3:
        print("Incorrect amount of args")
        return
    
    args = sys.argv[1:]
    try:
        int(args[0])
        float(args[1])
    except ValueError:
        print("Incorrect arg types")
        return
    

    if(int(args[0]) != 1 and float(args[1]) != 2):
        print("Turn arg must be 1 or 2")
        return

    # Initializes board
    board = init_board()
    turn = int(args[0])
    print("Initial board:")
    utils.print_board(board)

    # Loops until someone wins
    while len(utils.get_next_board_states(board, turn)) > 0:
        board = montecarlo(board, turn, float(args[1]))
        print(f"{turn} goes")
        utils.print_board(board)
        turn = utils.next_turn(turn)
    
    print(f"{utils.next_turn(turn)} wins!")
Ejemplo n.º 8
0
    def test_mock_0_deep_3(self):
        lines = 17
        for analyzer_class in analyzer_classes:
            analyzer = analyzer_class(max_deep=3,
                                      evaluation_func=material_evaluation,
                                      lines=lines)
            board = get_mock(0)
            print_board(board)

            analysis = analyzer.analyze(board)
            result = analysis['result']

            to_check = []
            for ind in xrange(9):
                to_check.append((result[ind]['evaluation'],
                                 result[ind]['moves'][-1]['piece'],
                                 result[ind]['moves'][-1]['new_position']))

            to_check.sort()
            assert_equal(to_check[0], (-2, 'king', (3, 0)))
            assert_equal(to_check[1], (-2, 'king', (3, 1)))
            assert_equal(to_check[2], (-2, 'pawn', (0, 1)))
            assert_equal(to_check[3], (-2, 'rook', (0, 3)))
            assert_equal(to_check[4], (-2, 'rook', (0, 4)))
            assert_equal(to_check[5], (-2, 'rook', (0, 5)))
            assert_equal(to_check[6], (-2, 'rook', (0, 6)))
            assert_equal(to_check[7], (-1, 'rook', (1, 7)))
            assert_equal(to_check[8][0], 0)
            assert_equal(len(result), 16)
Ejemplo n.º 9
0
 def predict_next_move(_):
     state, action = valid_data[np.random.choice(len(valid_data))]
     n_channel, row, column = state.shape
     if args.gpu >= 0:
         state = cuda.to_gpu(state)
     prediction = model.predict(state.reshape(1, n_channel, row, column))
     print_board(state)
     print(f'action : {translate(int(action))}')
     print(f'prediction : {translate(int(np.argmax(F.softmax(prediction).data, axis=1)))}')
def print_initial_state(data):

    board_dict = dict(zip(ALL_CELLS, [""] * len(ALL_CELLS)))
    for cell in data[PIECES]:
        board_dict[tuple(cell)] = data[COLOUR]
    for cell in data[BLOCKS]:
        board_dict[tuple(cell)] = "BLOCK"

    print_board(board_dict, "", True)
Ejemplo n.º 11
0
def get_approx_path_costs(exit_cells, blocks):

    ApproxPathCosts.blocks = blocks

    for cell in exit_cells:
        ApproxPathCosts.path_costs[cell] = 0
        uniform_cost_search(ApproxPathCosts(cell))

    print_board(ApproxPathCosts.path_costs)

    return ApproxPathCosts.path_costs
Ejemplo n.º 12
0
def player_loop(board, pieces):
    previous_board = deepcopy(board)
    previous_pieces = deepcopy(pieces)

    original_board = deepcopy(board)
    original_pieces = deepcopy(pieces)

    current_move = ""
    found_first_undo = False

    print()
    utils.print_board(board)

    while (True):
        if (check_end(pieces)):
            print("Level Completed!")
            break

        print()
        new_move = read_move()

        if (new_move == "undo" and found_first_undo == False):
            found_first_undo = True
            board = previous_board
            pieces = previous_pieces
            current_move = current_move[:-1]

        elif (new_move == "undo"):
            print("Second Undo in a Row. not allowed :p")
            pass

        elif (new_move == "restart"):
            found_first_undo = False
            board = deepcopy(original_board)
            pieces = deepcopy(original_pieces)
            current_move = ""
            utils.print_board(board)
            continue

        elif (new_move == "h"):
            hint = search_algorithms.a_star(board, pieces,
                                            heuristics.min_string)
            print("Hint: ", hint[0])

        else:
            found_first_undo = False
            previous_board = deepcopy(board)
            previous_pieces = deepcopy(pieces)

            current_move += new_move

        print("Current Move Sequence: {}".format(current_move))
        execute_move(current_move, board, pieces)
Ejemplo n.º 13
0
 def get_action(self, treeNode):
     state = treeNode.state
     print_board(state)
     while True:
         inp = input("Input position: ")
         try:
             lst = inp.split(",")
             assert(len(lst)==2)
             pos = tuple(int(l) for l in lst)
             break
         except:
             print()
     return pos
Ejemplo n.º 14
0
def next_pvc_move(size, board, move, win_conditions, is_first):
    if is_first == 1:
        board, move = utils.get_update_user_move(size, board, move)
        if move <= size * size - 1:
            board = play_comp_move(size, board, move, win_conditions)
        return board, move + 1
    else:
        board = play_comp_move(size, board, move, win_conditions)
        utils.print_board(size, board)
        move += 1
        if move <= size * size - 1:
            board, move = utils.get_update_user_move(size, board, move)
        return board, move
Ejemplo n.º 15
0
def main():
    board_size = 9
    game = goboard_slow.GameState.new_game(board_size)
    bots = {
        gotypes.Player.black: agent.naive.RandomBot(),
        gotypes.Player.white: agent.naive.RandomBot()
    }
    while not game.is_over():
        time.sleep(1)
        print(chr(27) + "[2J")
        print_board(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)
        game = game.apply_move(bot_move)
Ejemplo n.º 16
0
def game(player1, player2, status, iters, shows=False):
    while not status['finish']:
        turn = status['turn']
        if shows:
            print_board(status)
        if turn == 0:
            # jugador real
            status = player1(status, 0)
        elif turn == 1:
            # implementacion de mancala / computadora
            status = player2(status, 1, iters)
    board = status['board']
    score = [board[6], board[13]]
    return score.index(max(score))
Ejemplo n.º 17
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-b", "--board_size", type=int, default=15)
    parser.add_argument("-l", "--line_size", type=int, default=5)
    parser.add_argument("-r", "--num_rollouts", type=int, default=100)
    parser.add_argument("-C", "--exploration_coeff", type=float, default=1.0)
    parser.add_argument("-d", "--max_depth", type=int, default=5)
    parser.add_argument("-t", "--timeout", type=int, default=1)
    parser.add_argument("-s", "--selfplay", type=int, default=0)
    parser.add_argument("-w", "--num_workers", type=int, default=4)
    args = parser.parse_args()

    N, linesize = args.board_size, args.line_size
    num_rollouts, max_depth, timeout = args.num_rollouts, args.max_depth, args.timeout
    C = args.exploration_coeff

    game = Game(N, linesize)
    tree = Tree(game,
                num_rollouts,
                C,
                max_depth,
                timeout,
                num_workers=args.num_workers)

    turn = 0
    print_board(tree.root.board)
    while (True):
        board = tree.root.board
        if (turn == 1):
            print("-" * (8 * N), "")
            print("Your Turn")
            if (args.selfplay == 0):
                pos = player_move(board)
                board = tree.player_move(pos)
            else:
                board = tree.play_one_move()
        else:
            print("\nComputer's Turn")
            board = tree.play_one_move()

        print_board(board)
        if (tree.root.gameover != 0):
            if (turn == 1):
                print("Congrats!! You Won...")
            else:
                print("Sorry!! You Lost... Better Luck Next Time")
            break

        turn = 1 - turn
Ejemplo n.º 18
0
def player_turn(ai_ships_left, player_target_ship, player_hits):
    """
    :param ai_ships_left: int
    :param player_target_ship: Ship
    :param player_hits: list of made hits
    """
    _row = int(input("Which row?"))
    _col = int(input("Which column?"))

    # If player chose the wrong cell
    while not player_guesses.is_cell_on_board(_row, _col):
        print("Incorrect input, please try again")
        _row = int(input("Which row?"))
        _col = int(input("Which column?"))

    # If a player can hit this cell
    player_hit = not ai_board.is_cell_water(_row, _col)
    while player_hit:
        player_guesses.board[_row][_col] = HIT
        if ai_ships_left:
            print('Hit!')
            player_hits.append((_row, _col))

            # Check if any ai ship is sunk
            if not player_target_ship:
                player_target_ship = ai_board.get_hit_ship(_row, _col)
            else:
                is_ai_ship_sunk = player_target_ship.is_sunk(player_hits)
                if is_ai_ship_sunk:
                    player_hits = []
                    ai_ships_left -= 1
                    player_target_ship = None
                    print('AI ship sunk!')

            print_board(player_board, player_guesses, SIZE)

            # Asking again
            _row = int(input("Which row?"))
            _col = int(input("Which column?"))

            player_hit = not ai_board.is_cell_water(_row, _col)
        else:
            print('You win!')
            break
    print("Miss!")
    player_guesses.board[_row][_col] = MISS

    print_board(player_board, player_guesses, SIZE)
    return ai_ships_left
Ejemplo n.º 19
0
    def test_castle_obstacle_not_valid(self):
        for mock_id in [1, 9, 14]:
            board = get_mock(mock_id)
            print_board(board)

            for move in board.get_board_moves():
                revert_info = board.make_move(move)
                if revert_info is None:
                    continue

                board.revert_move(revert_info)

                if (move['piece'] == 'king'
                        and move['new_position'] == (6, 0)):
                    assert_true(False)
Ejemplo n.º 20
0
    def test_castle_beaten_cell_check(self):
        for mock_id in [11, 12, 13]:
            board = get_mock(mock_id)
            print_board(board)

            for move in board.get_board_moves():
                revert_info = board.make_move(move)
                if revert_info is None:
                    continue

                board.revert_move(revert_info)

                if (move['piece'] == 'king'
                        and abs(move['new_position'][0] - move['position'][0])
                        == 2):
                    assert_true(False)
Ejemplo n.º 21
0
    def test_get_board_moves_2(self):
        for mock_id in xrange(MOCKS_COUNT):
            board = get_mock(mock_id)

            print_board(board)
            assert_equal(sorted(board.get_board_moves()),
                         sorted(board.get_board_moves_old()))
            for move in board.get_board_moves():
                revert_info = board.make_move(move)
                if not revert_info:
                    continue

                assert_equal(sorted(board.get_board_moves()),
                             sorted(board.get_board_moves_old()))

                board.revert_move(revert_info)
Ejemplo n.º 22
0
def main():

    game = goboard.GameState.new_game(BOARD_SIZE)
    bot = alphabeta.AlphaBetaAgent(3, capture_diff)

    while not game.is_over():

        print_board(game.board)
        if game.next_player == gotypes.Player.black:
            human_move = input('-- ')
            point = point_from_coords(human_move.strip())
            move = goboard.Move.play(point)
        else:
            move = bot.select_move(game)
        print_move(game.next_player, move)
        game = game.apply_move(move)
Ejemplo n.º 23
0
def main():
    board_size = 9
    game = goboard.GameState.new_game(board_size)
    bot = agent.RandomBot()

    while not game.is_over():
        print(chr(27) + "[2J")
        print_board(game.board)
        if game.next_player == gotypes.Player.black:
            human_move = input('-- ')
            point = point_from_coords(human_move.strip())
            move = goboard.Move.play(point)
        else:
            move = bot.select_move(game)
        print_move(game.next_player, move)
        game = game.apply_move(move)

    print("Winner: ", game.winner())
Ejemplo n.º 24
0
    def test_castle_become_invalid(self):
        for mock_id in [16]:
            board = get_mock(mock_id)
            print_board(board)

            assert_equal(board.castles[BLACK_QC], True)
            is_any_move = False
            for move in board.get_board_moves():
                revert_info = board.make_move(move)
                if revert_info is None:
                    continue

                assert_equal(board.castles[BLACK_QC], False)
                board.revert_move(revert_info)
                is_any_move = True

            assert_equal(is_any_move, True)
            assert_equal(board.castles[BLACK_QC], True)
Ejemplo n.º 25
0
def start_a_new_game(white, black):
    """
    This function creates a new game of brandubh and asks the players
    to select moves until the game is over.
    """

    game = GameState.new_game()
    next_move = ' '

    while game.is_not_over():

        # Clear the output screen and print the current board position
        print(chr(27) + "[2J")
        utils.print_board(game, next_move)
        time.sleep(0.5)

        if game.player == 1:
            action = white.select_move(game)
            move = action.move
        else:
            action = black.select_move(game)
            move = action.move

        if move:
            next_move = utils.COLS[move[1]] + str(move[0]) + ' ' + \
                        utils.COLS[move[3]] + str(move[2])
        else:
            next_move = 'pass'

        # Try make the move and see if it is legal. If not, print
        # why it isn't to the screen and wait the next input
        # (Note, all actions produced by select_move methods should be legal,
        # this is just here to catch errors.)
        move_is_not_legal = game.take_turn(action)
        if move_is_not_legal:
            print(move_is_not_legal)

    # If the game is over, print the winning board position and who won
    print(chr(27) + "[2J")
    utils.print_board(game, next_move)
    winner = 'black' if game.winner == -1 else 'white'
    print('The winner is ' + winner)
    input('--')
Ejemplo n.º 26
0
def execute_move(move_sequence, board, pieces):

    if (len(move_sequence) == 0):
        utils.print_board(board)
        return
    move = move_sequence[-1]

    sort_pieces(pieces, move)

    for i in range(len(pieces)):
        cur_row = pieces[i].movable_row
        cur_col = pieces[i].movable_col

        if (move == "u"):
            newCoords = moveUp(board, cur_row, cur_col)
            pieces[i].movable_row = newCoords[0]

        elif (move == "d"):
            newCoords = moveDown(board, cur_row, cur_col)
            pieces[i].movable_row = newCoords[0]

        elif (move == "l"):
            newCoords = moveLeft(board, cur_row, cur_col)
            pieces[i].movable_col = newCoords[1]

        elif (move == "r"):
            newCoords = moveRight(board, cur_row, cur_col)
            pieces[i].movable_col = newCoords[1]

        size_board = int(len(board)**0.5)
        board[cur_row * size_board + cur_col] = "."
        board[newCoords[0] * size_board +
              newCoords[1]] = pieces[i].movable_symbol

    for i in range(len(pieces)):
        if (board[pieces[i].dest_row * size_board +
                  pieces[i].dest_col] == "."):
            board[pieces[i].dest_row * size_board +
                  pieces[i].dest_col] = pieces[i].dest_symbol

    utils.print_board(board)
Ejemplo n.º 27
0
def main():
    board_size = get_board_size()
    players, white, black = get_players()
    os.system('cls')
    turn = 0
    
    game = GameState.new_game(board_size, white, black) 
    print_intro(game.board)

    bot_move = None
    while not game.is_over():
        time.sleep(1) 

        turn = turn + 1
        print_board(game.board, turn, game.is_over(), game.next_player.other, bot_move)         
        bot_move = players[game.next_player].select_move(game)          
        game = game.apply_move(bot_move)                 

    print_board(game.board, turn, game.is_over(), game.next_player.other, bot_move)         
    winner = game.winner()
    print('%s Wins!!!' % (winner))
Ejemplo n.º 28
0
def main():
    
    board_size = 5
    game = goboard.GameState.new_game(board_size)
    
    bots = {        
        gotypes.Player.black: depthprune.DepthPrunedAgent(3, pruned_go.capture_diff),
        gotypes.Player.white: depthprune.DepthPrunedAgent(3, pruned_go.capture_diff),
    }

    
    while not game.is_over():
    
        time.sleep(0.3)  #

        print(chr(27) + "[2J")  
        print_board(game.board)
        bot_move = bots[game.next_player].select_move(game)
        print_move(game.next_player, bot_move)
        
        game = game.apply_move(bot_move)
Ejemplo n.º 29
0
 def run(self):
     overall_time = time.clock()
     board = []
     iter_num = 0
     for i in range(self.data.queens_num):
         row = (random.randint(0, 32767) % self.data.queens_num)
         board.append(row)
     while not self.is_solved(board):
         print("Iteration number " + str(iter_num))
         utils.print_board(board, self.data.queens_num)
         print()
         random_col = (random.randint(0, 32767) % self.data.queens_num)
         board[random_col] = self.find_best_row(board, random_col)
         iter_num = iter_num + 1
     overall_time = time.clock() - overall_time
     overall_clock_ticks = overall_time * self.data.clocks_per_second
     with open("output.txt", 'a') as file:
         file.write("Overall clock ticks: " + str(overall_clock_ticks) +
                    "\n")
         file.write("Overall time: " + str(overall_time) + "\n")
         file.write("Overall iterations: " + str(iter_num) + "\n")
Ejemplo n.º 30
0
    def test_mock_2_deep_4(self):
        lines = 17
        for analyzer_class in analyzer_classes:
            analyzer = analyzer_class(max_deep=4,
                                      evaluation_func=material_evaluation,
                                      lines=lines)
            board = get_mock(2)
            print_board(board)

            analysis = analyzer.analyze(board)
            result = analysis['result']

            to_check = []
            for ind in xrange(9):
                to_check.append((result[ind]['evaluation'],
                                 result[ind]['moves'][-1]['piece'],
                                 result[ind]['moves'][-1]['new_position']))

            to_check.sort(reverse=True)
            assert_equal(to_check[0], (997, 'queen', (6, 7)))
            assert_equal(to_check[1][0], 5)
            assert_equal(len(result), 17)