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")
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()
def run_games(self, generations): for generation in range(generations): print(f"Generation: {generation}") if generation == 0: self.genes = np.random.normal(0,1,(self.count, self.gene_size)) else: # selection new_genes = np.zeros((self.count, self.gene_size)) best_genes = self.get_best() new_genes[:len(best_genes)] = best_genes for i in range(len(best_genes), self.count): new_genes[i] = self.create() self.genes = new_genes self.fitness = np.zeros(self.count) # crossover self.players = [Negamax(self.depth, scoring=self.scoring(gene), tt=TT()) for gene in self.genes] num_games = self.count * self.count game_count = 0 for i, gene1 in enumerate(self.genes): for j, gene2 in enumerate(self.genes): if game_count % 100 == 0: self.tt.tofile(self.tt_file_name) print(f"Played game: {game_count} / {num_games}") game_count += 1 if i == j: continue result = self.game(self.players[i],self.players[j]) if result == 0: self.fitness[i] += 0.5 self.fitness[j] += 0.5 if result == 1: self.fitness[i] += 1 if result == 2: self.fitness[j] += 1 self.prob = self.fitness / self.fitness.sum() idx = np.argmax(self.prob) best_gene = self.genes[idx] print(f"Best player: {best_gene}") print(f"Best fitness: {np.max(self.fitness)/(2*(self.count - 1))}") negamax = Negamax(self.depth, tt=TT()) negamax_best = self.players[idx] score1 = self.game(negamax, negamax_best) print(f"When normal Negamax started: {score1}") score2 = self.game(negamax_best, negamax) print(f"When best player started: {score2}")
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
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()
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
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()
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)
def main(): # Search algorithm of the AI player algorithm = Negamax(7) # Start the game ConnectFour([Human_Player('R'), AI_Player(algorithm, 'Y')]).play()
def f(offset, max_exp): if max_exp == 0: return offset for i in range(max_exp + 1): n_playout = offset + 2**i print(f"Number of playouts {n_playout}") draws = 0 wins = [0, 0] player1 = MCTSPlayer(n_playout=n_playout, win_score=100) player2 = Negamax(depth=depth, tt=tt) players = [player1, player2] game = Game(9) while not game.is_terminal(): move = players[game.index](game) game.make_move(move) end, player = game.game_end() if end: wins[player] += 1 if player == 0: return min(n_playout, f(offset + 2**(i - 1) + 1, i - 1)) return 10000000
def add_ai_player(self, value: int): """adds AI player with given value for Negamax algorithm helper function for cli integration Args: value (int): value to be set for Negamax algorithm """ self.players.append(AI_Player(Negamax(value))) self.values_for_negamax.append(value)
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
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!")
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!")
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!")
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!")
def play_gomoku(): # Load transposition table table = TranspositionTable() table.from_file(f"{DIR}gtt.data") ply_1 = Human_Player() ply_2 = AI_Player(Negamax(4, tt=table)) game = Gomoku([ply_1, ply_2], moves=['H8', 'I7'], show='test') game.play() set_trace()
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()
def main(): pickle_in = open("class.pickle", "rb") clasificador = pickle.load(pickle_in) # Search algorithm of the AI player algorithm = Negamax(5) # Start the game os.system('') Connect4GameController([Human_Player(clasificador), AI_Player(algorithm)]).play()
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()
def main(): #clasificador = Clasificador() #pickle_out = open("class.pickle","wb") #pickle.dump(clasificador, pickle_out) #pickle_out.close() pickle_in = open("class.pickle","rb") clasificador = pickle.load(pickle_in) # Search algorithm of the AI player algorithm = Negamax(5) # Start the game os.system('') TicTacToeGameController([Human_Player(clasificador), AI_Player(algorithm)]).play()
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]}}
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 ]) # 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()
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!
flipped = [] for d in DIRECTIONS: ppos = pos + d streak = [] while (0 <= ppos[0] <= 7) and (0 <= ppos[1] <= 7): if board[ppos[0], ppos[1]] == 3 - nplayer: streak.append(+ppos) elif board[ppos[0], ppos[1]] == nplayer: flipped += streak break else: break ppos += d return flipped if __name__ == "__main__": from easyAI import Human_Player, AI_Player, Negamax # An example: Computer vs Computer: game = Reversi([AI_Player(Negamax(4)) for i in (1, 2)]) game.play() if game.score() > 0: print("player %d wins." % game.nplayer) elif game.score() < 0: print("player %d wins." % game.nopponent) else: print("Draw.")
self.board[move[0], move[1]] = 1 self.board[move[2], move[3]] = 1 def unmake_move(self, move): move = string2mov(move) self.board[move[0], move[1]] = 0 self.board[move[2], move[3]] = 0 def show(self): print('\n' + '\n'.join([' 1 2 3 4 5 6 7 8'] + ['ABCDEFGH'[k] + ' ' + ' '.join(['.*'[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 ai_algo = Negamax(6) game = Cram([AI_Player(ai_algo), AI_Player(ai_algo)], (5, 5)) game.play() print("player {%d} loses".format(game.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 AI = Negamax(7, win_score=80) game = ConnectFour([Human_Player(), AI_Player(AI)]) game.play() if game.lose(): print("Player %d wins." % (game.nopponent)) else: print("Looks like we have a draw.")
""" from easyAI import TwoPlayersGame,Human_Player,AI_Player,Negamax class GameofBones(TwoPlayersGame): def __init__(self,players): self.players=players self.pile=20 #start with 20 bones in the pile self.nplayer=2 #player 1 starts def possible_moves(self): return['1','2','3'] def make_move(self,move): self.pile -= int(move) def win(self): return self.pile <=0 def is_over(self): return self.win() def show(self): print("%d bones left in the pile"%self.pile) def scoring(self): return 100 if game.win() else 0 # for the AI ai= Negamax(13) game=GameofBones([Human_Player(),AI_Player(ai)]) history = game.play()
from easyAI.games import ConnectFour from easyAI import Human_Player, AI_Player, Negamax ai = Negamax(7) # AI thinks 7 moves in advance game = ConnectFour([AI_Player(ai), Human_Player()]) game.play()
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.")