c# - 在不中断用户输入的情况下更新倒计时数
问题描述
所以我有一个控制台游戏应用程序,它生成一个 x 长度的随机字符串,用户必须在时间用完或丢失之前输入相同的随机字符串。时间只是一个 int,它保存在 Game 类中。这是我用来绘制模板的类:
class Template
{
public static void DrawGameplay() //draws gameplay screen , the main method used to print
{
Console.WriteLine("=====================BOMB DEFUSE========================");
if (Game.level < 10)
{
Console.WriteLine("====================== Level {0} =========================", Game.level);
if(Game.level < 6)
{
Body(16);
}
else
{
Body(13);
}
}
else
{
if (Game.level == 10) //10 special case
{
Console.WriteLine("====================== Level {0} ========================", Game.level);
Body(13);
}
else
{
Console.WriteLine("====================== Level {0} ========================", Game.level);
Body(11);
}
}
}
public static void TimeLine() //draws the time line in the middle , feeds drawgameplay
{
Console.WriteLine("");
Console.WriteLine("");
if (Game.time > 9)
{
Console.WriteLine("====================== Time: {0} ========================", Game.time);
}
else
{
Console.WriteLine("====================== Time: {0} =========================", Game.time);
}
Console.WriteLine("");
}
public static void Body(int spaces) //prints everything under the top (game title and lvl) , feeds drawgameplay
{
Console.WriteLine("");
Words.Spaces(spaces);
Game.PrintList();
TimeLine();
Words.Spaces(spaces);
}
}
然后我有这个播放器类:
class Player
{
public static List<char> inputList = new List<char>(); //the list of inputted chars that is used to compare to the defuse code
static char[] arrayChar;
static string typed;
public static void GetInputList() //populates list with letters person typed during time
{
typed = Console.ReadLine();
typed.TrimEnd(); //Gets rid of any extra spaces at the end
arrayChar = typed.ToArray();
inputList = arrayChar.ToList();
}
public static void Print() // prints inputed letters
{
foreach (var letter in inputList)
{
Console.Write(letter);
}
}
}
我该如何做到这一点,以便我可以在计时器倒计时时更新时间视觉而不干扰用户输入?现在我在随机生成的字符串和用户输入之间有时间线视觉。感谢您的关注。
解决方案
我只是出于好奇而尝试过。
这是一个如何运行应用程序并获取用户输入的密钥的小示例:
static void Main()
{
StringBuilder msg = new StringBuilder(10);
var endTime = DateTime.Now.AddSeconds(10);
while (endTime > DateTime.Now)
{
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey();
msg.Append(key.KeyChar);
}
Thread.Sleep(1);
Console.Write("\r Enter the message within {0} seconds; message = {1}", (endTime - DateTime.Now).Seconds, msg);
}
}
但请记住,这段代码有很多问题。快乐的场景会起作用,但有很多事情会导致问题(非标准/非预期的用户行为只是可能的问题之一)。
推荐阅读
- reactjs - 当我通过对象数组获取数据时,它会显示此错误,否则定义索引,类型错误:无法读取未定义的属性(读取“索引”)
- go - 使用 GO 解析 API 响应
- python - 测试模型'numpy.ndarray'对象时fastapi中的错误没有属性'read'
- nginx - Nginx `$remote_addr` 总是只返回 `127.0.0.1`
- r - 使用分隔符拆分字符串,除非在括号中,并保留分隔符
- javascript - Firebase Auth v9:Object(...) 不是函数
- javascript - 如何进行循环,返回字典对象 - 未定义 - jquery
- tensorflow - tf.random_normal_initializer 和 tf.keras.initializers.RandomNormal 的区别
- assembly - EMU 8086 在寄存器中存储错误的数组元素值
- c++ - Codelite 使用 libpqxx 连接示例和 g++ 在 macOS 上失败