Home > Software engineering >  Ruby Mastermind White Pegs Count
Ruby Mastermind White Pegs Count

Time:02-10

I'm a newbie to Ruby programming. It is my second OOP project. I have trouble with counting white pegs under certain condition. And Wikipedia says that:

-A black key peg is placed for each code peg from the guess which is correct in both colour and position.
-A white key peg indicates the existence of a correct colour code peg placed in the wrong position.

I believe that my black peg condition is true, but I can not count my white pegs correctly. Here is the function code piece:

def check_guess(code, guess)
    @white_peg = 0
    @black_peg = 0
    index = 0
    while index < code.length
      if code[index] == guess[index]
        @black_peg  = 1
        puts "Black => #{@black_peg}"
      elsif guess.any? { |c| code.include?(c) } && code[index] != guess[index]
        @white_peg  = 1
        puts "White => #{@white_peg}"
      end
      index  = 1
    end
    puts "There are #{@white_peg} white peg and #{@black_peg} black peg"
    is_win?
  end
end

I'm invoking above function inside this condition

  def codebreaker_attempt
    guess_array = @codebreaker.guess_code
     @codebreaker.check_guess(@codemaker.code, guess_array)
  end

And lastly my game method is here for stop the game

def play
    codemaker_choose
    (1..12).each do |i|
      puts "#{i}. GUESS\n"
     #puts "Guess array is #{guess}"
      break if codebreaker_attempt == true
    end

I'm leaving here repl.it repo of all my codes if you want to inspect. https://replit.com/@Burakkepuc/Mastermind#main.rb

CodePudding user response:

-A white key peg indicates the existence of a correct colour code peg placed in the wrong position

I found my answer. The white peg code control should be

      elsif code.include?(guess[index]) && code[index] != guess[index]
  •  Tags:  
  • ruby
  • Related