I don't know how you're using a while
loop. Most likely you're trying to recreate the stack each iteration through the while
loop, which is a bad idea. The two solutions that spring immediately to mind are to handle the logic on a button click and keep track of the number correct in a row, like this:
Shoes.app do
num_correct = 0
first_num = 1 + rand(10)
second_num = 1 + rand(10)
answer = first_num * second_num
stack do
@info = para 'Hi, Timmy! This program will test your ',
'multiplication tables. When you get 10 ',
'correct, you get to stop, and you get your ',
'pet hamster back!'
@question = para "What is #{first_num} x #{second_num}?"
@response = edit_line :width => 100
btn = button 'OK' do
if @response.text == ''
alert('You need to put an answer in the box, Timmy.')
elsif @response.text.to_i == answer
num_correct += 1
if num_correct == 10
@info.text = "Good job! That's #{num_correct} in a row!"
alert('You did it, Timmy! You can have your ' \
'hamster back... for now.')
exit
else
@info.text = "Good job! That's #{num_correct} in a row!"
first_num = 1 + rand(10)
second_num = 1 + rand(10)
answer = first_num * second_num
@question.text = "What is #{first_num} x #{second_num}?"
@response.text = ''
end
else
num_correct = 0
@info.text = "Wrong, Timmy. The answer is #{answer}."
first_num = 1 + rand(10)
second_num = 1 + rand(10)
answer = first_num * second_num
@question.text = "What is #{first_num} x #{second_num}?"
@response.text = ''
end
end
end
end
Or, the solution which I think is much more interesting, using url
and visit
:
class MyTest < Shoes
url '/', :index
url '/correct/(\d+)', :correct
url '/wrong/(\d+)', :wrong
url '/question', :question
url '/question/(\d+)', :question
url '/done', :done
def index
stack do
para 'Hi, Timmy! This program will test your ' \
'multiplication tables. When you get 10 ' \
'correct, you get to stop, and you get your ' \
'pet hamster back!'
button 'OK' do
visit '/question'
end
end
end
def question(num_correct = 0)
num_correct = num_correct.to_i
first_num = 1 + rand(10)
second_num = 1 + rand(10)
answer = first_num * second_num
stack do
para "What is #{first_num} x #{second_num}?"
flow do
response = edit_line :width => 100
button 'Answer' do
if response.text.to_i == answer
num_correct += 1
if num_correct == 10
visit '/done'
else
visit "/correct/#{num_correct}"
end
else
visit "/wrong/#{answer}"
end
end
end
end
end
def correct(num_correct)
stack do
para "Good job! That's #{num_correct} in a row!"
button "Next Question" do
visit "/question/#{num_correct}"
end
end
end
def wrong(answer)
@num_correct = 0
stack do
para "Wrong! The correct answer is #{answer}."
button "Next Question" do
visit '/question'
end
end
end
def done
stack do
para 'You did it, Timmy! You can have your ' \
'hamster back... for now.'
button 'OK' do
exit
end
end
end
end
Shoes.app