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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值