class Notification(object): def __init__(self, window, styleFunction, stylesheet=["", "", ""], img_margin=5, top_margin=5, pos=[0, 0], size=[100, 20]): self._styleFunction = styleFunction self._currApp = '' self._pos = pos # Create components ### Notification Background self._background_main_stylesheet = stylesheet[0] self._background = QLabel(window) self._background.setGeometry(pos[0], pos[1], size[0], size[1]) self._background.hide() ### Notification Logo self._logo = None self._logo_geometry = [ img_margin, img_margin, size[1] - img_margin * 2, size[1] - img_margin * 2 ] ### Notification Title self._title = QLabel(self._background) self._title.setAttribute(Qt.WA_TranslucentBackground) self._title.setAlignment(Qt.AlignTop | Qt.AlignLeft) self._title.setStyleSheet('QLabel{' + stylesheet[1] + '}') self._title.setText('Title') self._title.adjustSize() self._title.setGeometry( img_margin + self._logo_geometry[2] + 4, top_margin, size[0] - img_margin - self._logo_geometry[2] - 4, self._title.height()) self._title.show() ### Notification Message self._message = QLabel(self._background) self._message.setAttribute(Qt.WA_TranslucentBackground) self._message.setAlignment(Qt.AlignTop | Qt.AlignLeft) self._message.setStyleSheet('QLabel{' + stylesheet[2] + '}') self._message.setText('Message') self._message.adjustSize() self._message.setGeometry( img_margin + self._logo_geometry[2] + 8, top_margin + self._title.height() + 2, size[0] - img_margin - self._logo_geometry[2] - 8, self._message.height() * 2) self._message.show() def setParent(self, p): self._background.setParent(p) def deleteLater(self): self._background.deleteLater() def setText(self, app, title, message): if self._currApp != app: logoPath, backgroundColor = self._styleFunction(app) if self._logo == None: self._logo = QSvgWidget(logoPath, self._background) self._logo.setGeometry(self._logo_geometry[0], self._logo_geometry[1], self._logo_geometry[2], self._logo_geometry[3]) self._logo.show() else: self._logo.load(logoPath) self._background.setStyleSheet('QLabel {background-color:' + backgroundColor + ';' + self._background_main_stylesheet + '}') self._logo.setStyleSheet('background-color:' + backgroundColor + ';') self._currApp = app # Update Textual Contents self._title.setText(title) self._message.setText(message) self._message.setWordWrap(True) def update(self): self._background.update() self._logo.update() self._title.update() self._message.update() def show(self): self._background.show() def hide(self): self._background.hide() def move(self, x, y): self._pos = [x, y] self._background.move(x, y) def moveX(self, x): self._pos[0] = x self._background.move(x, self._pos[1]) def moveY(self, y): self._pos[1] = y self._background.move(self._pos[0], y) def bringToFront(self): self._background.raise_() def bringToBack(self): self._background.lower()
import chess import chess.svg board = chess.Board() board.reset_board() app = QApplication(sys.argv) svgWidget = QSvgWidget() svgWidget.setGeometry(400, 300, 400, 400) svgWidget.show() board_picture = chess.svg.board(board) svg_bytes = bytearray(board_picture, encoding='utf-8') svgWidget.renderer().load(svg_bytes) svgWidget.update() svgWidget.show() loop = QEventLoop() QTimer.singleShot(1000, loop.quit) loop.exec_() source_cell_index = chess.square( chess.FILE_NAMES.index('a'), chess.RANK_NAMES.index('1')) #example: A1 is cell index = 0 (out of 63) dest_cell_index = chess.square(chess.FILE_NAMES.index('a'), chess.RANK_NAMES.index('3')) print('source_cell_index:', source_cell_index) print('dest_cell_index:', dest_cell_index)
class MainWindow(QWidget): def __init__(self): super().__init__() self.setGeometry(500, 50, 1000, 1000) self.widgetSvg = QSvgWidget(parent=self) self.widgetSvg.setGeometry(0, 0, 1000, 1000) if args.board is not None: self.chessboard = chess.Board(args.board) else: self.chessboard = chess.Board() self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8") self.widgetSvg.load(self.chessboardSvg) self.widgetSvg.mousePressEvent = self.onclick self.human_first_click = True self.human_move = '' with open(os.path.join(os.getcwd(), 'config.json'), 'r') as f: self.config = json.load(f) self.use_nn = args.nn self.use_database = args.database self.use_mcts = args.mcts # QTimer.singleShot(10, self.play) # QTimer.singleShot(10, self.play) def human_on_click(self, event): move = self.get_human_move(event) if move is None: return None if self.human_first_click: self.human_first_click = False self.human_move = move else: self.human_first_click = True self.human_move += move try: move = None start_position = position_to_index_1d(self.human_move[:2]) if self.chessboard.piece_at(start_position) in [chess.Piece.from_symbol('p'), chess.Piece.from_symbol('P')]: end_position = position_to_index_1d(self.human_move[2:]) if start_position in [end_position + ROW_SIZE, end_position - ROW_SIZE]: print('enter promotion: q, r, b, n') value = input() if value in ['q', 'r', 'b', 'n']: move = chess.Move.from_uci(self.human_move + value) if move is None: move = chess.Move.from_uci(self.human_move) if move in self.chessboard.legal_moves: # check for pawn to last row move and prompt player for type of piece conversion wanted return move except: pass return None def get_computer_move(self): if self.use_database: try: con_db = self.config['database'] database = get_database_from_file(self.chessboard.fen(), con_db['file_path'], con_db['file_name']) moves, probabilities = get_fen_moves_and_probabilities(database, self.chessboard.fen()) index = np.searchsorted(probabilities.cumsum(), np.random.rand(), side='left') return chess.Move.from_uci(moves[index]) except: pass if self.use_mcts: import gc MCTS_Node.use_nn = self.use_nn move = mcts_move(self.chessboard)[0] gc.collect(generation=2) gc.collect(generation=1) gc.collect(generation=0) return move if self.use_nn: try: if self.nn_model is None: from tensorflow import keras self.nn_model = keras.models.load_model(self.config['train']['nn_model_path']) # returns the best k moves moves, _ = get_nn_moves_and_probabilities([self.chessboard.copy()], self.nn_model)[0] for m in moves: if chess.Move.from_uci(m) in self.chessboard.legal_moves: return chess.Move.from_uci(m) except: pass # if no legal move was generated use alpha beta to find one. return alpha_beta_move(self.chessboard) def onclick(self, event): if event.button() == QtCore.Qt.LeftButton: if self.chessboard.turn: if args.whuman: move = self.human_on_click(event) if move is None: return else: move = self.get_computer_move() self.human_first_click = True print('white:', str(move)) else: if args.bhuman: move = self.human_on_click(event) if move is None: return else: move = self.get_computer_move() self.human_first_click = True print('black:', str(move)) self.chessboard.push(move) self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8") self.widgetSvg.load(self.chessboardSvg) if self.chessboard.is_checkmate(): if self.chessboard.turn: print('Black Wins') else: print('White Wins') if self.chessboard.is_insufficient_material(): print('Draw - insufficient material') if self.chessboard.is_stalemate(): print('Draw - stalemate') if event.button() == QtCore.Qt.RightButton: # undo last move self.chessboard.pop() self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8") self.widgetSvg.load(self.chessboardSvg) if event.button() == QtCore.Qt.MiddleButton: print(self.chessboard.__repr__()) # self.widgetSvg.update() # time.sleep(1) def get_human_move(self, event): SQUARE_START = 40 SQUARE_SIZE = 115 SQUARES_PER_ROW_COLUMN = 8 def get_square_index(pos): v = (pos - SQUARE_START) // SQUARE_SIZE if 0 <= v < SQUARES_PER_ROW_COLUMN: return v return None row = get_square_index(event.x()) if row is None: return None row = chr(ord('a') + row) col = get_square_index(event.y()) if col is None: return None col = SQUARES_PER_ROW_COLUMN - col return str(row) + str(col) def play(self): self.widgetSvg.update() self.show() time.sleep(1) for i in range(3): move = alpha_beta_move(self.chessboard) self.chessboard.push(move) self.chessboardSvg = chess.svg.board(self.chessboard).encode("UTF-8") self.widgetSvg.load(self.chessboardSvg) self.widgetSvg.update() time.sleep(1)