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
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)
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()
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
def main(): # Search algorithm of the AI player algorithm = Negamax(7) # Start the game ConnectFour([Human_Player('R'), AI_Player(algorithm, 'Y')]).play()
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])
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 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()
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 run_test(nr=1, timeout=5): board = test(nr) game = Gomoku_Strategic([AI_Player_Iterative_Deepening(timeout=timeout), Human_Player()], 6, board) game.play() if game.lose(): print("Player %d wins!" % game.nopponent) else: print("Draw!")
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 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()
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 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 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
]) # diagonal # Check if the game is over using the loss_condition method 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 using the loss_condition method def scoring(self): return -100 if self.loss_condition() else 0 #%% # Define the main function and start by defining the algorithm. # We can specify the number of steps in advance that the algorithm should think. # In this case, let's choose 5: if __name__ == "__main__": algorithm = Negamax(5) # Start the game GameController([Human_Player(), AI_Player(algorithm)]).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 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()
def init(self, width): # called at start of game self.start = True self.width = width self.ai_algo = DUAL(2) self.ttt = GomokuGame( [Human_Player(), AI_Player(self.ai_algo)], width, 2)
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 if __name__ == "__main__": global ttt ttt = GomokuGame([Human_Player(), AI_Player(ai_algo)], width, 1) app.run()
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()
return self.num_coins <= 0 # Stop the game when somebody wins def is_over(self): return self.win() # Compute score def scoring(self): return 100 if self.win() else 0 # Show number of coins remaining in the pile def show(self): print(self.num_coins, 'coins left in the pile') if __name__ == "__main__": # Define the transposition table tt = TT() # Define the method LastCoinStanding.ttentry = lambda self: self.num_coins # Solve the game result, depth, move = id_solve(LastCoinStanding, range(2, 20), win_score=100, tt=tt) print(result, depth, move) # Start the game game = LastCoinStanding([AI_Player(tt), Human_Player()]) game.play()
def scoring(self): return 20 if self.win() else 0 # For the AI ## TO DO ## # def possible_moves(self): return [self.hunt, self.target] # # def make_move(self, move): self.pile -= int(move) # remove bones. # # def win(self): return self.opponent.board # opponent took the last bone ? # # def is_over(self): return self.win() # Game stops when someone wins. # # def scoring(self): return 100 if self.win() else 0 # For the AI ### MAYBY USABLE MAYBY NOT # def hunt(self): # guess = random.randint(0, 99) # if guess in self.opponent.board: # return guess # # def randomly_locate_ships(board): # random.randint(0, 100) # # def ships_elements_left(list): # return -1 in list # Start a match (and store the history of moves when it ends) ai = Negamax(5) game = SpaghettiShips([Human_Player(), AI_Player(ai)]) history = game.play()
from easyAI import TwoPlayersGame, Human_Player, AI_Player, Negamax class SimpleNim(TwoPlayersGame): def __init__(self, players): self.players = players self.pile = 5 self.nplayer = 1 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('{} sticks left in the pile'.format(self.pile)) def scoring(self): return 1 if self.win() else 0 ai = Negamax(13) game = SimpleNim([Human_Player(), AI_Player(ai)]) history = game.play()
team_1 = self._state.team_1 team_2 = self._state.team_2 if winner == 0: return False if winner == team_1 and self.nplayer == 1: return True if winner == team_2 and self.nplayer == 2: return True return False def is_over(self): # return self.win() # Game stops when someone wins. return self._state.is_terminal() def show(self): # print ("%d bones left in the pile" % self.pile) print(self._state) def scoring(self): return 100 if self.win() else 0 # For the AI if __name__ == "__main__": # Start a match (and store the history of moves when it ends) ai = Negamax(32) # The AI will think 13 moves in advance game = GameOfDomino([Human_Player(), AI_Player(ai)]) history = game.play()
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 ai = Negamax(13) game = GameOfBones([Human_Player(), AI_Player(ai)]) history = game.play() # Code => 2 from easyAI import TwoPlayersGame, AI_Player, Negamax from easyAI.Player import Human_Player class GameController(TwoPlayersGame): def __init__(self, players): self.players = players self.nplayer = 1 self.board = [0] * 9 def possible_moves(self): return [a + 1 for a, b in enumerate(self.board) if b == 0]
def __init__(self): Human_Player.__init__(self) Player.__init__(self) self.moves = []
def scoring(self): return 100 if self.win() else 0 def show(self): print("%d bones left in the pile" % (self.pile)) if __name__ == "__main__": """ Start a match (and store the history of moves when it ends) ai = Negamax(10) # The AI will think 10 moves in advance game = GameOfBones( [ AI_Player(ai), Human_Player() ] ) history = game.play() """ # Let's solve the game from easyAI import id_solve, Human_Player, AI_Player from easyAI.AI import TT tt = TT() GameOfBones.ttentry = lambda self: self.pile r, d, m = id_solve(GameOfBones, range(2, 20), win_score=100, tt=tt) print(r, d, m) # see the docs. # Unbeatable AI ! game = GameOfBones([AI_Player(tt), Human_Player()]) game.play() # you will always lose this game :)
def is_over(self): return self.win() 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([AI_Player(tt) ,Human_Player()]) 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!
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!
from easyAI import Human_Player, AI_Player, Negamax from easyAI import TwoPlayersGame, Human_Player, AI_Player, DUAL from negamax import Negamax from pprint import pprint from flask import Flask, render_template_string, request, make_response from ai_negamax_faster import GomokuGame from easyAI import TT ai = Negamax(7, tt=TT()) game = GomokuGame([AI_Player(ai), Human_Player()], 15, 1) import cProfile cProfile.run("game.play(1)")