This time, we will modify our program to include multiple instances of the same object, storing them in a list for easy management.
import random
class ePet:
def __init__(self, strN):
self.strName = strN
self.intHunger = 5
self.intBoredom = 5
print(f"You adopted an ePet named {self.strName}.")
def feedPet(self):
print(f"You fed {self.strName}.")
self.intHunger += 3
def playPet(self):
print(f"You played with {self.strName}.")
self.intBoredom += 3
def takeTurn(self):
self.intBoredom -= random.randint(1,3)
self.intHunger -= random.randint(1,3)
print(f"Time passes... {self.strName} is getting more bored and hungry.")
print("Boredom:".ljust(15,".")+f"{self.intBoredom}".rjust(10,"."))
print("Hunger:".ljust(15, ".") + f"{self.intHunger}".rjust(10, "."))
print("ePet Shop".center(60))
strName = input("What do you want to name your pet?")
myPet = ePet(strName)
while True:
myPet.takeTurn()
if myPet.intHunger < 1 or myPet.intBoredom < 1:
print(f"{myPet.strName} has run away to find a better owner!")
break
print("""
1. Feed Pet
2. Play with Pet
""")
strChoice = input("What do you want to do?")
if strChoice == "1":
myPet.feedPet()
elif strChoice == "2":
myPet.playPet()
else:
print("Invalid Choice. You lose a turn!")
import random
class ePet:
def __init__(self, strN):
self.strName = strN
self.intHunger = 5
self.intBoredom = 5
print(f"You adopted an ePet named {self.strName}.")
def __str__(self):
return f"{self.strName} ".ljust(15)+"Boredom:".ljust(10, ".") + f"{self.intBoredom}".rjust(5, ".")+ " Hunger:".ljust(10, ".") + f"{self.intHunger}".rjust(5, ".")
def feedPet(self):
print(f"You fed {self.strName}.")
self.intHunger += 3
def playPet(self):
print(f"You played with {self.strName}.")
self.intBoredom += 3
def takeTurn(self):
self.intBoredom -= random.randint(0,2)
self.intHunger -= random.randint(0,2)
print(f"Time passes... {self.strName} is getting more bored and hungry.")
def listPets(liPets):
intIndex = 1
for pet in liPets:
print(f"{intIndex} - {pet.strName}")
intIndex += 1
print("ePet Shop".center(60))
liPets = []
while True:
print("""
1. Feed Pet
2. Play with Pet
3. Adopt a New Pet
""")
strChoice = input("What do you want to do?")
if strChoice == "1":
listPets(liPets)
intChoice = input("Which pet?")
if intChoice.isnumeric():
intChoice = int(intChoice) - 1
liPets[intChoice].feedPet()
else:
print("Invalid Input")
elif strChoice == "2":
listPets(liPets)
intChoice = input("Which pet?")
if intChoice.isnumeric():
intChoice = int(intChoice) - 1
liPets[intChoice].playPet()
else:
print("Invalid Input")
elif strChoice == "3":
strName = input("What do you want to name your pet?")
liPets.append(ePet(strName))
else:
print("Invalid Choice. You lose a turn!")
for pet in liPets:
pet.takeTurn()
for pet in liPets:
if pet.intHunger < 1 or pet.intBoredom < 1:
liPets.remove(pet)
print(f"{pet.strName} has run away!")
print("Here are your pets:")
for pet in liPets:
print(pet)