这个循环有什么问题?

时间:2011-07-13 15:31:32

标签: ruby-on-rails ruby loops

    class GameController < ApplicationController

      def index
        @games = Game.all
        respond_to do |format|
          format.html 
        end
      end

      def start_game
        session[:round] ||= 1
        session[:points] ||= 0
        @round = session[:round]
        @points = session[:points] 
      end

      def next_round
        session[:round] += 1
        session[:points] += 1200
                    @round = session[:round]
                @points = session[:points]
      end

      def generate_round
        numbers = Array.new(6){rand(9)}
        @addition = []
        @display = numbers
        numbers.inject do |s, i|
            @addition << s + i
            @addition.last
        end
      end

      def new
        if @round == nil
            start_game
            generate_round
        else
            generate_round
        end

        if session[:addition]
            if not session[:addition].index(params[:guess].to_i).nil?
                puts "Correct."
                next_round
            else
                puts 'Game over.'
            end
        end

        session[:addition] = @addition
        respond_to do |format|
          format.html 
        end
      end    

    end
嘿伙计们, 我试图将这个迷你游戏放在红宝石中,这取决于猜测数字。 在添加每个猜测点并且水平增加一之后。

然而,根据目前的代码,我在第2轮遇到困难。 很可能由于某些原因某些事情正在重置这些变量,但我似乎可以指出它是什么。

感谢任何帮助。

::编辑::

代码已更新。问题解决了! 感谢@ blackbird07,@ robertodecurnex和@ fl00r!

的帮助

3 个答案:

答案 0 :(得分:1)

控制器是无状态的,因此每次调用时都会重置所有变量。

您应该使用一些数据存储(数据库,文件系统)来存储您当前的状态。

另一个问题是所有这些代码都不应该属于控制器。

答案 1 :(得分:0)

由于您要保持会话的轮次,您应该使用会话值而不是实例变量,或者至少创建一个过滤器来为每个请求设置此变量。

使用过滤器:

before_filter :set_round

private

def set_round
  @round = session[:round]
end

新方法(行动)正在做以下事项:

if @round = 0 then

它将0分配给@round而非比较它。

尝试if @round == 0if @round.zero?

您还需要增加会话值,而不仅仅是@round变量。

记住:

=     #=> Assignation
==    #=> Equality, usually overwritten by the classes to return true base on the equality of the state/attributes of two objects.
===   #=> Equality, usually defined to compare the identity of two objects (to return true only if both objects are actually the same object).

答案 2 :(得分:0)

您不会在next_round操作中增加会话[:round]和会话[:points]的计数器。这样做,它应该工作。

session[:round] += 1
session[:points] += 1200
@round = session[:round]
@points = session[:points]
相关问题