0

我正在尝试通过制作俄罗斯方块控制台应用程序来学习 c#。我有一个游戏板类(代码中的“gb”)和一个块类(代码中的“bl”。)下面的代码是我迄今为止左右移动一个块的代码,但我不能包装我的在我接受用户输入的同时,围绕如何使块落下。

while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Escape)
        {
            switch (keyInfo.Key)
            {
                case ConsoleKey.LeftArrow:
                    currCol = bl.getCol();
                    if (currCol - 1 >= 0)
                    {
                        gb.removeBlock(bl.getCol(), bl.getRow());
                        bl.setCol(currCol - 1);
                        gb.putBlock(bl.getCol(), bl.getRow());
                        Console.Clear();
                        Console.WriteLine(gb.makeGrid());
                    }
                    break;

                case ConsoleKey.RightArrow:
                    currCol = bl.getCol();
                    if (currCol + 1 <= 9)
                    {
                        gb.removeBlock(bl.getCol(), bl.getRow());
                        bl.setCol(currCol + 1);
                        gb.putBlock(bl.getCol(), bl.getRow());
                        Console.Clear();
                        Console.WriteLine(gb.makeGrid());
                    }
                    break;
            }
        }

我假设 Timer 可能是这样做的方法,但我不知道如何将我的实例传递给 ElapsedEventHandler 的 OnTimedEvent 函数

public static void Main()
 {
     System.Timers.Timer aTimer = new System.Timers.Timer();
     aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
     // Set the Interval to 5 seconds.
     aTimer.Interval=5000;
     aTimer.Enabled=true;

     Console.WriteLine("Press \'q\' to quit the sample.");
     while(Console.Read()!='q');
 }

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

计时器是要走的路,还是我应该使用其他东西?如果计时器是我应该使用的,我应该从哪里开始学习如何使用它们?

谢谢!

4

3 回答 3

0

嗯,这似乎是一个尝试在 UI 线程上做不止一件事的问题。计时器只是解决方案的一种可能性。如果您发现计时器不够稳健,请根据您的需要查看或者每个计时器具有不同级别的控制BackgroundWorkerTaskThread

这里有一些参考BackgroundWorkerThreadTask-Parallel-Library只是为了让你了解如何使用这三个想法。

好的,现在解释一下为什么您的代码没有按预期工作。现在你要求从控制台输入中读取一个键。这将阻止控制台的所有执行,直到它读取一个密钥。看一下这个来解释为什么会发生这种情况,ReadKey()

但是,还有其他方法可以做到这一点,而无需ReadKey()查看此网站以设置低级键盘挂钩Low-Level Key Hook。此方法允许您在不阻塞控制台的情况下读取密钥。但是,这并不意味着它会阻止密钥进入控制台。所以在设计钩子时请记住这一点。我希望这有助于了解正在发生的事情。

另外只是为了获取更多信息,请查看此Console.ReadKey 取消,它将为您提供有关修改ReadKey().

因此,以防万一有关低级键盘挂钩的网站被删除,这是那里显示的代码:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

public static void Main()
{
    _hookID = SetHook(_proc);
    Application.Run();
    UnhookWindowsHookEx(_hookID);
}

private static IntPtr SetHook(LowLevelKeyboardProc proc)
{
    using (Process curProcess = Process.GetCurrentProcess())
    using (ProcessModule curModule = curProcess.MainModule)
    {
        return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
            GetModuleHandle(curModule.ModuleName), 0);
    }
}

private delegate IntPtr LowLevelKeyboardProc(
    int nCode, IntPtr wParam, IntPtr lParam);

private static IntPtr HookCallback(
    int nCode, IntPtr wParam, IntPtr lParam)
{
    if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
    {
        int vkCode = Marshal.ReadInt32(lParam);
        Console.WriteLine((Keys)vkCode);
    }
    return CallNextHookEx(_hookID, nCode, wParam, lParam);
}

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
    LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
    IntPtr wParam, IntPtr lParam);

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
}
于 2013-05-11T17:16:55.283 回答
0

试试这个简单的例子,看看当你点击左箭头和右箭头时会发生什么,然后是逃生:

class Program
{

    static void Main(string[] args)
    {
        const int delay = 100;
        DateTime nextMove = DateTime.Now.AddMilliseconds(delay);
        bool quit = false;
        bool gameOver = false;
        while (!quit && !gameOver)
        {
            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey(true); // read key without displaying it
                switch (key.Key)
                {
                    case ConsoleKey.LeftArrow:
                        Console.Write("L");
                        break;

                    case ConsoleKey.RightArrow:
                        Console.Write("R");
                        break;

                    case ConsoleKey.Escape:
                        quit = true;
                        break;
                }
            }

            if (!quit && !gameOver && DateTime.Now > nextMove)
            {
                // ... move the pieces ...
                Console.Write(".");
                nextMove = DateTime.Now.AddMilliseconds(delay);
            }

            System.Threading.Thread.Sleep(50);
        }

    }

}
于 2013-05-11T20:47:48.170 回答
0

似乎最简单的方法是计时器(在更复杂的情况下,您可以使用不同的线程)将参数传递给 OnTimedEvent 函数,您有不同的解决方案。

1-您可以在您的班级中使用计时器,并且 OnTimedEvent 是您班级的一个函数,因此您可以轻松地使用您的班级字段。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            GameManager gameManager = new GameManager();
            gameManager.StartGame();
        }


        public class GameManager
        {
            System.Timers.Timer aTimer;
            int Parameter
            {
                get;
                set;
            }
            public GameManager()
            {

            }
            public void StartGame()
            {
               aTimer = new System.Timers.Timer();
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
                // Set the Interval to 5 seconds.
                aTimer.Interval = 1000;
                aTimer.Enabled = true;

                Console.WriteLine("Press \'q\' to quit the sample.");
                Parameter = 200;
                while (Console.Read() != 'q') 
                {
                    Parameter =+ 10;
                }
            }
            private void OnTimedEvent(object source, ElapsedEventArgs e)
            {
                Parameter++;
                Console.WriteLine("Hello World!" + Parameter.ToString());
            }
        }
    }
}

2-使用委托

public static void Main()
        {
            System.Timers.Timer aTimer = new System.Timers.Timer();

            aTimer.Elapsed += delegate(object source, ElapsedEventArgs e) {
                OnTimedEvent(source, e, "Say Hello");
            };
            // Set the Interval to 5 seconds.
            aTimer.Interval = 1000;
            aTimer.Enabled = true;

            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }

        // Specify what you want to happen when the Elapsed event is raised.
        private static void OnTimedEvent(object source, ElapsedEventArgs e, string parameter)
        {
            Console.WriteLine("parameter");
        }

3-您也可以使用静态全局变量

于 2013-05-11T17:44:39.047 回答