Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def in_check?(color)
- king = find_king(color)
- opponents = opponents_pieces(color)
- @enemies_causing_check = []
- opponents.each do |piece|
- @enemies_causing_check << piece if piece.valid_move?(king.x_position, king.y_position) == true
- end
- return true if @enemies_causing_check.any?
- false
- end
- def i_can_move_out_of_check?(color)
- king = find_king(color)
- x_start = king.x_position
- y_start = king.y_position
- state = false
- ((king.x_position - 1)..(king.x_position + 1)).each do |x|
- ((king.y_position - 1)..(king.y_position + 1)).each do |y|
- king.update(x_position: x, y_position: y) if king.valid_move?(x, y)
- state = true unless in_check?(color)
- king.update(x_position: x_start, y_position: y_start)
- end
- end
- state
- end
- def capture_opponent_causing_check?(color)
- friendlies = friendly_pieces(color)
- the_liberator = []
- friendlies.each do |friend|
- @enemies_causing_check.each do |enemy|
- the_liberator << friend if friend.valid_move?(enemy.x_position, enemy.y_position) == true
- end
- end
- return true if the_liberator.any?
- false
- end
- def stalemate?(color)
- your_pieces = friends_on_board(color)
- available_moves = []
- your_pieces.each do |piece|
- 1.upto(8) do |x|
- 1.upto(8) do |y|
- if piece.valid_move?(x, y) && !piece.move_causes_check?(x, y)
- available_moves << [x, y]
- end
- end
- end
- end
- return false if available_moves.any?
- true
- end
- def friendly_pieces(color)
- friendly_pieces = if color == 'BLACK'
- 'BLACK'
- else
- 'WHITE'
- end
- pieces.where(color: friendly_pieces).to_a
- end
- def opponents_pieces(color)
- opposing_color = if color == 'BLACK'
- 'WHITE'
- else
- 'BLACK'
- end
- pieces.where(color: opposing_color).to_a
- end
- def move_to!(x, y)
- if occupied_by_mycolor_piece?(x, y)
- false
- elsif valid_move?(x, y)
- if occupied_by_opposing_piece?(x, y)
- capture_piece_at!(x, y)
- update_attributes(x_position: x, y_position: y)
- elsif unoccupied?(x, y)
- update_attributes(x_position: x, y_position: y)
- end
- else
- false
- end
- end
- def move_causes_check?(next_x, next_y)
- state = false
- ActiveRecord::Base.transaction do
- move!(next_x, next_y)
- state = game.check?(color)
- raise ActiveRecord::Rollback
- end
- reload
- state
- end
- def available_moves
- Game.all_board_coordinates.select do |coordinate_pair|
- valid_move?(coordinate_pair[0], coordinate_pair[1]) &&
- !is_obstructed?(coordinate_pair[0], coordinate_pair[1]) &&
- !occupied_by_mycolor_piece?(coordinate_pair[0], coordinate_pair[1])
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement