Check whether a move will cause check on the King

Though a major part of the validation check done in the preceding lines is simple, one of the validation steps needs to check whether a movement will cause the king to be in check. This is a tricky situation. We can only find this out after we have made the actual move. However, we cannot allow that movement to happen on the chessboard.

To do this, the pre_move_validation method calls a method named will_move_cause_check, which creates a copy of the Model class. Then, it performs a move on the new temporary copy to check whether it does cause a king to be in check. The code for this is as follows (4.06model.py):

def will_move_cause_check(self, start_position, end_position):
tmp = deepcopy(self)
tmp.move(start_position, end_position)
return tmp.is_king_under_check(self[start_position].color)
Note that when you create a copy by simple assignment, Python creates a shallow copy. In a shallow copy, the two variables now share the same data. So, a modification in one place affects the other as well.
In contrast to this, deep copies create a copy of everything—the structure as well as the elements. We need to create a deep copy of the chessboard because we want to check whether the king makes a valid move before it actually moves, and we want to do this without modifying the original object's state in any way.
..................Content has been hidden....................

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