Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # This code iterates through all of the current player's uncaptured pieces to ensure that
- # at least one has a legal next move (regular move or capture) that resolves check if necessary.
- # Each piece is temporarily moved to each square (and any captured pieces are temporarily
- # captured) while check state is examined. At the end of the loop, all pieces are returned to
- # their original positions.
- def no_legal_next_move?
- friendly_pieces = pieces.where(color: player_turn, captured: false)
- friendly_pieces.each do |piece|
- (1..8).each do |x|
- (1..8).each do |y|
- if piece.valid_move?(x, y)
- original_x = piece.x_position
- original_y = piece.y_position
- captured_piece = pieces.find_by(x_position: x, y_position: y)
- begin
- captured_piece.update(x_position: -1, y_position: -1) if captured_piece
- piece.update(x_position: x, y_position: y)
- reload
- check_state = check
- ensure
- piece.update(x_position: original_x, y_position: original_y)
- captured_piece.update(x_position: x, y_position: y) if captured_piece
- reload
- end
- if check_state.nil?
- return false
- end
- end
- end
- end
- end
- true
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement