What exactly is happening in this piece of code? - python

I attempted to recreate a piece of code which is basically a minimalist Tomagatchi like thing. However when it is fed, and listened to, it's "mood" value does not change. It remains "mad". Any help would be greatly appreciated!
{#Create name, hunger, boredom attributes. Hunger and Boredom are numberical attributes
class Critter(object):
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
#Creating a private attribute that can only be accessed by other methods
def __pass_time(self):
self.hunger += 1
self.boredom += 1
def __get_mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
mood = "happy"
if 5 <= unhappiness <= 10:
mood = "okay"
if 11 <= unhappiness <= 15:
mood = "frustrated"
else:
mood = "mad"
return mood
mood = property (__get_mood)
def talk(self):
print "Hi! I'm",self.name,"and I feel",self.mood,"now."
self.__pass_time()
def eat(self, food = 4):
print "Brrruuup. Thank you!"
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
def play(self, play = 4):
print "Yaaay!"
self.boredom -= play
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
def main ():
crit_name = raw_input("What do you want to name your critter? ")
crit = Critter (crit_name)
choice = None
while choice != "0":
print \
""" 0 - Quit
1 - Listen to your critter.
2 - Feed your critter
3 - Play with your critter
"""
choice = raw_input ("Enter a number: ")
#exit
if choice == "0":
print "GTFO."
#listen to the critter
elif choice == "1":
crit.talk()
#feed the crit crit critter
elif choice == "2":
crit.eat()
#play with the crit crit critter
elif choice == "3":
crit.play()
#some unknown choice
else:
print "\nwat"
main ()
raw_input ("\n\nHit enter to GTFO")

In _getMood, there should be elifs.
if unhappiness < 5:
mood = "happy"
elif 5 <= unhappiness <= 10:
mood = "okay"
elif 11 <= unhappiness <= 15:
mood = "frustrated"
else:
mood = "mad"
Without them, it was actually only checking if unhappiness was between 11 and 15, and if not, setting the mood to mad. So unhappines from 0 to 10, and up from 16 meaned a critter was mad.

I would say in cases like this, subsitute for a variable and trace the code.
unhappiness = 3
if unhappiness < 5:
mood = "happy"
ok we became happy
if 5 <= unhappiness <= 10:
mood = "okay"
nothing happened as 3 is not in range for 5 <= x <= 10
if 11 <= unhappiness <= 15:
mood = "frustrated"
nothing happened as 3 is not in range for 11 < x < 15
else:
mood = "mad"
else what? ah this refers to the last condition. so if it's not 11 < x < 15 then we're mad.
Subtitution of a variable with a value, and then tracing the code, line by line, is generally what you should try in situations like this, at least until it becomes second nature.

Related

How do I apply the sellProduct method to each choice in the menu?

I don't understand why I can't connect the processSale method to the sellProduct method. I think that the classes and other methods don't need any change because I only followed the criterias that were given to me.
#candy machine
class CashRegister:
def __init__(self, cashOnHand = 500,):
if cashOnHand < 0:
self.cashOnHand = 500
else:
self.cashOnHand = cashOnHand
def currentBalance(self):
return self.cashOnHand
def acceptAmount(self, cashIn):
self.cashOnHand += cashIn
class Dispenser:
def __init__(self, numberOfItems = 50, productCost = 50):
if numberOfItems < 0:
self.numberOfItems = 50
else:
self.numberOfItems = numberOfItems
if productCost < 0:
self.productCost = 50
else:
self.productCost = productCost
def getCount(self):
return self.numberOfItems
def getProductCost(self):
return self.productCost
def makeSale(self):
self.numberOfItems -= 1
class MainProgram:
def showMenu(self):
global userInput
print("**** Welcome to Eros' Candy Shop ****")
print("To select an item enter")
print("""1 for Candy
2 for Chips
3 for Gum
4 for Cookies
0 to View Balance
9 to Exit""")
userInput = int(input("Enter your choice: "))
def sellProduct(self, useDispenser = Dispenser(), useRegister = CashRegister()):
try:
self.useDispenser = useDispenser
self.useRegister = useRegister
if self.useDispenser.getCount != 0:
print(f"It costs {self.useDispenser.getProductCost} cents")
cash = int(input("Please enter your payment: "))
change = cash - self.useDispenser.getProductCost
if change < 0:
print("Insufficient money!")
print(f"You need {self.useDispenser.getProductCost - cash} cents more")
return
else:
print(f"Your change is {change} cents")
self.useRegister.acceptAmount(self.useDispenser.getProductCost)
self.useDispenser.makeSale
return
elif self.useDispenser.getCount == 0:
print("The product you chose is sold out! Try the other itmes")
return
except ValueError:
print("You entered an incorrect value. Please use the numbers on the menu only")
def processSale(self):
Register = CashRegister()
Candy = Dispenser()
Chips = Dispenser()
Gum = Dispenser()
Cookies = Dispenser()
while True:
self.showMenu
if userInput == 1:
self.sellProduct(Candy, Register)
elif userInput == 2:
self.sellProduct(Chips, Register)
elif userInput == 3:
self.sellProduct(Gum, Register)
elif userInput == 4:
self.sellProduct(Cookies, Register)
elif userInput == 0:
print("Current Balance is" + str(Register.currentBalance))
elif userInput == 9:
break
mainProgram = MainProgram()
mainProgram.showMenu()
How do i use sellProduct method on userInput 1-4. I get confused when applying the properties of a class and how to connect them. Can you point out what mistakes I made and what other improvements I can do.
here are some points you can improve :
When you call your methods do not forget the parenthesis :
self.useDispenser.getCount()
self.useDispenser.getProductCost()
Create an infinite loop to continuously ask for input within showMenu and delete the one within processSale (for example):
def showMenu(self):
global userInput
userInput = 0
print("**** Welcome to Eros' Candy Shop ****")
while userInput != 9:
print("To select an item enter")
print(MENU)
userInput = int(input("Enter your choice: "))
if userInput < 9:
self.processSale()
But please update the whole program accordingly.
Hope it helps !

I can't count the number of tries in this game in pythin

I am a beginner in python and I got a task to make a game of guesses using python. In my assignment, I was told to count the number of tries. But I can't make it work. Any suggestion would be appreciated. (note: the list is for nothing...I was just messing with the code and trying things.)
`
# import random
# a=random.randint(1,30)
a = 23
Dict1 = ["Hello there! How are you?", 0,
"Guess a number Between 1 to 50",
"Your number is too high",
"Your Number is too low",
"Make Your Number A Bit Higher",
"Make Your Number a Bit Lower",
"Congratulations You Have guessed the right number :)"
]
print(Dict1[0])
name = input("What is your Name?\n=")
# print("hi!,{}, Wanna Play a game?".format(name))
print(Dict1[2])
while 1:
inp = float(input("="))
if inp > 50:
print(Dict1[3])
continue
elif inp < 1:
print(Dict1[4])
continue
elif inp < a:
print(Dict1[5])
continue
elif inp > a:
print(Dict1[6])
continue
elif inp == a:
print(Dict1[7])
q = input("Do You Want to Go again? Y or N\n=")
if q.capitalize() == "Y":
print('You have', 5 - 4, "tries left")
print(Dict1[2])
continue
elif q.capitalize() == "N":
break
else:
break
op = inp
while 1:
x = 4
if -137247284234 <= inp <= 25377642:
x = x + 1
print('You have', 5 - x, "tries left")
if x == 5:
break
if x == 5:
print("Game Over")
`
One way to go about it would be to set up a variable to track attempts outside the while loop between a and Dict1
a = 23
attempts = 1
Dict1 = [...]
Then each time they make an attempt, increment in the while loop:
if inp > 50:
print(Dict1[3])
attempts += 1
continue
elif inp < 1:
print(Dict1[4])
attempts += 1
continue
elif inp < a:
print(Dict1[5])
attempts += 1
continue
elif inp > a:
print(Dict1[6])
attempts += 1
continue
EDIT:
Looking more carefully at your code, it seems like you want a countdown. So you could change it to
attempts = 5
and in the while loop
while 1:
...
if q.capitalize() == "Y":
attempts -= 1
print('You have', attempts, "tries left")
print(Dict1[2])
continue

Python repeat random integer in while loop

I am trying to code player and mob attacks for a text based RPG game I am making, I have randomint set up for player and mob hitchance and crit chance but I can't figure out how to get a new integer for them every time I restart the loop, it uses the same integer it got the first time it entered the loop.
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
roll = roll_dice()
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
while True:
roll.mobcrit
roll.mobhitchance
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
if roll.mobcrit <= 5 and roll.mobhitchance >= 25:
print("\nOrc crit for",str(orcMob.atk * 2),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk * 2
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance >= 25:
print("\nOrc hit for",str(orcMob.atk),"damage!")
userPlayer.hp = userPlayer.hp - orcMob.atk
print("Your HP",str(userPlayer.hp))
break
elif roll.mobcrit <= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
elif roll.mobcrit >= 5 and roll.mobhitchance <= 25:
print("Orc missed!")
print("Your HP:",str(userPlayer.hp))
break
if orcMob.hp <= 0 and userPlayer.hp >= 1:
break
elif orcMob.hp >= 1:
continue
The problem is with your roll_dice class. You have the values defined when the class initializes, but then you never update them again. Therefore self.escape or self.spawn will always be the same value after the program starts. The easiest way to solve your problem without rewriting much would be to make another instance of roll_dice() every time you want to roll the dice. Something like:
### GAME VALUES ###
class roll_dice:
def __init__(self):
self.spawn = random.randint(1,100)
self.escape = random.randint(1,100)
self.playercrit = random.randint(1,100)
self.playerhitchance = random.randint(1,100)
self.mobcrit = random.randint(1,100)
self.mobhitchance = random.randint(1,100)
# roll = roll_dice() # you don't need to make an instance here
### ORC SPAWN ###
if fight_walk.lower() == 'fight':
orcMobSpawn()
while True:
fight_orc = input(">>> ")
if fight_orc.lower() == 'a':
### PLAYER ATTACK ###
while True:
roll = roll_dice() # make a new instance with each loop
roll.playercrit
roll.playerhitchance
if roll.playercrit <= 10 and roll.playerhitchance >= 6:
print("You crit orc for",str(userPlayer.atk * 2),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk * 2
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance >= 6:
print("You hit orc for",str(userPlayer.atk),"damage!")
orcMob.hp = orcMob.hp - userPlayer.atk
print("Orc HP:",orcMob.hp)
break
elif roll.playercrit >= 11 and roll.playerhitchance <= 5:
print("You missed!")
break
elif roll.playercrit <= 10 and roll.playerhitchance <= 5:
print("You missed!")
break
elif orcMob.hp <= 0 and userPlayer.hp >= 1:
print("Your HP:",str(userPlayer.hp))
print("You win!")
break
elif userPlayer.hp <= 0:
print("You died!")
exit()
### ORC ATTACK ###
Use functions like
import random
for x in range(10):
print random.randint(1,101)
use a array around for a max 100 people and generate random digits to add in your code.
You can also use a array to create random umber structure and then use the numbers to be shuffled and added as you create them
from random import *
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

Access attributes of objects in a list

I'm using a book called Python for Absolute Beginners and am doing a challenge in the book's chapter 8 (Software Objects). My code works but I want to add another capability to the code; What code do I need to add to feed/play/talk with a specific critter?
In choice #7 of my code (7 - Feed a specific critter), I have written some code but it doesn't work. How might I access/change the attributes of a specific object that the user selects?
Also, any feedback to improve/shorten the code?
# Critter Caretaker
# A virtual pet to care for
class Critter(object):
import random
"""A virtual pet"""
def __init__(self, name, hunger = random.randint(0,9), boredom = random.randint(0,11)):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
self.hunger +=1
self.boredom +=1
def __str__(self):
m = "name is: {}, hunger is: {}, boredom is: {}".format(self.name, self.hunger,self.boredom)
return m
#property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness <5:
m = "happy"
elif 5 <= unhappiness <=10:
m = "okay"
elif 11 <= unhappiness <=15:
m = "frustrated"
else:
m= "mad"
return m
def talk(self):
print("I'm", self.name, "and I feel", self.mood, "now.\n")
self.__pass_time()
def eat(self, food=3):
print("Yummy! Thank you.")
self.hunger -=food
if self.hunger <0:
self.hunger = 0
self.__pass_time()
def play(self, fun=4):
print("That was fun! Thanks")
self.boredom -=fun
if self.boredom <0:
self.boredom = 0
self.__pass_time()
def main():
noc = []
noc.append(Critter("Chicken"))
print("An critter named Chicken has been created")
choice = None
while choice != "0":
print \
("""
Critter Caretaker
0 - Quit
1 - Listen to all your critters
2 - Feed all your critters
3 - Play with all your critters
4 - Create a new critter
5 - Show a list of critters
6 - Delete a critter
7 - Feed a specific critter
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# listen to critters
elif choice == "1":
if len(noc) != 0:
i.talk()
else:
print("No critters exist")
# feed your critters
elif choice == "2":
if len(noc) != 0:
for i in noc:
print(i.name, "says:", end = " ")
i.eat()
# play with your critters
elif choice == "3":
if len(noc) != 0:
for i in noc:
print(i.name, "says:", end = " ")
i.play()
else:
print("No critter exists")
# Create a new critter
elif choice == "4":
noc.append(Critter(input("Enter a name for your new critter: ")))
# Show critters
elif choice =="5":
b = 0
if len(noc) != 0:
for i in noc:
b +=1
print(b, "." ,i.name)
else:
print("No critter exists")
# delete a critter
elif choice == "6":
a = int(input("Enter the serial number of critter you want to delete: "))
a = a -1
del noc[a]
# feed a specific critter
elif choice == "7":
sctd = input("Enter name of critter you want to feed: ")
if sctd in noc:
noc.eat()
else:
print("That critter doesn't exists")
# print attributes of critters
elif choice == "919":
for i in noc:
print(i)
else:
print("\nSorry, but", choice, "isn't valid.")
main()
("\n\nPress the enter key to exit.")
In the branch for feeding a specific critter, you have the line noc.eat() -- noc is a list, which has no eat() method. You need to access the critter specified by the input, and call the eat() method on that object. Something like:
for c in noc:
if c.name == sctd:
c.eat()
break
(although there is an issue with this example if multiple critters match sctd -- solving that is something i'll leave to you)
an additional minor point of feedback on your code: a docstring should be the first statement inside the definition as per PEP 0257.
Just a small note is that I think the convention something like import random should probably be placed at the start rather than inside the class which also gets rid of the problem raised by #nthall which is that your docstring is currently not the first object.

want to improve simple python code

i am new to python programming. This is code that i want to improve
# Critter Caretaker
# A virtual pet to care for
class Critter(object):
"""A virtual pet"""
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
def __pass_time(self):
self.hunger += 1
self.boredom += 1
#property
def mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
m = "happy"
elif 5 <= unhappiness <= 10:
m = "okay"
elif 11 <= unhappiness <= 15:
m = "frustrated"
else:
m = "mad"
return m
def talk(self):
print("I'm", self.name, "and I feel", self.mood, "now.\n")
self.__pass_time()
def eat(self, food = 4):
print("Brruppp. Thank you.")
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
def play(self, fun = 4):
print("Wheee!")
self.boredom -= fun
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
def __str__(self):
rep = "Attribut value is\n"
rep += str(self.hunger) + "\n" + str(self.boredom) + "\n"
return rep
def main():
crit_name = input("What do you want to name your critter?: ")
crit = Critter(crit_name)
choice = None
while choice != "0":
print \
("""
Critter Caretaker
0 - Quit
1 - Listen to your critter
2 - Feed your critter
3 - Play with your critter
""")
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# listen to your critter
elif choice == "1":
crit.talk()
# feed your critter
elif choice == "2":
crit.eat()
# play with your critter
elif choice == "3":
crit.play()
# secret option
elif choice == "!":
print(crit)
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
main()
("\n\nPress the enter key to exit.")
You see it is a puppet that show his mood and search of you to feed and play with him. Every time puppet talk, eat or play counter pass_time add 2 level up. Attribute food and fun have always the same number that directly affects mood. I want to make that user can enter amount of food and time that can affect mood of puppet. Why i cant do this
def eat(self, food):
print("Brruppp. Thank you.")
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
def play(self, fun):
print("Wheee!")
self.boredom -= fun
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
and this
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# listen to your critter
elif choice == "1":
crit.talk()
# feed your critter
elif choice == "2":
food = int(input("How much food?: "))
crit.eat()
# play with your critter
elif choice == "3":
fun = int(input("How much time?: "))
crit.play()
# secret option
elif choice == "!":
print(crit)
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
You seem to be almost there if I understand your question right. Lets use the eat function as an example. You want to pass the food variable to the class function to use. If you want you can also add validation to check if that value entered is a number.
elif choice == "2":
food = int(input("How much food?: "))
crit.eat(food) # pass food in as a parameter

Categories

Resources