努力为我的 C# CONSOLE 打字游戏实现计时器

我当前的打字游戏功能(下面提供的代码)的目标是从 10(困难)、20(中等)或 30(简单)开始倒计时,这取决于游戏开始后用户的难度选择。一旦倒计时达到零或用户用完生命,游戏就结束了(这会停止倒计时)。游戏正常启动,显示用户输入的第一个单词,并从 10 开始倒计时。我目前的问题是我无法弄清楚如何停止计时器从 0 倒计时。我尝试使用 t .Change(Timeout.Infinite , Timeout.Infinite) 并检查 timeLeft == 0 时没有占上风。我真的觉得我想得太多了(或想得不够),非常感谢一些帮助或朝着正确方向轻推!


我的代码如下:


    class Program

{

    // List of words to be typed

    public static string[] words = { "some", "side", "add", "another", "would", "book" ,"water", "came" ,"your" ,"big","both", "from", "learn", "been", "me" ,"school" ,"land", "took", "place",

            "try", "line", "tell", "earth", "can", "do","children", "without", "my", "must", "take", "follow", "year", "is", "being", "different", "miss", "could", "on", "he", "open", "night", "were",

            "line","said", "around", "an", "plant", "know", "set","been", "life","young","of", "face", "we", "hand", "while", "is", "white", "call", "live","may", "study","after" ,"down", "him", "now", "different",

            "could", "over", "work","all", "mean","begin","go","fall", "really", "oil", "before","into","one","name","has","a", "well", "got","something","turn" };

    // Keeps track of words array

    public static int numWords = 88;

    public static int correctWords = 0;

    // Initialize our random number generator

    public static Random rand = new Random();

    // Handles user input

    public static string userInput = "";

    public static string endGameChoice = "";

    // Handles gamestate variables

    public static bool gameActive = false;

    public static int numLives = 0;

    public static int timeLeft;

    public static System.Threading.Timer t;



    // Entry Point

    static void Main(string[] args)

    {

        // Start the game

        Start();

    }


 

慕盖茨4494581
浏览 205回答 4
4回答

慕丝7291255

您不需要程序计时器或线程来拥有游戏计时器。只记录游戏开始时的时间://During initializationvar startTime = DateTime.Now;并且任何时候您希望显示或使用计时器,计算它:var timerValue = DateTime.Now - startTime;Console.WriteLine("Time elapsed: {0} seconds", timerValue.Seconds);

慕容森

尝试使用这个。如果你能让它工作,协程应该可以解决你的问题。

阿波罗的战车

您可以通过这种方式使用 Timer。它对你有用var timer2 = new Timer();timer2.Elapsed += (o, e) =>{    Console.WriteLine("Time Elapsed {0}", e.SignalTime);    timer2.Stop();};timer2.Interval = 1000;timer2.Start();

Helenr

作为对出现的问题的直接修复(定时器低于 0),您需要在不再需要时停止定时器。为此,请使用以下行:t.Change(Timeout.Infinite, Timeout.Infinite);您可以将此行添加到您的outOfLives和outOfTime方法的开头:private static void outOfLives(){    t.Change(Timeout.Infinite, Timeout.Infinite);    Console.WriteLine("Game over! You typed " + correctWords + " words correctly!");    ...和...private static void outOfTime(){    t.Change(Timeout.Infinite, Timeout.Infinite);    Console.WriteLine("Out of time! You typed " + correctWords + " words correctly!");    ...编辑:对不起。只需重新阅读您的问题并意识到您已经尝试过这条线。你把它放在正确的地方了吗?
打开App,查看更多内容
随时随地看视频慕课网APP