1

I try to programm Snakes with ruby. The first problem I encountered was to get input with out pressing enter at the end all the time. Luckily I found a solution for that at How to get a single character without pressing enter?.

The problem I am stuck with now is, that I want to have the input from the user only open for a certain amount of time. In order to let the snake keep on going if no change in direction is demanded by the user.

The code I got looks like this:

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

It tried with an if command around the input but that wouldn't work. I also tried looking it up on stack overflow but it seems that no one asked that question before. The only thing I found was the the sleep() command but I seems like that can't help either.

Any help would be highly appreciated.

Tobias Wilfert
  • 919
  • 3
  • 14
  • 26

1 Answers1

0

Use Timeout.

For example, if you want to wait 2 seconds, you could do something like this:

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
Gerry
  • 10,337
  • 3
  • 31
  • 40