我在Ruby中制作了一个简单的游戏来帮助学习它。现在,我一直在尝试在Sinatra中实现它,但是我不能让文本输入与'while'循环交互。谁能帮我看看我做错了什么?
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'haml'
#use Rack::Session::Pool
module HotColdApp
def initialize
guesses = 1
i = rand(10)
end
def play
"Guess a number from 1 to 10"
"You have 5 tries"
"----------"
guess = gets.to_i
while guess != i and guesses < 5
guesses = guesses + 1
if guess < i
"too cold"
guess = gets.to_i
else guess > i
"too hot"
guess = gets.to_i
end
end
if guess == i
"just right"
else
"try again next time"
end
end
end
include HotColdApp
get '/' do
p initialize
haml :index
end
post '/' do
guess = params[:guess]
haml :index, :locals => {:name => guess}
end
__END__
@@ index
!!!!
%html
%head
%title Hot/Cold
%body
%h1 hOt/cOld
%p
Guess a number from 1 to 10. You have 5 tries.
%form{:action => "/", :method => "POST"}
%p
%input{:type => "textbox", :name => "guess", :class => "text"}
%p
%input{:type => "submit", :value => "GUESS!", :class => "button"}
%p
答案 0 :(得分:1)
我不确定这是否与您正在寻找的完全相同,但它确实可以玩游戏。有些事情要注意:我改变了播放方法。使用while循环并获取并没有多大意义。相反,我抓住参数并传递给玩,同时保持猜测的数量。我缩进了表单,因为您没有在表单中嵌套提交或文本字段。我建议您在使用haml生成后查看页面的来源。它没有看到你完全理解发生了什么。这应该给你提供更多的步骤来获得成功。
require 'sinatra'
require 'sinatra/reloader'
require 'haml'
#use Rack::Session::Pool
module HotColdApp
def initialize
@guesses = 5
@i = rand(10)
end
def play(guess)
guess = guess.to_i
if(@i != guess && @guesses > 1)
@guesses -= 1
if guess < @i
return "#{@guesses} left. Too cold"
else guess > @i
return "#{@guesses} left. Too hot"
end
elsif(@i != guess && @guesses == 1)
return "You lose!"
elsif(@i == guess)
return "You win!"
end
end
end
include HotColdApp
get '/' do
p initialize
haml :index
end
post '/' do
guess = params[:guess]
@result = play(guess)
haml :index, :locals => {:name => guess}
end
__END__
@@ index
!!!!
%html
%head
%title Hot/Cold
%body
%h1 hOt/cOld
%p
Guess a number from 1 to 10. You get 5 tries.
%form{:action => "/", :method => "POST"}
%p
%input{:type => "textbox", :name => "guess", :class => "text"}
%p
%input{:type => "submit", :value => "GUESS!", :class => "button"}
%p
%p= @result