User-input does not match output of object list attributes - python

So I've been making a simple program where you can select cars and buy/sell them, and they get stored in the inventory. Additionally, you can ask for specific attributes of what you want in your car. The code is as followed:
class Consumer:
#create an inventory to store cars
garage = []
def __init__(self, budget):
self.budget = budget
#returns current budget of user
def checkBudget(self):
return self.budget
#take money away from the budget and store the car in the inventory
def buy(self, car):
self.budget = self.budget - car.price
self.garage.append(car)
def sell(self, value):
#takes back original money and takes out car
self.budget = self.budget + self.garage[value].getPrice()
return self.garage.pop(value)
def showGarage(self):
for i in self.garage:
print(i.getInfo())
def carCount(self):
return len(self.garage) - 1
class Car:
def __init__(self, model, color, price, year):
self.model = model
self.color = color
self.price = price
self.year = year
def getName(self):
return ("{} {} from {}".format(self.color, self.model, self.year))
def getInfo(self):
return ("{} {} from {} that costs ${}".format(self.color, self.model, self.year, self.price))
def getColor(self):
return self.color
def getYear(self):
return self.year
def getPrice(self):
return self.price
class Sedan(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 200
class SUV(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 300
class Sports(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 800
class Bike(Car):
def __init__(self, model, color, price, year):
super().__init__(model, color, price, year)
def colorPrice(self, color):
self.color = color
self.price = self.price + 400
class Catalogue:
#placeholder to store all cars
whole = []
#sets user-defined preferences of cars
preferences = []
def __init__(self):
pass
def addCars(self, car):
self.whole.append(car)
self.preferences.append(car)
#shortens list so that the catalogue shows only the cars from the year the user wants from
def year(self, year):
for i in self.preferences:
if int(i.getYear()) != int(year):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars from this year")
self.Reset()
print(self.preferences)
#shortens list so that the catalogue shows only the cars of a certain color
def color(self, color):
for i in self.preferences:
if str(i.getColor()) != str(color):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars of this color")
self.Reset()
print(self.preferences)
#shortens list so that it only shows the price range
def price(self, low, high):
for i in self.preferences:
if int(i.getPrice()) <= int(low) or int(i.getPrice()) >= int(high):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars from this price range")
self.reset()
#clears all preferences so that it shows all available cars
def Reset(self):
self.preferences.clear()
for i in self.whole:
self.preferences.append(i);
def showCatalogue(self):
for i in range(len(self.preferences)):
print(self.preferences[i].getInfo())
def getLength(self):
return len(self.preferences)
#gives the car away
def sell(self, value):
self.whole.pop(value)
a = self.preferences.pop(value)
return a
showcase = Catalogue()
Toyota = Sedan('Toyota Camry', 'blue', 64000, 2002)
Honda = Sedan('Honda Civic', 'red', 65000, 2002)
Dodge = SUV('Dodge Durango', 'black', 4324, 2015)
Yamaha = Bike('Yamaha x', 'red', 23240, 2015)
showcase.addCars(Toyota)
showcase.addCars(Honda)
showcase.addCars(Dodge)
showcase.addCars(Yamaha)
customer = Consumer(100000)
#garage module
def garage():
global customer
global showcase
a = input("What do you want to do? 1) check car collection 2) sell car 3) back ")
#shows all cars from the inventory
if int(a) == 1:
customer.showGarage()
garage()
#sells available cars
elif int(a) == 2:
customer.showGarage()
#will cancel if there care no cars in the inventory
if len(customer.garage) == 0:
print("You have no cars")
garage()
else:
#enter index no to select a car
b = input("Pick a car from 0 to {} ".format(customer.carCount()))
if int(b) > int(customer.carCount()):
print("You don't have that many cars!")
garage()
else:
c = input("Are you sure you want to sell this car? 1) yes 2) no ")
#asks for warning confirmation
if int(c) == 1:
d = customer.sell(int(b))
showcase.addCars(d)
print("This car has been sold; have a nice day!")
garage()
elif int(c) == 2:
garage()
#go back to main
elif int(a) == 3:
e = input("Are you sure you wanna go back? 1) yes 2) no ")
if int(e) == 1:
main()
elif int(e) == 2:
garage()
#asks if you want to specify the list
def access():
global showcase
showcase.showCatalogue()
print()
g = input("Looking for specifics? 1) yes 2) no: ")
if int(g) == 1:
options()
else:
choose()
print()
#would you like to access catalogue or garage?
def main():
a = input("Where do you want to go next? 1) check garage 2) browse more cars" )
if int(a) == 1:
garage()
elif int(a) == 2:
access()
else:
print("Try again")
main()
#car purchase confirmation
def buy(car):
global customer
global showcase
a = input("Are you sure you want to buy this car? 1) yes 2) no " )
if int(a) == 1:
#cancels purchase automatically if your balance is low
if int(customer.checkBudget()) < int(showcase.preferences[car].getPrice()):
print("You do not have enough money")
access()
else:
#takes the car out of the catalogue and stores it in the garage
print("Transaction taking place...")
sold = showcase.sell(car)
customer.buy(sold)
print("You purchased this car")
print("You now have a budget of {} dollars".format(customer.checkBudget()))
main()
def choose():
#which car you would like to purchase
global showcase
c = input("Which car would you like? enter from 0 to {} ".format(showcase.getLength()-1))
if int(c) > int(showcase.getLength()):
print("Out of bounds, please try again")
choose()
else:
buy(int(c))
def options():
#which specifics are you looking for?
global showcase
a = input("What are you looking for? 1) color 2) price 3) year: 4) reset ")
if int(a) == 1:
b = input("Pick a color: ")
showcase.color(b)
elif int(a) == 2:
b = input("Pick a lower price range: ")
c = input("Pick an upper price range: ")
if showcase.price(b) > showcase.price(c):
print("Invalid Error")
else:
showcase.price(b,c)
elif int(a) == 3:
b = input("Pick a year: ")
showcase.year(b)
elif int(a) == 4:
showcase.Reset()
else:
print("Invalid, try again")
options();
access()
access()
My main issue is with the specifics. For example, when I type for a blue car, it gives me a black car. When I type for a car from 2015, it gives me a car from 2002. When I ask for a car no more than $50000, it gives me a car worth $65000. Here are some runtime scenarios:
What are you looking for? 1) color 2) price 3) year: 4) reset #1
Pick a color: #blue
#returns
blue Toyota Camry from 2002 that costs $64000
black Dodge Durango from 2015 that costs $4324
What are you looking for? 1) color 2) price 3) year: 4) reset #3
Pick a year: #2015
#returns
red Honda Civic from 2002 that costs $65000
black Dodge Durango from 2015 that costs $4324
red Yamaha x from 2015 that costs $23240
The code problem can be found here:
#shortens list so that the catalogue shows only the cars of a certain color
def color(self, color):
for i in self.preferences:
if str(i.getColor()) != str(color):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars of this color")
self.Reset()
print(self.preferences)
#shortens list so that it only shows the price range
def price(self, low, high):
for i in self.preferences:
if int(i.getPrice()) <= int(low) or int(i.getPrice()) >= int(high):
self.preferences.remove(i)
if not self.preferences:
print("There are no cars from this price range")
self.reset()

The problem is, you are trying to remove items from a list which is being looped through. This may create unexpected behavior. Store the values to be removed and then later remove from the list, something like this
def color(self, color):
tobeRemoved = []
for i in self.preferences:
if str(i.getColor()) != str(color):
tobeRemoved.append(i)
for pref in tobeRemoved:
self.preferences.remove(pref)
if not self.preferences:
print("There are no cars of this color")
self.Reset()
print(self.preferences)
I was able to get the output you wanted
blue Toyota Camry from 2002 that costs $64000
red Honda Civic from 2002 that costs $65000
black Dodge Durango from 2015 that costs $4324
red Yamaha x from 2015 that costs $23240
Looking for specifics? 1) yes 2) no: 1
What are you looking for? 1) color 2) price 3) year: 4) reset 1
Pick a color: blue
blue Toyota Camry from 2002 that costs $64000
Looking for specifics? 1) yes 2) no:
You can do the same for price() also

Related

i would like to assign subclasses to the charecter? how do i do this?

the problem i has is that the errors that occur are found in the code that works. it doesnt make sence.
my code is:
import random
import pickle
class person():
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
self.name = name
self.hp = hp
self.luck = luck
self.xp = xp
self.level = level
self.strength = strength
self.gold = gold
self.location = location
self.age = age
self.intellegence = intellegence
#self.x = 0
#self.y = 0
def talk(self):
return "hello my name is %s. i have %d strength. i am %d years old. i am from %s. I have %d intellence" %(self.name,self.strength,self.age,self.location, self.intellegence)
#def walk(self,newlocation):
# self.x += movex
# self.y += movey
# self.location = newlocation
def takedmg(self, amount):
self.hp = self.hp - amount
def heal(self, amount):
self.hp = self.hp + amount
def attack(self):
pass
allpeople = []
def createperson():
global allpeople
name = input("enter name: ")
hp = 100
luck = random.randint(1,15)
xp = 0
level = 1
gold = 0
age = int(input("enter age: "))
location = input("enter location: ")
strength = random.randint(1,25)
intellegence = 50
aperson = person(name, hp, luck, xp, level, gold, age, location, strength, intellegence)
allpeople.append(aperson)
savedata()
def findchara():
charaname = input("enter the name of the charecter: ")
for foundchara in allpeople:
if foundchara.name == charaname:
print("found \n")
return(foundchara)
return""
def savedata():
savedata = open("mypeople.pickle","wb")
pickle.dump(allpeople,savedata)
savedata.close()
def loaddata():
global allpeople
loaddata = open("mypeople.pickle","rb")
allpeople = pickle.load(loaddata)
loaddata.close()
class warrior(person):
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
person.__init__(self)
class1 = warrior
class mage(person):
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
person.__init__(self)
class1 = mage
class trader(person):
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
person.__init__(self)
class1 = trader
def talk_warrior(person, warrior):
self.strength = self.strength + 15
self.intellegence = self.intellegence - self.intellegence + random.randint(0,5)
return "Hi, name is %s. %d strength. I am %d. from %s. intellegence? %d" %(self.name,self.strength,self.age,self.location,self.intellegence)
def talk_mage(person, mage):
self.strength = self.strength - self.strength + random.randint(0,5)
self.intellegence = self.intellegence + 50
return "Hello my name is The Great MAGE %s. I have %d strength DONT QUESTION MY STRENGTH. I am %d years old. I happened to be from %s. my intellegence also happens to be %d which is superior to everyone else." %(self.name,self.strength,self.age,self.location,self.intellegence)
def talk_trader(person, trader):
return "Hello my name is %s. I have %d strength. I am %d years old. I am from %s. I am very average and my intellegence is %d " %(self.name,self.strength,self.age,self.location,self.intellegence)
loaddata()
def classmenu():
charaloop = True
while charaloop == True:
option = int(input("1. warrior \n2. mage \n3. trader \n9. change class \n0. exit \n"))
if option == 1:
classchara = findchara()
class1 = warrior
print("Class has been set to warrior.")
talk_warrior()
elif option == 2:
classchara = findchara()
class1 = mage
print("Class has been set set to mage.")
talk_mage()
elif option == 3:
classchara = findchara()
class1 = trader
print("Class has been set to trader.")
talk_trader()
elif option == 9:
pass
elif option == 0:
print("returning to main menu. :) \n")
charaloop = False
savedata()
else:
print("invalid choice")
def menu():
mainloop = True
while mainloop == True:
option = int(input("1. create character. \n2. character list. \n3. look for a charecter. \n4. select charecter class. \n8. continue... \n9. delete character from list. \n0. exit \n choice: "))
if option == 1:
print("you will now create your character!!!")
createperson()
elif option == 2:
for aPerson in allpeople:
print(aPerson.talk())
elif option == 3:
findchara()
elif option == 4:
classmenu()
elif option == 8:
if class1 == warrior:
talk_warrior()
elif class1 == mage:
talk_mage()
elif class1 == trader:
talk_trader()
else:
print("ERROR!")
elif option == 9:
chara = findchara()
allpeople.remove(chara)
print("charecter removed")
savedata()
elif option == 0:
print("bye!!! :)")
mainloop = False
savedata()
else:
print("invalid choice")
menu()
the errors are:
Traceback (most recent call last):
File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 173, in <module>
menu()
File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 151, in menu
classmenu()
File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 118, in classmenu
talk_warrior()
TypeError: talk_warrior() missing 2 required positional arguments: 'person' and 'warrior'
the code is meant to run in the shell and is a simple class and subclass game that the player creates a character and then assigns it a subclass which changes the attributes of the character. this is where my problems started. in the future I want the character to be able to travel and then will encounter monsters attack and receive damage.
id like to hear some advice on what I could do to improve and make the code better smoother and also fix these problems that have occurred. I've only been coding for a while so there is allot of things wrong with this code.

Shopping Program not displaying results accurately

I am creating a program that lets a user choose an item to buy, specify how many units they want to purchase, adds the items to the users cart, and then gives a summary of the users cart when they are finished shopping.
I am currently having two problems:
I need to decrement the units available for purchase based on whatever quantity the user selects during checkout. For example, if the user purchases 2 shirts, the menu will print again and show that the units available decreased from 20 to 18.
In my cart summary, I am having trouble figuring out how to get the total price based on the quantity of whatever items the user chose.
I need to display they number of items left in the cart after the cart is cleared. I have tried using count() but received an AttributeError. Essentially, I just need to make sure the print statement looks like this "Number of items left in Cash Register: 0".
RetailItem class:
class RetailItem:
def __init__(self, description = '', units = 0, price = 0.0):
self.__description = description
self.__units = units
self.__price = price
def __str__(self):
displayString = (f'{"Descirption":10}{self.__desciption}\n'
f'{"Inventory":10}{self.__units:15}\n'
f'{"Price":10}{self.__price:<15.2f}\n')
return displayString
#property
def description(self):
return self.__description
#description.setter
def description(self, d):
self.__description = d
#property
def units(self):
return self.__units
#units.setter
def units(self, u):
self.__units = u
#property
def price(self):
return self.__price
#price.setter
def price(self, p):
self.__price = p
#property
def price(self):
return self.__price
#price.setter
def price(self, p):
self.__price = p
CashRegister class:
class CashRegister:
def __init__(self):
self.__item = []
def purchase_item(self, item):
self.__item.append(item)
def get_total(self):
total = 0.0
for item in self.__item:
total += (item.price * item.units)
return total
def show_items(self):
for item in self.__item:
print(f'{item.description}, units: {item.units}, price: {item.price}')
def clear(self):
for item in self.__item:
self.__item.remove(item)
def __str__(self):
return f'Listed Item: {self.__item}'
MakePurchase.py:
from RetailItem import RetailItem as ri
from CashRegister import CashRegister as cr
def showMenu():
jacket = ri('Jacket', 12, 59.95)
jeans = ri('Designer Jeans', 40, 34.95)
shirt = ri('Shirt', 20, 24.95)
register = cr()
choice = '1'
while choice != '0':
print('\n**Menu**')
print(f'{"Choice"}{"Description":>19} {"Price":>20} {"Stock":>21}')
print(f'{"======"}{"===========":>19} {"=====":>20} {"=====":>21}')
print(f'{"1"}{jacket.description:>19} {jacket.price:>25} {jacket.units:>18}')
print(f'{"2"}{jeans.description:>19} {jeans.price:>26} {jeans.units:>18}')
print(f'{"3"}{shirt.description:>19} {shirt.price:>26} {shirt.units:>18}')
print(f'{"======"}{"===========":>19} {"=====":>20} {"=====":>21}')
choice = input('Insert your choice or 0 to exit: ')
if choice == '0':
showCart(register)
elif choice == '1':
quantity = input('Insert quantity: ')
register.purchase_item(jacket)
elif choice == '2':
quantity = input('Insert quantity: ')
register.purchase_item(jeans)
elif choice == '3':
quantity = input('Insert quantity: ')
register.purchase_item(shirt)
else:
print('That item is not available')
def showCart(register):
print('\nCart')
print('====')
print(f'{register.show_items()}')
print('====')
print(f'Total Price: {register.get_total():.2f}')
print('============')
print('\nClearing cash register...')
print('\nNumber of items left in Cash Register: ',) #NEED TO GET NUMBER OF ITEAMS LEFT IN CART
print(register.clear())
def main():
showMenu()
if __name__ == '__main__':
main()
SAMPLE OUTPUT:
**Menu**
Choice Description Price Stock
====== =========== ===== =====
1 Jacket 59.95 12
2 Designer Jeans 34.95 40
3 Shirt 24.95 20
====== =========== ===== =====
Insert your choice or 0 to exit: 3
Insert quantity: 2
**Menu**
Choice Description Price Stock
====== =========== ===== =====
1 Jacket 59.95 12
2 Designer Jeans 34.95 40
3 Shirt 24.95 20
====== =========== ===== =====
Insert your choice or 0 to exit: 0
Cart
====
Shirt, units: 20, price: 24.95 #UNITS SHOULD BE 2
None #NOT SURE HOW TO PREVENT THIS FROM PRINTING
====
Total Price: 499.00 #SHOULD BE 49.90
============
Clearing cash register...
Number of items left in Cash Register: #SHOULD BE 0 INSTEAD OF NONE
None

Doing this for a school project. It doesnt work, any recommendations

import random
class Tamagotchi:
def __init__(self, name, animaltype, activities):
self.name = name
self.animaltype = animaltype
self.activities = activities
self.energy = 100
def getName(self):
return self.name
def getAnimalType(self):
return self.animaltype
def getEnergy(self):
return self.energy
def setHealth(self, newHealth):
self.energy = newHealth
def getExercise():
activity = random.choice(activities)
return (activity)
class Donkey (Tamagotchi):
def __init__ (self, name, activities):
super().__init__(name, "Donkey", activities)
self.__home = "Beach"
def getHome(self):
return (self.__home)
def __fightingSkill(self):
print(self.name, "fights by kicking with their back leg straight into the opponents head")
def DoExercise(self, activity):
if activity == "fighting":
energy = round(self.energy - 10)
print(energy)
print("Strong Kick")
if activity == "racing":
energy = round(self.energy - 15)
print("Hard work")
if activity == "Tail Launch":
energy = round(self.energy - 1)
print("I am a donkey, not a Walrus")
self.setHealth(energy)
if self.getEnergy() < 70:
print(self.getName(), "Is out of energy")
else:
print(self.getName(), "Tired, New Energy:", self.getEnergy())
class Horse(Tamagotchi):
def __init__(self, name, activities):
super().__init__(name, "Horse", activities)
def DoExercise(self, activity):
if activity == "fighting":
energy = round(self.energy - 15)
print("Beaten")
if activity == "racing":
energy = round(self.energy - 5)
print("I am a racing horse")
if activity == "Tail Launch":
energy = round(self.energy - 2)
print("I am a horse i dont tail launch")
self.setHealth(energy)
if self.getEnergy() < 70:
print(self.getName(), "Is out of energy")
else:
print(self.getName(), "Tired, New Energy:", self.getEnergy())
class Walrus(Tamagotchi):
def __init__(self, name, activities):
super().__init__(name, "Walrus", activities)
def DoExercise(self, activity):
if activity == "fighting":
energy = round(self.energy - 34)
print("Victorious")
if activity == "racing":
energy = round(self.energy - 5)
print("I am a Walrus, i dont race")
if activity == "Tail Launch":
energy = round(self.energy - 12)
print("Get launched lol")
self.setHealth(energy)
if self.getEnergy() < 70:
print(self.getName(), "Is out of energy")
else:
print(self.getName(), "Tired, New Energy:", self.getEnergy())
Pet1 = Donkey("Gracy", "fighting")
print("Player1, you are", Pet1.getName(), "who is a", Pet1.getAnimalType())
Pet2 = Horse("Mabel", "racing")
print("Player2, you are", Pet2.getName(), "who is a", Pet2.getAnimalType())
Pet3 = Walrus("Steve", "Tail Lauch")
print("Player3, you are", Pet3.getName(), "who is a", Pet3.getAnimalType())
activities = []
activities.append(Pet1.activities)
activities.append(Pet2.activities)
activities.append(Pet3.activities)
print(activities)
activity = Tamagotchi.getExercise()
print("Activity chosen", activity)
#Accessing private attributes
Pet1.__home = "Land"
print(Pet1.name, "lives on a", Pet1.getHome())
#Accessing private methods
Pet1._Donkey__fightingSkill()
while Pet1.getEnergy()>70 and Pet2.getEnergy()>70 and Pet3.getEnergy() > 70:
Pet1.DoExercise(activity)
if Pet2.getEnergy() > 70:
Pet2.DoExercise(activity)
if Pet3.getEnergy() > 70:
Pet3.DoExercise(activity)
if Pet1.getEnergy() >Pet2.getEnergy()and Pet3.getEnergy():
print("Player 1 wins")
else:
if Pet3.getEnergy() > Pet2.getEnergy():
print("Player 3 wins")
else:
print("Player 2 wins")
this code doesn't seem to work, any suggestions?
pls can you make the code work, im not the best at pyhton but i give it my all, any help would be greatly appreciated
Ive been working at it for 2 days now and it doesnt seem to work, it talks about an error which is:
'local variable 'energy' referenced before assignment'
and another error presented is;
'line 126, in
Pet1.DoExercise(activity)'
Mercinator
The error essentially means you are asking to use the value of "energy" even though it is empty(None/null)
In def DoExercise(self, activity): add an else statement that defines the value of energy when all if cases fail or give the value of energy before the if statement begins. It should solve the issue.

Is there a way to print all of a certain element of a class that is in a list?

The title is terrible, but hopefully I can explain in my post. Creating a little game as my pet project for python, and I'm currently creating the inventory. Everything was... ok when developing the game until it came to making the function that will show all of the player's inventory.
elif (prompt == "examine"):
print(inventory[1].name)
gameprompt()
Ok, so I created a list that basically has a bunch of classes from Items in it. To call on the name element of these classes I have to do something like this, otherwise I just get its memory location which is largely useless to the player. I've tried
elif (prompt == "examine"):
print(inventory[].name)
gameprompt()
Thought that this above example would print only the name of all the Item objects, but there's a compilation error instead because I didn't specify which one. So I then tried~
elif (prompt == "examine"):
print(inventory[1:1000].name)
gameprompt()
Thinking that it would print all of the Item objects names up to 1000, but I obviously don't have that so I thought it would print the names up to the latest object that was there and stop but there was another compilation error from this...
If there is anyway to print out an element of a class for all class objects in a list please let me know. The full code of this game is here, although I don't think you'll need it to help me solve my problem (it is also very large.)
playername = input("What is your name?")
zone = 1
movement = 0
restcounter = 0
searchcounter = 0
class Player:
def __init__(self, name, hp, mp, atk, xp, dodgerate, atkrate):
self.name = playername
self.hp = hp
self.mp = mp
self.atk = atk
self.xp = xp
self.dodgerate = dodgerate
self.atkrate = atkrate
class Enemy(Player):
def __init__(self, name, gold, maxhp, hp, mp, atk, xp):
self.name = name
self.gold = gold
self.maxhp = maxhp
self.hp = hp
self.mp = mp
self.atk = atk
self.xp = xp
class Items:
def __init__(self, name, quantity, description, price, weight):
self.name = name
self.quantity = quantity
self.description = description
self.price = price
self.weight = weight
Player = Player(playername, 1, 1, 1, 1, 25, 3)
print(Player.name + " has been created. ")
def raceselection():
raceinput = input("Do you float towards the TEMPLE, CAVE or FOREST?")
if raceinput == "TEMPLE":
print("You are now a high elf. High elves utlize a lot of magical power at the cost of being very frail.")
Player.hp = Player.hp + 24
Player.mp = Player.mp + 100
Player.atk = Player.atk + 50
print("You awaken from your slumber. Your room's walls are gold plated, and you rested on a flat board.")
print("Out the door, you see many elves with robes praying to some goddess.")
print("You walk out of your door and into the praying area. You are immediately greeted by a tall man.")
elif raceinput == "CAVE":
print("You are now an orc.")
Player.hp = Player.hp + 1000
Player.mp = Player.mp + 15
Player.atk = Player.atk + 50
print("cave")
elif raceinput == "FOREST":
print("You are now a human.")
Player.hp = Player.hp + 50
Player.mp = Player.mp + 25
Player.atk = Player.atk + 25
else:
print("You can't float there!")
raceselection()
raceselection()
inventory = []
def gameprompt():
global inventory
global zone
global movement
global restcounter
global searchcounter
if (movement == 5):
movement = movement - movement
zone = zone + 1
print("You have advanced to zone",zone,"!!!")
gameprompt()
if (zone == 1):
print("Welcome to the first zone! Easy enemies are here with not very good loot./fix grammar, add description of zone/")
elif (zone == 2):
print("Hey, it actually travelled to the second zone, awesome!")
elif (zone == 3):
print("No way would this actually work!")
prompt = input("Would you like to walk, search or rest?: ")
if (prompt == "walk"):
encounterchance = random.randint(1, 3)
if (encounterchance == 2):
if (zone == 1):
mobspawnrate = random.randint(1,3)
if (mobspawnrate == 1):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
elif (mobspawnrate == 2):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
elif (mobspawnrate == 3):
Enemy = Enemy("Blue SlimeBall", 50, 0, 25, 15, 25, 0.500)
print("You have encountered a " + Enemy.name + "!!!")
else:
movement = movement + 1
print("You have walked a step. You are now at ",movement," steps")
gameprompt()
elif (prompt == "search"):
if (searchcounter == 3):
print("You cannot search this area anymore! Wait until you reach the next zone!")
gameprompt()
else:
searchchance = random.randint(1, 5)
if (searchchance == 1 or 2 or 3 or 4):
searchcounter = searchcounter + 1
print(searchcounter)
print("You have found something!")
searchchance = random.randint(1,4)
if (searchchance == 1 or 2):
inventory.append(Items("Old Boot", 1, "An old smelly boot. It's a mystery as to who it belongs to...", 5, 50))
print("You have found a Boot!")
print(inventory)
elif(searchchance == 3):
inventory.append(Items("Shiny Boot", 1, "Looks like a boot that was lightly worn. You could still wear this.", 5, 50))
print(inventory)
print("You have found a Shiny Boot!")
elif(searchchance == 4):
inventory.append(Items("Golden Boot", 1, "It's too heavy to wear, but it looks like it could sell for a fortune!", 5, 50))
print("You have found a Golden Boot?")
print(inventory)
else:
searchcounter = searchcounter + 1
print(searchcounter)
print("You did not find anything of value")
gameprompt()
elif (prompt == "rest"):
if (restcounter == 1):
print("Wait until you reach the next zone to rest again!")
gameprompt()
else:
# Add a MaxHP value to the player later, and the command rest will give 25% of that HP back.
Player.hp = Player.hp + (Player.hp / 5)
print("You have restored ",(Player.hp / 5)," hit points!")
restcounter = restcounter + 1
gameprompt()
elif (prompt == "examine"):
print(inventory[1].name)
gameprompt()
gameprompt()
A list comprehension or map would work perfectly here:
print([item.name for item in inventory])
The comprehension iterates the list, and "replaces" each element in the list with whatever the part before for evaluates to. In this case, it's item.name.
° It actually doesn't replace the element in the original list. It evaluates to a new list full of replaced items.

Why is my variable not changing its values?

I have been making a text-based game. I have gotten to a point where I am trying to do a battle. I have the enemy's hp going down but when I hit it again, the enemy's hp is back to what I had originally set it as. I hope these help.
while do != 'hit rat with sword' or 'run away':
enemyhp= 50
enemyattack= [0,1,3]
OldSwordattack= [0,1,4]
print('What do you do?(attack or run away)')
do=input()
if do == 'run away':
print('You can\'t leave mom like that!')
if do == 'hit rat with sword':
hit= random.choice(OldSwordattack)
if hit == OldSwordattack[0]:
print('Your swing missed')
print('Enemy\'s HP=' + str(enemyhp))
if hit == OldSwordattack[1]:
print('Your swing hit, but very lightly.')
enemyhp= enemyhp - 1
print('Enemy\'s HP=' + str(enemyhp))
if hit == OldSwordattack[2]:
print('Your swing hit head on!')
enemyhp= enemyhp - 4
print('Enemy\'s HP=' + str(enemyhp))
>In front of mom you see a giant, yellow-teethed rat.
>What do you do?(attack or run away)
>hit rat with sword
>Your swing hit, but very lightly.
>Enemy's HP=49
>What do you do?(attack or run away)
>hit rat with sword
>Your swing hit, but very lightly.
>Enemy's HP=49
>What do you do?(attack or run away)
You see? The above is the program running. I do not see why the value is not being changed.
because you are initializing it at the beginning of the iteration. So just move the
enemyhp= 50
before the while loop, like this
enemyhp= 50
while do != 'hit rat with sword' or 'run away':
Just for fun I've extended your example program to include some more advanced language constructs. May you find it entertaining: (Python 3)
import random
import re
def dice(s, reg=re.compile('(\d+d\d+|\+|\-|\d+)')):
"""
Executes D+D-style dice rolls, ie '2d6 + 3'
"""
total = 0
sign = 1
for symbol in reg.findall(s):
if symbol == '+':
sign = 1
elif symbol == '-':
sign = -1
elif 'd' in symbol:
d,s = [int(k) for k in symbol.split('d')]
for i in range(d):
total += sign * random.randint(1, s)
else:
total += sign * int(symbol)
return total
class Character():
def __init__(self, name, attack, defense, health, weapon):
self.name = name
self.attack = attack
self.defense = defense
self.health = health
self.weapon = weapon
def hit(self, target):
if self.is_dead:
print('{} is trying to become a zombie!'.format(self.name))
return 0
attack = self.attack + self.weapon.attack_bonus + dice('2d6')
defense = target.defense + dice('2d6')
if attack > defense:
damage = int(random.random() * min(attack - defense + 1, self.weapon.damage + 1))
target.health -= damage
print('{} does {} damage to {} with {}'.format(self.name, damage, target.name, self.weapon.name))
return damage
else:
print('{} misses {}'.format(self.name, target.name))
return 0
#property
def is_dead(self):
return self.health <= 0
class Weapon():
def __init__(self, name, attack_bonus, damage):
self.name = name
self.attack_bonus = attack_bonus
self.damage = damage
def main():
name = input("So, what's your name? ")
me = Character(name, 4, 6, 60, Weapon('Old Sword', 2, 4))
mom = Character('Mom', 2, 2, 50, Weapon('Broom', 0, 1))
rat = Character('Crazed Rat', 5, 2, 40, Weapon('Teeth', 1, 2))
print("You are helping your mother clean the basement when a Crazed Rat attacks. "
"You grab your Grandfather's sword from the wall and leap to defend her!")
actors = {me, mom, rat}
coward = False
killer = None
while (me in actors or mom in actors) and rat in actors:
x = random.choice(list(actors))
if x is mom:
mom.hit(rat)
if rat.is_dead:
killer = mom
actors -= {rat}
elif x is rat:
target = random.choice(list(actors - {rat}))
rat.hit(target)
if target.is_dead:
actors -= {target}
if target is mom:
print('Your mother crumples to the floor. AARGH! This rat must die!')
me.attack += 2
else:
print('Well... this is awkward. Looks like Mom will have to finish the job alone...')
else: # your turn!
print('Me: {}, Mom: {}, Rat: {}'.format(me.health, 0 if mom.is_dead else mom.health, rat.health))
do = input('What will you do? [hit] the rat, [run] away, or [swap] weapons with Mom? ')
if do == 'hit':
me.hit(rat)
if rat.is_dead:
killer = me
actors -= {rat}
elif do == 'run':
if me.health < 20:
actors -= {me}
coward = True
else:
print("Don't be such a baby! Get that rat!")
elif do == 'swap':
me.weapon, mom.weapon = mom.weapon, me.weapon
print('You are now armed with the {}'.format(me.weapon.name))
else:
print('Stop wasting time!')
if rat.is_dead:
if mom.is_dead:
print('The rat is gone - but at a terrible cost.')
elif me.is_dead:
print("Your mother buries you with your trusty sword by your side and the rat at your feet.")
elif coward:
print("The rat is gone - but you'd better keep running!")
elif killer is me:
print("Hurrah! Your mother is very impressed, and treats you to a nice cup of tea.")
else:
print('Your mother kills the rat! Treat her to a nice cup of tea before finishing the basement.')
else:
print('I, for one, hail our new rat overlords.')
if __name__=="__main__":
main()

Categories