def __init__(self, master=None): """ init a game window """ Frame.__init__(self, master) self.board_start_x = 176 self.board_start_y = 28 ## turn is True if it is player's turn,false otherwise self.state = None ## state is the cur board state self.AI = "Computer" self.AI_pool = [] self.AI_pool.append(AI("Simple-1", 2, simple_heurstic, simple_search)) self.AI_pool.append(AI("Simple-2", 1, simple_heurstic, simple_search)) self.AI_pool.append( AI("Normal-1", 2, simple_heurstic, minmax_alpha_beta)) self.AI_pool.append( AI("Normal-2", 1, simple_heurstic, minmax_alpha_beta)) ## AI_pool contain all the AI class,with easy as first,normal as seconds ## master as third ## the cur AI fucntion used self.AI_cur = None self.AI_next = None self.board = None self.master = master self.side = None self.init_window()
def new_game(): global BOARD, AI, RAI, AI2, DICE_ROLL, CAPTURED_PIECES, CURRENT_MENU, GAME_RUNNING # Reset the board state BOARD = Board.Board(INITIAL_STATE) # BOARD.add_piece(0, "k", "K", [7, 0]) # BOARD.add_piece(0, "k", "K", [6, 0]) # BOARD.add_piece(1, "a", "R", [0, 0]) # BOARD.add_piece(1, "a", "L", [0, 3]) # BOARD.add_piece(1, "k", "K", [0, 7]) # Reset the AI AI = RandAI.RandomAI(BOARD, 1) AI = ai.AI(BOARD, 0) AI2 = ai.AI(BOARD, 1) RAI = RandAI.RandomAI(BOARD, 1) # Sets the dice to a random number DICE_ROLL = random.randint(1, 6) # Clear captured pieces list CAPTURED_PIECES = [] # Reset game menu to main menu CURRENT_MENU = "Main" # Set game running to true GAME_RUNNING = True # Reset other stats reset_state()
def run_game(event): pygame.display.update() game_display.fill(BLACK) Rect1.draw() Rect2.draw() if not GAME_MODE or GAME_MODE or GAME_MODE == 2: Rect1.move_rec(Rect1.get_vec(event)) if GAME_MODE: Rect2.move_rec(Rect2.get_vec(event)) if GAME_MODE == 2 or GAME_MODE == 3: Bot = bot.AI() if not Bot.fited: Bot.fit() poz_r_y = Rect2.y + Rect2.height / 2 - PlayBall.y poz_r_x = np.fabs(Rect2.x - PlayBall.x) ruch2 = Bot.predict(poz_r_y, poz_r_x, PlayBall.vy) Rect2.move_rec(ruch2) if GAME_MODE == 3: Bot = bot.AI('sgd') if not Bot.fited: Bot.fit() poz_r_y = Rect1.y + Rect1.height / 2 - PlayBall.y poz_r_x = np.fabs(Rect1.x - PlayBall.x) ruch1 = Bot.predict(poz_r_y, poz_r_x, PlayBall.vy) Rect1.move_rec(ruch1) PlayBall.check_coll_player(Rect1.x, Rect1.y, Rect1.width, Rect1.height) PlayBall.check_coll_player(Rect2.x, Rect2.y, Rect2.width, Rect2.height) PlayBall.ball_process() clock.tick(60)
def __init__(self): self.__weight = self.__loadWeights() # Logistelloパターン重み self.__board = indexBoard.IndexBoard(False) self.__player = [ AI.AI(self.__board, 0, None, self.__weight, Test.MIDTREEHEIGHT, Test.LASTPHASE, True), AI.AI(self.__board, 1, None, self.__weight, Test.MIDTREEHEIGHT, Test.LASTPHASE, True) ]
def set_game_for_aivai(self): self.status = False self.ai1 = AI("X", "PlayerX") self.ai2 = AI("O", "PlayerO") self.choose_who_starts_first(3) self.winner = Winner() self.win_count_pl1 = 0 self.win_count_pl2 = 0 self.draw_count = 0 self.run_ai_vs_ai = True
def run_AI_game(b, h): white = AI.AI(b, 1, h) black = AI.AI(b, -1, h) while not b.is_game_over(claim_draw=True): if b.turn == chess.BLACK: m = black.best_move() b.push(m) else: m = white.best_move() b.push(m) print(b) print()
def __init__(self): self.__weight = self.__loadWeights() # Logistelloパターン重み self.__board = indexBoard.IndexBoard(False) self.__player = [ AI.AI(self.__board, 0, None, self.__weight, Learner.MIDTREEHEIGHT, Learner.LASTPHASE, False), AI.AI(self.__board, 1, None, self.__weight, Learner.MIDTREEHEIGHT, Learner.LASTPHASE, False) ] self.__symmTable = self.__initSymmTable() # 各パターンの対称形のコードを格納するテーブル self.__gameCounter = 0 self.winB = 0 self.winW = 0 self.draw = 0
def get_dumb_ai_move(self): board = self.board # Deep copy of board so that the mini_max function doesn't modify the original board board_copy = board[:] ai = AI(board_copy, 'dumb') return ai.do_turn()
def main(): # #test board # input = {"grid":[[0,0,0,0,1,2], # [0,0,0,0,1,2], # [0,0,0,0,0,0], # [0,0,0,0,0,0], # [0,0,0,0,1,2], # [0,0,0,0,0,1], # [0,0,0,1,1,1]],"height":6,"player":1,"width":7} # finish_input ={"grid":[[0,2,2,1,2,1],[1,1,1,2,2,2],[1,2,2,1,2,1],[2,2,1,1,2,1],[2,1,2,2,1,1 ],[1,2,1,1,2,2],[1,2,1,2,1,1]],"height":6,"player":1,"width":7} # play manually # p1 = board(input) # ai = AI(p1) # bestmove, test = ai.best_move(4, p1.board,2) # print type(bestmove) # move = {"move":bestmove, "alpha": test} # print type(move) # print json.dumps(move) ###### RUN THIS FOR DRIVER. ###### DONE !!!! while (True): data = input() p1 = board(data) ai = AI(p1) bestmove, test = ai.best_move(2, p1.board, 2) move = {"move": bestmove} print json.dumps(move) sys.stdout.flush()
def train_main(): """ Test and train the AI using test_train(...) :return: None """ ai1 = AI() wins_ai1, wins_ai2, draws_all = train_test(100, 100, 50, ai1) # plot a1 wins plt.clf() plt.plot(wins_ai1, c='r') plt.plot(wins_ai2, c='b') plt.plot(draws_all, c='g') axis = plt.gca() axis.set_xlabel("Number of Iterations") axis.set_ylabel("Percantage of wins") # add legends red_patch = mpatches.Patch(color='red', label='AI_1 wins') blue_patch = mpatches.Patch(color='blue', label='AI_2 wins') green_patch = mpatches.Patch(color='green', label='Draws') plt.legend(handles=[red_patch, blue_patch, green_patch]) # print average values: print("Average AI_1 wins: {}%".format(mean(wins_ai1))) print("Average AI_2/Trainer wins: {}%".format(mean(wins_ai2))) print("Average draws: {}%".format(mean(draws_all)))
def __init__(self, parent): wx.Panel.__init__(self, parent) panel = wx.Panel(self, size=(WINDOW_WIDTH, WINDOW_HEIGHT)) nb = wx.Notebook(panel) cd = CharacterData(nb) cs = CharacterSprites(nb) ht = HitBox(nb) an = Animations(nb) sc = SparksCharacter(nb) co = Commands(nb) hc = HitStatesCharacter(nb) fm = FSM(nb) ai = AI(nb) nb.AddPage(cd, "Data") nb.AddPage(cs, "Sprites") nb.AddPage(ht, "Hitbox") nb.AddPage(an, "Animations") nb.AddPage(sc, "Sparks") nb.AddPage(co, "Commands") nb.AddPage(hc, "HitStates") nb.AddPage(fm, "FSM") nb.AddPage(ai, "AI") sizer = wx.BoxSizer() sizer.Add(nb, 1, wx.EXPAND) self.SetSizer(sizer)
def aiexample(): screen = pygame.display.set_mode([500, 500]) map1 = Map.Map(screen, size=[20, 20], walls=[[0, 1], [1, 1], [2, 1], [3, 1], [4, 1], [6, 0], [6, 1]]) clock = pygame.time.Clock() ai = AI.AI(map1) ai.moveto([15, 15]) while 1: screen.fill([255, 255, 255]) map1.draw() ai.move() pygame.draw.rect(screen, [0, 255, 0], [ ai.currentpos[0] * map1.cellsize[0], ai.currentpos[1] * map1.cellsize[1], map1.cellsize[0], map1.cellsize[1] ]) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() if event.type == MOUSEBUTTONDOWN: mpos = pygame.mouse.get_pos() loc = [ int(mpos[0] / map1.cellsize[0]), int(mpos[1] / map1.cellsize[1]) ] ai.moveto(loc) pygame.display.update() clock.tick(60) #simple() #aiexample()
def start_the_game(): isSinglePlayer = GAME_SETTINGS['isSinglePlayer'] currentPlayer = 1 ai = AI.AI(PLAYER_ONE, PLAYER_TWO, GAME_SETTINGS['difficulty']) board = b.Board(COLUMN_COUNT, ROW_COUNT, SQUARESIZE) pygame.draw.rect(surface, BACKGROUND_COLOUR, (0, 0, width, SQUARESIZE)) while not GAME_OVER: board.drawBoard(surface) pygame.display.update() #Tie game check and action if board.isFull(): label = myFont.render("Tie game fools", 1, BLUE) pygame.draw.rect(surface, BACKGROUND_COLOUR, (0, 0, width, SQUARESIZE)) surface.blit(label, (40, 10)) board.drawBoard() pygame.display.update() pygame.time.wait(2000) gameover = True for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # hovering chip animation if event.type == pygame.MOUSEMOTION: pygame.draw.rect(surface, BACKGROUND_COLOUR, (0, 0, width, SQUARESIZE)) posx = event.pos[0] if currentPlayer == 1: pygame.draw.circle(surface, RED, (posx, SQUARESIZE / 2), SQUARESIZE * 0.45) else: pygame.draw.circle(surface, YELLOW, (posx, SQUARESIZE / 2), SQUARESIZE * 0.45) if event.type == pygame.MOUSEBUTTONDOWN: #players turn posx = event.pos[0] col = int(math.floor(posx / SQUARESIZE)) if board.placeChip(col, currentPlayer): if board.checkWinner(currentPlayer): board.displayWinner(currentPlayer, surface) sys.exit() else: currentPlayer = changePlayer(currentPlayer) #AI's turn if isSinglePlayer: col = ai.pickMove(board) if board.placeChip(col, currentPlayer): if board.checkWinner(currentPlayer): board.displayWinner(currentPlayer, surface) sys.exit() else: currentPlayer = changePlayer(currentPlayer)
def init(): global playerObj, aiObj, rewardObj global screen os.environ["SDL_VIDEO_CENTERED"] = '1' pygame.init() screen = pygame.display.set_mode((st.windowWidth, st.windowHeight)) playerObj = player.Player() aiObj = ai.AI() rewardObj = rwd.Reward()
def set_game_for_aivspl(self): self.status = False self.player1 = Player("X", "PlayerX") self.ai = AI("O", "AI") self.choose_who_starts_first(2) self.winner = Winner() self.win_count_pl1 = 0 self.win_count_pl2 = 0 self.draw_count = 0
def __init__(self): self.grid = Grid.Grid(GRID_HEIGHT, GRID_WIDTH) self.current_piece = Piece.next_piece() self.ai = AI.AI([0.510066, 0.760666, 0.35663, 0.184483]) self.working_pieces = [Piece.next_piece(), Piece.next_piece()] self.working_piece = self.working_pieces[0] self.font_score = pygame.font.SysFont('comicsans', 60, True, False) self.is_ai_active = True self.score = 0
def get_smart_ai_move(self): board = self.board # Deep copy of board so that the mini_max function doesn't modify the original board board_copy = board[:] ai = AI(board_copy, self.ai_mode) if self.ai_mode == 'smart': val, best_move = ai.do_turn() return best_move else: return ai.do_turn()
def __init__(self): self.__board = indexBoard.IndexBoard(True) self.__player = [None] * 2 self.__openingBook = book.OpeningBook() self.__player[Config.AI_COLOR] = AI.AI(self.__board, Config.AI_COLOR, self.__openingBook, None, Config.MID_HEIGHT, Config.LAST_PHASE, True) self.__player[not Config.AI_COLOR] = You(self.__board, not Config.AI_COLOR, self.__openingBook)
def main(): AI = a.AI() P = p.Player() S = s.System(P, AI) print S.display_board() S.ask_config() S.ask_color() S.play_game()
def checkDone(self): complete = False if self.currentPiece is None: for k in self.pieceData: if self.pieceData[k][0] == 0: complete = True else: break if complete: self.ai = AI(self) # initialize AI self.ai.placePieces() self.gamePhase = 2
def test_player_is_winning(self): c = colors s = symbols(c) b1 = Board() b1[0] = 1 b1[1] = 1 b1[2] = 1 p1 = PrettyPrintedBoard(b1, s) poz = b1.getline ai = AI(b1) ai.playerMoves(2, 5) self.assertEqual(True, ai.playerIsWinning())
def __init__(self, mode=1, dis=0, showMove=True, showSearch=False, showGUI=True, saveInfo=False): self.board = ChessBoard() self.Player_Side = False self.GameMode = mode self.distribution = dis self.ai_0 = AI() self.ai_1 = AI() self.ShowMoveInfo = showMove self.ShowSearchInfo = showSearch self.ShowGraphUI = showGUI self.SaveInfo = saveInfo self.view = ChessView(self)
def __init__(self): self.current_state = 2 self.card_on_hand = None # <Sprites> Спрайты self.gameBoard = pygame.image.load('images/gameBoard.png') # </Sprites> # <GameThings> Разное self.shop = Shop.Shop() self.computer = AI.AI(self.shop) self.computer.tower = Tower.Tower(self.computer, False) self.player = Player.Player("abc", self.shop, self.computer) self.player.tower = Tower.Tower(self.player, True) self.computer.opponent = self.player self.shop.player = self.player self.shop.computer = self.computer self.timer = Timer(20) self.end_turn = False # </GameThings> # <GameButtons> self.end_turn_button = GameButton( Sprite.Sprite(pygame.image.load('images/EndTurnButton.png')), 750, 12) self.delete_card_button = GameButton( Sprite.Sprite(pygame.image.load('images/DeleteButton.png')), 960, 569) # </GameButtons> # <Cards> Карты self.all_cards = [] self.player.cards = [] #Предлагаю складывать карты не по номерам, а по ссылкам #Ссылки в python есть! #Сделать! #for i in range(0, 5): # card_ = Card.Card(...) # player.cards.append(card_) # </Cards> #<Временное> self.getStartCards()
def setupUi(self, Widget): self.hexy = [] self.size = 40 self.key = 0 self.agentHistory = [] self.notReplay = True self.visitedX = [] self.visitedY = [] self.enableAI = False self.counter = 1 #tworzenie xml self.history = History() # Inicjalizacja mapy self.dimension = 20 self.matrix = [[0 for w in range(self.dimension)] for h in range(self.dimension)] self.changes = np.ones((self.dimension, self.dimension)) # button = QPushButton('zapisz', self) # button.move(10,self.dimension*self.size*0.77 ) # button.clicked.connect(self.saveToXML) # # button1 = QPushButton('powtorka', self) # button1.move(150,self.dimension*self.size*0.77 ) # button1.clicked.connect(self.replay) button = QPushButton('AI', self) button.move(10, self.dimension * self.size * 0.77) button.clicked.connect(self.saveToXML) self.map = Map() self.map.fill_matrix(self.matrix) self.ai = AI() self.tank = Tank() # kolor obramowania i wypełnienia w formacie RGB self.kolorW = QColor(0, 0, 0) self.timer = QtCore.QBasicTimer() # Timer self.speed = 500 self.timer.start(self.speed, self) width = self.dimension * self.size * 0.9 height = self.dimension * self.size * 0.82 self.resize(width, height) self.setWindowTitle('Widżety')
def gameLoop(): """The main function that runs the whole game.""" score = 0 # Initialise screen window = Window.Window(Vector.Vector(width, height), 'ShopQuest', TILE_SIZE) # Fill background window.clearScreen() stepSize, N, maze, itemPos = GenerateMaze() # Initialise both users player = Player.Player(1, 15, (0, 0, 255), 'icons/player.png', TILE_SIZE) ai = AI.AI(1, 3, (255, 0, 255), 'icons/AI.png', TILE_SIZE) window.drawScreen(player, ai, maze) clock = pygame.time.Clock() time = 0 # Game loop while 1: """Event loop: Checks all the events and acts accordingly""" for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return if event.type == KEYUP: # Move the player around player.move(event.key, maze) if player.isOnItem(maze): window.ShowPopUp() maze[player.pos.x][player.pos.y].payload = 0 score += 1 print score itemPos = getRandomEmptyBlock(maze) maze[itemPos.x][itemPos.y].payload = 2 ai.path = [] time += clock.get_time() if time > GAME_SPEED: # Move the AI around time = 0 # ai.moveInDirection(random.randint(0, 3), maze) ai.moveToNode(maze, maze[itemPos.x][itemPos.y]) if ai.isOnItem(maze): maze[ai.pos.x][ai.pos.y].payload = 0 itemPos = getRandomEmptyBlock(maze) maze[itemPos.x][itemPos.y].payload = 2 window.drawScreen(player, ai, maze) clock.tick(60)
def square_clicked(self, event=None): if self.chessboard.player_turn == "white": col_size = row_size = self.square_size selected_column = int(event.x / col_size) # because the size of the board is column * square_size selected_row = 7 - int(event.y / row_size) # chess board's rows are arranged oppositely pos = self.chessboard.alpha_notation( (selected_row, selected_column)) if self.selected_piece: self.shift(self.selected_piece[1], pos) self.selected_piece = None self.focused = None self.draw_board() self.draw_pieces() self.viable_piece_to_move(pos) self.draw_board() self.canvas.update() for coord in self.chessboard: # updating piece's board self.chessboard[coord].place(self.chessboard) if not self.chessboard.promote_pawn: if self.chessboard.is_game_over(): self.game_over() if self.chessboard.player_turn == "black": og = deepcopy(self.chessboard) boards = self.chessboard.all_boards("white") for board in boards: self.chessboard = board self.draw_board() self.draw_pieces() self.chessboard = og ai = AI(self.chessboard) move = ai.ai_play() self.info_label[ "text"] = '' + "Black: " + move + ", " + self.chessboard.player_turn.capitalize() + \ "\'s turn" self.selected_piece = None self.focused = None self.draw_board() self.draw_pieces() if self.chessboard.is_game_over(): self.game_over()
def main(): filename = "log" + raw_input("name and # try ") + ".txt" gameboard = board.BaseBoard() userinput = raw_input("Would you like to be WHITE or BLACK: ") while userinput.upper() != "WHITE" and userinput.upper() != "BLACK": userinput = raw_input("Would you like to be WHITE or BLACK: ") if userinput.upper() == "WHITE": user = 1 if userinput.upper() == "BLACK": user = -1 #Get difficulty userinput = int(raw_input("What difficulty would you like: 1, 2, 3? ")) if userinput == 1: dif = 1 elif userinput == 2: dif = 2 else: dif = 3 ai = AI.AI(dif, board=copy.deepcopy(gameboard)) while not gameboard.over: file = open(filename, "a") print(gameboard.__unicode__()) if gameboard.turn == user: #User's turn try: #Cause oh well I'm lazy row = int(raw_input("Please enter a row: ")) column = int(raw_input("Please enter a column: ")) newrow = int(raw_input(("Please enter a new row: "))) newcolumn = int(raw_input(("Please enter a new column: "))) usermove = board.Move(row, column, newrow, newcolumn) if gameboard.legalmove(usermove): gameboard.makemove(usermove) ai.makemove(usermove) except: print("Try again.") else: #Computer turn print("AI is thinking...") aimove = ai.alphabeta(dif) print("AI makes move.") print(aimove) gameboard.makemove(aimove) ai.makemove(aimove) file.write(ai.gameTree.__unicode__().encode("UTF-8")) file.close() print("Good Game!") print(gameboard) return None
def run_human_AI_game(b, h, color): ai = AI.AI(b, color, h) while not b.is_game_over(claim_draw=True): if b.turn == chess.WHITE and color == 1 or b.turn == chess.BLACK and color == -1: print("AI is thinking...") m = ai.best_move() else: while True: try: move = input("Enter your move: ") m = b.parse_san(move) break except ValueError as e: print(e) b.push(m) print(b) print("Current static score:", h.static_score(b.fen())) print()
def init(self, numPlayers=4): self.hideCards = True self.screen = 'splash' # 'game', 'gameOver', 'help', 'credits' # 'help-game' self.timerDelay = 0; self.tickSpeed = 10 self.font = pygame.font.Font(pygame.font.get_default_font(), 12) self.players = [Player(i) for i in range(numPlayers)] self.boardImage = getBoardImage(self.width, self.height) self.statusBoardImage = getStatusBoardImage(self, 4) self.cardScale = 30 # changes size of cards self.cardImages = getCardImages(self.cardScale) self.drawPlayerPositions = getDrawPlayerPositions(self,numPlayers) self.buttonImages = getButtonImages() self.status = GameController(numPlayers, self.players) self.buttonPositions = dict() self.status.chooseStartCards(self.players) self.aiList = [None] + [AI(i) for i in range(1,numPlayers)] self.aiDiff = 'easy'
def make_players(): ''' Function to make players depending on users choice if he wants to face AI or other humanoid Return: ------- list of Player obj ''' players = [] if ask_if_single_player(): os.system('clear') players = [AI(), Player(input("Enter player's name: "))] else: for i in range(2): os.system('clear') players.append(Player(input("Enter player's name: "))) os.system('clear') return players