Time limit when entering choice

From TRCCompSci - AQA Computer Science
Revision as of 13:08, 24 May 2018 by Jared (talk | contribs)
Jump to: navigation, search

Extra declarations and namespacing

using System.Timers;//Add the Timer class to allow checking how much real time has passed
        

        private static Timer T = new Timer(5000);//Create a new instance of the class Timer with a 5 second delay between event calls
        private static bool Timeout = false;//A variable to check whether time has run out

GetChoice

private static string GetChoice()
        {
            Timeout = false; //This ensures that each time a player enters a choice they have the right amount of time.
            
            // . . .
            
            T.Start();//This starts counting real time using an event.
            T.Elapsed += T_Elapsed;//This subscribes the event to a delegate, it allows a method to run after a set amount of time
            
            // . . .
            
            //The following if clears the choice to make it tidier
            if (Timeout)
            {
                Choice = "";
            }

            // . . .
        }

New Method

        //This method is auto generated upon entering T.Elapsed += then pressing tab
        //It is a method that is called whenever T.Elapsed is called. (This is a event that is subscribed to the delegate T.Elapsed)
        static void T_Elapsed(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("Your time has run out. Press enter to continue");
            Timeout = true;//Once time has run out the program needs to know for future use
            T.Stop();//The delegate should not keep running, otherwise the time player 2 gets is less then player 1.
            T.Elapsed -= T_Elapsed;//If the event doesn't unsubscribe then it will begin stacking, each time it runs the message will appear an extra time
            
        }