Snippets

Pierre-Adrien Buisson Starting to compute legal chess moves, for now only for the rook

Created by Pierre-Adrien Buisson
  # Returns possible couples of moves/positions for a given start position
  # player: white | black
  def possible_moves(player : string, position : array(array(string?)) = @position) : hash(string, array(array(string?)))
    possible_moves = hash(string, array(array(string?))).new

    if player == "white"
      position.each_with_index do |row, row_index|
        row.each_with_index do |square, column_index|
          next unless square

          new_positions =
            if square == "r"
              (0..7).map do |new_row|
                (0..7).map do |new_column|
                  same_square = new_row == row_index && new_column == column_index
                  next if same_square
                  different_row = new_row != row_index
                  different_col = new_column != column_index
                  next if different_col && different_row
                  next if piece_of_same_colour_on_destination?(position, player, new_row, new_column)

                  # todo: if a piece on the "row", i can't reach squares beyond the piece
                  piece_in_between = false
                  next if piece_in_between

                  new_position = position.clone
                  # remove piece from current square
                  new_position[row][column] = nil
                  # move piece to new square
                  new_position[new_row][new_column] = square

                  letters = ('a'..'h').to_a
                  uci_move = "#{letters[column_index]}#{row_index+1}#{letters[new_column]}#{new_row+1}"
                  possible_moves[uci_move] = new_position
                end
              end
          end

        end
      end
    elsif player == "black"
    end

    possible_moves
  end

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.