【问题标题】:C# clickclickclick console game - correct button readingC# clickclickclick 控制台游戏 - 正确的按钮读取
【发布时间】:2017-02-09 11:54:10
【问题描述】:

我正在尝试使用 Visual Studio 在 c# 中为控制台创建一个简单的 clickclickclick 游戏。唯一还没有工作的是控制台如何计算键盘上 any 按钮的按下次数。现有代码的问题是即使释放按钮后该语句仍保持为真。

using System;
using System.Diagnostics;
public class clickclickclickgame
{
    public static void Main()
    {
        Stopwatch timer = new Stopwatch();
        int amountofpresses = 0;
        timer.Start();
        while (timer.ElapsedMilliseconds < 2000)
        {
            if (Console.KeyAvailable == true) // this is where my question is about.
            {
                timer.Restart();
                amountofpresses++;
            }
        timer.Stop();
        Console.WriteLine(amountofpresses);
    }
}

【问题讨论】:

  • 你必须Read密钥...
  • @Damion Gans 阅读我的回答,我会解释一些事情并为您提供解决方案。

标签: c# input console


【解决方案1】:

替换为:

        int i = 0;
        Stopwatch sw = new Stopwatch();
        sw.Start();
        while(true)
        {
            Console.ReadKey(true);//True makes it so you don't see the key in Console
            if(sw.ElapsedMilliseconds < 2000)
            {
                i++;
                sw.Restart();
            }
            else
            {
                sw.Stop();
                break;
            }
        }
        Console.WriteLine("Pressed amount: " + i);
        Console.ReadKey();

这就像你想要的那样工作,唯一的问题是它会在 ReadKey 女巫之后检查状态,这意味着如果我游戏结束,我必须再按一次以获得我的高分。顺便说一句,2000 毫秒是 2 秒,对于这个游戏来说相当高 :)
为了帮助您提高难度,请说将 2000 设为变量并在每次按键时减去 score * 2(只是一个示例)。这样就越来越难了。

【讨论】:

  • 我很抱歉回答迟了,但这确实有帮助!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
  • 2022-06-23
  • 1970-01-01
  • 2013-02-03
  • 1970-01-01
相关资源
最近更新 更多