def local_init(self): print(13) self.player_enter() self.player = Model(self,random.randint(0,1000),200,200,self.pSelect,self.is_online) self.player.skillChosen = self.skillChosen self.camera.player = self.player self.charList.append(self.player) self.player.playerName=self.playerName print(23) self.enemy = AI(self,random.randint(0,1000),700,200,2,self.is_online) self.enemy.playerName='pyq' self.enemy2 = AI(self,random.randint(0,1000),600,200,1,self.is_online) self.enemy2.playerName='hzs' self.enemy3 = AI(self,random.randint(0,1000),600,200,3,self.is_online) self.enemy3.playerName='zn' #self.player.enemy = self.enemy self.enemy.enemy = self.player self.enemy2.enemy = self.player self.enemy3.enemy = self.player self.charList.append(self.enemy) self.charList.append(self.enemy2) self.charList.append(self.enemy3) print(33)
def test_model_vs_random(self, n_games=100, size=10, display=False, model_path="models/trained.h5"): ai1 = AI(mode="NN", size=10, player=1, load=True, model_file=model_path) ai2 = AI(mode="random", size=10, player=2) nb_wins = 0 nb_losses = 0 nb_draws = 0 for i in range(n_games): winner = self.run_game(size=10, players=[ai1, ai2], save_positions=False) if winner == 1: nb_wins += 1 elif winner == 2: nb_losses += 1 else: nb_draws += 1 print( "Model won %i games, lost %i and drawn %i against random (out of %i games)" % (nb_wins, nb_losses, nb_draws, n_games))
def main(): board = Board(5, 5, 4) player1 = AI() player2 = AI() player1.maxdepth = 2 player2.maxdepth = 2 gameloop(player1, player2, board)
def __init__(self): self.goldenBank = GoldenBank("goldenballvalues.txt") self.distributionPanel = DistributionPanel() self.playerLyst = [User("user"), AI("com1"), AI("com2"), AI("com3")] self.binOrWinTable = BinOrWinTable() self.splitOrSteal = SplitOrSteal() self.theVote = TheVote()
def setup(grid): print("Insert Player 1 information:") # Get Player 1 type player1_type = get_player_type() print("Player 1 is ", player1_type) # Get Player 1 icon 'X' or 'O' player1_icon = get_player_icon() print("Player 1 is ", player1_icon) print("Insert Player 2 information:") # Get Player 2 type player2_type = get_player_type() print("Player 2 is ", player2_type) # Player 2 icon is opposite of Player 1 if player1_icon == 'X': player2_icon = 'O' else: player2_icon = 'X' print("Player 2 is ", player2_icon) if player1_type == 'Human': player.append(Player(player1_icon, grid)) else: player.append(AI(player1_icon, grid)) if player2_type == 'Human': player.append(Player(player2_icon, grid)) else: player.append(AI(player2_icon, grid))
def call(self, _inputs, _states, training=None): # print(_inputs.shape, _states[0].shape) h_tm1_c = _states[0][:, :self.units] # the center of the last state h_tm1_r = _states[0][:, self.units:self.units * 2] # the radius of the last state h_tm1_e = _states[0][:, self.units * 2:] # the errors of the last state inputs_c = _inputs[:, :self.input_dim] # the center of the inputs inputs_r = _inputs[:, self.input_dim:self.input_dim * 2] # the radius of the inputs inputs_e = _inputs[:, self.input_dim * 2:] # the errors of the last state h_tm1 = AI(h_tm1_c, h_tm1_r, h_tm1_e, False) inputs = AI(inputs_c, inputs_r, inputs_e, False) matrix_inner = AI(h_tm1_c, h_tm1_r, h_tm1_e, False) # print(inputs_c, inputs_r, inputs_e) if self.implementation == 1: raise NotImplementedError() else: # inputs projected by all gate matrices at once inputs.matmul(self.kernel) if self.use_bias: # biases: bias_z_i, bias_r_i, bias_h_i inputs.bias_add(self.input_bias) x_z = inputs[:, :self.units] x_r = inputs[:, self.units:2 * self.units] x_h = inputs[:, 2 * self.units:] if self.reset_after: # hidden state projected by all gate matrices at once matrix_inner.matmul(self.recurrent_kernel) if self.use_bias: matrix_inner.bias_add(self.recurrent_bias) else: # hidden state projected separately for update/reset and new matrix_inner.matmul(self.recurrent_kernel[:, :2 * self.units]) recurrent_z = matrix_inner[:, :self.units] recurrent_r = matrix_inner[:, self.units:2 * self.units] z = x_z + recurrent_z # z.activation(self.recurrent_activation) r = x_r + recurrent_r r.activation(self.recurrent_activation) if self.reset_after: recurrent_h = r * matrix_inner[:, 2 * self.units:] else: recurrent_h = r * h_tm1 recurrent_h.matmul(self.recurrent_kernel[:, 2 * self.units:]) hh = x_h + recurrent_h # hh.activation(self.activation) # previous and candidate state mixed by update gate h = z.GRU_merge1(self.recurrent_activation, h_tm1, hh, self.activation) h_state = h.to_state() return h_state, [h_state]
def createPlayers(mode): global playerOne global playerTwo if mode == 'Human vs AI': playerOne = Human('playerOne') playerTwo = AI('playerTwo') if mode == 'AI vs AI': playerOne = AI('playerOne') playerTwo = AI('playerTwo')
def init(self): if (self.player1IsHuman): self.player1 = Player(Game.SIDE_X) else: self.player1 = AI(Game.SIDE_X) if (self.player2IsHuman): self.player2 = Player(Game.SIDE_O) else: self.player2 = AI(Game.SIDE_O)
def goAI_GAME(self, dif1, dif2): # setup difficulty d1 = self.setupDif(dif1) d2 = self.setupDif(dif2) # initialize chess board board = Board(self.row, self.col) board.printBoard() # initialize players p1 = AI("A1", Player("A2"), d1[0], d1[1]) p2 = AI("A2", p1, d2[0], d2[1]) players = [p1, p2] playerIndex = 0 # get user input print(players[playerIndex].color + "'s turn") # user movement while (True): try: # AI1 makes move players[0].think(board, self.count) board.printBoard() # count the round and judge the game self.count = self.count + 1 j = self.judge(board) if j != "" and self.count > 1: print(j + " wins!") break print(players[1].color + "'s turn") except RecursionError as error: print(players[0].color + " wins!") break try: # AI2 make move players[1].think(board, self.count) board.printBoard() # count the round and judge the game self.count = self.count + 1 j = self.judge(board) if j != "" and self.count > 1: print(j + " wins!") break print(players[0].color + "'s turn") except RecursionError as error: print(players[1].color + " wins!") break
def cell(h_tm1_c, h_tm1_r, h_tm1_e, inputs_c, inputs_r, inputs_e): h_tm1 = AI(h_tm1_c, h_tm1_r, h_tm1_e, False) inputs = AI(inputs_c, inputs_r, inputs_e, False) matrix_inner = AI(h_tm1_c, h_tm1_r, h_tm1_e, False) # print(inputs_c, inputs_r, inputs_e) if self.implementation == 1: raise NotImplementedError() else: # inputs projected by all gate matrices at once inputs.matmul(self.kernel) if self.use_bias: # biases: bias_z_i, bias_r_i, bias_h_i inputs.bias_add(self.input_bias) x_z = inputs[:, :self.units] x_r = inputs[:, self.units:2 * self.units] x_h = inputs[:, 2 * self.units:] if self.reset_after: # hidden state projected by all gate matrices at once matrix_inner.matmul(self.recurrent_kernel) if self.use_bias: matrix_inner.bias_add(self.recurrent_bias) else: # hidden state projected separately for update/reset and new matrix_inner.matmul(self.recurrent_kernel[:, :2 * self.units]) recurrent_z = matrix_inner[:, :self.units] recurrent_r = matrix_inner[:, self.units:2 * self.units] z = x_z + recurrent_z # z.activation(self.recurrent_activation) r = x_r + recurrent_r r.activation(self.recurrent_activation) if self.reset_after: recurrent_h = r * matrix_inner[:, 2 * self.units:] else: recurrent_h = r * h_tm1 recurrent_h.matmul(self.recurrent_kernel[:, 2 * self.units:]) hh = x_h + recurrent_h # hh.activation(self.activation) # previous and candidate state mixed by update gate h = z.GRU_merge1(self.recurrent_activation, h_tm1, hh, self.activation) return h
def __init__(self, size, p1, p2): self.board = [] self.size = size self.turn = 'X' self.moves = 0 self.p1 = p1 self.p2 = p2 self.AI1 = AI(size, "X") self.AI2 = AI(size, "O") for i in range(size): self.board.append([]) for _ in range(size): self.board[i].append(' ')
def SetUp(self): game_params = TkinterGameSetupParams() (player1Type, player1Depth, player2Type, player2Depth) = game_params.GetGameSetupParams() if player1Type == 'AI': if player1Depth > 0: self.ai_players[chess.WHITE] = AI(self.board, chess.WHITE, player1Depth) else: self.ai_players[chess.WHITE] = RandomAI() if player2Type == 'AI': if player2Depth > 0: self.ai_players[chess.BLACK] = AI(self.board, chess.BLACK, player2Depth) else: self.ai_players[chess.BLACK] = RandomAI(self.board)
def pve(turn=0): ai = AI(PLAYER_1, PLAYER_2) i = 0 game.__init__() print_game(game) while not game.check_winner(): i += 1 if i % 2 == turn: # TODO: Get AI turn # player = PLAYER_1 # move = move = ai.search(game) game.put_piece(move, PLAYER_1) print_game(game) print('\n', ai.pred) else: # Make player move while True: try: move = int(input('\n{} - Enter col:'.format(PLAYER_2))) - 1 except ValueError: continue except EOFError: import sys sys.exit() if game.put_piece(move, PLAYER_2): break print_game(game) print_ending(game)
def __init__(self): self.board = ChessBoard() self.view = ChessView(self) self.view.showMsg("Red") self.view.draw_board(self.board) self.player_is_red = True self.ai = AI()
def goAI(self, difficulty): # setup difficulty dif = self.setupDif(difficulty) # initialize chess board board = Board(self.row, self.col) board.printBoard() # initialize players p1 = Player("P") players = [p1, AI("C", p1, dif[0], dif[1])] playerIndex = 0 # get user input print(players[playerIndex].color + "'s turn") inp = input() # user movement while (inp != "q"): try: move = [int(n) for n in inp.split()] try: # player makes move players[0].makeMove(board, move[0], move[1]) board.printBoard() # count the round and judge the game self.count = self.count + 1 j = self.judge(board) if j != "" and self.count > 1: print(j + " wins!") break print(players[1].color + "'s turn") except RecursionError as error: print(players[0].color + " wins!") break try: # AI make move players[1].think(board, self.count) board.printBoard() # count the round and judge the game self.count = self.count + 1 j = self.judge(board) if j != "" and self.count > 1: print(j + " wins!") break print(players[0].color + "'s turn") except RecursionError as error: print(players[1].color + " wins!") break except ValueError as error: self.count = self.count - 1 print(repr(error)) inp = input()
def __init__(self, settings, screen, scoreboard): super().__init__() self.settings = settings self.screen = screen self.screen_rect = self.screen.get_rect() self.scoreboard = scoreboard self.__label = None self.__moving_up = None self.__moving_down = None self.__moving_left = None self.__moving_right = None self.paddles = None self.__is_ai = False self.ai = AI(self, settings) self.__score = 0 self.reset()
def __init__(self, threadID, name, monitor): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.monitor = monitor self.AI = AI()
def main(): ai_1 = AI(str(random.randint(1, 100000))) ai_2 = AI(str(random.randint(1, 100000))) i = 1 print(i,':', end='') result = ai_1.play('', first=True) print(result) while True: i = i+1 print(i, ':', end='') result = ai_2.play(result) print(result) i=i+1 print(i, ':', end='') result = ai_1.play(result) print(result)
def startGame(self, firstRun): self.team1Score = 0 self.team2Score = 0 self.scoreFont = scoreFont = pygame.font.Font(None, 52) self.messageFont = pygame.font.Font(None, 42) self.subMessageFont = pygame.font.Font(None, 24) self.messageColor = pygame.color.Color("black") self.message = "GAME ON" self.subMessage = "First to " + str(self.scoreLimit) + " points wins!" self.playerMessageFlashRate = self.framerate / 2 self.playerMessageFlashFrameMarker = 0 self.drawPlayerMessage = False self.playerPowerBarOutlineFlashRate = self.framerate / 4 self.playerPowerBarOutlineFrameMarker = 0 self.drawPlayerPowerBarOutline = True self.insultsUsedAlready = [] self.frameCount = 0 self.gameOver = False self.AI = AI() if bool(random.getrandbits(1)) == True: self.teamToServe = self.team1 else: self.teamToServe = self.team2 self.resetPositions() self.resetPlayerPowers() if firstRun == True: self.gameLoop()
def game_loop(screen, white_turn): board = Board(screen) ai_engine = AI() start = None game_over = False has_quit = False #LOOP while not game_over and not has_quit: #PROCESS EVENTS if white_turn: for event in pygame.event.get(): if event.type == pygame.QUIT: has_quit = True elif event.type == pygame.MOUSEBUTTONDOWN: x, y = pygame.mouse.get_pos() i, j = utils.chess_index(x, y) if board.is_white((i, j)) and white_turn: start = i, j elif start and board.make_move(start, (i, j)): game_over = board.board.is_game_over() start = None white_turn = not white_turn else: move = ai_engine.minimax(5, board, white_turn, -INFINITY, INFINITY) board.board.push(move[0]) white_turn = not white_turn #DRAW board.render_board() board.render_selections(start) board.render_pieces() pygame.display.flip()
def __init__(self): pygame.init() logo = pygame.image.load(str(BASE_DIR.joinpath('logo.png'))) pygame.display.set_icon(logo) self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) pygame.display.set_caption("BATTLESHIPS!") self.clock = pygame.time.Clock() menu_font = pygame.font.Font( 'DejaVuSans.ttf', 16) # default font can't display check mark self.gui = Gui(self.init, self.save, self.load, self.set_ai, menu_font) self.font = pygame.font.Font(None, 36) menu_offset = (0, self.gui.menus.rect.h) self.my_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, menu_offset) self.crosshair = Crosshair(self.my_board, (0, 0), menu_offset) self.enemy_board = Board(BOARD_WIDTH, BOARD_HEIGHT, self.screen, (550, 25)) self.ai = AI(self.enemy_board) self.gui.update_ai_menu(self.ai.strength) self.textpos = pygame.Rect(10, 545, 50, 30) self.ship_images = {} for size in range(1, 6): self.ship_images[size] = load_image(f'ship{size}.bmp', 'gfx')
def main(): board = Board() playerSide = askForPlayerSide() print() aiDepth = askForDepthOfAI() opponentAI = AI(board, not playerSide, aiDepth) startGame(board, playerSide, opponentAI)
def main(): if len(sys.argv) < 2: print "Please enter a host name." exit(1) ai = AI() socket = library.open_server_connection(sys.argv[1], "19000") if socket == -1: sys.stderr.write("Unable to connect to server\n") exit(1) if not library.serverLogin(socket, ai.username(), ai.password()): exit(1) if len(sys.argv) < 3: socket = library.createGame() else: socket = library.joinGame(int(sys.argv[2])) while library.networkLoop(socket, 0): if ai.startTurn(): library.endTurn() else: library.getStatus() #request the log file while library.networkLoop(socket, 0): pass exit(0)
def main(): if len(sys.argv) < 2: print "Please enter a host name." exit(1) connection = library.createConnection(); ai = AI(connection) success = library.serverConnect(connection, sys.argv[1], "19000") if not success: sys.stderr.write("Unable to connect to server\n") exit(1) if not library.serverLogin(connection, ai.username(), ai.password()): exit(1) if len(sys.argv) < 3: library.createGame(connection) else: library.joinGame(connection, int(sys.argv[2])) while library.networkLoop(connection): if ai.startTurn(): library.endTurn(connection) else: library.getStatus(connection) #Grab the end game state library.networkLoop(connection) #request the log file library.networkLoop(connection) ai.end() exit(0)
def __init__(self, root): self.root = root Frame.__init__(self, self.root) self.board = Board() width = self.root.winfo_screenwidth() height = self.root.winfo_screenheight() self.size = min([height,width]) self.canvas = Canvas(self.root, width=self.size, height=self.size) self.squareSize = 0.75*min([height, width])/8 self.board.draw(self.canvas,self.squareSize) self.canvas.pack(fill='both', expand=True) self._drag_data = {'loc': (0, 0), 'loc_i': (0, 0), 'loc_offset': (0, 0), 'piece_loc': None} self.canvas.tag_bind('piece', '<ButtonPress-1>', self.on_piece_press) self.canvas.tag_bind('piece', '<ButtonRelease-1>', self.on_piece_release) self.canvas.tag_bind('piece', '<B1-Motion>', self.on_piece_motion) self.ai = {color: AI(color, show=False) for color in ['white', 'black']} while not self.board.game_over and self.is_ai_turn(): self.make_ai_move() self.check_promotion_or_game_end() self.board.draw(self.canvas, self.squareSize) self.root.update() time.sleep(1) '''self.canvas.update()
def __init__(self, x, y, direction): self.x = x self.y = y self.positions = [[x, y, direction]] self.AI = AI('yolov3.weights', 'yolov3.cfg', 0.7) self.tool = Manipulator() self.direction = direction
def play(self): self.b1 = Board(6, 7) self.p1 = players(1) self.a1 = AI(2) Board.print_board(self.b1) game_over = False while not game_over: if self.turn == 0: game_over = self.p1.make_move(self.b1) self.b1.print_board() if self.b1.winning_move(self.p1.piece): print("Player 1 wins") game_over = True else: col, minimax_score = AI.minimax(self.a1, self.b1, 5, -math.inf, math.inf, True) if self.b1.is_valid_location(col): row = self.b1.get_next_open_row(col) self.b1.drop_piece(row, col, self.a1.piece) if self.b1.winning_move(self.a1.piece): print("player 2 wins") game_over = True self.b1.print_board() self.update_turn()
def __init__(self, settings_file): self.settings_file = settings_file self.sending_flag = True self.conf = {} self.network = None self.queue = Queue() self.model = Model(self.queue) self.client = AI()
def move(self,stiuation): player_ai = AI(stiuation) if(type(player_ai.decision()) == str): print(player_ai.decision()) else: move_x, move_y = player_ai.decision() self.position_x += move_x self.position_y += move_y
def getAlphaBetaMove(board, parser): import MoveNode as MoveNode depth = 1 AIagent = AI(board, True, depth) legalMoves = board.getAllMovesLegal(board.currentSide) bestMove = None moveTree = AIagent.generateMoveTree() legalBestMoves = AIagent.bestMovesWithMoveTree(moveTree) #conLegalMoves = AIagent.getAllMovesLegalConcurrent(board.currentSide) def alphaBetaMax(alpha, beta, depth): global bestMove value = -float(999999) #if (depth == 0 or board.isCheckmate or board.isStalemate): if (depth == 0): return (board.getPointValueOfSide(board.currentSide), ) random.shuffle(legalBestMoves) for move in legalBestMoves: random.shuffle(legalMoves) for m in legalMoves: random.shuffle(legalMoves) value = max(value, alphaBetaMin(alpha, beta, depth - 1)[0]) if (value >= beta): return beta, m if (value > alpha): alpha = value bestMove = m bestMove.notation = parser.notationForMove(bestMove) #return {'alpha': alpha, 'bestMove': bestMove} return alpha, bestMove #return bestMove def alphaBetaMin(alpha, beta, depth): global bestMove value = float(999999) #if (depth == 0 or board.isCheckmate or board.isStalemate): if (depth == 0): return (-board.getPointValueOfSide(board.currentSide), ) random.shuffle(legalBestMoves) for move in legalBestMoves: random.shuffle(legalMoves) for m in legalMoves: random.shuffle(legalMoves) value = min(value, alphaBetaMax(alpha, beta, depth - 1)[0]) if (value <= alpha): return alpha, m if (value < beta): beta = value bestMove = m bestMove.notation = parser.notationForMove(bestMove) #return {'beta': beta, 'bestMove': bestMove} return beta, bestMove #return bestMove score, action = alphaBetaMax(-999999, 999999, 3) return score, action