简体   繁体   中英

How to create a Python timer to count down?

My code:

def timer():
    while True:
        try:
           when_to_stop = 90
        except KeyboardInterrupt:
             break
        except:
             print("error, please star game again")
        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + 
            str(s).zfill(2) # got cut off, belongs to the line before this
            print("time:", time_left + "\r", end="")
            if time_left == 0:
               print("TIME IS UP!")
            time.sleep(1)
        when_to_stop -= 1

This works perfectly fine, except that time.sleep means my whole program sleeps, so anything after that while stop for 90 seconds. Any way to fix that?(or make a new timer without time.sleep?)

I think that, alternatively, you could keep track of when the timer starts, and check the time by seeing if the time that's passed is longer than the timer is supposed to last. I'm not sure how much you know about classes and objects in Python, but here is the solution that came to mind:

import datetime

class Timer:
  def __init__(self,**kwargs):
      self.start = datetime.datetime.now()
      self.length = datetime.timedelta(**kwargs)
      self.end = self.start+self.length
  def isDone(self):
      return (self.end-datetime.datetime.now()).total_seconds()<=0
  def timeLeft(self):
      return self.end-datetime.datetime.now()
  def timeElapsed(self):
      return datetime.datetime.now()-self.start

Even if you don't quite understand the class itself, if you put it in your code it should work like a charm:

#This has the same options as:
#class datetime.timedelta(days, seconds, microseconds, milliseconds, minutes, hours, weeks)
t = Timer(days=2)

while(not t.isDone()):
  #Do other game stuff here....
    time_left = t.timeLeft()
    print(f"time: {time_left}")
    #And here....
print("Done now")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM