I am building a small program just kind of to apply some of what I've learned and see if I can push my limits to learn more. I have so far created a Character class and used a constructor to create a "character" named Dick. I have also created a number of variables and methods that when called, increment or decrement certain variables and output certain activities that Dick is involved in on the console screen. My question is whether there is a way to track time while the program is running so that I can set the time when the program is started and then keep track of it as it runs so it will adjust variables such as hunger, tiredness, time to go to work, time to leave work, and then when those variables hit certain numbers, they will call the methods such as go to work, eat, go to sleep, leave work. Basically, if I could track time some how, I could use every 5 seconds to update the variables, and then the "game" would basically run itself. Any ideas?
Asked
Active
Viewed 92 times
0
-
you should take a look of this : http://stackoverflow.com/questions/12535722/what-is-the-best-way-to-implement-a-timer – Mike Jun 26 '16 at 05:07
1 Answers
1
Here is how you could do it using the System.Diagnostics namespace:
Stopwatch time = new Stopwatch(); //Create a new Stopwatch
time.Start(); //Start The Timer
Thread.Sleep(5000); //Sleeps The Program For 5 Seconds
System.WriteLine("The Timer Is At: " + time.Elapsed); //Displays What The Timer Is At, Should Be 5 Seconds.
Once you have started your timer you can ignore the Thread.Sleep(5000); part because that was just to show that the timer counts up to 5 seconds as the program is slept for 5 seconds. After starting the timer you can go back and compare the time.Elapsed() part to check if it is a multiple of 5 and if it is then update your variables, like so:
Stopwatch time = new Stopwatch();
if (time.Elapsed % 5 == 0) { //Checks If The Remainder of The Timer When Divided By 5 Is 0.
//Change Variables Or Do Whatever Here
} else {
//Do Whatever Needs To Be Done If Timer Isn't At An Interval Of 5
}
Hope this was of some help.

PropsPanda
- 69
- 1
- 7
-
yes very helpful! I had found both the stop watch and the sleep functions but was having problems with implementing then correctly! – ethan codes Jun 27 '16 at 11:28