Example #1
0
def gomoku_AI_run():
    table = TranspositionTable()
    ai_1 = AI_Player(Negamax(2, tt=table))
    ai_2 = AI_Player(Negamax(2, tt=table))
    game = Gomoku([ai_1, ai_2], moves=['H8', 'I7', 'G7', 'I9', 'G6'])
    game.play()
    set_trace()
Example #2
0
def tt_s(idx, mv_i):
    table = TranspositionTable()
    ai_1 = AI_Player(Negamax(4, tt=table))
    ai_2 = AI_Player(Negamax(4, tt=table))
    game = Gomoku([ai_1, ai_2], moves=mv_i)
    game.play(nmoves=8, verbose=False)
    table.to_file(f"{DIR}tt_{idx}.data")
Example #3
0
 def _nextmove(self, State):
     AIClient.ttentry = lambda self: State  # Send State to the Transposition tables
     AI = Negamax(6, tt=TT(), win_score=90
                  )  # Algorithm(depth, scoring=None, win_score=inf,tt=None)
     Quarto = AIClient([AI_Player(AI), AI_Player(AI)], State)
     Move = Quarto.get_move()  # find the best move possible
     return json.dumps(Move)  # send the Move
Example #4
0
def tt_s(depth, mv_i):
    table = TranspositionTable()
    ai_1 = AI_Player(Negamax(depth, tt=table))
    ai_2 = AI_Player(Negamax(depth, tt=table))
    game = Gomoku([ai_1, ai_2], moves=mv_i.tolist())
    game.play(nmoves=1, verbose=False)
    rst = {key: value for key, value in table.d.items() if value['depth'] == depth}
    return rst
Example #5
0
def tt_s(idx, mv_i):
    table = TranspositionTable()
    table.from_file(f"{DIR}gtt3s.data")
    ai_1 = AI_Player(SSS(4, tt=table))
    ai_2 = AI_Player(SSS(4, tt=table))
    game = Gomoku([ai_1, ai_2], moves=mv_i)
    game.play(verbose=False)
    table.to_file(f"{DIR}tt3s_{idx}.data")
Example #6
0
 def __init__(self):
     self.table = DictTT()
     self.algo = Negamax(
         4,
         win_score=1000,
         tt=self.table
     )
     AI_Player.__init__(self, self.algo)
     Player.__init__(self)
Example #7
0
def gomoku_AI_run():
    table = TranspositionTable()
    table.from_file(f"{DIR}gtt.data")
    print(len(table.d))
    set_trace()
    ai_1 = AI_Player(Negamax(3, tt=table))
    ai_2 = AI_Player(Negamax(3, tt=table))
    game = Gomoku([ai_1, ai_2], moves=['H8', 'I7', 'G7'])
    game.play()
    print(len(table.d))
    set_trace()
Example #8
0
 def _nextmove(self, State):
     QuartoMind.ttentry = lambda self: State  # Send State to the Transposition tables
     quarto_algo_neg = SSS(
         3)  # Algorithm(depth, scoring=None, win_score=inf)
     quarto_algo_sss = Negamax(
         6, win_score=90,
         tt=TT)  # Algorithm(depth, scoring=None, win_score=inf,tt=None)
     Quarto = QuartoMind(
         [AI_Player(quarto_algo_neg),
          AI_Player(quarto_algo_sss)], State)
     print(str(Quarto.get_move()))
     move = Quarto.get_move()  # find best move possible
     return json.dumps(move)  # send the Move
Example #9
0
    def _nextmove(self, state):
        visible = state._state['visible']
        move = {}

        #List of the number of free places on the board
        verif = []
        for i in range(4):
            verif.append([visible['board'][4 * i + e]
                          for e in range(4)].count(None))
            verif.append([visible['board'][4 * e + i]
                          for e in range(4)].count(None))
        verif.append([visible['board'][5 * e] for e in range(4)].count(None))
        verif.append([visible['board'][3 + 3 * e]
                      for e in range(4)].count(None))

        #First is a random AI
        if verif.count(1) == 0:
            ls_test = [i for i, x in enumerate(visible['board']) if x == None]

            # select a random position

            if visible['pieceToPlay'] is not None:
                move['pos'] = random.choice(ls_test)

            # select a random piece

            test1 = visible['remainingPieces']
            a = random.randint(0, len(test1) - 2)
            move['nextPiece'] = a

            # applymove will raise if we announce a quarto while there is not
            move['quarto'] = True
            try:
                state.applymove(move)
            except:
                del (move['quarto'])

            return json.dumps(move)  # send the move

        #When the number of free place per line/column/diag is brought down to 1, begin easyAI
        else:
            easyAI.ttentry = lambda self: state
            ai_algo_neg = Negamax(6, tt=TT(), win_score=90)  # Algorithm
            Quarto = easyAI([AI_Player(ai_algo_neg),
                             AI_Player(ai_algo_neg)], state)
            best_move = Quarto.get_move()  # find the best move possible
            print("BEST MOVE", best_move)
            return json.dumps(best_move)  # send the Move
Example #10
0
def aieasyup(body):
    grid = body["game"]
    tower = body["players"].index(body["you"])
    depth = 2
    if len(body["moves"]) > 24:
        depth = (len(body["moves"]) // 8)
    print(depth)
    ai = Negamax(depth)
    game = Avalam([AI_Player(ai), Human_Player()], grid, tower)
    ai_move = game.get_move()
    move = {"from": ai_move[0], "to": ai_move[1]}
    return {"move": move}


# grid2 = [[[], [], [], [], [], [], [], [], []], [[], [], [], [], [], [], [], [], []], [[], [], [], [], [1, 1, 0, 0, 1], [], [], [], []], [[], [], [], [], [0], [], [0, 0, 1, 1], [], [0, 0, 0, 1, 1]], [[], [], [1, 1, 1, 0, 0], [], [], [], [1, 1, 0, 1, 0], [], []], [[], [], [0], [1, 0], [0], [1], [], [], []], [[1], [0], [1, 1, 0, 0], [0], [1], [0], [1, 0], [], []], [[], [1], [0], [1], [0], [1], [], [], []], [[], [], [], [], [1], [0], [], [], []]]
# grid0 = [
# 		[ [],  [],  [], [], [],  [],  [],  [],  []],
# 		[ [],  [],  [], [], [], [], [], [],  []],
# 		[ [],  [], [], [0, 1], [], [], [], [], []],
# 		[ [],  [], [], [1,0,1], [0,1,0], [], [], [], []],
# 		[ [], [], [], [],  [], [], [], [],  []],
# 		[ [1], [1], [], [1], [], [1,1,0,0,1], [],  [],  []],
# 		[ [0], [], [], [], [0], [], [],  [],  []],
# 		[ [], [], [], [], [], [],  [],  [],  []],
# 		[ [],  [],  [],  [], [], [],  [],  [],  []]
# 	]
# ai = Negamax(3)
# game = Avalam([AI_Player(ai), Human_Player()], grid0, 1)
# # score = game.scoring()
# # print(score)
# # print(game.make_move([[3, 4], [2, 3]]))
# # print(game.show())
# ai_move = game.get_move()
# print(ai_move)
# game.play()
Example #11
0
class LastCoin_game(TwoPlayersGame):
	def __init__(self, players):
		self.players = players
		self.nplayer = 1
		self.num_coins = 15
		self.max_coins = 4

	def possible_moves(self):
	return [str(a) for a in range(1, self.max_coins + 1)]
#Define the removal of the coins .
	def make_move(self, move):
		self.num_coins -= int(move)
#Define who took the last coin.
	def win_game(self):
		return self.num_coins <= 0
#Define when to stop the game, that is when somebody wins.
	def is_over(self):
		return self.win()
#Define how to compute the score.
	def score(self):
		return 100 if self.win_game() else 0
#Define number of coins remaining in the pile.
	def show(self):
		print(self.num_coins, 'coins left in the pile')
if __name__ == "__main__":
	tt = TT()
#LastCoin_game.ttentry = lambda self: self.num_coins
#Solving the game with the following code block:
	r, d, m = id_solve(LastCoin_game,
	range(2, 20), win_score=100, tt=tt)
	print(r, d, m)
	#Deciding who will start the game
	game = LastCoin_game([AI_Player(tt), Human_Player()])
	game.play()
Example #12
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
Example #13
0
def main():

    # Search algorithm of the AI player
    algorithm = Negamax(7)

    # Start the game
    ConnectFour([Human_Player('R'), AI_Player(algorithm, 'Y')]).play()
Example #14
0
    def onMessage(self, author_id, message_object, thread_id, thread_type,
                  **kwargs):
        self.markAsDelivered(thread_id, message_object.uid)
        self.markAsRead(thread_id)

        if author_id != self.uid:
            messenger = message_object.text
            if messenger == 'inicio':
                self.send(Message(text="Comiensa el juego"),
                          thread_id=thread_id,
                          thread_type=thread_type)
                ai_algo = Negamax(6)
                tresenraya = TresEnRaya([Human_Player(), AI_Player(ai_algo)])
                tresenraya.play()
            else:
                print(messenger)
                traduccion = traducir(messenger, language_translator)
                print(traduccion)
                respuesta = mensaje(traduccion, session)
                print(respuesta)
                voz(respuesta, service)
                guardarPregunta(con, messenger, respuesta, traduccion)
                #self.send(Message(text=respuesta), thread_id=thread_id, thread_type=thread_type)
                self.sendLocalVoiceClips('output.mp3',
                                         Message(text=respuesta),
                                         thread_id=thread_id,
                                         thread_type=thread_type)
Example #15
0
def play_game():
    ttt = TicTacToe([Human_Player(), AI_Player(ai_algo)])
    while not (ttt.is_over()):
        #ttt = TicTacToe([AI_Player(ai_algo), AI_Player(ai_tup)])
        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():
                print('ggg')
                print(ttt.nplayer)
                ai_move = ttt.get_move()
                ttt.play_move(ai_move)
                print('ggg')
                print(ttt.nplayer)
                #ai_move = ttt.get_move()
                #ttt.play_move(request.form["choice"])
                #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
Example #16
0
    def opp(self, x, y):  # add opponent turn to internal data structure
        if self.start:
            self.ttt = GomokuGame(
                [Human_Player(), AI_Player(self.ai_algo)], self.width, 1)
            self.start = False

        self.ttt.play_move([x, y])
Example #17
0
def play_game():
    global ttt
    game_cookie = request.cookies.get('game_board')
    reset = False
    if "choice" in request.form:
        req = (request.form["choice"].split(','))
        coord = [int(req[0]), int(req[1])]
        ttt.play_move(coord)
        if not ttt.is_over2():
            ai_move = ttt.get_move()
            ttt.play_move(ai_move)
    if "reset" in request.form:
        ttt.hboard = tuple(np.zeros((width, width), np.int8))
        ttt.htob()
        reset = True

    msg = ttt.winner()
    resp = make_response(render_template_string(TEXT, ttt=ttt, msg=msg))
    pickled = (pickle.dumps(pack(ttt.hboard)))
    resp.set_cookie("game_board", pickled)
    if reset:
        ttt = GomokuGame([Human_Player(), AI_Player(ai_algo)], width, 1)
        ttt.hboard = tuple(np.zeros((width, width), np.int8))
        ttt.htob()
        resp.set_cookie('game_board', '', expires=0)
    return resp
Example #18
0
        def make_move(self, move):
            self.num_coins -= int(move)

            def win_game(self):
                return self.num_coins <= 0

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

            def score(self):
                return 100 if self.win_game() else 0

            def show(self):
                print(self.num_coins, 'coins left in the pile')

            if __name__ == "__main__":
                tt = TT()
                LastCoin_game.ttentry = lambda self: self.num_coins
                r, d, m = id_solve(LastCoin_game,
                                   range(2, 20),
                                   win_score=100,
                                   tt=tt)
                print(r, d, m)
                game = LastCoin_game([AI_Player(tt), Human_Player()])
                game.play()
Example #19
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!")
Example #20
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!")
Example #21
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!")
Example #22
0
def play_perfect(state):
    ai = Negamax(28)
    easy_ai = GameOfDomino([AI_Player(ai), Human_Player()])
    easy_ai._state = state
    move = easy_ai.get_move()
    easy_ai.play_move(move)

    return easy_ai._state
Example #23
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!")
Example #24
0
def play_gomoku():
    # Load transposition table
    table = TranspositionTable()
    table.from_file(f"{DIR}gtt3s.data")
    ply_1 = Human_Player()
    ply_2 = AI_Player(SSS(4))
    game = Gomoku([ply_1, ply_2], moves=['H8', 'I7'], show='test')
    game.play()
    set_trace()
Example #25
0
def main():

    # Search algorithm of the AI player
    algorithm = Negamax(18)

    # Start the game
    #TronGameController([Human_Player(), Human_Player()]).play()
    #TronGameController([AI_Player(algorithm), AI_Player(SSS(18))]).play()
    TronGameController([Human_Player(), AI_Player(algorithm)]).play()
Example #26
0
def main():

    # Search algorithm of the AI player

    # Start the game
    try:
        input('Press Enter to start!')
        algorithm = Negamax(1)
        #TronGameController([Human_Player(mlp=mlp, encoders=encoder), Human_Player(mlp=mlp, encoders=encoder)]).play()
        TronGameController([Human_Player(mlp=mlp, encoders=encoder), AI_Player(algorithm)]).play()
    except FloatingPointError:
        main()
Example #27
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 ''
 
        self.body = cherrypy.request.json
        if self.body["players"][0] == self.body["you"]:
            self.couleur = 0
        else:
            self.couleur = 1
        match = Match([AI_Player(Negamax(4)),Human_Player()], self.body, self.couleur)
        nextMove = match.get_move()
        a = nextMove.split()
 
        return {"move": {"cube": int(a[0]),
                         "direction": a[1]}} 
Example #28
0
def play_game():
    global ttt 
    reset = False
    if "choice" in request.form:
        req = (request.form["choice"].split(','))
        coord = [ int(req[0]), int(req[1])]
        ttt.play_move(coord)
        if not ttt.is_over2():
            ai_move = ttt.get_move()
            ttt.play_move(ai_move)
    if "reset" in request.form:
        ttt.hboard = tuple(np.zeros((width, width), np.int8))
        ttt.htob()
        reset = True

    msg = ttt.winner()
    resp = make_response(render_template_string(TEXT, ttt=ttt, msg=msg))
    if reset:
        ttt = GomokuGame([Human_Player(), AI_Player(ai_algo)],width,1)
    return resp
Example #29
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()
Example #30
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 ''

        body = cherrypy.request.json

        if len(
                body['moves']
        ) <= 25:  #sert à déterminer la profondeur de recherche, SSS pourrait être remplacé par Negamax mais c'est moins performant
            ai_algo = SSS(3)
            ai_algo2 = SSS(3)

        if 25 < len(body['moves']) <= 40:
            ai_algo = SSS(5)
            ai_algo2 = SSS(3)

        if 40 < len(body['moves']) <= 150:
            ai_algo = SSS(6)
            ai_algo2 = SSS(3)

        game = Avalam(
            [AI_Player(ai_algo), AI_Player(ai_algo2)]
        )  #dit que game est de classe Avalam et détermine les algorithmes à utiliser
        #game.play(1)
        movelist = game.get_move(
        )  #permet de prendre en une liste le move fait.[[postion initiale],[position finale],[nombre de pions déplacés]]
        messagelist = [
            "Ton IA va faire aïe",
            "On va tellement te défoncer que tu vas finir sur Giteub",
            "C'est une IA qui joue là ou c'est aléatoire ?",
            "Tu feras mieux la prochaine fois",
            " T'aurais mieux fait d'étudier mécaflotte que de coder ça",
            "Souriez, vous êtes cernés", "Elle est où ma limonaaaaaaaade ?",
            "Cython AI marche pas, reviens l'année prochaine",
            "On me dit à l'oreillette que t'auras pas les 2.5 points bonus",
            "  J’adore l’odeur de la victoire au petit matin",
            " Tu vois, le monde se divise en deux catégories: ceux qui ont une IA chargée et ceux qui creusent. Toi tu creuses.",
            "Trois syllabes, huit lettres et un seul sens : T'as perdu.",
            " Figurez-vous que votre IA n’est pas moche, elle n’a pas un physique facile… c’est différent.",
            "C’est pas ton IA qui va voler nos jobs",
            "C'est quand même bien mieux une IA propre, non ? À l'occasion, je vous mettrai un petit coup de polish.",
            "23-0 ! C'est la piquette Jack !!! Tu sais pas jouer, Jack ! T'es mauvais hahahahaha !!!",
            "On est en 1955 les gars, faut se réveiller. Les boucles for partout, ne pas utiliser Cython, l'écriture illisible, ça va hein ! S'agirait de grandir ! S'agirait de grandir...",
            "Une défaite c'est quand les IA sont communistes, déjà. Qu'elles ont froid, avec des chapeaux gris et des chaussures à fermeture éclair. C'est ça, une défaite, Dolorès",
            "Ça fait un peu Jacadi a dit : « Pas de bon move !",
            "Chou blanc donc…",
            "J'appelle ça l'IA, mademoiselle. Et pas n'importe laquelle ; l'IA du général de Gaulle.",
            "Ou tu sors ou je te sors...",
            "Je ne crois pas qu'il y ait de bonne ou de mauvaise IA...ah bah si, la tienne",
            "Alors, on n'attend pas Patrick ?", "Cassé !!!",
            "J'ai glissé chef...",
            "Les IA connes ça ose tout. C’est même à ça qu’on les reconnait",
            "Une grande IA implique de grandes responsabilités",
            "Faut arrêter ces conneries de nord et de sud ! Une fois pour toutes, le nord, suivant comment on est tourné, ça change tout !",
            "Ah ! oui... j' l'ai fait trop fulgurant, là. Ça va ?",
            "Une fois, à une exécution, je m'approche d'une fille. Pour rigoler, je lui fais : « Vous êtes de la famille de l'IA ? »... C'était sa sœur. Bonjour l'approche !",
            "On en a gros !", "PAYS DE GALLES INDÉPENDAAAAANT !",
            "SI VOUS VOULEZ QU'ON SORTE LES PIEDS DEVANT, FAUDRA NOUS PASSER SUR L'COOOORPS !",
            "Je vu ton IA une fois dans une carriole, tirée par un cheval. Enfin, la carriole tirée par un cheval.",
            "Mais cherchez pas à faire des phrases pourries... On en a gros, c'est tout !",
            "Vous, vous avez une idée derrière la main, j'en mettrais ma tête au feu!",
            "Faut pas respirer la compote, ça fait tousser.",
            " Et deux jus de pomme qui piquent !",
            "Nouvelle technique : on passe pour des cons, les autres se marrent, et on frappe. C’est nouveau."
        ]  #répliques librement inspirées d'OSS 117, Kaamelott, Rap Contenders,... et notre imagination.
        return {
            "move": {
                'from': movelist[0],
                'to': movelist[1]
            },
            "message": messagelist[random.randint(0,
                                                  len(messagelist) - 1)]
        }
    def scoring(self):
        return 100 if self.win() else 0

    def ttentry(self):
        return tuple(self.piles)  # optional, speeds up AI


if __name__ == "__main__":
    # IN WHAT FOLLOWS WE SOLVE THE GAME AND START A MATCH AGAINST THE AI

    from easyAI import AI_Player, Human_Player, Negamax, id_solve
    from easyAI.AI import TT
    # we first solve the game
    w, d, m, tt = id_solve(Nim, range(5, 20), win_score=80)
    print
    w, d, len(tt.d)
    # the previous line prints -1, 16 which shows that if the
    # computer plays second with an AI depth of 16 (or 15) it will
    # always win in 16 (total) moves or less.

    # Now let's play (and lose !) against the AI
    ai = Negamax(16, tt=TT())
    game = Nim([Human_Player(), AI_Player(tt)])
    game.play()  # You will always lose this game !
    print("player %d wins" % game.nplayer)

    # Note that with the transposition table tt generated by id_solve
    # we can setup a perfect AI which doesn't have to think:
    # >>> game = Nim( [ Human_Player(), AI_Player( tt )])
    # >>> game.play() # You will always lose this game too!