3

I want to give myself a small fun challenge and code a game of Snake (nokia style) in C#, to make things even harder, I want to make it text based and use the terminal only.

My first stumble block is that in order to make the game playable, I need to be able to use the arrow keys to move the snake head around, thus having the rest of the snake follow along.

I've seen it done before, but I don't remember where, so can anyone help me?

Note that this is a specific programming problem, in that I'm not sure what classes to use or how to use them.

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
  • have you seen this article about keystrokes and mouse events? http://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C – apollosoftware.org Sep 06 '13 at 16:27
  • 1
    See [C# arrow key input for a console app](http://stackoverflow.com/questions/4351258/c-sharp-arrow-key-input-for-a-console-app) – p.s.w.g Sep 06 '13 at 16:28
  • @DavidStratton yes I'm sure – Electric Coffee Sep 06 '13 at 16:28
  • Perhaps you can run the 'UI-updating' code in a seperate thread and use ReadKey in the main thread? – Silvermind Sep 06 '13 at 16:31
  • @Silvermind - simple `while` loop is enough, `Thread.Sleep(10)` to get 0% cpu usage... Multiple threads will definitely make project more fun, but may be too hard for one just starting (or coming from other language/platform where "console" called "terminal") – Alexei Levenkov Sep 06 '13 at 16:40
  • @AlexeiLevenkov I've been using C# for the past 2 years, but I moved away from console applications pretty quickly so I'm not familiar with all the console related classes – Electric Coffee Sep 06 '13 at 16:45
  • 1
    @Alexei Levenkov, but how would you update the screen with a blocking readkey? The snake must go on :) – Silvermind Sep 06 '13 at 17:07
  • 2
    @Silvermind By using standard game loop - `while(true){if (KeyAvaialble) ReadKey; UpdateState; DrawScreen;Sleep }`. – Alexei Levenkov Sep 06 '13 at 17:57
  • @AlexeiLevenkov, I Learn something new every day, cool. – Silvermind Sep 06 '13 at 18:25

1 Answers1

6

You can handle arrow input in console using ReadKey() method.

var key = Console.ReadKey().Key;
if (key == ConsoleKey.DownArrow)
   Console.WriteLine("Down arrow pressed");

Arrows keys have codes ConsoleKey.UpArrow, ConsoleKey.DownArrow, ConsoleKey.LeftArrow and ConsoleKey.RightArrow.

hmnzr
  • 1,390
  • 1
  • 15
  • 24