Skip to content

Instantly share code, notes, and snippets.

@sneeu
Created September 24, 2014 07:57
Show Gist options
  • Save sneeu/50dcc50cf60fda48b5d2 to your computer and use it in GitHub Desktop.
Save sneeu/50dcc50cf60fda48b5d2 to your computer and use it in GitHub Desktop.
import random
import threading
import time
SPEED = 0.5
class Tamagotchi(object):
def __init__(self, name):
self.name = name
self.age = 0
self.health = 100
self.poops = 0
self.poops_at = {}
self.tiredness = random.randint(0, 4)
self.is_sleeping = False
self.hunger = 3 + random.randint(0, 3)
self.is_dead = False
def tick(self):
self.age += 1
if self.is_sleeping:
self.tiredness -= 1
else:
self.tiredness += 1
if self.is_tired():
self.put_to_bed()
elif self.tiredness <= 0:
self.wake_up()
if self.poops > 0:
self.health -= 5
if self.hunger > 10:
self.health -= 3
elif self.hunger < 0:
self.poops += 1
if random.randint(0, 10) < 3:
self.hunger += 1
self.poops += self.poops_at.get(self.age, 0)
if self.health <= 0 or self.age >= 100:
self.is_dead = True
return
print 'A{0}; H{1};'.format(self.age, self.health),
if self.hunger > 10:
print 'hungry;', # + str(self.hunger),
if self.is_sleeping:
print 'sleeping;', # + str(self.tiredness),
if self.poops > 0:
print 'poopy;', # + str(self.poops),
print
def is_tired(self):
return self.tiredness > 10
def feed(self):
if self.is_sleeping:
print "Cannot feed when sleeping"
else:
print "Fed"
self.health += 1
poops_at = self.age + random.randint(5, 10)
self.poops_at.setdefault(poops_at, 0)
self.poops_at[poops_at] += 1
self.hunger -= 2
def clean_poop(self):
self.poops -= 1
if self.poops < 0:
self.health -= 2
self.poops = 0
def put_to_bed(self):
self.is_sleeping = True
def wake_up(self):
if self.is_sleeping:
self.is_sleeping = False
if self.tiredness > 0:
self.health -= self.tiredness
class Ticker(threading.Thread):
def __init__(self, tamagotchi):
super(Ticker, self).__init__()
self.tamagotchi = tamagotchi
def run(self):
while True:
if self.tamagotchi.is_dead:
print "\nYour favourite Tamagotchi, {0}, died".format(self.tamagotchi.name)
break
self.tamagotchi.tick()
time.sleep(SPEED)
class InputReader(threading.Thread):
def __init__(self, tamagotchi):
super(InputReader, self).__init__()
self.tamagotchi = tamagotchi
def run(self):
while True:
action = raw_input('')
if self.tamagotchi.is_dead:
break
if action == "f":
self.tamagotchi.feed()
elif action == "b":
self.tamagotchi.put_to_bed()
elif action == "w":
self.tamagotchi.wake_up()
elif action == "c":
self.tamagotchi.clean_poop()
def main():
print "f - feed"
print "b - put to bed"
print "w - wake up"
print "c - clean a poop"
name = raw_input("name> ")
t = Tamagotchi(name)
tick_thread = Ticker(t)
input_thread = InputReader(t)
tick_thread.start()
input_thread.start()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment