WIN
Create a WIN method that accepts a board as an argument and returns
false/nil if there is no win combination present in the board and
returns the winning combination indexes as an array if there is a win.
To clarify: this method should not return who won (aka X or O), but
rather how they won – by means of the winning combination.
Iterate over the possible win combinations defined in WIN_COMBINATIONS
and check if the board has the same player token in each index of a
winning combination.
That is a very verbose and explicit example of how you might iterate
over a nested array of WIN_COMBINATIONS and checking each win
combination index against the value of the board at that position.
For example, on a board that has a winning combination in the top row,
#‘win’ should return [0,1,2], the indexes in the board that created the
win:
Board with winning X in the top row.
board = [“X”, “X”, “X”, " ", " ", " ", " ", " ", " "]
win(board) #=> [0,1,2]
A board with a diagonal win would function as follows:
Board with winning X in the right diagonal.
board = [“X”, “O”, “X”, “O”, “X”, “O”, “X”, “X”, “O”]
X | O | X
-----------
O | X | O
-----------
X | X | O
win(board) #=> [2,4,6]
A board with no win would return false/nil:
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
win(board) #=> nil
You should be able to iterate over the combinations defined in
WIN_COMBINATIONS using each or a higher-level iterator to return the
correct board indexes that created the win.
Your method should work for both boards that win with an “X” or boards
that win with an “O”. We’ve provided you with a helper method called
position_taken? that takes a board and an index as arguments and returns
true or false based on whether that position on the board has been
filled.
so here is what I have so far:
WIN_COMBINATIONS =
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 4, 8],
[2, 4, 6],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8]]
def win(board)
combo = 0
while combo < WIN_COMBINATIONS.length
current_combo = WIN_COMBINATIONS[combo]
current_combo.all? { |position|
board[position[0]] == "X" && board[position[1]] == "X" &&
board[position[2]] == “X” || board[position[0]] == “O” &&
board[position[1]] == “O” && board[position[2]] == “O”
}
if current_combo.all? == true
return current_combo
else return false
end
combo += 1
end
end
I’ve tried many things, but whenever I test it and pass the method a
board, it always seems to only return the first combo. Would greatly
appreciate the help.