Saturday, 14 September 2013

Ruby - Why aren't they equal?

Ruby - Why aren't they equal?

I was trying to create this program (link): http://geograph.co/mastermind.txt
The place that reads puts "#{code[0]}hi#{code[0]==guess[0]}" in the
compare_code function always reads false. Does anyone know why is the
result always false?



def assign_numbers(arr)
flag = false;
while !flag
random = (rand()*8).round()
flag2 = false
arr.size.times do
|x|
if (arr[x]==random)
flag2 = true
break
end
end
if (flag2==false)
flag = true
end
end
return random
end
def compare_code(guess, code)
in_place=0
out_place=0
4.times do
|x|
guess[x-1] = guess[x-1].to_i
code[x-1]=code[x-1].to_i
end
4.times do
|x|
puts "#{code[0]}hi#{code[0]==guess[0]}"
end
if in_place == 4
puts "You won! Thanks for playing the game!"
else
puts "You got #{out_place} right numbers but in the wrong
places,\nand you got #{in_place} numbers in the right place."
end
end
code = Array.new(4)
puts "Welcome to Mastermind!"
puts "I have a code that contains four of the following eight numbers:
1,2,3,4,5,6,7,8."
4.times do
|x|
code[x-1] = assign_numbers(code)
end
i=1
flag = false
while (!flag)
print "Enter guess #{i}: "
guess = gets().chomp()
if guess.to_i>1110 && guess.to_i<8889
guess = guess.split()
flag = compare_code(guess, code)
if i!=12
i+=1
else
puts "Game Over! The code was #{code.join}"
flag=true
end
else
puts "Please try again. Please enter a four digit number."
end
end

No comments:

Post a Comment