def export(puzzle, include_first_move=True): fen = puzzle.last_pos.fen() board = chess.Board(fen) game = Game().from_board(board) result = PgnExporter.determine_result_tag(board) moves = puzzle.positions.move_list() if include_first_move: first_move = puzzle.last_move else: # simulate the move (blunder) board.push(puzzle.last_move) board.clear_stack() # take resulting board and create new game game = Game().from_board(board) first_move = Move.from_uci(moves.pop(0)) # start the line node = game.add_main_variation(first_move) # add the rest of the moves for m in moves: node = node.add_variation(Move.from_uci(m)) # copy headers from the original game and override result tag for h in puzzle.game.headers: game.headers[h] = puzzle.game.headers[h] game.headers['Result'] = result return str(game)
def get_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score, moves: str) -> None: board = Board(fen) game = Game.from_board(board) node = game.add_main_variation(Move.from_uci(move)) current_eval = PovScore(current_score, not board.turn) result = self.gen.analyze_position(node, prev_score, current_eval, tier=10) self.assert_is_puzzle_with_moves(result, [Move.from_uci(x) for x in moves.split()])
def play(): # TODO: get player move from GET request object # TODO: if there is no player move, render the page template if request.method == 'POST': move_str = request.form["move"] try: start, end = game.split_input(move_str) move = Move(start, end) except InputError: ui.errmsg = 'Invalid move format, please try again' return render_template('chess.html', ui=ui) movetype = game.movetype(start, end) if movetype is None: ui.errmsg = 'Invalid move for the piece, please try again' return render_template('chess.html', ui=ui) move.storepiece(game) movehis.push(move) game.update(move.tuple()) coord = game.check_for_promotion() if coord is not None: return redirect('/promote') game.next_turn() ui.board = game.display() ui.inputlabel = f'{game.turn} player: ' ui.errmsg = None if game.winner != None: ui.inputlabel = game.winner return render_template('win.html', ui=ui) return render_template('chess.html', ui=ui)
def is_pseudo_legal(self, move: chess.Move) -> bool: if move.board_id is None: move.board_id = self.board_id output = super().is_pseudo_legal(move) move.board_id = None return output else: return super().is_pseudo_legal(move)
def run(self): from chess import Board, Move b = Board() b.make_move(Move.from_uci("f2f3")) b.make_move(Move.from_uci("e7e6")) b.make_move(Move.from_uci("g2g4")) b.make_move(Move.from_uci("d8h4")) assert (b.checkmate())
def get_output(self, headers, board, real_move_uci, moves): output_headers = {"FEN": board.fen(), **headers} game = pgn.Game(headers=output_headers) best_move = moves[0] game.add_main_variation(Move.from_uci(best_move["pv"]), comment=self.get_comment( best_move, real_move_uci)) for move in moves[1:]: game.add_variation(Move.from_uci(move["pv"]), comment=self.get_comment(move, real_move_uci)) return str(game)
def _push(self, move: chess.Move) -> None: self._updateJustMovedCells(False) turn = self.board.turn if self._isCellAccessible(self.cellWidgetAtSquare(move.from_square)) \ and move.promotion is None and self.isPseudoLegalPromotion(move): w = self.cellWidgetAtSquare(move.to_square) promotionDialog = _PromotionDialog(parent=self, color=turn, order=self._flipped) if not self._flipped and turn: promotionDialog.move(self.mapToGlobal(w.pos())) else: promotionDialog.move( self.mapToGlobal( QtCore.QPoint(w.x(), w.y() - 3 * w.height()))) promotionDialog.setFixedWidth(w.width()) promotionDialog.setFixedHeight(4 * w.height()) exitCode = promotionDialog.exec_() if exitCode == _PromotionDialog.Accepted: move.promotion = promotionDialog.chosenPiece elif exitCode == _PromotionDialog.Rejected: self.foreachCells(CellWidget.unhighlight, lambda w: w.setChecked(False)) return if not self.board.is_legal(move) or move.null(): # //HACK this is the only way for a move to be illegal (without playtesting) # self.illegalClassicalMove.emit(move) self.entangle_move = True # raise IllegalMove(f"illegal move {move} by ") # logging.debug(f"\n{self.board.lan(move)} ({move.from_square} -> {move.to_square})") san = self.board.san(move) self.board.push(move) # logging.debug(f"\n{self.board}\n") self._updateJustMovedCells(True) self.popStack.clear() self.foreachCells(CellWidget.unmark, CellWidget.unhighlight) self.synchronizeAndUpdateStyles() self.moveMade.emit(move) self.movePushed.emit(san)
def read(doc) -> Puzzle: board = Board(doc["fen"]) node = Game.from_board(board) for uci in doc["moves"]: move = Move.from_uci(uci) node = node.add_main_variation(move) return Puzzle(doc["_id"], node.game())
def run(self): """continuous game """ pubsub = self._red.pubsub() pubsub.subscribe([self.opp_id]) self.info("Entering in the pubsub") for move in pubsub.listen(): self.info("Incoming message") if move['type'] == 'subscribe' and move['data'] == 1: self.info("Init message") if self._color: while not self._red.get(self._game_id): self.info("Waiting for black") self.info("Black is connected, playing first move") decision, _ = self._engine.go(movetime=2000) self._red.publish(self.own_id, decision.uci()) self._board.push(decision) self.info("Move played") else: self._red.set(self._game_id, "ready") self.info("Telling white we are ready") else: self.info("Receiving move") self._board.push(Move.from_uci(move['data'].decode('utf8'))) decision, _ = self._engine.go(movetime=2000) self._red.publish(self.own_id, decision.uci()) self.info("Playing move") self._board.push(decision)
def async_training(params): global board, whose_playing, weights, current_board_features, white_castle_status, black_castle_status game = params[0] board = params[1] whose_playing = params[2] weights = params[3] current_board_features = params[4] white_castle_status = params[5] black_castle_status = params[6] for expected_move in game: get_current_board_features() actual_move = get_move_to_be_played(board, whose_playing) update_weights(expected_move, board.san(Move.from_uci(str(actual_move)))) board.push_san(expected_move) if whose_playing == chess.WHITE: whose_playing = chess.BLACK else: whose_playing = chess.WHITE return [ weights, current_board_features, white_castle_status, black_castle_status ]
def button_release(self, event): print(event) if event.num == 1: self.buttonPressed = False before_x = math.floor(event.x / self.height) before_a = math.floor(event.y / self.height) [start_a, start_x] = self.board.get_coordinate_from_square(self.x, self.y) [goal_a, goal_x ] = self.board.get_coordinate_from_square(before_x, before_a) print(start_a + str(start_x) + goal_a + str(goal_x)) move = Move.from_uci(start_a + str(start_x) + goal_a + str(goal_x)) print(1) if move in self.board.board_pgn.legal_moves: self.board.board_pgn.push(move) print(2) self.board.make_board_to_gui() print(3) self.board.check_if_right() print(4) return
def pv_to_san(self): if(self.san_arr == None): return "" else: try: pv_san = [] board = Bitboard(self.san_arr[0]) moves = self.san_arr[1] for uci in moves: move = Move.from_uci(uci) if(move in board.pseudo_legal_moves): pv_san.append(board.san(move)) board.push(move) if(len(pv_san) > 0): s = "" white_moves = True move_no = (self.no_game_halfmoves//2)+1 if(self.no_game_halfmoves % 2 == 1): white_moves = False s += str(move_no)+". ... " move_no += 1 for san in pv_san: if(white_moves): s += " "+str(move_no)+". "+san move_no +=1 else: s += " "+san white_moves = not white_moves return s else: return "" except ValueError: return ""
def parse(): char_dict = { 'a':0, 'b':1, 'c':2, 'd':3, 'e':4, 'f':5, 'g':6, 'h':7, } int_dict = { '8':0, '7':1, '6':2, '5':3, '4':4, '3':5, '2':6, '1':7 } with open("Adams.txt") as f: content = f.readlines() long_string = "".join(content).replace("\n"," ") long_string = re.split("\d\/?\d?-\d\/?\d?",long_string) re_prog = re.compile("[a-z]\d\-[a-z]\d") output = [] for ls in long_string: z = re_prog.findall(ls) output.append(z) print(len(output)) new_games = [[Move(int_dict[move[1]],char_dict[move[0]],int_dict[move[4]],char_dict[move[3]]) for move in game] for game in output] return new_games
def read(doc) -> Puzzle: board = Board(doc["fen"]) node: GameNode = Game.from_board(board) for uci in (doc["line"].split(' ') if "line" in doc else doc["moves"]): move = Move.from_uci(uci) node = node.add_main_variation(move) return Puzzle(doc["_id"], node.game(), int(doc["cp"]))
def pv_to_san(self): if(self.san_arr == None): return "" else: try: pv_san = [] board = Board(self.san_arr[0]) moves = self.san_arr[1] for uci in moves: move = Move.from_uci(uci) if(move in board.pseudo_legal_moves): pv_san.append(board.san(move)) board.push(move) if(len(pv_san) > 0): s = "" white_moves = True move_no = (self.no_game_halfmoves//2)+1 if(self.no_game_halfmoves % 2 == 1): white_moves = False s += str(move_no)+". ... " move_no += 1 for san in pv_san: if(white_moves): s += " "+str(move_no)+". "+san move_no +=1 else: s += " "+san white_moves = not white_moves return s else: return "" except ValueError: return ""
def search_position(self, board: chess.Board, position: Position) -> None: """Recursive tree search with an already loaded position.""" print('Searching position') position_id = typing.cast(int, position.position_id) children = self.database.get_child_positions(position_id) legal_moves = list(board.legal_moves) if len(children) == len(legal_moves): # This position is full, recurse on one of the children move = select_child_move(children) print(f'Making move {move}') board.push(Move.from_uci(move)) self.search_position(board, children[move]) board.pop() print('pop move') return unanalyzed_moves = [move for move in legal_moves if move.uci() not in children] move = unanalyzed_moves[0] print(f'Making move {move}') board.push(move) self.database.insert_position(self.analyze_board(board), ParentRelationship(position_id, move.uci())) print('pop move') board.pop() if len(unanalyzed_moves) == 1: print('Back progogate')
def decode_tcn(tcn_string: str) -> list[Move]: moves: list[Move] = [] for i in range(0, len(tcn_string), 2): from_value_index: int = TCN_INDEX_STRING.index(tcn_string[i]) to_value_index: int = TCN_INDEX_STRING.index(tcn_string[i + 1]) promotion: Optional[PieceType] = None drop: Optional[PieceType] = None if to_value_index > 63: promotion = PIECE_SYMBOLS.index( TCN_PIECE_INDEX_STRING[(to_value_index - 64) // 3]) to_value_index = from_value_index + ( -8 if from_value_index < 16 else 8) + (to_value_index - 1) % 3 - 1 if from_value_index > 75: drop = PIECE_SYMBOLS.index( TCN_PIECE_INDEX_STRING[from_value_index - 79]) moves.append( Move(from_square=from_value_index, to_square=to_value_index, promotion=promotion, drop=drop)) return moves
def not_puzzle(self, fen: str, prev_score: Score, move: str, current_score: Score) -> None: board = Board(fen) game = Game.from_board(board) node = game.add_main_variation(Move.from_uci(move)) current_eval = PovScore(current_score, not board.turn) result = self.gen.analyze_position( node, prev_score, current_eval, tier=10) self.assertIsInstance(result, Score)
def check_move(): def parse_request(agrs): #print(request.args) piece = request.args.get('piece') piece_color = piece[0] piece_type = piece[1] src = request.args.get('from', default='') dst = request.args.get('to', default='') promotion = request.args.get('promotion', default='') promotion = promotion if (dst[1] == '8' and piece_type == 'P') else '' return piece_color, piece_type, src, dst, promotion piece_color, piece_type, src, dst, promotion = parse_request(request.args) move = Move.from_uci(src + dst + promotion) if piece_color != 'w' or move not in board.legal_moves: print('*' * 20) print(list(board.legal_moves)) print(move) print('*' * 20, 'ilegal move') value = 'ilegal' else: value = 'legal' board.push(move) return json.dumps({'value': value, 'board': board.fen()})
def simple_test(move, sense_square): hp = { 'num_conv': 3, 'conv_filters': 70, 'conv_kernel': 3, 'num_lstm': 1, 'lstm_size': 250, 'num_dense': 8, 'dense_size': 1500, 'lr': 0.1, 'momentum': 0.3, 'batch_size': 128 } model = ChessModel(hp, True, training=False) board = ReconBoard() # Start of game observation = board.get_current_state(board.turn) print(np.round(model.get_belief_state(observation), 2)) board.push(Move.from_uci(move)) # Turn 1 observation = board.get_pre_turn_observation() print(np.round(model.get_belief_state(observation), 2)) observation = board.sense(sense_square) print(np.round(model.get_belief_state(observation), 2))
def on_move(self, data): game_id = data.get('game_id', None) move_uci = data.get('move', None) if game_id is None or move_uci is None: raise KeyError('invalid move') move = Move.from_uci(move_uci)
def mobility(board: Board): mobility = 0 if board.turn == WHITE: mobility -= sum(1 for m in board.generate_pseudo_legal_moves() if not board.is_into_check(m)) board.push(Move.null()) mobility += sum(1 for m in board.generate_pseudo_legal_moves() if not board.is_into_check(m)) board.pop() else: mobility += sum(1 for m in board.generate_pseudo_legal_moves() if not board.is_into_check(m)) board.push(Move.null()) mobility -= sum(1 for m in board.generate_pseudo_legal_moves() if not board.is_into_check(m)) board.pop() return mobility
def get_captures(board: chess.Board, prev_moce: chess.Move, count: int, piece_count: Dict[int, int]) \ -> Tuple[int, int, int]: if not board.is_en_passant(prev_moce): # is it not en passant, the norm piece = piece_delta(board, count, piece_count, board.turn) else: # needs seperate code path piece = (1, uci_to_1d_array_index(prev_moce.uci()), count) return piece
def make_move(self, to_cell: Cell): promotion = "q" if self.is_promotion(to_cell) else "" uci_move = f"{self.gui_board.selected_cell}{to_cell}{promotion}" move = Move.from_uci(uci_move) if self.board.is_legal(move): self.board.push(move) self.gui_board.selected_cell.selected = False self.gui_board.selected_cell = None self.gui_board.update_piece_positions(self.board.board_fen())
def _flip_move(move: chess.Move): uci = move.uci() from_column = uci[0] from_row = 9 - int(uci[1]) to_column = uci[2] to_row = 9 - int(uci[3]) flipped_move = chess.Move.from_uci("{}{}{}{}".format( from_column, from_row, to_column, to_row)) return flipped_move
def get_root(fen, moves): board = Board(fen) root = Node(fen) if moves is not None: for move in moves: fen = board.fen().split(' ') root.previous.append(' '.join(fen[:2])) board.push(Move.from_uci(move)) root.position = board.fen() return root
def handle_state_change(self, event): board = Board(fen=self.initial_fen) for move in event["moves"].split(): board.push(Move.from_uci(move)) self.node = Node(fen=board.fen()) self.my_turn = not self.my_turn print(f"My turn? {self.my_turn}") if self.my_turn: self.make_move()
def mouse_release(self, event): """ Called when mouse is released, Stop dragging piece and ask if the move is legal """ global drag_sq if drag_sq != -1: # dst_sq = (event.y // sq_size) * 8+ (event.x // sq_size) dst_sq = self.coord_to_sq((event.x, event.y)) m = Move(drag_sq, dst_sq) m.set_from_user() # this is input from user (not file) if not self.on_move_piece(m): # Withdraw the piece to original spot obj = self.piece_objs[drag_sq] self.canvas.coords(obj, self.sq_to_coord(drag_sq)) # ((drag_sq%8)*sq_size, (drag_sq//8)*sq_size)) drag_sq = -1 return
def __explore_leaves(self, board): values = defaultdict(list) for move in board.legal_moves: board.push(move) #score = self.__minimax(board, False, self.DEPTH) score = self.__alpha_beta(board, -self.MAX_VAL, self.MAX_VAL, False, self.DEPTH) values[score].append(move.uci()) board.pop() values = sorted(values.items()) print(values) return Move.from_uci(random.choice(values[0][1]))
def mouse_release(self,event): """ Called when mouse is released, Stop dragging piece and ask if the move is legal """ global drag_sq if drag_sq != -1: # dst_sq = (event.y // sq_size) * 8+ (event.x // sq_size) dst_sq = self.coord_to_sq((event.x, event.y)) m = Move(drag_sq, dst_sq) m.set_from_user() # this is input from user (not file) if not self.on_move_piece(m): # Withdraw the piece to original spot obj = self.piece_objs[drag_sq] self.canvas.coords(obj, self.sq_to_coord(drag_sq)) # ((drag_sq%8)*sq_size, (drag_sq//8)*sq_size)) drag_sq = -1 return
def seq_test(move, sense_square): model = ChessModel(True, training=True) board = ReconBoard() observations = [] observations.append(board.get_current_state(board.turn)) board.push(Move.from_uci(move)) observations.append(board.get_pre_turn_observation()) observations.append(board.sense(sense_square)) batch = np.asarray([np.asarray(observations)]) print(np.round(model.belief_state.predict(batch)[0][-1]), 2)
def get_move_to_be_played(board, whose_playing): moves_and_target_values = {} all_legal_moves = board.legal_moves for legal_move in all_legal_moves: moves_and_target_values[legal_move] = get_target_value( board.san(Move.from_uci(str(legal_move))), board, whose_playing) return max(moves_and_target_values, key=lambda i: moves_and_target_values[i])
def __init__(self): self.castles = { ('K', 'e1', 'g1'): Move.from_uci('h1f1'), ('K', 'e1', 'c1'): Move.from_uci('a1d1'), ('k', 'e8', 'g8'): Move.from_uci('h8f8'), ('k', 'e8', 'c8'): Move.from_uci('a8d8'), } self.castles_reversed = { ('K', 'g1', 'e1'): Move.from_uci('f1h1'), ('K', 'c1', 'e1'): Move.from_uci('d1a1'), ('k', 'g8', 'e8'): Move.from_uci('f8h8'), ('k', 'c8', 'e8'): Move.from_uci('d8a8'), } self.position = None self._start_name = None
return BoardString(str(self.position.fen)) def initialMove(self): '''Special game move to hold starting position.''' # FIXME: use iswhite start = GameMove( self._start_name, self.position.fen.full_move, self.position.fen.turn == 'w', None, self.fen, None, None, None, None ) return start if __name__ == '__main__': fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" engine = ChessLibGameEngine() engine.newGame(fen) move = Move.from_uci('e2e4') engine.makeMove(move) b = BoardString() print b.toFen()