Example #1
0
def maq_maq(game, state, player, heur_maq, heur_jugador2):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            print "Thinking maquina O..."
            move = games.alphabeta_search(state,
                                          game,
                                          d=heur_jugador2.depth,
                                          eval_fn=heur_jugador2.modo)
            state = game.make_move(move, state)
            player = 'X'
        else:
            print "Thinking maquina X..."

            move = games.alphabeta_search(state,
                                          game,
                                          d=heur_maq.depth,
                                          eval_fn=heur_maq.modo)

            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #2
0
def play(state, player):
    while True:
        if player == 'X':
            print("Jugador a mover:", game.to_move(state))

        else:
            print("Jugador a mover:", game.to_move(state))

        game.display(state)

        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:  # Máquina.
            print("\nThinking...")
            # move = games.minimax_decision(state, game)
            # move = games.alphabeta_full_search(state, game)
            # state, game, d=4, cutoff_test=None, eval_fn=None, player='X', dificultad=2
            if dificultad == 2:
                move = games.alphabeta_search(state,
                                              game,
                                              d=3,
                                              eval_fn=heu.run_heuristic,
                                              player=player,
                                              dificultad=dificultad)
            if dificultad == 1:
                move = games.alphabeta_search(state,
                                              game,
                                              d=2,
                                              eval_fn=heu.run_heuristic,
                                              player=player,
                                              dificultad=dificultad)
            if dificultad == 0:
                move = games.alphabeta_search(state,
                                              game,
                                              d=1,
                                              eval_fn=heu.run_heuristic,
                                              player=player,
                                              dificultad=dificultad)
            state = game.make_move(move, state)
            player = 'O'
        print("-------------------")
        if game.terminal_test(state):
            game.display(state)
            print("Final de la partida")
            break
Example #3
0
def cpu_play():
    global state, player
    if player == 'X':
        print "Thinking..."
        move = games.alphabeta_search(state, game, d=4 , cutoff_test=None, eval_fn=heuristic.best_move_heuristic2)
        state = game.make_move(move, state)
        player = 'O'
    else:
        print "Thinking..."
        move = games.alphabeta_search(state, game, d=1 , cutoff_test=None, eval_fn=heuristic.random_heuristic)
        state = game.make_move(move, state)
        player = 'X'
Example #4
0
def make_ab(depth):
    global z
    if z == 'First':
        function = lambda game, state: alphabeta_search(state, game, d=depth, eval_fn=lambda state: game.utility1(state, 'Player'))
        function.label = "AB(" + str(depth) + ")" + z
        z = 'Second'
    else:
        function = lambda game, state: alphabeta_search(state, game, d=depth,
                                                        eval_fn=lambda state: game.utility4(state, 'Opponent'))
        function.label = "AB(" + str(depth) + ")" + z
        z = 'Second'
        z = 'First'
    return function
Example #5
0
def maquina(state,player,dif):
    print "Thinking..."
    if dif == '1':
        move = games.alphabeta_search(state, game, d=5, eval_fn=heuristicas.h1,player=player)
        state = game.make_move(move, state)
    elif dif == '2':
        move = games.alphabeta_search(state, game, d=4, eval_fn=heuristicas.h1,player=player)
        state = game.make_move(move, state)
    else:
        move = games.alphabeta_search(state, game, eval_fn=heuristicas.h0,player=player)
        state = game.make_move(move, state)

    return state
Example #6
0
def maquinaVSmaquina(state):
    while not game.terminal_test(state):
        game.display(state)
        print "Thinking X...\n"
        move = games.alphabeta_search(state, game, eval_fn=heuristic.h1,player='X', d=4)
        state = game.make_move(move, state)
        print "-------------------"
        game.display(state)
        print chr(27)+"[0;36m"+"Thinking O...\n"+chr(27)+"[0m"
        move = games.alphabeta_search(state, game, eval_fn=heuristic.h1,player='O', d=4)
        state = game.make_move(move, state)
        print "-------------------"
    game.display(state)
    print "Final de la partida"
Example #7
0
def machineMove(state2, player2, nextPlayer,heuristic):
    print "Thinking..."
    # move = games.minimax_decision(state, game)
    # move = games.alphabeta_full_search(state, game)
    if level == '1':
        move = games.alphabeta_search(state2, game, eval_fn=heuristic, d=1, player=player2)
    elif level == '2':
        move = games.alphabeta_search(state2, game, eval_fn=heuristic, d=2, player=player2)
    else:
        move = games.alphabeta_search(state2, game, eval_fn=heuristic, d=4, player=player2)

    global state
    state = game.make_move(move, state2)
    global player
    player = nextPlayer
Example #8
0
def alphabeta_search(board, game, finish_by=None):
    "Find a move based on an alpha-beta search of the game tree."

    # Pick at least some default to move if we're really slow.
    # We also keep it updated each level further we go down.
    best_completed_move = board.moves()[0]

    try:
        state = TronState(board, tron.ME)

        # Use iterative deepening search around the AIMA minimax
        # algorithm (the one that uses alpha-beta pruning and allows
        # the search to be cutoff and evaluated early. We deepen by
        # 2 to account for the way the moves are handled simultaneously
        # by the game class to match the production engine.
        for depth_limit in xrange(2, sys.maxint, 2):

            stats = utils.Struct(nodes=0, max_depth=0)
            cutoff_fn = make_cutoff_fn(depth_limit, stats, finish_by, game)
            move = games.alphabeta_search(state, game, None, cutoff_fn,
                                          eval_fn)

            # Return this move if we didn't get any deeper.
            if stats.nodes <= 2:
                return game.move_to_return(move)
            else:
                best_completed_move = game.move_to_return(move)

    except TimeAlmostUp:
        return best_completed_move
Example #9
0
def calc_move(model, table, search_time, conn):
    move = None
    # term_event.clear()
    captures = model.captures_available()
    if captures:
        time.sleep(0)
        move = longest_of(captures)
    else:
        depth = 0
        start_time = time.time()
        curr_time = start_time
        checkpoint = start_time
        model_copy = copy.deepcopy(model)
        while 1:
            depth += 1
            table.set_hash_move(depth, -1)
            move = games.alphabeta_search(model_copy.curr_state, model_copy,
                                          depth)
            checkpoint = curr_time
            curr_time = time.time()
            rem_time = search_time - (curr_time - checkpoint)
            # if term_event.is_set(): # a signal means terminate
            #     term_event.clear()
            #     move = None
            #     break
            if (curr_time - start_time > search_time
                    or ((curr_time - checkpoint) * 2) > rem_time
                    or depth > MAXDEPTH):
                break
    if conn:
        conn.send(move)
    else:
        return move
Example #10
0
def maq_jug(game, state, player, heur_maq):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."

            move = games.alphabeta_search(state,
                                          game,
                                          d=heur_maq.depth,
                                          eval_fn=heur_maq.modo)

            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #11
0
def humanVsMachine(state,d,player):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."
            #move = games.alphabeta_full_search(state, game)
            move = games.alphabeta_search(state, game,d, eval_fn=heuristics.h)
            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #12
0
def empiezaMaquina(state, player):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."
            # move = games.minimax_decision(state, game)
            # move = games.alphabeta_full_search(state, game)
            move = games.alphabeta_search(state, game, eval_fn=h1, d=d)
            # print h1(state)

            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #13
0
def alphabeta_search(board, game, finish_by=None):
    "Find a move based on an alpha-beta search of the game tree."

    # Pick at least some default to move if we're really slow.
    # We also keep it updated each level further we go down.
    best_completed_move = board.moves()[0]
    
    try:
        state = TronState(board, tron.ME)

        # Use iterative deepening search around the AIMA minimax
        # algorithm (the one that uses alpha-beta pruning and allows
        # the search to be cutoff and evaluated early. We deepen by
        # 2 to account for the way the moves are handled simultaneously
        # by the game class to match the production engine.
        for depth_limit in xrange(2, sys.maxint, 2):

            stats = utils.Struct(nodes=0, max_depth=0)
            cutoff_fn = make_cutoff_fn(depth_limit, stats, finish_by, game)
            move = games.alphabeta_search(state, game, None, cutoff_fn, eval_fn)

            # Return this move if we didn't get any deeper.
            if stats.nodes <= 2:
                return game.move_to_return(move)
            else:
                best_completed_move = game.move_to_return(move)
                
    except TimeAlmostUp:
        return best_completed_move
def make_ab(depth, YesOrNo):
    if YesOrNo == 'Yes':
        function = lambda game, state: alphabeta_search(
            state,
            game,
            d=depth,
            eval_fn=lambda state: game.utility4(state, 'Opponent'))
    if YesOrNo == 'No':
        function = lambda game, state: alphabeta_search(
            state,
            game,
            d=depth,
            eval_fn=lambda state: game.utility4(state, 'Player'))
    function.label = "AB(" + str(depth) + ")"

    return function
Example #15
0
def maq_jug(game, state, player, heur_maq):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."

            move = games.alphabeta_search(state, game, d=heur_maq.depth, eval_fn=heur_maq.modo)

            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #16
0
    def bdrop(self, column):
        if (self.gameState.first_player):
            return self.gameState.drop(column)

        else:
            guess = games.alphabeta_search(self.gameState, self.game, 4)
            return self.gameState.drop(guess)
Example #17
0
def quienEmpieza(state,player):
    while not game.terminal_test(state):
        if player=='X':
            print "Jugador a mover:", game.to_move(state)
        else: print "Jugador a mover:", game.to_move(state)
        game.display(state)
        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]
            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."
            move = games.alphabeta_search(state, game, eval_fn=heuristic.h1,d=dificultad)
            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
    game.display(state)
    print "Final de la partida"
def calc_move(model, table, search_time, conn):
    move = None
    # term_event.clear()
    captures = model.captures_available()
    if captures:
        time.sleep(0)
        move = longest_of(captures)
    else:
        depth = 0
        start_time = time.time()
        curr_time = start_time
        checkpoint = start_time
        model_copy = copy.deepcopy(model)
        while 1:
            depth += 1
            table.set_hash_move(depth, -1)
            move = games.alphabeta_search(model_copy.curr_state,
                                          model_copy,
                                          depth)
            checkpoint = curr_time
            curr_time = time.time()
            rem_time = search_time - (curr_time - checkpoint)
            # if term_event.is_set(): # a signal means terminate
            #     term_event.clear()
            #     move = None
            #     break
            if (curr_time - start_time > search_time or
               ((curr_time - checkpoint) * 2) > rem_time or
               depth > MAXDEPTH):
                break
    if conn:
        conn.send(move)
    else:
        return move
Example #19
0
def calc_move(model, search_time, term_event, child_conn):
    move = None
    term_event.clear()
    captures = model.captures_available()
    if captures:
        time.sleep(0.7)
        move = longest_of(captures)
    else:
        depth = 0
        start_time = time.time()
        curr_time = start_time
        model_copy = copy.deepcopy(model)
        while 1:
            depth += 1
            move = games.alphabeta_search(model_copy.curr_state,
                                          model_copy,
                                          depth)
            checkpoint = curr_time
            curr_time = time.time()
            rem_time = search_time - (curr_time - checkpoint)
            if term_event.is_set():  # a signal means terminate
                term_event.clear()
                move = None
                break
            if curr_time - start_time > search_time or (curr_time - checkpoint) * 2 > rem_time or depth > MAXDEPTH:
                break
    child_conn.send(move)
Example #20
0
def humanVsMachine():
    player = selectPlayer()
    game = games.ConnectFour(h=7, v=6, k=4, player=player)
    state = game.initial
    heu = selectDifficulty(state, game)
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            x = checkValidMove()
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]
            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."
            move = games.alphabeta_search(state, game, d=5, cutoff_test=None, eval_fn=heu)
            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #21
0
File: run.py Project: luiszoran/fsi
def computersTurn():
    global state, player
    print "Thinking..."
    # move = games.minimax_decision(state, game)
    # move = games.alphabeta_full_search(state, game)
    move = games.alphabeta_search(state, game, d=profundidad, eval_fn=heuristic.heuristic)
    state = game.make_move(move, state)
    player = 'player'
Example #22
0
def cpu_play():
    global state, cpu_log, player
    move = games.alphabeta_search(state, game, d=difficult, cutoff_test=None,
                                  eval_fn=heuristic.compute_utility)
    state = game.make_move(move, state)
    grid[move[0]][move[1]] = 2
    cpu_log = "La CPU ha movido en la posicion" + str(move)
    check_terminal()
    player = 'X'
Example #23
0
def play(state, player):
    while True:
        if player == 'X':
            print ("Jugador a mover:", game.to_move(state))

        else:
            print ("Jugador a mover:", game.to_move(state))


        game.display(state)

        if player == 'O':
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else: # Máquina.
            print("\nThinking...")
            # move = games.minimax_decision(state, game)
            # move = games.alphabeta_full_search(state, game)
            # state, game, d=4, cutoff_test=None, eval_fn=None, player='X', dificultad=2
            if dificultad == 2:
                move = games.alphabeta_search(state, game, d=3, eval_fn=heu.run_heuristic, player=player,
                                              dificultad=dificultad)
            if dificultad == 1:
                move = games.alphabeta_search(state, game, d=2, eval_fn=heu.run_heuristic, player=player,
                                              dificultad=dificultad)
            if dificultad == 0:
                move = games.alphabeta_search(state, game, d=1, eval_fn=heu.run_heuristic, player=player,
                                              dificultad=dificultad)
            state = game.make_move(move, state)
            player = 'O'
        print("-------------------")
        if game.terminal_test(state):
            game.display(state)
            print("Final de la partida")
            break
Example #24
0
def cpu_play():
    global state, player
    if player == 'X':
        print "Thinking..."
        move = games.alphabeta_search(state,
                                      game,
                                      d=4,
                                      cutoff_test=None,
                                      eval_fn=heuristic.best_move_heuristic2)
        state = game.make_move(move, state)
        player = 'O'
    else:
        print "Thinking..."
        move = games.alphabeta_search(state,
                                      game,
                                      d=1,
                                      cutoff_test=None,
                                      eval_fn=heuristic.random_heuristic)
        state = game.make_move(move, state)
        player = 'X'
Example #25
0
def machineVsMachine(state,d,player):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            print "Thinking..."
            move = games.alphabeta_search(state, game,d, eval_fn=heuristics.h,player='O')
            state = game.make_move(move, state)
            player = 'X'
        else:
            print "Thinking..."
            move = games.alphabeta_search(state, game,d, eval_fn=heuristics.h)
            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #26
0
 def select_move(self, game, state):
     sys.stdout.write('\nThinking ... ')
     movelist = games.alphabeta_search(state, game, False, self.searchDepth)
     positions = []
     step = 2 if game.captures_available(state) else 1
     for i in range(0, len(movelist), step):
         idx, old, new = movelist[i]
         positions.append(str(CBMAP[idx]))
     move = '-'.join(positions)
     print 'I move %s' % move
     return movelist
Example #27
0
 def select_move(self, game, state):
     sys.stdout.write('\nThinking ... ')
     movelist = games.alphabeta_search(state, game, False,
                                       self.searchDepth)
     positions = []
     step = 2 if game.captures_available(state) else 1
     for i in range(0, len(movelist), step):
         idx, old, new = movelist[i]
         positions.append(str(CBMAP[idx]))
     move = '-'.join(positions)
     print 'I move %s' % move
     return movelist
Example #28
0
def maq_maq(game, state, player, heur_maq, heur_jugador2):
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            print "Thinking maquina O..."
            move = games.alphabeta_search(state, game, d=heur_jugador2.depth, eval_fn=heur_jugador2.modo)
            state = game.make_move(move, state)
            player = 'X'
        else:
            print "Thinking maquina X..."

            move = games.alphabeta_search(state, game, d=heur_maq.depth, eval_fn=heur_maq.modo)

            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #29
0
def machineVsMachine():
    game = games.ConnectFour(h=7, v=6, k=4)
    state = game.initial
    player = 'X'
    while True:
        print "Jugador a mover:", game.to_move(state)
        game.display(state)

        if player == 'O':
            print "Don't Think, Just ACT"
            move = games.alphabeta_search(state, game, d=2, cutoff_test=None, eval_fn=heu.heuristicRIA)
            state = game.make_move(move, state)
            player = 'X'
        else:
            print "Thinking..."
            move = games.alphabeta_search(state, game, d=3, cutoff_test=None, eval_fn=heu.heuristicN)
            state = game.make_move(move, state)
            player = 'O'
        print "-------------------"
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
Example #30
0
def game_start(game, level=2):
    state = game.initial
    while True:
        print "Your turn, ", game.to_move(state)
        game.display(state)
        if game.to_move(state) == 'O':
            state = update_state(game, state, raw_input("In which column do you want to play?: "))
        else:
            print "Thinking..."
            state = game.make_move(games.alphabeta_search(state, game, level), state)
        print "-------------------------------"
        if game.terminal_test(state):
            game.display(state)
            show_game_result(game, state)
            return
Example #31
0
def maquina(state, player, dif):
    print "Thinking..."
    if dif == '1':
        move = games.alphabeta_search(state,
                                      game,
                                      d=5,
                                      eval_fn=heuristicas.h1,
                                      player=player)
        state = game.make_move(move, state)
    elif dif == '2':
        move = games.alphabeta_search(state,
                                      game,
                                      d=4,
                                      eval_fn=heuristicas.h1,
                                      player=player)
        state = game.make_move(move, state)
    else:
        move = games.alphabeta_search(state,
                                      game,
                                      eval_fn=heuristicas.h0,
                                      player=player)
        state = game.make_move(move, state)

    return state
Example #32
0
def start_game(d, player):

    game = games.ConnectFour(player=player)
    state = game.initial

    while True:
        clear()
        print "Difficulty level:", d if d == 1 else d/2
        if game.to_move(state) == 'X':
            print "Player to move: CPU"
        else:
            print "Player to move: Human"

        game.display(state)

        if player == 'O':
            col_str = raw_input("\n--> Movement: ")

            while int(col_str) < 1 or int(col_str) > 7:
                col_str = raw_input("--> Movement: ")

            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "\nThinking..."

            move = games.alphabeta_search(state, game, d, eval_fn=heuristic.h0)

            state = game.make_move(move, state)
            player = 'O'
        print "-------------"
        if game.terminal_test(state):
            clear()
            game.display(state)
            print "\nEND OF THE GAME. Press any key to back main menu."
            raw_input()
            break
Example #33
0
    def bdrop(self, column):
        if(self.gameState.first_player):
         #   self.gameState.grid
         #   print(column.gameState.grid)

            return self.gameState.drop(column)

        else:
            for x in range(0,7):
                for y in range(0,len(column.gameState.grid[x])):
                    print(column.gameState.grid[x][y])
                #d = {column.gameState.grid[x], x}

                #print(column.gameState.grid[x])
            #print(b)
            #guess = randint(0, 6)
            # guess = g.utility(self, self.gameState, self.currentPlayerLabel)
            guess = games.alphabeta_search(self.gameState, self.game, 1)
           # print(d)
          #  print(column.gameState.grid)
            return self.gameState.drop(guess)
Example #34
0
def make_alphabeta_player(N=0):
    """ Returns a player function that uses alpha_beta search to depth N """
    if N == 0:
        return lambda g, s: games.alphabeta_search(s, g)
    else:
        return lambda g, s: games.alphabeta_cutoff_search(s, g, d=N)
Example #35
0
def maquina():
    print "Thinking..."
    return games.alphabeta_search(state, game, eval_fn=h2.hO, d=5)
Example #36
0
def make_ab(depth):
    function = lambda game, state: alphabeta_search(state, game, d=depth)
    function.label = "AB(" + str(depth) + ")"
    return function
Example #37
0
while True:
    print "Jugador a mover:", game.to_move(state)
    game.display(state)

    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        player = 'X'
    else:
        print "Thinking..."
        #move = games.minimax_decision(state, game)
        #move = games.alphabeta_full_search(state, game)
        move = games.alphabeta_search(state, game, dificultad)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"
        break
Example #38
0

def check_terminal():
    global done
    if game.terminal_test(state):
        done = True


while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_h:
                if hints > 0:
                    hint_move = games.alphabeta_search(state, game, d=6, cutoff_test=None,
                                                       eval_fn=heuristic.compute_utility)
                    hints -= 1
                    hint_flag = 1
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if mode == 1:
                single_player()
            else:
                player_play()
    screen.fill(black)
    display_board()
    display_igtexts()
    pygame.display.flip()
    if mode != 1 and player == 'O':
        cpu_play()
play_end_music()
while credit_flag:
Example #39
0
while True:
    print "Player to move:", game.to_move(state)
    game.display(state)

    if jugador == 'O':
        col_str = raw_input("Movement: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        jugador='X'
    else:
        print "Thinking..."
        #move = games.minimax_decision(state, game)
        #move = games.alphabeta_full_search(state, game)
        #move = games.alphabeta_search(state, game, eval_fn=heuristic.h0)
        move = games.alphabeta_search(state, game, dificultad)

        state = game.make_move(move, state)
        jugador = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "End of the game"
        break
Example #40
0
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."
            if d is 0:
                move = games.alphabeta_full_search(state, game)
            else:
                move = games.alphabeta_search(state, game, eval_fn=h.heuristica_enemiga, d=d)

            state = game.make_move(move, state)
        player = 'X'
    else:
        print "Thinking..."
        # move = games.minimax_decision(state, game)
        # move = games.alphabeta_full_search(state, game)
        if d is 0:
            move = games.alphabeta_full_search(state, game)
        else:
            move = games.alphabeta_search(state, game, eval_fn=h.heuristica, d=d)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
Example #41
0
def player4(game, state):
    return alphabeta_search(state, game, eval_fn=eval_fn4)
Example #42
0
    else:
        print "Entrada no valida"

while True:
    # Jugador no humano 'O'
    if dificultad1 != 'human':
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
            break
        print "Jugador a mover:", game.to_move(state)
        game.display(state)
        print "Thinking..."
        move = games.alphabeta_search(state,
                                      game,
                                      d=prof,
                                      cutoff_test=None,
                                      eval_fn=dificultad1[1])
        state = game.make_move(move, state)
        player = 'X'
        jugadas += 1
        # Cada 20 jugadas aumentamos la profundidad de busqueda
        #if jugadas % 20 == 0:
        #prof += 2
        print "Profundidad:", prof
        print "Dificultad:", dificultad1[0], "vs", dificultad2[0]
    # Jugador humano 'O'
    else:
        if game.terminal_test(state):
            game.display(state)
            print "Final de la partida"
Example #43
0

def make_alphabeta_player(N=0):
    """ Returns a player function that uses alpha_beta search to depth N """
    if N == 0:
        return lambda g, s: games.alphabeta_search(s, g)
    else:
        return lambda g, s: games.alphabeta_cutoff_search(s, g, d=N)


# PLAYERS is a dictionary mapping player names to the python functions
# that implement them.
PLAYERS = {
    'me': games.query_player,
    'random': games.random_player,
    'ab': lambda g, s: games.alphabeta_search(s, g)
}

# add to the PLAYERS dictionary player function named ab1,ab2,...ab20
# that use alpha_beta search with depth cutoffs between 1 and 20
for i in range(1, 21):
    PLAYERS['ab' + str(i)] = make_alphabeta_player(i)

# NIM problems for testing
tests = [([1], 'random', 'random'), ([3], 'random', 'random'),
         ([1, 1], 'ab', 'ab'), ([1, 1, 1], 'ab', 'ab'),
         ([1, 1, 1, 1], 'ab', 'ab'), ([2, 2], 'ab', 'ab'),
         ([5, 4, 3, 2, 1], 'ab2', 'ab3'), ([5, 4, 3, 2, 1], 'ab3', 'ab2'),
         ([7, 6, 5, 4, 3, 2, 1], 'ab2', 'ab3'),
         ([7, 6, 5, 4, 3, 2, 1], 'ab3', 'ab2'),
         ([7, 6, 5, 4, 3, 2, 1, 1, 1, 1], 'ab2', 'ab3'),
Example #44
0
print()
print("================================")
print("Whose turn is it now?")
print(nextToMove)
print("===================================================")
print("How many states did the minimax algorithm evaluate?")
numberOfStates = 0
if (len(moves) > 0):
    optimalMove, numberOfStates = minimax_decision(gameState, ticTacToe, True)
print(numberOfStates)
print("==============================================================")
print("How many states did the alpha-beta pruning algorithm evaluate?")
numberOfStates = 0
if (len(moves) > 0):
    optimalMove, numberOfStates = alphabeta_search(gameState, ticTacToe, True)
print(numberOfStates)
print("=================================================================")

# The below command is to continue game from the state the input was given
numberOfStates = 0
if (len(moves) > 0):
    utility, board = ticTacToe.continue_game(gameState, False,
                                             alphabeta_player,
                                             alphabeta_player)

currentGameState = 0
print("What is the value of the current state from the perspective of X?")
if len(moves) == 0:
    getValue = ticTacToe.full_table(board)
    if (getValue == 'X'):
Example #45
0
    print "Jugador a mover:", game.to_move(state)
    game.display(state)

    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        player = 'X'
    else:
        print "Thinking..."
        # move = games.minimax_decision(state, game)
        # move = games.alphabeta_full_search(state, game)
        move = games.alphabeta_search(state, game, d=level, eval_fn=heuristics.get_move)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "\n\nFinal de la partida"
        decision = raw_input("¿Desea reiniciarla? (S/N)")

        restart(decision.lower())
Example #46
0
state = game.initial

while True:
    print "Jugador a mover:", game.to_move(state)
    game.display(state)

    if player == 'O':
        col_str = raw_input("Movimiento: ")
        x = int(str(col_str).strip())
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        player = 'X'
    else:
        print "Thinking..."
        # move = games.minimax_decision(state, game)
        # move = games.alphabeta_full_search(state, game)
        move = games.alphabeta_search(state, game, d=difficulty[dif], eval_fn=heuristicas.main_heuristics)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"
        break
Example #47
0
def team_player12(depth, eval_fn):

    return (lambda game, state: alphabeta_search(
        state, game, d=depth, eval_fn=eval_fn))
Example #48
0
     y = -1
     legal_moves = game.legal_moves(state)
     for lm in legal_moves:
         if lm[0] == x:
             y = lm[1]
     state = game.make_move((x, y), state)
     state.to_move = 'X'
     jugadas += 1
     # Cada 20 jugadas aumentamos la profundidad de busqueda
     # if jugadas % 20 == 0:
     #     prof += 2
     print "Profundidad:", prof
     print "Dificultad:", dificultad1[0]
 elif state.to_move == 'O' and dificultad2 != 'human': # OTRA MAQUINA
     print "Thinking..."
     move = games.alphabeta_search(state, game, d=prof, cutoff_test=None, eval_fn=dificultad2[1])
     state = game.make_move(move, state)
     player = 'X'
     jugadas += 1
     # Cada 20 jugadas aumentamos la profundidad de busqueda
     # if jugadas % 20 == 0:
     #     prof += 2
     print "Profundidad:", prof
     print "Dificultad:", dificultad2[0]
     print "-------------------"
 else: #MAQUINA
     print "Thinking..."
     move = games.alphabeta_search(state, game, d=prof, cutoff_test=None, eval_fn=dificultad1[1])
     state = game.make_move(move, state)
     player = 'O'
     jugadas += 1
Example #49
0
def main():
    rows = []
    brd = []
    count_ab = 0
    print("Enter the first row.")
    # TODO - Implement. Write code to get the first line from the user.
    # An example input line: X - O
    # In this example, the first entry is X, the second entry is -, indicating blank, and the third entry is O
    rows.append(input())
    print("Enter the second row.")
    # TODO - Implement
    rows.append(input())

    print("Enter the third row.")
    # TODO - Implement
    rows.append(input())

    #compiling the rows.
    for x in range(3):
        brd.append(rows[x].split())
    # For the following questions, you can implement everything here or under the questions or you can do a mix.
    # It's totally up to you where to put your implemention in this file.
    # However, please pay special attention to the instructions regarding the format of the answers.

    print("Whose turn is it now?")
    # TODO - Implement. Compute and print the answer.
    # The answer should a single letter: either X or O. No punctuation. No other text.
    ttt, my_state = buildGame(brd)
    #print((my_state.utility))
    if my_state.utility != 0:  #The game is already in a terminal state so its no ones move.
        print('None')
    else:
        print(my_state.to_move)  #prints whose turn it is.

    print("What is the value of the current state from the perspective of X?")
    # TODO - Implement. Compute and print the answer.
    # The answer should a single number: either -1 or 1 or 0. No punctuation. No other text.
    # Important: this is always from the perspective of X; *not* from the perspective of whose turn it is.
    if my_state.utility == None:
        print('0')
        comp = my_state.utility
    elif my_state.utility != 0:
        print(str(my_state.utility))
        comp = my_state.utility
    else:
        decision, count_ab = games.alphabeta_search(my_state, ttt)
        new_state = games.GameState(to_move=my_state.to_move,
                                    utility=my_state.utility,
                                    board=my_state.board,
                                    moves=my_state.moves)
        new_state = ttt.result(new_state, decision)
        while new_state.utility == 0 and len(new_state.moves) != 0:
            decision, c = games.alphabeta_search(new_state, ttt)
            #comp = ttt.compute_utility(new_state.board, decision, new_state.to_move)
            new_state = ttt.result(new_state, decision)
        comp = new_state.utility
        print(str(new_state.utility))

    print("How many states did the minimax algorithm evaluate?")
    # TODO - Implement. Compute and print the answer.
    # The answer should a single number. No punctuation. No other text.
    # You probably need to modify games.py to compute this.
    if my_state.utility != 0:
        print('1')
    else:
        decision, count = games.minimax_decision(my_state, ttt)
        print(str(count))

    print("How many states did the alpha-beta pruning algorithm evaluate?")
    # TODO - Implement. Compute and print the answer.
    # The answer should a single number. No punctuation. No other text.
    # You probably need to modify games.py to compute this.
    if my_state.utility != 0:
        print('1')
    else:
        print(str(count_ab))

    print(
        "Assuming both X and O play optimally, does X have a guaranteed win? Is it a tie? Is it a guaranteed loss for X?"
    )
    # TODO - Implement. Compute and print the answer.
    # The answer should be either of "X will win.", or "It is a tie." or "X will lose."
    # Note: you already computed this somewhere above.
    if comp == 1:  #and len(my_state.moves) != 0:
        print("X will win.")
    elif comp == -1:
        print("X will lose.")
    else:
        print("It is a tie.")

    print(
        "Assuming both X and O would play optimally, how would they play till the game ends?"
    )
    # TODO - Implement. Compute.
    # Display the states one at a time, using the display method of the Game class (or its subclasses, whichever is appropriate).
    # Print a single blank line between the states. That is, use print(). Do not print any additional info.
    ttt.display(my_state)
    print()
    if my_state.utility == 0:
        ttt.play_game(my_state, games.alphabeta_player, games.alphabeta_player)
Example #50
0
    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        player = 'X'

    else:
        print "Thinking..."
        move = games.alphabeta_search(state, game,dificultad,eval_fn = h4)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"

        if state.utility == 0:
            print "Empate"
        elif player == "O":
            print "Ganó Pc"
        elif player == "X":
            print"Ganó Usted"
        break
Example #51
0
    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]
    
        state = game.make_move((x, y), state)
        player = 'X'
    else:
        print "Thinking..."
        #move = games.minimax_decision(state, game)
        #move = games.alphabeta_full_search(state, game)
        if difficultyLevel == 3:
            move = games.alphabeta_search(state, game, 3, heuristic.calculateHeuristic, player, 2)
        if difficultyLevel == 2:
            move = games.alphabeta_search(state, game, 2, heuristic.calculateHeuristic, player, 1)
        else:
            move = games.alphabeta_search(state, game, 1, None, player, 1)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"
        break
Example #52
0
        if tipo == "H":
            col_str = raw_input("Movimiento: ")
            coor = int(str(col_str).strip())
            x = coor
            y = -1
            legal_moves = game.legal_moves(state)
            for lm in legal_moves:
                if lm[0] == x:
                    y = lm[1]

            state = game.make_move((x, y), state)
            player = 'X'
        else:
            print "Thinking..."
            move = games.alphabeta_search(state,
                                          game,
                                          eval_fn=heuristicaCompanero,
                                          d=6)
            state = game.make_move(move, state)
            player = 'X'

    else:
        print "Thinking..."
        move = games.alphabeta_search(state, game, eval_fn=heuristicaMaquina)
        state = game.make_move(move, state)
        player = 'O'

    print "-------------------"

    if game.terminal_test(state):
        game.display(state)
        if len(state.moves) == 0:
    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        print("El jugador ha movido en: ", (x, y))
        player = 'X'
    else:
        print "Thinking..."
        #move = games.minimax_decision(state, game)
        #move = games.alphabeta_full_search(state, game)
        move = games.alphabeta_search(state,
                                      game,
                                      d=int(difficulty),
                                      eval_fn=h1)
        state = game.make_move(move, state)
        print("La maquina ha movido en: ", move)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"
        break
Example #54
0
while True:
    print "Jugador a mover:", game.to_move(state)
    game.display(state)

    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        player = 'X'
    else:
        print "Thinking..."
        #move = games.minimax_decision(state, game)
        #move = games.alphabeta_full_search(state, game)
        #move = games.alphabeta_search(state, game, eval_fn=heuristic.h0)
        move = games.alphabeta_search(state, game)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"
        break
Example #55
0
game = games.ConnectFour()
state = game.initial
player = game.to_move(state)
welcome = "New Game of {0} and begin the player {1}"
print welcome.format(game, player).center(80, "*")
adversary_computer = players()
if adversary_computer:
    depth = difficulty()


while True:
    print "It's up to: ", game.to_move(state)
    print "Legal moves: ", game.legal_moves(state)
    if player == 'X':
        if adversary_computer:
            move = games.alphabeta_search(state, game, d=depth, eval_fn=heu.heuristic)
            state = game.make_move(move, state)
        else:
            state = next_state(state, game)
    else:
        state = next_state(state, game)
    game.display(state)
    print "-------------------"
    if game.terminal_test(state):
        if state.utility != 0:
            print "The winner is: ", player
        else:
            print "Draw!"
        break
    player = game.to_move(state)
def intelligent_player(game, state, depth=4):
    return alphabeta_search(state, game, d=depth, eval_fn=intel_eval_fn)
Example #57
0
while True:
    print "Jugador a mover:", game.to_move(state)
    game.display(state)

    if player == 'O':
        col_str = raw_input("Movimiento: ")
        coor = int(str(col_str).strip())
        x = coor
        y = -1
        legal_moves = game.legal_moves(state)
        for lm in legal_moves:
            if lm[0] == x:
                y = lm[1]

        state = game.make_move((x, y), state)
        player = 'X'
    else:
        print "Thinking..."
        #move = games.minimax_decision(state, game)
        #move = games.alphabeta_full_search(state, game)

        move = games.alphabeta_search(state, game, eval_fn=heuristic.posibles4EnRaya)

        state = game.make_move(move, state)
        player = 'O'
    print "-------------------"
    if game.terminal_test(state):
        game.display(state)
        print "Final de la partida"
        break