set_it_off
set_it_off

Reputation: 3

Coding a simple CLI Tic Tac Toe game, my loop is only iterating once before breaking (code inside)

I'm trying to program a method that determines if there is a winning combination of moves on a tic tac toe board. The program is a simple CLI application. The method accepts a board array, a " " is considered and open space and "X" and "O" represent moves. The method returns "false" for a board that has no winning combination, or returns the the winning combination if there is one as an array of indexes. Each index represents a spot on the board as follows:

0 1 2

3 4 5

6 7 8

An example of a board would be

board = ["X", "O", " ", "O", "X", " ", " ", " ", "X"]

'#won? would return [0, 4, 8]

The problem is that my code only iterates through one winning combination before breaking out of the loop.

I have each winning combination stored as a constant WIN_COMBINATIONS. My code is as follows,

def won?(board)
  WIN_COMBINATIONS.each do | win_combination |
    win_combination.each do | win_index |
      if win_combination.all? { | win_index | board[win_index] == "X" }
        win_combination
      elsif win_combination.all? { | win_index | board[win_index] == "O" }
        win_combination
      else
        false
      end
    end
  end
end

Upvotes: 0

Views: 160

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Enumerable#each just iterates the list/array. What you need is Enumerable.detect or Enumerable.any?:

def won?(board)
  WIN_COMBINATIONS.detect do |win_combination|
    win_combination.all? { |win_index| board[win_index] == "X" } ||
    win_combination.all? { |win_index| board[win_index] == "O" }
  end
end

Upvotes: 2

Related Questions