簡體   English   中英

努力為我的C#CONSOLE打字游戲實現計時器

[英]Struggling to implement a timer to my C# CONSOLE Typing Game

我目前的打字游戲功能(下面提供的代碼)的目標是從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();
    }

    // Handles gameplay
    static void Play()
    {
        // Assigns the current word to any random word in
        // the words array
        string currentWord = words[rand.Next(0, 88)];
        // Print the current word separated by lines
        Console.WriteLine("********");
        Console.WriteLine(currentWord);
        Console.WriteLine("********");
        // While the answser is incorrect/empty
        while (!userInput.Equals("exit"))
        {
            // Reads user input
            userInput = Console.ReadLine();
            if (userInput.Equals(""))
            {
                Play();
            }
            // Checks if userInput is equal to current word
            if (!(userInput.Equals(currentWord)))
            {
                // If incorrect, display loss of life
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Incorrect!!!");
                Console.WriteLine("Lives: " + numLives);
                numLives--; // Take a life away
                Console.ResetColor();

            }
            if (numLives == -1)
            {
                outOfLives();
            }
            if (userInput.Equals(currentWord))
            {
                correctWords++;
                Play();
            }
        }
        if (userInput.Equals("exit"))
        {
            Environment.Exit(0);
        }

    }
    // Function for running out of lives
    private static void outOfLives()
    {
        Console.WriteLine("Game over! You typed " + correctWords + " words correctly!");
        Console.WriteLine("Type anything and press enter to retry, Press Escape to Quit!");

        var endGameKey = Console.ReadKey();

        if (endGameKey.Key == ConsoleKey.Escape)
        {
            Environment.Exit(0);
        }
        if (endGameKey.Key == ConsoleKey.Enter)
        {
            restartGame();
        }
        else
        {
            outOfLives();

        }

    }
    // Function for running out of time
    private static void outOfTime()
    {
        Console.WriteLine("Out of time! You typed " + correctWords + " words correctly!");
        Console.WriteLine("Type anything and press enter to retry, Press Escape to Quit!");

        var endGameKey = Console.ReadKey();

        if (endGameKey.Key == ConsoleKey.Escape)
        {
            Environment.Exit(0);
        }
        if (endGameKey.Key == ConsoleKey.Enter)
        {
            restartGame();
        }
        else
        {
            outOfTime();
        }

    }

    // Prompts user for input for difficulty along with game instructions
    static void StartMessage()
    {
        Console.WriteLine("Welcome to my Typing Practice App!");
        Console.WriteLine("Type the word displayed as fast as you can");

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("Difficulties are listed from hardest to easiest");
        Console.WriteLine();
        Console.WriteLine("Select a difficulty( 1 ,2 , or 3 ): ");
        Console.WriteLine();
        Console.ResetColor();

        Console.ForegroundColor = ConsoleColor.DarkRed;
        Console.WriteLine("-- Press ENTER --");
        Console.WriteLine("***  Satan Himself  ***");
        Console.WriteLine();
        Console.ResetColor();

        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("-- Type 1 --)");
        Console.WriteLine("***  Software Engineer  ***");
        Console.WriteLine();
        Console.ResetColor();

        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("-- Type 2 --)");
        Console.WriteLine("***  Social Media Fanatic  ***");
        Console.WriteLine();
        Console.ResetColor();

        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("-- Type 3 --)");
        Console.WriteLine("*** Filthy Peasant ***");
        Console.WriteLine();
        Console.ResetColor();

        string difficultyChoice = Console.ReadLine();
        switch (difficultyChoice)
        {
            case "1":
                numLives = 1;
                Console.WriteLine("You have 2 lives! Good luck!");
                timeLeft = 10;
                break;
            case "2":
                numLives = 3;
                Console.WriteLine("You have 4 lives! Good luck!");
                timeLeft = 20;
                break;
            case "3":
                numLives = 5;
                Console.WriteLine("You have 6 lives! Good luck!");
                timeLeft = 30;
                break;

            default:
                numLives = 0;
                Console.ForegroundColor = ConsoleColor.DarkRed;
                Console.WriteLine("Miss one and you're done!!!!!");
                Console.ResetColor();
                timeLeft = 10;
                break;
        }
    }
    public static void restartGame()
    {
        Console.Clear();
        //numLives = 5;
        numWords = words.Length;
        correctWords = 0;
        Start();
    }

    public static void SetTimer(Object o)
    {
        timeLeft--;
        Thread.Sleep(1000);
        Console.WriteLine(timeLeft);
        if (timeLeft == 0)
        {
            outOfTime();
        }

    }


    public static void Start()
    {
        // Display start message
        StartMessage();
        gameActive = true;
        t = new System.Threading.Timer(SetTimer, null, 0, 1250);
        // While user wants to play
        while (!userInput.Equals("exit"))
        {
            // While the game is active
            while (gameActive == true)
            {
                // Start the game
                Play();
            }
        }
        if (userInput.Equals("exit"))
        {
            Environment.Exit(0);
        }

    }
}

}

嘗試使用這個 協程應該可以解決您的問題,如果您可以使它正常工作。

您不需要編程計時器或線程即可擁有游戲計時器。 只需記錄游戲開始時的時間即可:

//During initialization
var 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();

作為對所出現問題的直接解決(計時器低於0),需要在不再需要計時器時停止計時器。 為此,請使用以下行:

t.Change(Timeout.Infinite, Timeout.Infinite);

您可以將此行添加到outOfLivesoutOfTime方法的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!");
    ...

編輯:對不起。 只需重新閱讀您的問題並意識到您已經嘗試過此行。 您是否把它放在正確的地方?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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