【问题标题】:How do I avoid infinite recursion when building an event loop in Ruby?在 Ruby 中构建事件循环时如何避免无限递归?
【发布时间】:2015-12-20 06:19:02
【问题描述】:

我想在 Ruby 中实现一个游戏循环,但我当前的实现收到“堆栈级别太深”(SystemStackError)。

这是我在类似俄罗斯方块的落块游戏中取得的进展:

# falling block game
class Tetris
  class EndGame < StandardError; end

  def start
    @canvas = Canvas.new
    @canvas.banner = "New game"
    @canvas.draw
    update
  end

  def update
    step
    update
  rescue EndGame
    puts "Game over!"
  end

  def step
    puts "Take one step..."
    # TODO: do stuff here
  end

  # draws our game board
  class Canvas
    SIZE = 10

    attr_accessor :banner, :board

    def initialize
      @board = SIZE.times.map { Array.new(SIZE) }
    end

    def update(point, marker)
      x, y = point
      @board[x, y] = marker
    end

    alias_method :draw, :to_s
    def draw
      [banner, separator, body, separator].join("\n")
    end

    private

    def separator
      "=" * SIZE
    end

    def body
      @board.map do |row|
        row.map { |e| e || " " }.join
      end.join("\n")
    end
  end
end

game = Tetris.new
game.start

产生这个错误:

Take one step...
Take one step...
Take one step...
Take one step...
Take one step...
Take one step...
Take one step...
Take one step...
Take one step...
Take one step...
gameloop.rb:20:in `puts': stack level too deep (SystemStackError)
    from gameloop.rb:20:in `puts'
    from gameloop.rb:20:in `step'
    from gameloop.rb:13:in `update'
    from gameloop.rb:14:in `update'
    from gameloop.rb:14:in `update'
    from gameloop.rb:14:in `update'
    from gameloop.rb:14:in `update'
    from gameloop.rb:14:in `update'
     ... 10067 levels...
    from gameloop.rb:14:in `update'
    from gameloop.rb:14:in `update'
    from gameloop.rb:9:in `start'
    from gameloop.rb:59:in `<main>'

更新

Ruby 默认不启用尾调用优化,但可以在 Ruby VM 中启用。

RubyVM::InstructionSequence.compile_option = {
  tailcall_optimization: true,
  trace_instruction: false
}

【问题讨论】:

  • 你不能用 while true 循环来实现吗?
  • 添加一个正式的答案,我会接受它,因为它非常有效。
  • 这个问题很好地证明了尾递归是一种考虑循环的自然方式。 (做点什么,然后从头开始。)很遗憾有这么多语言设计者如此反对正确的尾递归和正确的尾调用。

标签: ruby loops runtime-error


【解决方案1】:

使用while true ... 循环而不是递归。您还可以添加简短的sleep 以避免不必要的更新。

【讨论】:

    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 2012-10-26
    • 2020-11-10
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    相关资源
    最近更新 更多