Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python2
- import datetime
- import time
- HEAL_SECONDS = 2
- class Health(object):
- def __init__(self, initial=10):
- self.hearts = initial
- if initial < 10:
- self.lasthealing = datetime.datetime.utcnow()
- else:
- self.lasthealing = None
- def monitor(self):
- if self.hearts < 10:
- if self.lasthealing:
- # calculate how much time has passed, how much there is to heal
- # then update the time info
- now = datetime.datetime.utcnow()
- spendtime = now - self.lasthealing
- healing = spendtime.seconds / HEAL_SECONDS
- maxhealing = 10 - self.hearts
- realhealing = min(healing, maxhealing)
- for _ in xrange(realhealing):
- print "+1 heart :D"
- self.hearts += realhealing
- if self.hearts < 10:
- healupdate = healing * HEAL_SECONDS
- self.lasthealing += datetime.timedelta(seconds=healupdate)
- else:
- self.lasthealing = None
- else:
- # apparently we just lost some hearts
- self.lasthealing = datetime.datetime.utcnow()
- if self.hearts < 1:
- # we check this in the end so that healings that occured
- # previously are properly accounted for
- print "You are dead"
- else:
- self.lasthealing = None
- def __iadd__(self, amount):
- self.monitor()
- self.hearts += amount
- print "+{} hearts! :D".format(amount)
- self.monitor()
- return self
- def __isub__(self, amount):
- self.monitor()
- self.hearts -= amount
- print "-{} hearts! :'(".format(amount)
- self.monitor()
- return self
- @property
- def dead(self):
- return self.hearts < 1
- def main():
- me = Health()
- me.monitor()
- me -= 2
- assert(me.hearts == 8)
- time.sleep(2)
- me.monitor()
- assert(me.hearts == 9)
- time.sleep(4)
- me.monitor()
- assert(me.hearts == 10)
- me -= 6
- time.sleep(4)
- me -= 5
- assert(me.hearts == 1)
- me -= 1
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement