1

我用 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
4

1 回答 1

1

我不确定这是否完全符合您的要求,但确实可以玩游戏。需要注意的一些事情:我改变了播放方法。使用 while 循环并获取并没有多大意义。相反,我抓住了参数并传递给play,同时保持猜测的数量。我缩进了表单,因为您没有嵌套提交或表单内的文本字段。我建议您在使用 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
于 2012-09-28T19:20:07.210 回答