Esempio n. 1
0
def baseline(seed):
    random.seed(seed)
    game = Tetris(numColumns=10, numRows=10)
    baselineAI = AI(baselineFunction)
    while (not game.lost):
        baselineAI.aiSequence(game)
    random.seed()

    if VERBOSE: print(f"Baseline AI played game with score {game.numLines}.")
    return game.numLines
Esempio n. 2
0
def playGame():
    game = Tetris(numColors=MAXCOLORS, numColumns=10, numRows=10)
    ai = AI(function)
    # loop count variables:
    numTicks = 0
    while not game.lost:  # game loop ends when game is lost
        ai.ai(game, display=False)
        game.incrementTime()
        numTicks += 1
    return game.numLines
def playGame():
    game = Tetris(numColors=MAXCOLORS)
    ai = AI(function)
    # loop count variables:
    numPieces = 0
    sumHeights = 0
    while not game.lost and game.numPieces < 200:  # game loop ends when game is lost
        ai.ai(game)
        game.incrementTime()
        if game.numPieces > numPieces:
            sumHeights += height(game)
            numPieces += 1
    return (game.numLines, sumHeights / numPieces)
Esempio n. 4
0
    def callback(self):
        self.mode = self.sender().text()

        if self.mode == "Single Mode":
            self.ai = None
        elif self.mode == "AI Mode":
            self.ai = AI()
            notice = DifficultyNotice(self.ai)
            notice.exec_()
            print(self.ai.searcher.depth)

        self.singleButton.hide()
        self.aiButton.hide()

        self.turn = Team.WHITE
        self.drawBoard()
Esempio n. 5
0
 def __init__(self,
              player_id,
              name,
              game,
              main_name=None,
              index=None,
              initialize=False,
              filtered_moves=None):
     Player.__init__(self, player_id, name, game)
     self.ai = AI()
     if not initialize:
         assert main_name is not None
         assert index is not None
         self.ai.load_model(main_name, index=index)
     else:
         self.ai.create_model()
     self.filtered_moves = filtered_moves
Esempio n. 6
0
def test_ai_init_knowledgebase(mock_request, mock_post):
    lab_connection_args = {}
    pennai = AI(rec_class=None,
                api_path='http://lab:5080',
                user="******",
                verbose=True,
                n_recs=1,
                warm_start=False,
                datasets={},
                use_knowledgebase=True)
Esempio n. 7
0
    def __init__(self,
                 screen: pygame.Surface,
                 rows=cfg.DEF_ROWS,
                 cols=cfg.DEF_COLS,
                 cell_padding=cfg.CELL_PAD,
                 color=cfg.BOARD_BG_COLOR,
                 border_color=cfg.BOARD_BRD_COLOR,
                 border_size=cfg.BOARD_BRD_SIZE):

        Drawable.__init__(self,
                          screen=screen,
                          color=color,
                          border_color=border_color,
                          border_size=border_size)
        self.rows: int = rows
        self.cols: int = cols
        self.cell_pad = cell_padding
        self.mouse_wall = None  # Wall painted on mouse move
        self.player: int = 0  # Current player 0 or 1
        self.board: List[List[Cell]] = []
        self.computing = False  # True if a non-human player is moving
        self._state = None

        for i in range(rows):
            self.board.append([])
            for j in range(cols):
                self.board[-1].append(Cell(screen, self, coord=Coord(i, j)))

        self.pawns: List[Pawn] = []
        self.pawns += [
            Pawn(
                screen=screen,
                board=self,
                color=cfg.PAWN_A_COL,
                border_color=cfg.PAWN_BORDER_COL,
                coord=Coord(rows - 1, cols >> 1)  # Centered
            )
        ]
        self.pawns += [
            Pawn(
                screen=screen,
                board=self,
                color=cfg.PAWN_B_COL,
                border_color=cfg.PAWN_BORDER_COL,
                coord=Coord(0, col=cols >> 1)  # Centered
            )
        ]

        self.regenerate_board(cfg.CELL_COLOR, cfg.CELL_BORDER_COLOR)
        self.num_players = cfg.DEFAULT_NUM_PLAYERS
        self.walls: Set[Wall] = set()  # Walls placed on board
        self.draw_players_info()
        self._AI = []
        # self._AI += [AI(self.pawns[0])]
        self._AI += [AI(self.pawns[1], level=cfg.LEVEL)]
def playGame():
    game = Tetris(numColors=MAXCOLORS)
    ai = AI()

    # a dictionary of pygame buttons and their functions:
    global AI_BUTTON
    AI_BUTTON = pygame.Rect(
        (WINDOWWIDTH - 122, 300, 50, 30))  # ai enable button

    render(game)

    # loop count variables:
    numTicks = 0
    timeSinceIncrement = 0

    pressedKeys = [-1, -1, -1, -1]  # up, down, left, right
    while not game.lost:  # game loop ends when game is lost

        if INPUT: handleInput(game, pressedKeys, numTicks)
        else:
            for event in pygame.event.get():  # event handling loop
                if event.type == pygame.QUIT:
                    terminate()  # exit game

        # increment time (move blocks down)
        if timeSinceIncrement > DELAY:  # number of ticks between time increments

            if not INPUT: ai.ai(game)

            game.incrementTime()
            timeSinceIncrement = 0
            render(game)

        FPSCLOCK.tick(FPS)
        numTicks += 1
        timeSinceIncrement += 1
    return "Game Over"
def playGame():
    seed = int(time.time())
    game = Tetris(numColors=MAXCOLORS, seed=seed)
    aiGame = Tetris(numColors=MAXCOLORS, seed=seed)
    ai = AI()
    render(game, aiGame)

    DELAY = 20  # delay between each incrementTime

    # loop count variables:
    numTicks = 0
    timeSinceIncrement = 0
    level = 0
    pressedKeys = [-1, -1, -1, -1]  # up, down, left, right
    while not game.lost or aiGame.lost:  # game loop ends when game is lost

        updated = handleInput(game, pressedKeys, numTicks)
        while aiGame.numTurns < game.numTurns:
            ai.ai(aiGame)
            aiGame.incrementTime()
            if game.numTurns - aiGame.numTurns % 10 == 0 or game.numTurns - aiGame.numTurns % 5 < 10:
                render(game, aiGame)
        if updated:
            render(game, aiGame)
        if timeSinceIncrement > DELAY:  # number of ticks between time increments
            game.incrementTime()
            timeSinceIncrement = 0
            render(game, aiGame)
        if game.numLines // 10 > level:
            level = game.numLines // 10
            DELAY = DELAY * 0.8

        FPSCLOCK.tick(FPS)
        numTicks += 1
        timeSinceIncrement += 1

    return "Game Over" if game.lost else "You Win!"
Esempio n. 10
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
        for key, value in body.items():
            if key == "game":
                map = value
            if key == "players":
                player = value
            if key == "you":
                me = value
        if player[0] == me:
            pawn = 0
        if player[1] == me:
            pawn = 1
        ai = AI(map, pawn)
        return ai.run()
Esempio n. 11
0
def main():
    amount_of_ais = int(sys.argv[1])
    host = sys.argv[2]
    port = int(sys.argv[3])
    while True:
        ais = []
        try:
            for i in range(amount_of_ais):
                ais.append(
                    AI("The Machine Thread", i + 1, renderer, host, port))

            for ai in ais:
                ai.join()
        except socket_error as serr:
            for ai in ais:
                ai.stop()
            log("Retry in 3s.")
            time.sleep(3)
def playGame():
    game = Tetris(numColors=MAXCOLORS, seed=int(time.time()))
    ai = AI(func1)

    game2 = Tetris(numColors=MAXCOLORS, seed=int(time.time()))
    ai2 = AI(func2)

    render(game, game2)

    pressedKeys = [-1, -1, -1, -1]  # up, down, left, right
    while not game.lost and not game2.lost:  # game loop ends when game is lost
        for event in pygame.event.get():  # event handling loop
            if event.type == pygame.QUIT:
                terminate()  # exit game

        # increment time (move blocks down)
        ai.aiSequence(game)
        ai2.aiSequence(game2)
        render(game, game2)

        FPSCLOCK.tick(FPS)
    return "Player 2 (Will) won" if game.lost else "Player 1 (Bill) won"
Esempio n. 13
0
def test_ai_init(mockLabApi):  #, mockRequestsPost
    labApiInstance = mockLabApi.return_value

    labApiInstance.launch_experiment.return_value = {'launch_experiment'}
    labApiInstance.get_projects.return_value = {'get_projects'}
    labApiInstance.get_filtered_datasets.return_value = {
        'get_filtered_datasets'
    }
    labApiInstance.get_new_experiments.return_value = {'get_new_experiments'}
    labApiInstance.set_ai_status.return_value = {'set_ai_status'}
    labApiInstance.get_all_ml_p.return_value = pd.DataFrame({
        'algorithm': ['testAlgo', 'testAlgo'],
        'parameters': [{
            'criterion': 'gini',
            'max_depth': 2
        }, {
            'criterion': 'entropy',
            'max_depth': 3
        }]
    })

    lab_connection_args = {}
    pennai = AI()
Esempio n. 14
0
import numpy as np
from ai.ai import AI
import keras
import tables

data_filename = 'data'

hdf5_path = "./data/{0}.hdf5".format(data_filename)
extendable_hdf5_file = tables.open_file(hdf5_path, mode='r')
x = extendable_hdf5_file.root.x[:]
y = extendable_hdf5_file.root.y[:]
extendable_hdf5_file.close()

latest_version = None

ai = AI()
ai.load_data(x,y)
if latest_version is None:
    ai.create_model()
    latest_version = -1
else:
    ai.load_model('model', index=latest_version)
ai.train_model()
ai.save_model('model', index=latest_version+1)
Esempio n. 15
0
class Board(QWidget):
    def __init__(self, chessBoard, ai=None):
        super().__init__()
        self.oriChessBoard = copy.deepcopy(chessBoard)
        self.chessBoard = chessBoard
        self.ai = ai
        self.tiles = []
        self.lastMove = []
        self.pickedPiece = None
        self.edge = None
        self.checkEdge = None
        self.notice = None
        self.blackCheckBoard, self.blackCheck = fillCheckBoard(
            self.chessBoard, Team.BLACK)
        self.whiteCheckBoard, self.whiteCheck = fillCheckBoard(
            self.chessBoard, Team.WHITE)
        # self.repaintBoard()
        self.initUI()
        self.setCenter()

    def initUI(self):
        self.setFixedSize(800, 800)
        self.setGeometry(0, 0, 800, 800)
        self.setWindowTitle("Chess")
        self.selectMode()

        self.show()

    def selectMode(self):
        self.mainPalette = QPalette()
        self.mainPalette.setBrush(
            10,
            QBrush(
                QImage(
                    os.path.dirname(os.path.abspath(__file__)) +
                    '/images/mainWin.jpg').scaled(QSize(800, 800))))
        self.setPalette(self.mainPalette)

        self.singleButton = QToolButton(self)
        self.singleButton.setText("Single Mode")
        self.setStyleSheet("font-size: 40px;")
        self.singleButton.setStyleSheet("background-color:#993800;")
        self.singleButton.setGeometry(150, 200, 500, 100)
        self.singleButton.clicked.connect(self.callback)

        self.aiButton = QToolButton(self)
        self.aiButton.setText("AI Mode")
        self.aiButton.setStyleSheet("background-color:#FFDEA9;")
        self.aiButton.setGeometry(150, 500, 500, 100)
        self.aiButton.clicked.connect(self.callback)

    def callback(self):
        self.mode = self.sender().text()

        if self.mode == "Single Mode":
            self.ai = None
        elif self.mode == "AI Mode":
            self.ai = AI()
            notice = DifficultyNotice(self.ai)
            notice.exec_()
            print(self.ai.searcher.depth)

        self.singleButton.hide()
        self.aiButton.hide()

        self.turn = Team.WHITE
        self.drawBoard()

    def drawBoard(self):
        # 체스 보드를 배경화면으로 설정
        self.chessPalette = QPalette()
        self.chessPalette.setBrush(
            10,
            QBrush(
                QImage(
                    os.path.dirname(os.path.abspath(__file__)) +
                    '/images/chessboard.png').scaled(QSize(800, 800))))
        self.setPalette(self.chessPalette)

        self.repaintBoard()

    def setCenter(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def pickPiece(self):
        piece = self.sender().piece
        if piece.team == self.turn:
            self.pickedPiece = piece
            if self.edge != None:
                self.edge.move(piece.pos['x'] * 100, piece.pos['y'] * 100)
            else:
                self.edge = QLabel(self)
                self.edge.setPixmap(
                    QPixmap(
                        os.path.dirname(os.path.abspath(__file__)) +
                        '/images/yellowedge.png'))
                self.edge.move(piece.pos['x'] * 100, piece.pos['y'] * 100)
                self.edge.show()
        else:
            if self.pickedPiece != None:
                self.lastMove = [self.pickedPiece.pos, piece.pos]
                if self.pickedPiece.getType() == "Pawn":
                    #미리 움직여서 왕이 체크인지 확인. 체크이면 리턴
                    preBoard = copy.deepcopy(self.chessBoard)
                    prePiece = copy.deepcopy(self.pickedPiece)
                    preSuccess = prePiece.move(
                        Position(piece.pos['x'], piece.pos['y']), preBoard)[0]

                    if not (preSuccess):
                        return
                    check = fillCheckBoard(preBoard, prePiece.team)[1]
                    if check:
                        return

                    #실제 움직임
                    success, promotion = self.pickedPiece.move(
                        Position(piece.pos['x'], piece.pos['y']),
                        self.chessBoard)
                    if not (success):
                        return
                    else:
                        if promotion:
                            self.notice = PromotionNotice(
                                self.pickedPiece.team, self.chessBoard,
                                Position(self.pickedPiece.pos['x'],
                                         self.pickedPiece.pos['y']))
                            self.notice.exec_()
                elif self.pickedPiece.getType() != "King":
                    #미리 움직임
                    preBoard = copy.deepcopy(self.chessBoard)
                    prePiece = copy.deepcopy(self.pickedPiece)
                    preSuccess = prePiece.move(
                        Position(piece.pos['x'], piece.pos['y']), preBoard)

                    if not (preSuccess):
                        return
                    check = fillCheckBoard(preBoard, prePiece.team)[1]
                    if check:
                        return

                    #실제 움직임
                    if not (self.pickedPiece.move(
                            Position(piece.pos['x'], piece.pos['y']),
                            self.chessBoard)):
                        return
                else:  # King
                    if not (self.pickedPiece.move(
                            Position(piece.pos['x'], piece.pos['y']),
                            self.chessBoard, self.whiteCheckBoard if self.turn
                            == Team.WHITE else self.blackCheckBoard)):
                        return
                # try:
                self.blackCheckBoard, self.blackCheck = fillCheckBoard(
                    self.chessBoard, Team.BLACK)
                self.whiteCheckBoard, self.whiteCheck = fillCheckBoard(
                    self.chessBoard, Team.WHITE)
                # except:
                #     notice = EndNotice(self.turn)
                #     notice.exec_()
                #     self.deleteLater()
                self.turn = Team.BLACK if self.turn == Team.WHITE else Team.WHITE
                self.edge.hide()
                self.edge.deleteLater()
                self.edge = None
                self.repaintBoard()
                self.repaint()
                if self.ai != None and len(self.lastMove) == 2:
                    self.aiMove()
                    self.repaintBoard()
                self.pickedPiece = None
            else:
                return

    def mousePressEvent(self, e):
        x, y = e.x() // 100, e.y() // 100
        if self.pickedPiece != None:
            self.lastMove = [self.pickedPiece.pos, Position(x, y)]
            if self.pickedPiece.getType() == "Pawn":
                #미리 움직여서 왕이 체크인지 확인. 체크이면 리턴
                preBoard = copy.deepcopy(self.chessBoard)
                prePiece = copy.deepcopy(self.pickedPiece)
                preSuccess = prePiece.move(Position(x, y), preBoard)[0]
                if not (preSuccess):
                    return
                check = fillCheckBoard(preBoard, prePiece.team)[1]
                if check:
                    return

                #실제 움직임
                success, promotion = self.pickedPiece.move(
                    Position(x, y), self.chessBoard)
                if not (success):
                    return
                else:
                    if promotion:
                        self.notice = PromotionNotice(self.pickedPiece.team,
                                                      self.chessBoard,
                                                      Position(x, y))
                        self.notice.exec_()
            elif self.pickedPiece.getType() != "King":
                #미리 움직여서 왕이 체크인지 확인. 체크이면 리턴
                preBoard = copy.deepcopy(self.chessBoard)
                prePiece = copy.deepcopy(self.pickedPiece)
                preSuccess = prePiece.move(Position(x, y), preBoard)
                if not (preSuccess):
                    return
                check = fillCheckBoard(preBoard, prePiece.team)[1]
                if check:
                    return

                #실제 움직임
                if not (self.pickedPiece.move(Position(x, y),
                                              self.chessBoard)):
                    return
            else:
                if not (self.pickedPiece.move(
                        Position(x, y), self.chessBoard, self.whiteCheckBoard
                        if self.turn == Team.WHITE else self.blackCheckBoard)):
                    return
            self.pickedPiece = None
            self.edge.hide()
            self.edge.deleteLater()
            self.edge = None
            # try:
            self.blackCheckBoard, self.blackCheck = fillCheckBoard(
                self.chessBoard, Team.BLACK)
            self.whiteCheckBoard, self.whiteCheck = fillCheckBoard(
                self.chessBoard, Team.WHITE)
            # except:
            # notice = EndNotice(self.turn)
            # notice.exec_()
            # self.deleteLater()
            self.turn = Team.BLACK if self.turn == Team.WHITE else Team.WHITE
            self.repaintBoard()
            self.repaint()
            if self.ai != None and len(self.lastMove) == 2:
                self.aiMove()
                self.repaintBoard()

    def repaintBoard(self):
        ck = None
        for tile in self.tiles:
            tile.deleteLater()
        self.tiles = []
        if self.checkEdge != None:
            self.checkEdge.hide()
            self.checkEdge.deleteLater()
            self.checkEdge = None

        for y in range(8):
            for x in range(8):
                if self.chessBoard[y][x] == None:
                    continue
                # 폰의 dieByEnpassant 값을 내림.
                if self.chessBoard[y][x].getType() == "Pawn":
                    if self.chessBoard[y][x].dieByEnpassant > 0:
                        self.chessBoard[y][x].dieByEnpassant -= 1
                # 킹이 체크인 경우 하이라이팅
                elif self.chessBoard[y][x].getType() == "King":
                    if self.chessBoard[y][x].team == self.turn and (
                            self.whiteCheck
                            if self.turn == Team.WHITE else self.blackCheck):
                        self.checkEdge = QLabel(self)
                        self.checkEdge.setPixmap(
                            QPixmap(
                                os.path.dirname(os.path.abspath(__file__)) +
                                '/images/rededge.png'))
                        self.checkEdge.move(x * 100, y * 100)
                        self.checkEdge.show()

                        #체크메이트 확인
                        ck = checkmate(
                            self.chessBoard, self.whiteCheckBoard if self.turn
                            == Team.WHITE else self.blackCheckBoard, self.turn)
                        if ck:
                            print("CheckMate", ck)
                        else:
                            print("Check", ck)

                tile = Tile(self.chessBoard[y][x], self)
                self.tiles.append(tile)
                tile.setGeometry(x * 100, y * 100, 100, 100)
                tile.clicked.connect(self.pickPiece)
                tile.show()

        self.setWindowTitle(
            f"Chess: {Team.BLACK if self.turn == Team.BLACK else Team.WHITE}")
        if ck:
            self.reset("Checkmate")

        #스테일메이트 확인
        stm = staleMate(
            self.chessBoard, self.whiteCheckBoard
            if self.turn == Team.WHITE else self.blackCheckBoard, self.turn)
        if stm:
            print("Stalemate")
            self.reset("Stalemate")
        print(stm)

    # def reduceValueOfPawnEnpassant(self):
    #     for y in range(8):
    #         for x in range(8):
    #             if self.chessBoard[y][x] != None and self.chessBoard[y][x].getType() == "Pawn":
    #                 if self.chessBoard[y][x].dieByEnpassant > 0:
    #                     self.chessBoard[y][x].dieByEnpassant -= 1

    def reset(self, state):
        notice = EndNotice(
            Team.BLACK if self.turn == Team.WHITE else Team.WHITE, state)
        notice.exec_()
        self.singleButton.show()
        self.aiButton.show()
        self.chessBoard = copy.deepcopy(self.oriChessBoard)
        self.setPalette(self.mainPalette)
        for tile in self.tiles:
            tile.deleteLater()
        self.tiles = []
        self.lastMove = []
        if self.edge != None:
            self.edge.deleteLater()
            self.edge = None
        self.pickedPiece = None
        if self.checkEdge != None:
            self.checkEdge.deleteLater()
            self.checkEdge = None
        if self.notice != None:
            self.notice.deleteLater()
            self.notice = None
        self.blackCheckBoard, self.blackCheck = fillCheckBoard(
            self.chessBoard, Team.BLACK)
        self.whiteCheckBoard, self.whiteCheck = fillCheckBoard(
            self.chessBoard, Team.WHITE)
        self.repaint()

    def aiMove(self):
        self.setWindowTitle("Chess: AI")

        # parse
        move = ""
        for p in self.lastMove:
            move += chr(p['x'] + ord('a')) + str(8 - p['y'])
        print(f"player move: {move}")
        self.ai.hist.append(self.ai.hist[-1].move(
            (self.ai.parse(move[:2]), self.ai.parse(move[2:]))))
        self.ai.print_pos(self.ai.hist[-1].rotate())

        # search
        start = time.time()
        for _, move, _ in self.ai.searcher.search(self.ai.hist[-1],
                                                  self.ai.hist):
            if time.time() - start > self.ai.time:
                break

        # move
        self.ai.hist.append(self.ai.hist[-1].move(move))
        move = self.ai.render(119 - move[0]) + self.ai.render(119 - move[1])
        print(f"ai move: {move}")
        x1, y1, x2, y2 = ord(move[0]) - ord('a'), 8 - int(move[1]), ord(
            move[2]) - ord('a'), 8 - int(move[3])

        self.ai.print_pos(self.ai.hist[-1])

        if self.chessBoard[y1][x1].getType() == "Pawn":
            piece = self.chessBoard[y1][x1]
            _, promotion = piece.move(Position(x2, y2), self.chessBoard)
            if promotion:
                self.chessBoard[y2][x2] = Queen(piece.pos, piece.team)
        elif self.chessBoard[y1][x1].getType() == "King":
            self.chessBoard[y1][x1].move(Position(x2, y2), self.chessBoard,
                                         self.blackCheckBoard)
        else:
            self.chessBoard[y1][x1].move(Position(x2, y2), self.chessBoard)
        # refresh CheckBoard
        self.whiteCheckBoard, self.whiteCheck = fillCheckBoard(
            self.chessBoard, Team.WHITE)
        self.blackCheckBoard, self.BlackCheck = fillCheckBoard(
            self.chessBoard, Team.BLACK)
        self.turn = Team.WHITE

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.close()
Esempio n. 16
0
def test_ai_random_recommender(mock_request, mock_post):
    lab_connection_args = {}
    pennai = AI()
Esempio n. 17
0
def test_ai_init(mock_request, mock_post):
    lab_connection_args = {}
    pennai = AI()
Esempio n. 18
0
import numpy as np
from ai.ai import AI
import keras
import tables
import constants

constants.use_gpu()

print("Loading data")
hdf5_path = "./data/seeded.hdf5"
extendable_hdf5_file = tables.open_file(hdf5_path, mode='r')
x = extendable_hdf5_file.root.x[:]
y = extendable_hdf5_file.root.y[:]
extendable_hdf5_file.close()
print("Data loaded")

latest_version = None

ai = AI()
ai_name = 'seeded_last_20'
ai.load_data(x, y)
print("AI Loaded data")
if latest_version is None:
    ai.create_model()
    latest_version = -1
else:
    ai.load_model(ai_name, index=latest_version)
    print("AI Model Loaded")
x, y = ai.filter_by_tiles_collected(20)
ai.train_model(x=x, y=y)
ai.save_model(ai_name, index=latest_version + 1)
Esempio n. 19
0
    def __init__(self,
                 screen: pygame.Surface,
                 rows=cfg.DEF_ROWS,
                 cols=cfg.DEF_COLS,
                 cell_padding=cfg.CELL_PAD,
                 color=cfg.BOARD_BG_COLOR,
                 border_color=cfg.BOARD_BRD_COLOR,
                 border_size=cfg.BOARD_BRD_SIZE):

        Drawable.__init__(self,
                          screen=screen,
                          color=color,
                          border_color=border_color,
                          border_size=border_size)
        self.rows: int = rows
        self.cols: int = cols
        self.cell_pad = cell_padding
        self.mouse_wall = None  # Wall painted on mouse move
        self.player: int = 0  # Current player 0 or 1
        self.board: List[List[Cell]] = []
        self.computing = False  # True if a non-human player is moving
        self._state = None

        # Create NETWORK server
        try:
            if cfg.NETWORK_ENABLED:
                self.server = EnhancedServer(("localhost", cfg.PORT))
                log('Network server active at TCP PORT ' + str(cfg.PORT))
                self.server.register_introspection_functions()
                self.server.register_instance(Functions())
                self.server.start()
        except BaseException:
            log('Could not start network server')
            self.server = None

        for i in range(rows):
            self.board.append([])
            for j in range(cols):
                self.board[-1].append(Cell(screen, self, coord=Coord(i, j)))

        self.pawns: List[Pawn] = []
        self.pawns += [
            Pawn(
                screen=screen,
                board=self,
                color=cfg.PAWN_A_COL,
                border_color=cfg.PAWN_BORDER_COL,
                coord=Coord(rows - 1, cols >> 1),  # Centered
                # URL = SERVER_URL + ':%i' % (BASE_PORT + PAWNS)
            )
        ]
        self.pawns += [
            Pawn(
                screen=screen,
                board=self,
                color=cfg.PAWN_B_COL,
                border_color=cfg.PAWN_BORDER_COL,
                coord=Coord(0, col=cols >> 1)  # Centered
            )
        ]

        self.regenerate_board(cfg.CELL_COLOR, cfg.CELL_BORDER_COLOR)
        self.num_players = cfg.DEFAULT_NUM_PLAYERS
        self.walls: Set[Wall] = set()  # Walls placed on board
        self.draw_players_info()
        self._AI = []
        # self._AI += [AI(self.pawns[0])]
        self._AI += [AI(self.pawns[1], level=cfg.LEVEL)]
Esempio n. 20
0
def load_ai(main_name, index):
    ai = AI()
    ai.load_model(main_name, index=index)
    return ai
Esempio n. 21
0
class NaiveAIPlayer(Player):
    def __init__(self,
                 player_id,
                 name,
                 game,
                 main_name=None,
                 index=None,
                 initialize=False,
                 filtered_moves=None):
        Player.__init__(self, player_id, name, game)
        self.ai = AI()
        if not initialize:
            assert main_name is not None
            assert index is not None
            self.ai.load_model(main_name, index=index)
        else:
            self.ai.create_model()
        self.filtered_moves = filtered_moves

    def get_model_move(self, possible_moves):
        new_states = None
        for move in possible_moves:
            '''
            start = time.time()
            cloned_game = deepcopy(self.game)
            print(time.time() - start)

            start = time.time()
            cloned_game.do_move(move, save_history=False)
            print(time.time() - start)
            start = time.time()
            new_state = cloned_game.get_state().convert_to_xs_for_neural_net()
            print(time.time() - start)
            '''
            new_state = self.state_from_move(
                move).convert_to_xs_for_neural_net()
            if new_states is None:
                new_states = new_state
            else:
                new_states = np.concatenate((new_states, new_state), axis=0)
        predictions = self.ai.make_prediction(new_states)
        choice_index = choose_from_probs(predictions)
        return possible_moves[choice_index]

    def get_random_move(self, possible_moves):
        return random.choice(possible_moves)

    def move(self):
        possible_moves = self.game.get_possible_moves(self)
        if self.filtered_moves is not None:
            if (
                    self.game.get_moves_played() - 1
            ) >= self.filtered_moves:  # -1 because the next state is equal to the
                # filtered moves...also should be tiles collected but whatevr
                move = self.get_model_move(possible_moves)
            else:
                move = self.get_random_move(possible_moves)
        else:
            move = self.get_random_move(possible_moves)
        return move

    def state_from_move(self, action):
        player_id = action.player.get_player_id()
        player_who_moved = player_id
        new_board = deepcopy(self.game.board)
        new_player_index = None
        new_players = deepcopy([p.get_state() for p in self.game.players
                                ])  # [penguins, score, tiles_collected]
        for i, player in enumerate(self.game.players):
            if player_id == player.get_player_id():
                new_player_index = i
            else:
                next_player_id = player.get_player_id()
        if new_player_index is None:
            raise Exception("This player not playing")
        cur_player = new_players[new_player_index]
        next_player_index = 1 if new_player_index == 0 else 0
        next_player = new_players[next_player_index]
        player_ids = deepcopy(self.game.get_player_ids())

        if action.type == "move":
            hex_from = new_board.pieces[action.start]
            hex_from.move_penguin_away()

            cur_player[2] += 1
            cur_player[1] += hex_from.value

            hex_from.empty()

            if action.start != action.end:
                hex_to = new_board.pieces[action.end]
                hex_to.move_penguin_here()

            start = action.start
            end = action.end
            for i, penguin in enumerate(cur_player[0]):
                if penguin == start:
                    if start == end:
                        # penguin died
                        cur_player[0][i] = end = -1
                    else:
                        cur_player[0][i] = end
                    break

            if next_player[0] == [-1, -1, -1, -1]:
                next_player_id = player_id
        elif action.type == "place":
            player_who_moved = player_id
            hex = new_board.pieces[action.start]
            hex.move_penguin_here()
            cur_player[0].append(action.start)
        else:
            raise Exception("WRONG ACTION TYPE")
        return FishState(deepcopy(new_board.pieces), deepcopy(new_players),
                         deepcopy(next_player_id), deepcopy(player_who_moved),
                         deepcopy(player_ids))

    def train_and_save_new_model(self, x, y, new_index):
        self.ai.load_data(x, y)
        self.ai.create_model()
        self.ai.train_model()
        self.ai.save_model('model', index=new_index)
Esempio n. 22
0
                                            tables.Atom.from_dtype(y.dtype),
                                            shape=(0, ),
                                            filters=filters,
                                            expectedrows=len(y))
        for n, (d, c) in enumerate(zip(x, y)):
            x_storage.append(x[n][None])
            y_storage.append(y[n][None])
        hdf5_file.close()

    if wins[new_challenger_name] > (win_threshold * games_played):
        if random_player_1:
            random_player_1 = False
        print("NEW BEST PLAYER")
        best_model = last_model + iters
    else:
        best_model = best_model

    print('TRAINING NEW MODEL')
    hdf5_path = "./data/data.hdf5"
    extendable_hdf5_file = tables.open_file(hdf5_path, mode='r')
    x = extendable_hdf5_file.root.x[:]
    y = extendable_hdf5_file.root.y[:]
    extendable_hdf5_file.close()

    ai = AI()
    ai.load_data(x, y)
    ai.create_model()
    ai.train_model()
    ai.save_model('model', index=iters + last_model + 1)
    print("MODEL TRAINED LETS GO")
    iters += 1