We next emphasize one of the uses for the ReadKey method. With this method, you can create fully interactive console programs in the C# language.
using System;
class Program
{
static char[,] _board = new char[5, 5];
static void Main()
{
int positionX = 0;
int positionY = 0;
while (true)
{
// At current position, write special char and update board.
_board[positionX, positionY] = '@';
for (int i = 0; i < 5; i++)
{
for (int z = 0; z < 5; z++)
{
Console.Write(_board[z, i] == char.MinValue ?
"." : _board[z, i]);
}
Console.WriteLine();
// End line.
}
// Handle directional keys with ReadKey.
Console.Write(
">");
var info = Console.ReadKey();
Console.WriteLine();
switch (info.KeyChar)
{
case 'w':
positionY--;
break;
case 'a':
positionX--;
break;
case 's':
positionY++;
break;
case 'd':
positionX++;
break;
}
}
}
}
@....
.....
.....
.....
.....
>d
@@...
.....
.....
.....
.....
>d
@@@..
.....
.....
.....
.....
>s
@@@..
..@..
.....
.....
.....
>s
@@@..
..@..
..@..
.....
.....
>s
@@@..
..@..
..@..
..@..
.....
>d
@@@..
..@..
..@..
..@@.
.....
>d
@@@..
..@..
..@..
..@@@
.....
>w
@@@..
..@..
..@.@
..@@@
.....
>