【问题标题】:Timer with questions in c#c#中带问题的计时器
【发布时间】:2017-04-10 04:25:25
【问题描述】:

我有一个单独的应用程序 在此尝试设置计时器,即问题显示时应启动计时器,并且在 10 秒内回答未给出时应启动下一个问题,我想这样做

我已经完成了 我首先设置了 3 个条件,他们应该输入要尝试多少个问题的数字,然后选择级别,然后选择运算符 .. 所以当所有问题都输入时,即

no of question : 2
level : 1
operator: +

然后计时器开始 10 秒,当 10 秒完成时显示问题 我想要第一个问题显示和计时器,然后当问题在 10 秒内没有回答时,下一个应该开始

这就是我的工作

class Program
{
    static void Main(string[] args)
    {
        Random rnd = new Random();
        int userans;
        int computerans;
        int numofquestions;
        int numofquestionsleft;
        int correctanswer = 0;



        Console.WriteLine("\t\t OPERATOR OF QUIZ \t\t");
        Console.WriteLine("\t\tOperator 1:Addition(+)\t\t");
        Console.WriteLine("\t\tOperator 2:Subtarction(-)\t\t");

        Console.WriteLine("\t\tLEVELS OF QUIZ\t\t");
        Console.WriteLine("\t\tLevel 1 (1-9)\t\t");
        Console.WriteLine("\t\tLevel 2 (10-99)\t\t");

        Console.WriteLine("\t\t-------------------\t\t");
        Console.WriteLine("\t\tYour quiz start now\t\t");
        Console.WriteLine("\t\t-------------------\t\t");
        Console.Write("How many questions do you want to attempt?   ");
        numofquestions = Convert.ToInt32(Console.ReadLine());

        Console.Write("Which  level that you want to play?   ");
        int level = Convert.ToInt32(Console.ReadLine());

        Console.Write("which operator do you want to play?");
        string opt = Console.ReadLine();
        //for (int a = 10; a >= 0; a--)
        //{
        //    Console.SetCursorPosition(0, 2);
        //    Console.Write("Generating Preview in {0} ", a);  // Override complete previous contents
        //    System.Threading.Thread.Sleep(1000);
        //}


        numofquestionsleft = numofquestions;

        while (numofquestionsleft > 0)
        {
            if (level == 1)
            {
                switch (opt)
                {
                    case "+":
                        {
                            int num1 = rnd.Next(1, 10);
                            int num2 = rnd.Next(1, 10);
                            Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");

                            computerans = num1 + num2;
                            userans = Convert.ToInt32(Console.ReadLine());
                            Console.WriteLine("The correct answer is\n" + computerans);
                            Console.WriteLine("Your answer is \n" + userans);
                            if (computerans == userans)
                            {

                                Console.WriteLine(" Congratulation your answer is correct!\n");
                                correctanswer++;
                            }
                            else
                            {
                                Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
                            }
                            numofquestionsleft--;
                            num1 = rnd.Next(1, 10);
                            num2 = rnd.Next(1, 10);
                            Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + "  question");
                            break;
                        }
                    case "-":
                        {
                            int num3 = rnd.Next(1, 10);
                            int num4 = rnd.Next(1, 10);
                            Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
                            computerans = num3 - num4;
                            userans = Convert.ToInt32(Console.ReadLine());
                            Console.WriteLine("The correct answer is\n" + computerans);
                            Console.WriteLine("Your answer is \n" + userans);
                            if (computerans == userans)
                            {

                                Console.WriteLine(" Congratulation your answer is correct!\n");
                                correctanswer++;
                            }
                            else
                            {
                                Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
                            }
                            numofquestionsleft--;
                            num3 = rnd.Next(1, 10);
                            num4 = rnd.Next(1, 10);
                            Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + "  question");
                            break;
                        }


                }
            }
            if (level == 2)
            {
                switch (opt)
                {
                    case "+":
                        {
                            int num1 = rnd.Next(10, 99);
                            int num2 = rnd.Next(10, 99);
                            Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
                            computerans = num1 + num2;
                            userans = Convert.ToInt32(Console.ReadLine());
                            Console.WriteLine("The correct answer is\n" + computerans);
                            Console.WriteLine("Your answer is \n" + userans);
                            if (computerans == userans)
                            {

                                Console.WriteLine(" Congratulation your answer is correct!\n");
                                correctanswer++;
                            }
                            else
                            {
                                Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
                            }
                            numofquestionsleft--;
                            num1 = rnd.Next(10, 99);
                            num2 = rnd.Next(10, 99);
                            Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + "  question");
                            break;
                        }
                    case "-":
                        {
                            int num3 = rnd.Next(10, 99);
                            int num4 = rnd.Next(10, 99);
                            Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
                            computerans = num3 - num4;
                            userans = Convert.ToInt32(Console.ReadLine());
                            Console.WriteLine("The correct answer is\n" + computerans);
                            Console.WriteLine("Your answer is \n" + userans);
                            if (computerans == userans)
                            {

                                Console.WriteLine(" Congratulation your answer is correct!\n");
                                correctanswer++;
                            }
                            else
                            {
                                Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
                            }
                            numofquestionsleft--;
                            num3 = rnd.Next(10, 99);
                            num4 = rnd.Next(10, 99);
                            Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + "  question");
                            break;
                        }


                }
            }


            //if(numofquestions>)
            for (int a = 10; a >= 0; a--)
            {
                Console.SetCursorPosition(0, 2);
                Console.Write("Generating Preview in {0} ", a);  // Override complete previous contents
                System.Threading.Thread.Sleep(1000);
            }




            Console.ReadKey();
        }
    }
}

}

【问题讨论】:

  • 我没有看到任何与计时器相关的代码...在这种形式的问题中,您只需询问“编辑我的答案以添加此新功能”
  • Thread.Sleep() 等待 10 秒是一种不好的做法,因为它会使整个程序无响应。尝试任何类型的多任务处理或只是检查经过的时间。
  • for 循环末尾的@L.B 是计时器代码
  • 那我该怎么办@devRicher
  • @Super 看看this 的问题,定时器是一个很好的实践。如果您不想要它们,我仍然可以告诉您检查经过的时间,就像演示的here 一样。尽管它是用 Java 编写的,但您可以想出一个类比。

标签: c# timer


【解决方案1】:

您的代码非常混乱。您可以通过一种方法获得所有内容。因此,创建计时器需要的其他方法,您无法访问对计时器很重要的任何变量。您需要开始制作自己的课程。这使您可以更好地控制程序的变量。您的代码很难将您引向正确的方向。你需要改变很多。

为了好玩,也为了一些经验,我创造了你正在做的事情。一个计算游戏,或测试,或者你想调用它。我将与您分享我的代码,希望您能从中学到一些东西。

程序.cs:

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

namespace CalculatingGame
{
    class Program
    {
        static void Main(string[] args)
        {
            // Add different difficulty options
            Dictionary<string, Difficulty> DifficultyOptions = new Dictionary<string, Difficulty>();
            DifficultyOptions.Add("easy", new EasyDifficulty());
            DifficultyOptions.Add("medium", new MediumDifficulty());
            DifficultyOptions.Add("hard", new HardDifficulty());

            // Add different game options
            Dictionary<string, GameType> GameOptions = new Dictionary<string, GameType>();
            GameOptions.Add("additive", new GameAdditive());
            GameOptions.Add("subtractive", new GameSubtractive());
            GameOptions.Add("randomize", new GameRandomize());

            // Default game settings at start up
            string GameDiff = "easy";
            string GameMode = "additive";

            Console.WriteLine("Welcome to Verkade's Calculating Game.");
            Console.WriteLine("By default game difficulty has been set to " + GameDiff);
            Console.WriteLine("Type in the following commands to change that:");

            // This will take out all possible options out of DifficultOptions variable, and display them
            foreach (KeyValuePair<string, Difficulty> kvp in DifficultyOptions)
            {
                Console.WriteLine("/difficulty " + kvp.Key);
            }

            Console.WriteLine("");

            Console.WriteLine("By default game mode has been set to " + GameMode);
            Console.WriteLine("Type in the following commands to change that:");

            // This will take out all possible options out of game options and display them
            foreach (KeyValuePair<string, GameType> GameTypes in GameOptions)
            {
                Console.WriteLine("/gamemode " + GameTypes.Key);
            }

            Console.WriteLine("");

            Console.WriteLine("When you're done setting up, type in /start to start the game,");
            Console.WriteLine("/stop to stop the game. /exit to stop entirely.");

            //This will keep the instance of the game once started
            Game CurrentGame = null;

            //this will keep the program alive. By typing /exit, it will turn into false, and stops the program.
            bool KeepProgramAlive = true;

            //This is a loop that keeps on listening to your input
            while (KeepProgramAlive)
            {
                // This will split up the users input, when a space is used.
                // This way the first cut will contain /start, /stop, /gamemode, etc. It will be stored as 'UserInput[0]'
                // In the second cut, which is 'UserInput[1]', things like 'easy', 'medium', 'hard', 'subtractive', etc will be stored
                string[] UserInput = Console.ReadLine().Split(' ');
                switch (UserInput[0])
                {
                    case "/exit":
                        {
                            KeepProgramAlive = false;
                            break;
                        }
                    case "/start":
                        {
                            if (DifficultyOptions.ContainsKey(GameDiff) && GameOptions.ContainsKey(GameMode))
                            {
                                Console.WriteLine("Game has been set up. When you're ready, press Enter so you'll get your first question");
                                CurrentGame = new Game(DifficultyOptions[GameDiff], GameOptions[GameMode]);
                            }
                            break;
                        }
                    case "/stop":
                        {
                            if (CurrentGame != null)
                            {
                                CurrentGame.Stop();
                                CurrentGame = null;
                                Console.WriteLine("Game has been stopped. You can not change settings and start again if you like.");
                            }
                            break;
                        }
                    case "/gamemode":
                        {
                            // checking the length to see there are 2 values. /gamemode is 1 of them. 'subtractive' is another one.
                            if (UserInput.Length >= 2)
                            {
                                // very important, because i am using a dictionary, i can check whether the gamemode exists or not
                                if (GameOptions.ContainsKey(UserInput[1]))
                                {
                                    Console.WriteLine("You have changed gamemode to " + UserInput[1]);
                                    GameMode = UserInput[1];
                                }
                                else
                                {
                                    Console.WriteLine("That gamemode does not exist");
                                }
                            }
                            break;
                        }
                    case "/difficulty":
                        {
                            if (UserInput.Length >= 2)
                            {
                                if (DifficultyOptions.ContainsKey(UserInput[1]))
                                {
                                    Console.WriteLine("You have changed the difficulty to " + UserInput[1]);
                                    GameDiff = UserInput[1];
                                }
                                else
                                {
                                    Console.WriteLine("That difficulty does not exist");
                                }
                            }
                            break;
                        }
                    default:
                        {
                            // checking if the game has started, and if so, Handler in the game-class will check your input
                            if (CurrentGame != null)
                            {
                                int NumberGiven;
                                Int32.TryParse(UserInput[0], out NumberGiven);
                                CurrentGame.Handler(NumberGiven);
                            }
                            break;
                        }
                }
            }
        }
    }
}

Operators.cs:

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

namespace CalculatingGame
{
    abstract class GameType
    {
        public int Answer;
        public Random Rnd = new Random();

        public abstract string MakeSum(Difficulty Diff);
    }

    class GameAdditive : GameType
    {
        public override string MakeSum(Difficulty Diff)
        {
            int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
            int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);

            Answer = num1 + num2;

            return num1 + " + " + num2;
        }
    }

    class GameSubtractive : GameType
    {
        public override string MakeSum(Difficulty Diff)
        {
            int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
            int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);

            Answer = num1 - num2;

            return num1 + " - " + num2;
        }
    }

    class GameRandomize : GameType
    {
        public override string MakeSum(Difficulty Diff)
        {
            int mode = Rnd.Next(0, 2);

            if (mode == 0)
            {
                int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
                int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
                Answer = num1 + num2;

                return num1 + " + " + num2;
            }
            else
            {
                int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
                int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
                Answer = num1 - num2;

                return num1 + " - " + num2;
            }
        }
    }
}

Game.cs:

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

namespace CalculatingGame
{
    class Game
    {
        Difficulty Game_Diff;
        GameType Game_Type;

        int TicksRemaining = 0;

        int TotalAnswers = 0;
        int CorrectAnswers = 0;
        int WrongAnswers = 0;

        Timer TimerCountdown;

        public Game(Difficulty GDiff, GameType GType)
        {
            Game_Diff = GDiff;
            Game_Type = GType;

            TimerCountdown = new Timer(100);
            TimerCountdown.Elapsed += TimerCD;
            TimerCountdown.AutoReset = true;
        }

        public void Handler(int Answer)
        {
            if (TicksRemaining > 0)
            {
                if (Answer == Game_Type.Answer)
                {
                    CorrectAnswers++;
                    Console.WriteLine("Good job. You got the correct answer.");
                }
                else
                {
                    WrongAnswers++;
                    Console.WriteLine("Wrong answer. The answer was " + Game_Type.Answer + ".");
                }
                TotalAnswers++;

                Console.WriteLine("Current score: " + CorrectAnswers + " correct answers out of " + TotalAnswers);

                TicksRemaining = 0;
                Console.WriteLine("Press Enter to get your new sum.");
                TimerCountdown.Stop();
            }
            else
            {
                string SumText = Game_Type.MakeSum(Game_Diff);
                Console.WriteLine("What is the solution to the sum " + SumText);
                TicksRemaining = Game_Diff.Time;
                TimerCountdown.Start();
            }
        }

        public void TimerCD(Object source, ElapsedEventArgs e)
        {
            if(TicksRemaining > 0)
            {
                TicksRemaining--;

                if ((TicksRemaining % 10) == 0)
                {
                    Console.Write(Math.Floor((decimal)(TicksRemaining / 10)) + "...");
                }

                if (TicksRemaining == 0)
                {
                    WrongAnswers++;
                    Console.WriteLine("\r\nTime is up. The answer was " + Game_Type.Answer);
                    Console.WriteLine("Press Enter to get your new sum.");
                    TimerCountdown.Stop();
                }
            }
        }

        public void Stop()
        {
            TimerCountdown.Stop();
        }
    }
}

难度.cs:

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

namespace CalculatingGame
{
    // nice thing about abstract classes and child classes are that you can store a 'EasyDifficulty' object under variable-type 'Difficulty'
    // this allows me to create a dictionary, with 'Difficulty' type as value, and yet put all the different child classes in there
    // another thing you can do, and you can see it under 'Operators.cs' file, is that you can have a method, with the same name in every
    // child class, and yet they perform different things.
    abstract class Difficulty
    {
        public int MinNumber = 1;
        public int MaxNumber = 1;
        // Time in ticks. 1 tick = 100ms. Reason why I made it so is because maybe you want to give the player 7.5 seconds to do the sum
        public int Time = 100;
    }

    class EasyDifficulty : Difficulty
    {
        public EasyDifficulty()
        {
            MinNumber = 1;
            MaxNumber = 9;
            Time = 100;
        }
    }

    class MediumDifficulty : Difficulty
    {
        public MediumDifficulty()
        {
            MinNumber = 1;
            MaxNumber = 99;
            Time = 75;
        }
    }

    class HardDifficulty : Difficulty
    {
        public HardDifficulty()
        {
            MinNumber = 1;
            MaxNumber = 999;
            Time = 50;
        }
    }
}

【讨论】:

【解决方案2】:

您的延迟只有 1 秒。通过以下方式将延迟增加到 10 秒:

for (int a = 10; a >= 0; a--)
            {
                Console.SetCursorPosition(0, 2);
                Console.Write("Generating Preview in {0} ", a);  // Override complete previous contents
                System.Threading.Thread.Sleep(10000);
            }

【讨论】:

  • 是的,但是我如何在问题开始时显示计时器以及在 10 秒内未回答问题时如何显示下一个问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多