Skip to content

Commit 9fd2d3e

Browse files
committed
Add Board.root()
1 parent 530750a commit 9fd2d3e

File tree

1 file changed

+30
-21
lines changed

1 file changed

+30
-21
lines changed

chess/__init__.py

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1268,6 +1268,26 @@ def __init__(self, board):
12681268
self.halfmove_clock = board.halfmove_clock
12691269
self.fullmove_number = board.fullmove_number
12701270

1271+
def restore(self, board):
1272+
board.pawns = self.pawns
1273+
board.knights = self.knights
1274+
board.bishops = self.bishops
1275+
board.rooks = self.rooks
1276+
board.queens = self.queens
1277+
board.kings = self.kings
1278+
1279+
board.occupied_co[WHITE] = self.occupied_w
1280+
board.occupied_co[BLACK] = self.occupied_b
1281+
board.occupied = self.occupied
1282+
1283+
board.promoted = self.promoted
1284+
1285+
board.turn = self.turn
1286+
board.castling_rights = self.castling_rights
1287+
board.ep_square = self.ep_square
1288+
board.halfmove_clock = self.halfmove_clock
1289+
board.fullmove_number = self.fullmove_number
1290+
12711291

12721292
class Board(BaseBoard):
12731293
"""
@@ -1365,6 +1385,15 @@ def clear_stack(self):
13651385
del self.move_stack[:]
13661386
del self.stack[:]
13671387

1388+
def root(self):
1389+
"""Returns a copy of the root position."""
1390+
if self.stack:
1391+
board = type(self)(None, chess960=self.chess960)
1392+
self.stack[0].restore(board)
1393+
return board
1394+
else:
1395+
return board.copy(stack=False)
1396+
13681397
def remove_piece_at(self, square):
13691398
piece = super(Board, self).remove_piece_at(square)
13701399
self.clear_stack()
@@ -1915,27 +1944,7 @@ def pop(self):
19151944
:raises: :exc:`IndexError` if the stack is empty.
19161945
"""
19171946
move = self.move_stack.pop()
1918-
state = self.stack.pop()
1919-
1920-
self.pawns = state.pawns
1921-
self.knights = state.knights
1922-
self.bishops = state.bishops
1923-
self.rooks = state.rooks
1924-
self.queens = state.queens
1925-
self.kings = state.kings
1926-
1927-
self.occupied_co[WHITE] = state.occupied_w
1928-
self.occupied_co[BLACK] = state.occupied_b
1929-
self.occupied = state.occupied
1930-
1931-
self.promoted = state.promoted
1932-
1933-
self.turn = state.turn
1934-
self.castling_rights = state.castling_rights
1935-
self.ep_square = state.ep_square
1936-
self.halfmove_clock = state.halfmove_clock
1937-
self.fullmove_number = state.fullmove_number
1938-
1947+
self.stack.pop().restore(self)
19391948
return move
19401949

19411950
def peek(self):

0 commit comments

Comments
 (0)