Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. # This code iterates through all of the current player's uncaptured pieces to ensure that
  2. # at least one has a legal next move (regular move or capture) that resolves check if necessary.
  3. # Each piece is temporarily moved to each square (and any captured pieces are temporarily
  4. # captured) while check state is examined. At the end of the loop, all pieces are returned to
  5. # their original positions.
  6.  
  7. def no_legal_next_move?
  8. friendly_pieces = pieces.where(color: player_turn, captured: false)
  9. friendly_pieces.each do |piece|
  10. (1..8).each do |x|
  11. (1..8).each do |y|
  12. if piece.valid_move?(x, y)
  13. original_x = piece.x_position
  14. original_y = piece.y_position
  15. captured_piece = pieces.find_by(x_position: x, y_position: y)
  16. begin
  17. captured_piece.update(x_position: -1, y_position: -1) if captured_piece
  18. piece.update(x_position: x, y_position: y)
  19. reload
  20. check_state = check
  21. ensure
  22. piece.update(x_position: original_x, y_position: original_y)
  23. captured_piece.update(x_position: x, y_position: y) if captured_piece
  24. reload
  25. end
  26. if check_state.nil?
  27. return false
  28. end
  29. end
  30. end
  31. end
  32. end
  33. true
  34. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement