Terminal-based snake game: input thread manipulates output

Posted by enlightened on Stack Overflow See other posts from Stack Overflow or by enlightened
Published on 2012-07-03T15:12:23Z Indexed on 2012/07/03 15:15 UTC
Read the original article Hit count: 222

Filed under:
|
|

I'm writing a snake game for the terminal, i.e. output via print.

The following works just fine:

while status[snake_monad] do
  print to_string draw canvas, compose_all([
    frame,
    specs,
    snake_to_hash(snake[snake_monad])
  ])

  turn! snake_monad, get_dir
  move! snake_monad, specs

  sleep 0.25
end

But I don't want the turn!ing to block, of course. So I put it into a new Thread and let it loop:

Thread.new do
  loop do
    turn! snake_monad, get_dir
  end
end

while status[snake_monad] do
  ...
  # no turn! here
  ...
end

Which also works logically (the snake is turning), but the output is somehow interspersed with newlines. As soon as I kill the input thread (^C) it looks normal again.

So why and how does the thread have any effect on my output? And how do I work around this issue?
(I don't know much about threads, even less about them in ruby. Input and output concurrently on the same terminal make the matter worse, I guess...)



Also (not really important): Wanting my program as pure as possible, would it be somewhat easily possible to get the input non-blockingly while passing everything around?

Thank you!

© Stack Overflow or respective owner

Related posts about ruby

Related posts about multithreading