输入仅在Ruby中打开一段时间

时间:2017-05-28 09:53:04

标签: ruby

我尝试用红宝石编程Snakes。 我遇到的第一个问题是输入而不是一直按下输入。幸运的是,我在How to get a single character without pressing enter?找到了解决方案。

我现在遇到的问题是,我希望用户的输入只打开一段时间。如果用户不要求方向改变,为了让蛇继续前进。

我得到的代码如下:

system("stty raw -echo")
str = STDIN.getc
ensure
system("stty -raw echo")
end
p str.chr 

case str 
 when "z"
  velocityX = -1
  velocityY = 0
 when "q"
  velocityY = -1
  velocityX = 0
 when "d"
  velocityY  = 1
  velocityX = 0
 when "s"
  velocityX = 1
  velocityY = 0
 when "e"
  puts "Bye"
  on = false
 else
  puts "Not found"
end

x += velocityX
y += velocityY

尝试使用输入的if命令,但这不起作用。我也试过查看堆栈溢出,但似乎之前没有人问过这个问题。我发现的唯一的事情是sleep()命令,但我似乎也无能为力。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

使用Timeout

例如,如果您想等待2秒钟,您可以执行以下操作:

require 'timeout'

begin
  system("stty raw -echo")
  str = Timeout::timeout(2) { STDIN.getc }
rescue Timeout::Error
  str = "no input"
ensure
  system("stty -raw echo")
end