Answer to Best of Ruby Quiz, quiz 4 "the animal quiz"

[["an elephent", true]]
$stack = []

def input
gets.chomp
end

# convert_answer_to_question
def c_a_t_q(key)
"Is it a/an #{key}? (y or n)"
end

def agent_answer
case gets.chomp
when "y"
true
when "n"
false
else
raise "Invalid input, please input 'y' or 'n'"
end
end

def play_again?
$stack.clear
puts "Thanks.\nPlay again? (y or n)"
if agent_answer
main_process
else
exit
end
end

#convert_question_to_answer
def c_q_t_a(question)
question.match(/Is it (.*)\?$/) ? $1 : raise("Invalid input, please input the sentance 'Is it xxx?'")
end

# warning
def final_answer?
$answers[$stack[0]].size == ($stack[1] + 1)
end

def header_process
puts "Think of an animal..."
rand_num = rand($answers.size)
$stack << rand_num << 0
end

# push common stack to $stack
def p_c_s
$answers << []
($stack[1]).times do |i|
$answers.last << $answers[$stack[0]][i]
end
end

def body_process
current_pair = $answers[$stack[0]][$stack[1]]
puts c_a_t_q(current_pair[0])
if agent_answer == current_pair[1]
if final_answer?
puts "I win. Pretty smart, aren't I?"
else
$stack[1] += 1
body_process
end
else
puts "You win. Help me learn from my mistake before you go... \nWhat animal were you thinking of?"
real_answer = input
puts "Give me a question to distinguish #{real_answer} from #{current_pair[0]}."
distinguish_question = c_q_t_a(input)
puts "For #{real_answer}, what is the answer to your question? (y or n)"
distinguish_answer = agent_answer
p_c_s
$answers.last << [distinguish_question, distinguish_answer] << [real_answer, true]
end

end

def main_process
header_process
body_process
play_again?
rescue => e
puts e.message
play_again?
end

main_process
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章