Before we allow chess pieces to move on click of the mouse button, we must have a record of all possible movement options on the board. At every move, we also need to check that it is a legitimate turn for a given player, and that the proposed move should not cause a check on the king.
Now a check may occur on the king, not only from a piece that was moved, but from any other piece on the board as a consequence of such movement. Thus, after every move, we need to calculate the possible moves for all the pieces of the opponent.
Accordingly we will need two methods to:
Let's add the code for the preceding methods into our Board
class. (See code 4.05: chessboard.py)
The code for keeping track of all available moves for a player is as follows:
def all_moves_available(self, color): result = [] for coord in self.keys(): if (self[coord] is not None) and self[coord].color == color: moves = self[coord].moves_available(coord) if moves: result += moves return result
The description of the code is listed as follows:
Before we code the method to verify if a king is in check, we first need to know the exact position of the king. Let's define a method to get the current position of the king, as follows (see code 4.05: chessboard.py):
def position_of_king(self, color): for pos in self.keys(): if is instance(self[pos], pieces.King) and self[pos].color == color: return pos
The preceding code simply iterates through all items in the dictionary. If a given position is an instance of the King
class, it simply returns its position.
Finally, we define a method to verify if the king is under check from the opponent as follows:
def king_in_check(self, color): kingpos = self.position_of_king(color) opponent = ('black' if color =='white' else 'white') for pieces in self.iteritems(): if kingpos in self.all_moves_available(opponent): return True else: return False
The description of the code is listed as follows:
True
, else we return False
.3.138.120.187