Пример #1
0
    def move(self):
        # Deal with CORS
        cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'
        cherrypy.response.headers[
            'Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
        cherrypy.response.headers[
            'Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With'
        if cherrypy.request.method == "OPTIONS":
            return ''

        #Récupération des données du jeu
        body = cherrypy.request.json
        game = body['game']
        players = body['players']
        you = body['you']
        pion = check_player(players, you)

        #Démarage de l'algorithme de recherche du meilleur move
        ai_algo = Negamax(depth(count_moves(game)))
        a = AvalamAI([AI_Player(ai_algo), Human_Player()], game, pion)
        move = a.player.ask_move(a)
        json_move = {
            "move": {
                "from": move[0],
                "to": move[1]
            },
            "message": "What do you say about that?!"
        }
        return json_move
Пример #2
0
def play_game_transposition_table(size=6):
    ai_algo = Negamax(4, tt=TT())
    game = Gomoku_Strategic([Human_Player(), AI_Player(ai_algo)], size)
    game.play()
    if game.lose():
        print("Player %d wins!" % game.nopponent)
    else:
        print("Draw!")
Пример #3
0
def play_game_simple():
    ai_algo = Negamax(5)
    game = Gomoku_optimized([Human_Player(), AI_Player(ai_algo)], 5)
    game.play()
    if game.lose():
        print("Player %d wins!" % game.nopponent)
    else:
        print("Draw!")
Пример #4
0
def play_game_simple(size=6):
    ai_algo = Negamax(4)
    game = Gomoku_Strategic([Human_Player(), AI_Player(ai_algo)], size)
    game.play()
    if game.lose():
        print("Player %d wins!" % game.nopponent)
    else:
        print("Draw!")
Пример #5
0
def play_game_transposition_table():
    ai_algo = Negamax(5, tt=TT())
    game = Gomoku_optimized([Human_Player(), AI_Player(ai_algo)], 5)
    game.play()
    if game.lose():
        print("Player %d wins!" % game.nopponent)
    else:
        print("Draw!")
Пример #6
0
def play_iterative_deepening(size=6, timeout=5):
    game = Gomoku_Strategic(
        [Human_Player(),
         AI_Player_Iterative_Deepening(timeout=timeout)], size)
    game.play()
    if game.lose():
        print("Player %d wins!" % game.nopponent)
    else:
        print("Draw!")
Пример #7
0
def play_game():
    ttt = TicTacToe([Human_Player(), AI_Player(ai_algo)])
    game_cookie = request.cookies.get('game_board')
    if game_cookie:
        ttt.board = [int(x) for x in game_cookie.split(",")]
    if "choice" in request.form:
        ttt.play_move(request.form["choice"])
        if not ttt.is_over():
            ai_move = ttt.get_move()
            ttt.play_move(ai_move)
    if "reset" in request.form:
        ttt.board = [0 for i in range(9)]
    if ttt.is_over():
        msg = ttt.winner()
    else:
        msg = "play move"
    resp = make_response(render_template_string(TEXT, ttt=ttt, msg=msg))
    c = ",".join(map(str, ttt.board))
    resp.set_cookie("game_board", c)
    return resp
Пример #8
0
def solve_game_df():
    ai_algo = Negamax(10, tt=TT())
    game = Gomoku_optimized([Human_Player(), AI_Player(ai_algo)], 5)
    result = df_solve(game, win_score=100, maxdepth=10, tt=TT(), depth=0)
    print result
Пример #9
0
    def make_move(self, move):
        self.board[int(move) - 1] = self.nplayer

    def umake_move(self, move):
        self.board[int(move) - 1] = 0

    def condition_for_lose(self):
        possible_combinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
                                 [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
        return any([
            all([(self.board[z - 1] == self.nopponent) for z in combination])
            for combination in possible_combinations
        ])

    def is_over(self):
        return (self.possible_moves() == []) or self.condition_for_lose()

    def show(self):
        print('\n' + '\n'.join([
            ' '.join([['.', 'O', 'X'][self.board[3 * j + i]]
                      for i in range(3)]) for j in range(3)
        ]))

    def scoring(self):
        return -100 if self.condition_for_lose() else 0


if __name__ == "__main__":
    algo = Negamax(7)
    TicTacToe_game([Human_Player(), AI_Player(algo)]).play()
Пример #10
0
                return get_bottom_left(first_move)
        if not get_top_right(first_move) is None:
            if destination == get_top_right(get_top_right(first_move)):
                return get_top_right(first_move)
        if not get_top_left(first_move) is None:
            if destination == get_top_left(get_top_left(first_move)):
                return get_top_left(first_move)
        if board[first_move] in ['X', 'Y']:
            brd = get_bottom_right_diagonal(first_move)
            bld = get_bottom_left_diagonal(first_move)
            trd = get_top_right_diagonal(first_move)
            tld = get_top_left_diagonal(first_move)
            if not brd is None:
                if destination in brd:
                    return get_top_left(destination)
            if not bld is None:
                if destination in bld:
                    return get_top_right(destination)
            if not trd is None:
                if destination in trd:
                    return get_bottom_left(destination)
            if not tld is None:
                if destination in tld:
                    return get_bottom_right(destination)
    return None


if __name__ == "__main__":
    pygame.init()
    GameController([Human_Player(), AI_Player(Negamax(6))]).play()
Пример #11
0
            for y, n in enumerate(row):
                self.board[x, y] = n
        self.players[0].pos = string2pos(entry[-2])
        self.players[1].pos = string2pos(entry[-1])

    def show(self):
        print('\n' + '\n'.join(['  1 2 3 4 5 6 7 8'] +
              ['ABCDEFGH'[k] + 
               ' ' + ' '.join([['.', '1', '2', 'X'][self.board[k, i]]
               for i in range(self.board_size[0])])
               for k in range(self.board_size[1])] + ['']))

    def lose(self):
        return self.possible_moves() == []

    def scoring(self):
        return -100 if (self.possible_moves() == []) else 0

    def is_over(self):
        return self.lose()


if __name__ == "__main__":
    from easyAI import AI_Player, Negamax
    from easyAI.Player import Human_Player

    ai_algo = Negamax(11)
    game = Knights([AI_Player(ai_algo), Human_Player()], (5, 5))
    game.play()
    print("player %d loses" % (game.nplayer))
Пример #12
0
            for line in [
                [1, 2, 3],
                [4, 5, 6],
                [7, 8, 9],  # horiz.
                [1, 4, 7],
                [2, 5, 8],
                [3, 6, 9],  # vertical
                [1, 5, 9],
                [3, 5, 7]
            ]
        ])  # diagonal

    def is_over(self):
        return (self.possible_moves() == []) or self.lose()

    def show(self):
        print('\n' + '\n'.join([
            ' '.join([['.', 'O', 'X'][self.board[3 * j + i]]
                      for i in range(3)]) for j in range(3)
        ]))

    def scoring(self):
        return -100 if self.lose() else 0


if __name__ == "__main__":

    from easyAI import AI_Player, Negamax
    ai_algo = Negamax(6)
    TicTacToe([Human_Player(), AI_Player(ai_algo)]).play()
        for row in range(6):
            index = column + row*7
            if self.board[index] != 0:
                self.board[index] = 0
                return

    def lose(self):
        return any([all([(self.board[c] == self.nopponent)
                         for c in line])
                    for line in self.tuples])

    def is_over(self):
        return (self.possible_moves() == []) or self.lose()

    def show(self):
        print('\n'+'\n'.join([
            ' '.join([['.', 'O', 'X'][self.board[7*row+column]]
                      for column in range(7)]
                     )
            for row in range(6)])
        )

    def scoring(self):
        return -100 if self.lose() else 0


if __name__ == "__main__":
    from easyAI import AI_Player, Negamax
    ai_algo = Negamax(6)
    ConnectFour([Human_Player(), AI_Player(ai_algo)]).play()
Пример #14
0
    # El 7 significa que la IA anticipa 7 movimientos antes de mover
    algorithm = Negamax(7)

    # Título de la aplicación
    print('TicTacToe con easyAI')

    # Se pregunta al usuario el número de jugadores humanos
    players = -1
    while players < 0 or players > 2:
        players = int(input('Jugadores humanos (0, 1, 2): '))

    # Se configura el juego con el parámetro de número de jugadores
    game = None
    if players == 2:
        # Se inicia el juego con dos jugadores humanos
        game = TicTacToeGame([Human_Player(), Human_Player()])
    elif players == 1:
        # Se inicia el juego con un jugador humano
        game = TicTacToeGame([Human_Player(), AI_Player(algorithm)])
    elif players == 0:
        # Se inicia el juego con cero jugadores humanos (2 IA)
        game = TicTacToeGame([AI_Player(algorithm), AI_Player(algorithm)])

    # Se inicia el juego
    game.play()

    # Se comprueba la condición de victoria
    winner = game.check_winner()

    # Se imprime el ganador (o tablas si no ha ganado nadie)
    if winner == 1:
Пример #15
0
 def add_human_player(self):
     """adds HumanPlayer, helper function for cli integration
     it always set value_for_negamax to 1 as it does not matter
     """
     self.players.append(Human_Player())
     self.values_for_negamax.append(1)
Пример #16
0
        if self.is_over():
            if self.lose(tour_top_zero, tour_top_un): return -300
            elif self.win(tour_top_zero, tour_top_un): return 300
            else: return 0  #EGALITE
        else:
            return 10 * (self.score_tour(tour_top_zero, tour_top_un)) - 5 * (
                self.score_tour_lonely(tour_lonely_zero, tour_lonely_un)
            ) + 1 * (self.score_tour_full(tour_full_zero, tour_full_un))


#Utilisé pour le debuggage
if __name__ == "__main__":

    from easyAI import AI_Player, Negamax

    game = [[[], [], [], [], [], [], [], [], []],
            [[], [], [], [], [0, 0], [], [], [], []],
            [[], [], [], [], [1], [], [], [], []],
            [[], [], [], [1], [0], [1], [], [], []],
            [[], [], [], [], [0, 1, 0, 1], [1], [], [], []],
            [[], [], [], [], [], [], [], [], []],
            [[], [], [], [], [], [], [], [], []],
            [[], [], [], [], [], [], [], [], []],
            [[], [], [], [], [], [], [], [], []]]

    pion = 1

    ai_algo = Negamax(6)
    t = AvalamAI([AI_Player(ai_algo), Human_Player()], game, 1)
    move = t.player.ask_move(t)
    print(move)
Пример #17
0
        self.board = [0] * 9

    def possible_moves(self):
        return [a + 1 for a, b in enumerate(self.board) if b == 0]

    def make_move(self, move):
        self.board[int(move) - 1] = self.nplayer

    def loss_condition(self):
        possible_combinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9],
                                 [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]

        return any([all([(self.board[i - 1] == self.nopponent)
                     for i in combination]) for combination in
                possible_combinations])

    def is_over(self):
        return (self.possible_moves() == []) or self.loss_condition()

    def show(self):
        print('\n' + '\n'.join([' '.join([['. ', 'O', 'X'][self.board[3 * j +
                                                                      i]]
                                          for i in range(3)]) for j in range(3)]))

    def scoring(self):
        return -100 if self.loss_condition() else 0

if __name__ == "__main__":
    algorithm = Negamax(7)
    TicTacToe([Human_Player(), AI_Player(algorithm)]).play()
Пример #18
0
        """
        print('\\', end=' ')
        for x in range(self.size):
            print(x + 1, end=' ')
        print('')
        for i in range(self.size):
            print(i + 1, end=' ')
            for j in range(self.size):
                if self.board[i][j] == 1:
                    print("0", end=' ')
                elif self.board[i][j] == 2:
                    print("X", end=' ')
                else:
                    print(".", end=' ')
            print("")

    def scoring(self):
        """
        The function to score player

        Returns:
        score (int): -1000 when lose, 500 when win
        """
        return -1000 if self.lose() else 500


if __name__ == "__main__":
    from easyAI import AI_Player, Negamax
    ai_algo = Negamax(6)
    PticPtacPtoc([Human_Player(), AI_Player(ai_algo)]).play()
Пример #19
0
        possible_combinations = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7],
                                 [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]

        return any([
            all([(self.board[i - 1] == self.nopponent) for i in combination])
            for combination in possible_combinations
        ])

    # Check if the game is over
    def is_over(self):
        return (self.possible_moves() == []) or self.loss_condition()

    # Show current position
    def show(self):
        print('\n' + '\n'.join([
            ' '.join([['.', 'O', 'X'][self.board[3 * j + i]]
                      for i in range(3)]) for j in range(3)
        ]))

    # Compute the score
    def scoring(self):
        return -100 if self.loss_condition() else 0


if __name__ == "__main__":
    # Define the algorithm
    algorithm = Negamax(7)

    # Start the game
    GameController([Human_Player(), AI_Player(algorithm)]).play()
Пример #20
0
def solve_game_df():
    # to run this method we need to modify the max score to 100(check with self.win())
    ai_algo = Negamax(10, tt=TT())
    game = Gomoku_Strategic([Human_Player(), AI_Player(ai_algo)], 5)
    result = df_solve(game, win_score=100, maxdepth=10, tt=TT(), depth=0)
    print result