Pre-move validation

The chess piece must only be moved if it does not violate the rules of the game. For example, a chess piece can move to a valid location only if that location is not already occupied by a chess piece of the same color. Similarly, a piece can move only if it is the player's turn to move. Another rule states that a piece can only move if the resulting move does not result in check for the king of the same color. 

This pre_move_validation method is responsible for checking all the rules. If all validations pass, it calls the move method to update the move, as follows (see 4.06model.py):

    def pre_move_validation(self, initial_pos, final_pos):
initial_pos, final_pos = initial_pos.upper(), final_pos.upper()
piece = self.get_piece_at(initial_pos)
try:
piece_at_destination = self.get_piece_at(final_pos)
except:
piece_at_destination = None
if self.player_turn != piece.color:
raise exceptions.NotYourTurn("Not " + piece.color + "'s turn!")
enemy = ('white' if piece.color == 'black' else 'black')
moves_available = piece.moves_available(initial_pos)
if final_pos not in moves_available:
raise exceptions.InvalidMove
if self.get_all_available_moves(enemy):
if self.will_move_cause_check(initial_pos, final_pos):
raise exceptions.Check
if not moves_available and self.is_king_under_check(piece.color):
raise exceptions.CheckMate
elif not moves_available:
raise exceptions.Draw
else:
self.move(initial_pos, final_pos)
self.update_game_statistics(
piece, piece_at_destination, initial_pos, final_pos)
self.change_player_turn(piece.color)

If the rules are not being followed, this code raises several exceptions, which are defined in the exceptions class as follows (see 4.06exceptions.py):

 class Check(ChessError): pass
class InvalidMove(ChessError): pass
class CheckMate(ChessError): pass
class Draw(ChessError): pass
class NotYourTurn(ChessError): pass

We could have further coded the error classes, but we chose not to because we simply updated the name of the error class to the bottom label, which is sufficient for our current purpose. The error message is displayed from the shift method of the View class, as follows (see 4.06view.py):

self.info_label["text"] = error.__class__.__name__
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5