-2

I have a cosole appliction in this try to set timer that is when question display then timer should be start and when in 10 seconds answer not give then should start next question i want to do this

i am done with I set 3 conditions first they should type number that how many question want to attemppt then select level then select operator .. so when all question typed i.e.

no of question : 2
level : 1
operator: +

then timer start of 10 seconds and when 10 seconds complete then question is display where as i want first question display and timer then when question not answered with in 10 seconds then next should start

this is what i do

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();
        }
    }
}

}

Super
  • 23
  • 1
  • 8
  • I don't see any code related with timer... In this form of your question, you just ask "edit my answer to add this new functionality" – L.B Nov 25 '16 at 18:26
  • `Thread.Sleep()` is a bad practice for waiting 10 seconds, as it makes the whole program unresponsive. Try any type of multitasking or just checking the passed time. – devRicher Nov 25 '16 at 18:34
  • @L.B at the end for loop is code for timer – Super Nov 25 '16 at 18:40
  • so what should i do @devRicher – Super Nov 25 '16 at 18:41
  • @Super Take a look at [this](http://stackoverflow.com/questions/8496275/c-sharp-wait-for-a-while-without-blocking) question, Timers are quite a good practice. If you don't want them, I can still tell you to check the time elapsed, like demonstrated [here](http://www.greenfoot.org/topics/1291). Though it's in Java, you can figure out an analogy. – devRicher Nov 25 '16 at 18:44
  • but i want this in console – Super Nov 25 '16 at 18:47
  • @Super See for ex, http://stackoverflow.com/a/12797382/932418 You can also google *system threading timer* – L.B Nov 25 '16 at 18:48

2 Answers2

0

Your code is quite messy. You got everything in a single method. So creating additional method(s), which a timer needs, you cannot access any variable that is important to the timer. You need to start making your own classes. This gives you so much more control over the variables of your program. It is difficult with your code, to put you in the right direction. You need to change so much.

For fun, and some experience as well, I created what you was working on. A calculating game, or test, or w/e you wanna call it. I will share my code with you, in the hope you will learn some things out of it.

Program.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();
        }
    }
}

Difficulty.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;
        }
    }
}
Verkade89
  • 373
  • 2
  • 12
  • @Super My code is a bit too long to explain exactly what everything does. But all the way down on this page will show clearly how a Timer works: https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx – Verkade89 Nov 27 '16 at 14:04
  • @Super You can also download my project with this link; Hopefully that way you can open it, and run it, and see how it works: https://drive.google.com/open?id=0B8yrEMMQonlYZHFtUERUNUlJUHc – Verkade89 Nov 27 '16 at 14:05
-1

Your delay is only 1 second. Increase the delay to 10 seconds by:

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);
            }
Harminder
  • 141
  • 1
  • 8
  • yes but how i display timer when question is start and when question not answered then with in 10 seconds then want to show next question – Super Nov 25 '16 at 18:42