So, I was bored and decided to write an ASCII game in C# for the fun of it, and I have drawing, clearing, updating, etc.. Although, I'm stuck at one part, input. I want to get input every frame, without the player pressing enter, So far the player has to press enter, but it doesn't do anything.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
namespace ASCII
{
public static class Game
{
static string map = File.ReadAllText("Map.txt");
public static void Draw()
{
Console.CursorVisible = false;
Console.WriteLine(map);
}
public static void Update()
{
Clear();
Input();
}
public static void Input()
{
string input = Console.ReadLine();
switch (input)
{
case "a":
//Do something
break;
}
}
public static void Clear()
{
Console.Clear();
Draw();
}
}
}
As you can see in the Input()
void, it gets input every frame, but I only want to get it once, the do a move method or something that I will implement later.
BTW Map.txt displays this:
###################
# #
# @ # #
######## #
# #
# #
# #
# #
# #
# #
# #
###################
Console.ReadLine
will wait for the enter-key to continue making the application kind of modal. What you want instead is handle keyboard-events on the concole. So you could use ReadKey
instead:
var input = Console.ReadKey(true);
switch (input.Key)
{
case ConsoleKey.A:
//Do something
break;
}
To hold on moving you may implement this in a loop. The key here is to remember your current action until the next key-event passes
int action = 0;
while(!exit)
{
// handle the action
myPlayer.X += action; // move player left or right depending on the previously pressed key (A or D)
if(!Console.KeyAvailable) continue;
var input = Console.ReadKey(true);
switch (input.Key)
{
case ConsoleKey.A:
action = -1
break;
case ConsoleKey.D:
action = 1
break;
}
}
I'm not sure I understood the question right, but if I did, you can use Console.KeyAvailable
and Console.ReadKey
to check if a key is available before reading it.
So something like:
public static void Input()
{
if(!Console.KeyAvailable) return;
ConsoleKeyInfo key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.A:
//Do something
break;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.