-2

I can play the game. Switch the player all working fine but not getting result who won the game.

def initialize_board
  @count = 9
  @player = PLAYER_ONE   #current_player
  @board = Array.new(3){ Array.new(3, " ") }
end

 def play
      inputs = get_inputs
      return false if !inputs
      update_board(inputs)
      print_board
    end

def switch_player
  if(@player == PLAYER_ONE)
    @player = PLAYER_TWO
  else
    @player = PLAYER_ONE
  end
end

def game_over?
  # @count = @count - 1
  # @count <= 0

  if check_winner
    puts "#{@player} won "
  end

end


def check_winner
  WIN_COMBINATIONS.find do |indices|
    binding.pry
    values = @board.values_at(*indices)
    values.all?('X') || values.all?('O')
  end 
end  

my debugging result

Here I am getting indices [0,1,2] in all cases while debugging.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sanju Basnet
  • 136
  • 2
  • 9
  • 1
    Please show `WIN_COMBINATIONS`. I suspect `@board` has been defined incorrectly. – Cary Swoveland Jan 17 '22 at 18:49
  • [This question](https://stackoverflow.com/questions/70139369/how-to-use-an-array-method-as-condition-for-if-statement-in-ruby) shows other ways to implement the game. – Cary Swoveland Jan 17 '22 at 21:04

1 Answers1

2

The main reason why you're not getting the winner is because your 'values = @board.values_at(*indices)' statement returns an array of arrays. And values.all?('X') || values.all?('O') checks not an 'X' or 'O' pattern but an array object. So you need to flatten an array first.

values.flatten!

Stefan already answered similar question , but his board was one-dimensional because of %w expression, you can read about it here

steimo
  • 170
  • 1
  • 2
  • 10