簡體   English   中英

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.KeyAvailableConsole.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM