Example #1
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 #2
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 #3
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)]
        }
Example #4
0
File: c4.py Project: AntixK/Ezhil
                streak += 1
                if streak == 4:
                    return True
            else:
                streak = 0
            pos = pos + direction
    return False


POS_DIR = np.array([[[i, 0], [0, 1]] for i in range(6)] + [[[0, i], [1, 0]]
                                                           for i in range(7)] +
                   [[[i, 0], [1, 1]]
                    for i in range(1, 3)] + [[[0, i], [1, 1]]
                                             for i in range(4)] +
                   [[[i, 6], [1, -1]]
                    for i in range(1, 3)] + [[[0, i], [1, -1]]
                                             for i in range(3, 7)])

if __name__ == '__main__':
    # LET'S PLAY !

    from easyAI import Human_Player, AI_Player, Negamax, SSS, DUAL

    ai_algo_neg = Negamax(5)
    ai_algo_sss = SSS(5)
    game = ConnectFour([AI_Player(ai_algo_neg), AI_Player(ai_algo_sss)])
    game.play()
    if game.lose():
        print("Player %d wins." % (game.nopponent))
    else:
        print("Looks like we have a draw.")
    def ttentry(self):
        """
            Returns game entry
        """
        entry = [self.hands[i][j] for i in range(self.numplayers) for j in range(self.numhands)]
        entry = entry + [self.nplayer]
        return tuple(entry)  
    
    def back_to_startstate(self, move):
        """
            Checking if move will cause returning to start state - never-ending loop protection
        """
        nextstate = self.copy()
        nextstate.make_move(move)
        hands_min = min([min(nextstate.hands[i]) for i in range(self.numplayers)])
        hands_max = max([max(nextstate.hands[i]) for i in range(self.numplayers)])
        return hands_min == 1 and hands_max == 1
    
if __name__ == "__main__":
    from easyAI import Negamax, AI_Player, SSS, DUAL
    from easyAI.AI.TT import TT
    ai_algo_neg = Negamax(4)
    ai_algo_sss = SSS(4)
    dict_tt = DictTT(32, JSWHashTT())
    ai_algo_dual = DUAL(4, tt=TT(dict_tt))
    Chopsticks( [AI_Player(ai_algo_neg),AI_Player(ai_algo_dual)]).play()  #first player never wins
    
    print '-'*10
    print 'Statistics of custom dictionary:'
    print 'Calls of hash: ', dict_tt.num_calls
    print 'Collisions: ', dict_tt.num_collisions
Example #6
0
#==================================== PARAMETERS =========================================
timeNo = 20  # the no of times the test should run
player1Win = 0

pl1No = "negamax"
pl2No = "rlAgent"

pl1Steps = 4  # the number of steps each algo thinks in advanced
pl2Steps = 4

rlAgent = RLAgent('./models/mix3/train_49500.h5')

aiAlgosPl1 = {
    "negamax": Negamax(pl1Steps),
    "dual": DUAL(pl1Steps),
    "sss": SSS(pl1Steps),
    "negamaxRand": NegamaxRand(pl1Steps),
    "rlAgent": rlAgent
}

aiAlgosPl2 = {
    "negamax": Negamax(pl2Steps),
    "dual": DUAL(pl2Steps),
    "sss": SSS(pl2Steps),
    "negamaxRand": NegamaxRand(pl2Steps),
    "rlAgent": rlAgent
}
resultList = []
strategy = Strategy.NORMAL  # scoring method
strategyVal = strategy.value
model.add( Dense(10,     activation = 'relu', input_dim = 9))
model.add( Dense(100,    activation = 'relu') )
model.add( Dense(100,    activation = 'relu') )
model.add( Dense(9,      activation = 'linear') )

model.compile(loss='mse', optimizer='adam', metrics=['mae'])

# model = keras.models.load_model('./models/mix/train_49500.h5')
#=================================== PARAMETERS ==========================================

env             =   TicTacToe3D(3, (1,3,3), [Human_Player(),Human_Player() ], 4)
num_episodes    =   100000
y               =   0.95
rlFirst         =   True
decay           =   0.9999
aiAlgos         =   [SSS(5), NegamaxRand(4), NegamaxRand(2), Negamax(2)]

#=================================== TRAINING LOOP =======================================
print('Start training')
for i in range(num_episodes):

    #reset the environment
    state       =   env.reset()                         
    done        =   False                       

    #get the training conditions
    rlFirst         =   random.choice([True,False])  
    trainAlgo       =   random.choice(aiAlgos)                         
    trainPlayer     =   AI_Player(trainAlgo)

    y *= decay                                          #it learn slower after many iterations
Example #8
0
    def unmake_move(self, move): # optional method (speeds up the AI)
        self.board[int(move)-1] = 0
    
    def lose(self):
        """ Has the opponent "three in line ?" """
        return any( [all([(self.board[c-1]== self.nopponent)
                      for c in line])
                      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, SSS
    ai_algo = Negamax(10)
    TicTacToe( [AI_Player(SSS(20)),AI_Player(ai_algo)]).play()
Example #9
0
def create_sss_tt(depth):
    ai_algo_sss = SSS(depth, tt=TT())
    return create_benchmark_game(ai_algo_sss)
Example #10
0
def create_sss(depth):
    ai_algo_sss = SSS(depth)
    return create_benchmark_game(ai_algo_sss)
Example #11
0
            if board[pos[0], pos[1]] == nplayer:
                streak += 1
                if streak == 4:
                    return True
            else:
                streak = 0
            pos = pos + direction
    return False


POS_DIR = np.array([[[i, 0], [0, 1]] for i in range(6)] +
                   [[[0, i], [1, 0]] for i in range(7)] +
                   [[[i, 0], [1, 1]] for i in range(1, 3)] +
                   [[[0, i], [1, 1]] for i in range(4)] +
                   [[[i, 6], [1, -1]] for i in range(1, 3)] +
                   [[[0, i], [1, -1]] for i in range(3, 7)])

if __name__ == '__main__':
    # LET'S PLAY !

    from easyAI import Human_Player, AI_Player, Negamax, SSS, DUAL

    ai_algo_neg = SSS(5)
    ai_algo_sss = SSS(7)
    game = ConnectFour([AI_Player(ai_algo_sss), AI_Player(ai_algo_neg)])
    game.play()
    if game.lose():
        print("Player %d wins." % (game.nopponent))
    else:
        print("Looks like we have a draw.")
Example #12
0
def get_pm(moves):
    game = Gomoku([AI_Player(SSS(1)), AI_Player(SSS(1))], moves=moves)
    next_move = game.possible_moves()
    nml = [moves + [x] for x in next_move]
    return nml
Example #13
0
            for j in range(self.numhands)
        ]
        entry = entry + [self.nplayer]
        return tuple(entry)

    def back_to_startstate(self, move):
        """
            Checking if move will cause returning to start state - never-ending loop protection
        """
        nextstate = self.copy()
        nextstate.make_move(move)
        hands_min = min(
            [min(nextstate.hands[i]) for i in range(self.numplayers)])
        hands_max = max(
            [max(nextstate.hands[i]) for i in range(self.numplayers)])
        return hands_min == 1 and hands_max == 1


if __name__ == "__main__":
    from easyAI import Negamax, AI_Player, SSS, DUAL, MTDbi, MTDf, MTDstep
    from easyAI.AI.TT import TT

    dict_tt = DictTT(32)
    ai_algo_sss = SSS(6, tt=TT(dict_tt))  # SSS algorithm
    ai_algo_neg = Negamax(6, tt=TT(dict_tt))  # Negamax algorithm
    ai_algo_bi = MTDbi(6, tt=TT(dict_tt))  # MTDbi algorithm
    ai_algo_f = MTDf(5, tt=TT(dict_tt))  # MTDf algorithm
    ai_algo_step = MTDstep(5, tt=TT(dict_tt))  # MTDstep algorithm
    ai_algo_dual = DUAL(4, tt=TT(dict_tt))  # DUAL algorithm
    Chopsticks([AI_Player(ai_algo_neg), AI_Player(ai_algo_step)]).play()
    dict_tt.print_stats()