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.