[英]c# console app press spacebar without displaying it on screen
我想使用 c# 控制台应用程序制作一个真正简单的 cookie 点击器。 这个想法是,每次您单击空格键时,您都会得到一个 cookie(无穷无尽),但我的代码不起作用,有谁知道我做错了什么或忘记了什么?
这是我的代码:
static void Main(string[] args)
{
int cookie = 0;
Console.WriteLine("Coockie Clicker, druk op spatie om te beginnen...");
Console.ReadKey();
Console.Clear();
while (cookie <1000000)
{
Console.ReadLine();
if(Console.ReadLine() == " ")
{
cookie++;
Console.WriteLine("Cookies ="+cookie);
}
else
{
}
Console.ReadKey();
}
}
我期望工作什么?=每次我按空格键( if(Console.ReadLine() == " ") <--- 那里的那一点应该将 +1 添加到 int cookie 并执行此操作直到 1.000.000 但那里显然有些东西不起作用
希望这是您正在寻找的。
static void Main(string[] args)
{
int cookie = 0;
Console.WriteLine("Coockie Clicker, druk op spatie om te beginnen...");
Console.Clear();
while (cookie < 1000000)
{
if (Console.ReadKey(true).Key == ConsoleKey.Spacebar)
{
cookie++;
Console.Clear();
Console.WriteLine("Cookies =" + cookie);
}
}
}
如果您只是想为每个空格键单击提供一个 cookie,那么您可以使用Console.ReadKey
。 有一个过载需要 boolean 指示您是否要“拦截”按键。 当您拦截按键时,不会向用户显示该值。
另一方面, Console.ReadLine
仅在您点击返回时返回一个值。 无论如何,该值都会显示给用户。
这是一个更新的代码示例:
static void Main(string[] args)
{
int cookie = 0;
Console.WriteLine("Coockie Clicker, druk op spatie om te beginnen...");
Console.ReadKey();
Console.Clear();
while (cookie <1000000)
{
var ch = Console.ReadKey(true);
if(ch.KeyChar == ' ')
{
cookie++;
Console.WriteLine("Cookies ="+cookie);
}
}
}
首先,如果你想让它无穷无尽,你应该使用类似的东西
while (true)
代替
while (cookie <1000000)
但请注意,虽然我怀疑你会得到比 int.MaxValue 更多的 cookies 但从技术上讲它可能会溢出。
其次Console.ReadLine()
读取一行,所以最后需要一个 Enter 键,你应该只使用Console.ReadKey()
第三个是你有一个额外的读取行:
Console.ReadLine();
if(Console.ReadLine() == " ")
所以它希望您输入一行(您不使用它,只是等待用户最终单击输入)然后您读取另一行并将其与" "
进行比较
if(Console.ReadKey().Key == ConsoleKey.Spacebar)
{
//generate your cookie here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.