I am writing a mastermind game in Ruby. So far I have the code located here on github.
The problem I am running into is this: when I run the function below, the instance variable @code which is generated at the beginning of the game returns empty after the first run of the function.
I have assigned a local variable, tempcode, the value of @code, and all the operations are done to tempcode within the function. I have also assigned an attr_reader to @code, instead of an attr_accessor. So @code shouldn't change!
def compare_guess_to_code()
correct_color = "1"
correct_color_and_pos = "2"
incorrect_color = "0"
tempcode = @code
a = 0
@guess.length.times do #maybe a for loop that goes through both arrays simultaneously?
case
when @guess[a] == tempcode[a]
feedback.push(correct_color_and_pos)
tempcode.delete_at[a]
@guess.delete_at[a]
when guess[a] != tempcode[a] && tempcode.include?(guess[a])
feedback.push(correct_color)
tempcode.delete_at[a]
@guess.delete_at[a]
when !(tempcode.include?(guess[a]))
feedback.push(incorrect_color)
tempcode.delete_at[a]
@guess.delete_at[a]
else
puts "Error"
end
end
feedback.sort!
feedback.reverse!
print "Feedback: #{feedback}"
end
The feedback returns properly, everything seems to be working fine, I just can't do the comparison function more than one time before @code empties out. How can I hold the value consistent?
If you want to run the program to test it, use mastermind/lib/mastermind.rb.