0

您好,我一直在向 Chris Pine 学习有关 ruby​​ 的学习编程书籍,自从完成后我一直在尝试编写一个文本冒险游戏,从按位文章“adventures in ruby​​”中获取一些想法。

对于战斗,我添加了一个 while 语句,当玩家的生命值或敌人的生命值达到 0 时该语句会中断。有一个计时器每 2 秒运行一次伤害数学运算。我想要某种方式让玩家在战斗期间以不中断计时器的方式输入命令,但是当要求代码调用gets.chomp时,如果玩家花费超过2秒,计时器崩溃。这是去掉了大部分无用位的代码:-

while true
    start_time = Time.now
    hp[1] = hp[1] - (enemy.stats[0] - rand(enemy.stats[0]))
    enemy.hp = enemy.hp.to_i - (mystats[0] - rand(mystats[0]))
    if hp[1] <= 0 or enemy.hp <= 0
        break
    end
    puts " "
    puts "(hp: #{hp[1]} mp: #{mp[1]} st: #{st[1]})"
    #enemy conditions go here
    puts "Enemy condition: " + condition
    puts " "
    total_time = Time.now - start_time 
    sleep(2.0 - total_time)
end

我可以做到的方法是每 2 秒再刷新一次gets.chomp,但我想不出这样做。

任何帮助我都会非常感激。

4

1 回答 1

0

You don't say what version of Ruby you're running. Also, your sample code doesn't demonstrate your use of gets, which is important if you're having a problem with it. Nor does it show any sample of how you're trying to loop in the background as it waits for the user.

Based on your title and the use of Time, this is the minimum code I could think of that would start to test the problem:

time = Time.now
asdf = STDIN.gets
p Time.now - time

In Ruby 1.8.7:

test.rb(main):004:0> greg-mbp-wireless:Desktop greg$ rvm 1.8.7; rvm list

rvm rubies

=> ruby-1.8.7-p302 [ x86_64 ]
   ruby-1.9.2-head [ x86_64 ]
   ruby-1.9.2-p0 [ x86_64 ]

greg-mbp-wireless:Desktop greg$ irb -f test.rb
test.rb(main):001:0> time = Time.now
=> Sun Nov 21 13:24:58 -0700 2010
test.rb(main):002:0> asdf = STDIN.gets

=> "\n"
test.rb(main):003:0> p Time.now - time
3.802123
=> nil

In Ruby 1.9.2:

test.rb(main):004:0> greg-mbp-wireless:Desktop greg$ rvm 1.9.2; rvm list

rvm rubies

   ruby-1.8.7-p302 [ x86_64 ]
   ruby-1.9.2-head [ x86_64 ]
=> ruby-1.9.2-p0 [ x86_64 ]

greg-mbp-wireless:Desktop greg$ irb -f test.rb
test.rb(main):001:0> time = Time.now
=> 2010-11-21 13:25:37 -0700
test.rb(main):002:0> asdf = STDIN.gets

=> "\n"
test.rb(main):003:0> p Time.now - time
3.578869
=> 3.578869

In each test I paused a couple seconds which is reflected in the Time calculations.

Besides p returning a value in 1.9.2 and nil in 1.8.7, I don't see any real difference. Show some sample of how you're looping in the background to do your calculations and I can expand the test code.

于 2010-11-21T20:02:00.797 回答