[英]How do I ignore every input after the first few characters in the console in C#?
[英]C# - Console How to get input every frame
因此,我很无聊,因此决定以C#编写一个ASCII游戏,并且我要进行绘图,清除,更新等工作。尽管我只停留在输入的一部分。 我想在每一帧都获得输入,而无需玩家按Enter键,到目前为止,玩家必须按Enter键,但是它什么也没做。
这是我的代码:
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();
}
}
}
正如您在Input()
void中看到的那样,它在每一帧都获取输入,但是我只想获取一次,执行move方法或稍后将实现的操作。
BTW Map.txt显示如下:
###################
# #
# @ # #
######## #
# #
# #
# #
# #
# #
# #
# #
###################
Console.ReadLine
将等待enter键继续使应用程序变为模态。 相反,您想要的是在Condel上处理键盘事件。 因此,您可以改用ReadKey
:
var input = Console.ReadKey(true);
switch (input.Key)
{
case ConsoleKey.A:
//Do something
break;
}
要继续前进,您可以循环执行此操作。 关键是要记住您当前的操作,直到下一个关键事件过去为止
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;
}
}
我不确定我是否理解正确的问题,但是如果知道,可以在读取之前使用Console.KeyAvailable
和Console.ReadKey
检查密钥是否可用。
所以像这样:
public static void Input()
{
if(!Console.KeyAvailable) return;
ConsoleKeyInfo key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.A:
//Do something
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.