I'm working on a chess game and want to search the nested array for the King piece K(b)
and then return the coordinates.
I've tried the following method which returns 4 (the x coordinate - the index in the internal array). However, I'm trying to figure out how to also return index of the outer array. Expected output is [4, 7]
:
piece = "K(b)"
def coordinates_for_piece(piece)
@board.map { |item| item.find_index(piece) }
end
Board:
def piece_setup
@board = Array.new(8) { Array.new([" . ", " . ", " . ", " . ", " . ", " . ", " . ", " . "]) }
@board[0] = ["R(w)", "N(w)", "B(w)", "Q(w)", "K(w)", "B(w)", "N(w)", "R(w)"]
@board[1] = ["P(w)", "P(w)", "P(w)", "P(w)", "P(w)", "P(w)", "P(w)", "P(w)"]
@board[6] = ["P(b)", "P(b)", "P(b)", "P(b)", "P(b)", "P(b)", "P(b)", "P(b)"]
@board[7] = ["R(b)", "N(b)", "B(b)", "Q(b)", "K(b)", "B(b)", "N(b)", "R(b)"]
end
EDIT: This is a VERY clunky way of accomplishing the goal. Looking for something more streamlined.
def coordinates_for_piece(piece)
test = @board.map { |item| item.find_index(piece) }
=> [nil, nil, nil, nil, nil, nil, nil, 4]
x = test.find{|x| !x.nil?}
=> 4
y = test.find_index{|y| !y.nil?}
=> 7
[x, y]
end
Aucun commentaire:
Enregistrer un commentaire