Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

setting Time limit  RSS feed

 
Vanitha Sugumaran
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am writing code for a game, I want to set the time limit for this game, how can I do this?

Thanks,
Vanitha.
 
Ashwin Desai
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
You can create your own timer class (that runs in a seperate thread) that keeps track of the time. This class sends an indication to the main class when the timer expires.
for e.g.
Timer class implements Runnable
1) Get the Max time.
2) In the run(), start a counter that counts the time elapsed.
3) Make the Thread sleep for 1 sec and update the counter by 1 sec (if the smallest unit of time measurement is 1 second).
4) when the above loop terminates, send an indication to the main program.
But, the sleep time is not accurate but could be used for gaming purposes.
Hope this helps.
Ashwin.

[This message has been edited by Ashwin Desai (edited May 02, 2001).]
 
Vanitha Sugumaran
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ashwin,
Thank you, I will try to implement this idea.
Vanitha
 
Noah Carroll
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to get an accurate time limit, you can use the system clock. As the program begins you should run the command System.currentTimeMillis(); and store the value returned. Then in a seperate thread you can run a loop that will call run the same command again getting a new time. Then it will test to see if the difference between the two is equal to the length of time that you want to have passed (in milliseconds). Then if not it will pause for a second or so and then repeat. This is very accurate use for time limits.
<PRE>
long startTime = System.currentTimeMillis();

//seperate thread
long timeLimit = 60*1000; //60 seconds
long testTime = System.currentTimeMillis();
while((testTime - startTime) < timeLimit) {
Thread.sleep(1000);
testTime = System.currentTimeMillis();
}
//send information to main thread to stop execution
</pre>

------------------
I hope its helps, feel free to email me noahcarroll@juno.com
 
Vanitha Sugumaran
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Noah,
Thanks for your reply.
Vanitha
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!