Home > Enterprise >  Building tic tac toe game through scratch stuck while checking winning
Building tic tac toe game through scratch stuck while checking winning

Time:01-18

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.

CodePudding user response:

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

  •  Tags:  
  • Related