__init__() missing 7 required positional arguments - python

I want to Inheritance my animal class to Dog class.Everything is good until ı want to write Dog.add_info() at operation 1.I wrote Dog = Dog(animal) at line 46 but ı think there are a problem but ı can't find out what it is.I learning 'class' thing and 'Inheritance' thing first.
import random
class animal():
def __init__(self,name,legs,place,move,weight,lenght):
self.name = name
self.legs = legs
self.place = place
self.move = move
self.weight = weight
self.lenght = lenght
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nLenght: {}".format(self,self.name,self.legs,self.place,self.move,self.weight,self.lenght)
def add_info(self):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_lenght =input("Enter lenght")
self.name = info_name
self.legs = info_legs
self.place = info_place
self.move = info_move
self.weight = info_weight
self.lenght = info_lenght
class Dog(animal):
def __init__(self,name,legs,place,move,weight,lenght,feather,aggresivity):
super().__init__(self,name,legs,place,move,weight,lenght)
self.feather = feather
self.aggresivity = aggresivity
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nLenght: {}\nFeather: {}\nAggresivity {}".format(self, self.name, self.legs,self.place, self.move,self.weight, self.lenght,self.feather,self.aggresivity)
def add_info(self):
super().add_info()
info_feather = input("Enter are your dog have feather or not 'have' or 'haven't")
info_aggresivity =input("Enter are your dog aggresive or passive")
self.feather = info_feather
self.aggresivity = info_aggresivity
def pick_random(self):
list_dog = ["Labrador","Bulldog","Retriever,","Poodle","Beagle","Husky"]
random_dog = random.choice(list_dog)
print("Your dog is :",random_dog)
Dog = Dog(animal)
print("""
1 for add info to your dog
2 for get infos your dog have
3 for pick random dog type
q for quit
""")
choice = input("Enter operation: ")
while True:
if (choice =="q"):
print("BYE...")
break
elif(choice == "1"):
Dog.add_info()
elif(choice =="2"):
pass
elif(choice =="3"):
pass
else:
print("İnvalid operation")

Dog expects all the same arguments as animal; you are passing the class animal itself as a single argument.
Rather than duplicating all the arguments from Animal.__init__, though, use keyword arguments to simplify the definition of Dog.__init__.
First, we'll clean up Animal a little. Note that you were passing self unnecessarily to a lot of methods, as super() already captures the value to pass.
class Animal:
def __init__(self, *, name, legs, place, move, weight, length, **kwargs):
super().__init__(**kwargs)
self.name = name
self.legs = legs
self.place = place
self.move = move
self.weight = weight
self.length = length
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nLength: {}".format(self.name, self.legs, self.place, self.move, self.weight, self.length)
def add_info(self):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_length = input("Enter length")
self.name = info_name
self.legs = info_legs
self.place = info_place
self.move = info_move
self.weight = info_weight
self.length = info_length
Now we define Dog with only the extra arguments; anything intended for the superclass methods will be passed as arbitrary keyword arguments that Dog will pass on.
class Dog(Animal):
def __init__(self, *, feather, aggresivity, **kwargs):
super().__init__(**kwargs)
self.feather = feather
self.aggresivity = aggresivity
def __str__(self):
x = super().__str__()
return x + "\nFeather: {}\nAggresivity {}".format(self.feather, self.aggresivity)
def add_info(self):
super().add_info()
info_feather = input("Enter are your dog have feather or not 'have' or 'haven't")
info_aggresivity =input("Enter are your dog aggresive or passive")
self.feather = info_feather
self.aggresivity = info_aggresivity
def pick_random(self):
list_dog = ["Labrador","Bulldog","Retriever,","Poodle","Beagle","Husky"]
random_dog = random.choice(list_dog)
print("Your dog is :",random_dog)
Finally, we instantiate Dog using keyword arguments.
d = Dog(name="...", legs="...", ...) # etc

When initializing a class, you must provide all of the arguments required by the init method. See this great (and similarly themed) answer which illustrates the right way to initialize a instance:
class Dog:
def __init__(self, legs, colour):
self.legs = legs
self.colour = colour
fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")
In your case, you need to provide all of the required arguments: name, legs, place, move, weight, length, feather, aggresivity.
If you'd like to write a function which helps a user instantiate an instance, you could create a classmethod:
class Animal:
...
#classmethod
def add_info(cls):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_lenght =input("Enter lenght")
return cls(
info_name,
info_legs,
info_place,
info_move,
info_weight,
info_lenght
)
now, calling Animal.add_info() will prompt the user for the correct attributes and then return a properly instantiated object.

This answer is based on the information in my comments above:
import random
class animal():
def __init__(self,name,legs,place,move,weight,length):
self.name = name
self.legs = legs
self.place = place
self.move = move
self.weight = weight
self.length = length
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nlength: {}".format(self,self.name,self.legs,self.place,self.move,self.weight,self.length)
def add_info(self):
info_name = input("Enter name")
info_legs = input("Enter how many legs this animal have")
info_place = input("Enter where this animal live")
info_move = input("Enter how move this animal")
info_weight = input("Enter Weight")
info_length =input("Enter length")
self.name = info_name
self.legs = info_legs
self.place = info_place
self.move = info_move
self.weight = info_weight
self.length = info_length
class Dog(animal):
def __init__(self, name="sparky", legs=4, place="right here", move=True, \
weight="45 pounds", length="30 inches", feather=False, aggresivity="friendly"):
super().__init__(name, legs, place ,move, weight, length)
self.feather = feather
self.aggresivity = aggresivity
def __str__(self):
return "Name: {}\nLegs: {}\nPlace: {}\nMove: {}\nWeight: {}\nlength: {}\nFeather: {}\nAggresivity {}".format(self, self.name, self.legs,self.place, self.move,self.weight, self.length,self.feather,self.aggresivity)
def add_info(self):
super().add_info()
info_feather = input("Enter are your dog have feather or not 'have' or 'haven't")
info_aggresivity =input("Enter are your dog aggresive or passive")
self.feather = info_feather
self.aggresivity = info_aggresivity
def pick_random(self):
list_dog = ["Labrador","Bulldog","Retriever,","Poodle","Beagle","Husky"]
random_dog = random.choice(list_dog)
print("Your dog is :",random_dog)
Dog = Dog()
print("""
1 for add info to your dog
2 for get infos your dog have
3 for pick random dog type
q for quit
""")
while True:
choice = input("Enter operation: ")
if (choice =="q"):
print("BYE...")
break
elif(choice == "1"):
Dog.add_info()
elif(choice =="2"):
pass
elif(choice =="3"):
pass
else:
print("İnvalid operation")

Related

My function menu.displayHomeMenu(m) is stuck in an infinite loop. Why?

In the code below, I want the menu to display and prompt the user for a selection. Based on the selection, I want to move on to the following if statements which allow the user to define the attributes of their vehicle. The code worked before I put the menu in a function, but this format is required for my assignment. No errors. It simply prompts for a selection over and over again. Any suggestions?
class Menu:
""" Create a Menu """
def __init__(self):
self.selection = selection
def displayHomeMenu(self):
if 2 == vehicleCount:
print("----Press 1 for car ")
print("----Press 2 for pickup ")
selection = input("----Press 3 to quit ")
return selection
else:
print("----Press 1 for car ")
selection = input("----Press 2 for pickup ")
return selection
class Vehicle:
""" Model a vehicle"""
def __init__(self, make = " ", model = "n/a", color = "n/a ", fuelType = "n/a ", *options):
""" Initialize vehicle attributes """
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = {"power windows", "powerlocks", "remote start", "backup camera", "bluetooth", "cruise control", "heated seats", "heated steering wheel"}
def getMake(self):
self.make = input("Please enter your make ")
return self.make
def getModel(self):
self.model = input("Please enter your model ")
return self.model
def getColor(self):
self.color = input("Please enter the color ")
return self.color
def getFuelType(self):
self.fuelType = input("Please enter your fuel type ")
return self.fuelType
def getOptions(self):
print("Please select from the following options: ")
input(self.options)
return self.options
class Car(Vehicle):
"""Represents a car"""
def __init__(self, make = "n/a ", model = "n/a", color = "n/a ", fuelType = "n/a "):
super().__init__(make, model, color, fuelType)
""" Initialize car attributes"""
self.engineSize = " "
self.numDoors = " "
def getEngineSize(self):
self.engineSize = input("Please enter your engine size ")
return self.engineSize
def getNumDoors(self):
self.numDoors = input("How many doors do you have ")
return self.numDoors
class pickup(Vehicle):
"""Represents a pickup"""
def __init__(self, make = " ", model = " ", color = " ", fuelType = " "):
super().__init__(make, model, color, fuelType)
""" Initialize pickup attributes """
self.cabStyle = " "
self.bedLength = " "
def getCabStyle(self):
self.cabStyle = input("Please enter your cab style ")
def getBedLength(self):
self.bedLength = input("Please enter the length of your bed ")
i = 0
list = []
vehicleCount = 0
carCount = 0
pickupCount = 0
selection = 0
while True:
vehicleCount = pickupCount + carCount
m = Menu()
Menu.displayHomeMenu(m)
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)
You are not using the return value from displayHomeMenu():
while True:
vehicleCount = pickupCount + carCount
m = Menu()
selection = m.displayHomeMenu() # Assign the return value to selection
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)

How do I print out a list of objects?

I have been trying to get my objects to be printed out as list. The list is the inventory. It should be printed out by typing i. But I only an error that shows there objects in a list that can't be printed. I keep getting an error. Please can you help me?
def play():
while True:
Action_input = get_player_action()
if Action_input in ["n","North"]:
print("Go North")
elif Action_input in ["s","South"]:
print("Go South")
elif Action_input in ["e","East"]:
print("Go East")
elif Action_input in ["w","West"]:
print("Go West")
elif Action_input in ["i","I"]:
print("Inventory")
for i in inventory:
print(inventory)
else:
print("Not an availble direction. Use only n,e,w,s,North,South,East, or West")
class Resources:
def __init__(self):
self.name = name
self.description = description
self.health = health
def __str__(self):
return " Name: " + self.name + "Description: " + str(self.description) + " Damage: " + str(self.damage)
class bread(Resources):
def __init__(self):
self.name = "bread"
self.description = "A kind of food that is cheap and nice."
self.health = 4
class pako(Resources):
def __init__(self):
self.name = "pako"
self.description = "A long piece of wood that can be used as a weapon"
self.damage = 10
class punch(Resources):
def __init__(self):
self.name = "punch"
self.description = "Using the fist to strike"
self.damage = 6
class owo(Resources):
def __init__(self):
self.name = "owo"
self.description = "What you use to buy goods or services"
self.value = 10
def get_player_action():
return input("What is your move?")
def best_attack_move(inventory):
Max_Attack = 0
Best_attack_move = None
for item in inventory:
if item.damage > Max_Attack:
Best_attack_move = item
Max_Attack = item.damage
return Best_attack_move
inventory = [bread(),pako(),punch(),owo()]
play()
Error:
What is your move?i
Inventory
[<main.bread object at 0x02ADC418>, <main.pako object at 0x02ADC448>, <main.punch object at 0x02ADC478>, <main.owo object at 0x02ADC4A8>]
[<main.bread object at 0x02ADC418>, <main.pako object at 0x02ADC448>, <main.punch object at 0x02ADC478>, <main.owo object at 0x02ADC4A8>]
[<main.bread object at 0x02ADC418>, <main.pako object at 0x02ADC448>, <main.punch object at 0x02ADC478>, <main.owo object at 0x02ADC4A8>]
[<main.bread object at 0x02ADC418>, <main.pako object at 0x02ADC448>, <main.punch object at 0x02ADC478>, <main.owo object at 0x02ADC4A8>]
What is your move?
a simple solution to your problem is in for loop.
elif Action_input in ["i","I"]:
print("Inventory")
for i in inventory:
print(i)
Replace inventory by i. also there are few errors as described below.
In bread class
class bread(Resources):
def __init__(self):
self.name = "bread"
self.description = "A kind of food that is cheap and nice."
self.health = 4
replace self.health by self.damage
and same for owo class
class owo(Resources):
def __init__(self):
self.name = "owo"
self.description = "What you use to buy goods or services"
self.damage = 10
replace self.value by above
Your final code should look alike
def play():
while True:
Action_input = get_player_action()
if Action_input in ["n","North"]:
print("Go North")
elif Action_input in ["s","South"]:
print("Go South")
elif Action_input in ["e","East"]:
print("Go East")
elif Action_input in ["w","West"]:
print("Go West")
elif Action_input in ["i","I"]:
print("Inventory")
for i in inventory:
print(i)
else:
print("Not an availble direction. Use only n,e,w,s,North,South,East, or West")
class Resources:
def __init__(self):
self.name = name
self.description = description
self.health = health
def __str__(self):
return " Name: " + self.name + "\n Description: " + str(self.description) + "\n Damage: " + str(self.damage)
class bread(Resources):
def __init__(self):
self.name = "bread"
self.description = "A kind of food that is cheap and nice."
self.damage = 4
class pako(Resources):
def __init__(self):
self.name = "pako"
self.description = "A long piece of wood that can be used as a weapon"
self.damage = 10
class punch(Resources):
def __init__(self):
self.name = "punch"
self.description = "Using the fist to strike"
self.damage = 6
class owo(Resources):
def __init__(self):
self.name = "owo"
self.description = "What you use to buy goods or services"
self.damage = 10
def get_player_action():
return input("What is your move?")
def best_attack_move(inventory):
Max_Attack = 0
Best_attack_move = None
for item in inventory:
if item.damage > Max_Attack:
Best_attack_move = item
Max_Attack = item.damage
return Best_attack_move
inventory = [bread(),pako(),punch(),owo()]
play()
You need to put every instance of the inventory variable inside str(), and also.
inventory = [str(bread()),str(pako()),str(punch()),str(owo())]
(By the way, the bread and owo have no damage attribute, so you will get an error about it)

Is there a better way to print more than 1 student with object oriented programming?

is there any way to print each new student without copping and pasting the code like I have done below? Could it be possible to use a loop or something like that?
class Student:
def __init__(self, name, course, age):
self.name = name
self.course = course
self.age = age
def roomNumber(self):
if self.course == "Computing":
room = "S227"
elif self.course == "Art":
room = "Art Studio 1"
else:
room = "Main hall"
return (room)
def parientSign(self):
if self.age > 17:
print("Parent doesn't need to sign")
else:
print("Parent needs to sign")
return
newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)
print("Student Name: ", newStudent.name)
print("Student Course: ",newStudent.course)
print("Your room number is: ", newStudent.roomNumber())
print("Your Age is: ",newStudent.age)
newStudent.parientSign()
print ("\n--------------\n")
print("Student Name: ", newStudent1.name)
print("Student Course: ",newStudent1.course)
print("Your room number is: ", newStudent1.roomNumber())
print("Your Age is: ",newStudent1.age)
newStudent1.parientSign()
print ("\n--------------\n")
print("Student Name: ", newStudent2.name)
print("Student Course: ",newStudent2.course)
print("Your room number is: ", newStudent2.roomNumber())
print("Your Age is: ",newStudent2.age)
newStudent2.parientSign()
print ("\n--------------\n")
Credit & as mentioned by DeepSpace in comments
You can try something like this:
class Student:
def __init__(self, name, course, age):
self.name = name
self.course = course
self.age = age
def __str__(self):
return """Student Name: %s\n
Student Course: %s\n
Your room number is: %s\n
Your Age is: %s\n
%s""" % (self.name, self.course, self.age, self.roomNumber(), self.parentSign())
def roomNumber(self):
if self.course == "Computing":
room = "S227"
elif self.course == "Art":
room = "Art Studio 1"
else:
room = "Main hall"
return (room)
def parentSign(self):
return "Parent doesn't need to sign" if self.age > 17 else "Parent needs to sign"
newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)
print(newStudent)
print(newStudent1)
print(newStudent2)
class Student:
def __init__(self, name, course, age):
self.name = name
self.course = course
self.age = age
def roomNumber(self):
if self.course == "Computing":
room = "S227"
elif self.course == "Art":
room = "Art Studio 1"
else:
room = "Main hall"
return (room)
def parientSign(self):
if self.age > 17:
print("Parent doesn't need to sign")
else:
print("Parent needs to sign")
return
def printStudent(self):
print("Student Name: ", self.name)
print("Student Course: ", self.course)
print("Your room number is: ", self.roomNumber())
print("Your Age is: ", self.age)
studentList = []
studentList.append(Student("Name One", "Computing", 18))
studentList.append(Student("Bob Smart", "Art", 19))
studentList.append(Student("Big Terry", "Computing", 16))
for student in studentList:
student.printStudent()
student.parientSign()
print("------------")
You can create a printer function and create your students inside your list and loop over them to print their properties
There are many ways to solve this problem.
The Way I prefer is by using the __repr__ method of the class
Here's an implementation:
class Student:
def __init__(self, name, course, age):
self.name = name
self.course = course
self.age = age
def roomNumber(self):
if self.course == "Computing":
room = "S227"
elif self.course == "Art":
room = "Art Studio 1"
else:
room = "Main hall"
return (room)
def parientSign(self):
if self.age > 17:
print("Parent doesn't need to sign")
else:
print("Parent needs to sign")
return
def __repr__(self):
return "Student({},{},{})".format(self.name, self.course,self.age)
newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)
print(newStudent,newStudent1,newStudent2,sep = "\n")
I assume that the use of the __repr__ method is self explanatory. You can basically print the class name and all it's attributes
Another (not recommended) way to do this is by using the list of the the students object.
class Student:
def __init__(self, name, course, age):
self.name = name
self.course = course
self.age = age
def roomNumber(self):
if self.course == "Computing":
room = "S227"
elif self.course == "Art":
room = "Art Studio 1"
else:
room = "Main hall"
return (room)
def parientSign(self):
if self.age > 17:
print("Parent doesn't need to sign")
else:
print("Parent needs to sign")
return
newStudent = Student("Name One", "Computing", 18)
newStudent1 = Student("Bob Smart", "Art", 19)
newStudent2 = Student("Big Terry", "Computing", 16)
l = [newStudent,newStudent1,newStudent2]
for students in l:
print("Student Name: ", students.name)
print("Student Course: ",students.course)
print("Your room number is: ", students.roomNumber())
print("Your Age is: ",students.age)
students.parientSign()

How to make an inventory program execute

I'm still learning python. I am trying to write a program that develops a car inventory. I am creating an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class:
private string make
private string model
private string color
private int year
private int mileage
How can I make this execute and give prompts for input. It's not doing it.
class Automobile():
__make = ""
__model = ""
__color = ""
__year = 0
__mileage = 0
def __init__(self, make = None, model = None, color = None, year = None, mileage = None):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
def add_vehicle(self):
auto = Automobile()
vehicle_file = open('vehicle.txt', 'a')
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = input("Enter year: ")
mileage = input("Enter mileage: ")
vehicles = Automobile(make, model, color, year, mileage)
vehicle_list = [vehicles.make, vehicles.model, vehicles.color, vehicles.year, vehicles.mileage]
for item in vehicle_list:
vehicle_file.write("%s\t" % item)
vehicle_file.write("\n")
vehicle_file.close()
print("Your record has been succesfully added to the inventory")
def delete_vehicle(self):
del_rec = input("Enter record to delete: ")
with open("vehicle.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if del_rec not in line:
f.write(line)
f.truncate()
print("Succesfully deleted record from inventory")
def set_make(self, make):
self.make = make
def get_make(self):
return self.make
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def set_year(self, year):
self.year = year
def get_year(self):
return self.year
def set_mileage(self, mileage):
self.mileage = mileage
def get_mileage(self):
return self.mileage

Inheritance issue I don't understand

I'm a beginner and stumbled across an issue with inheritance.
When I use this block of code, the program doesn't work correctly thanks to a line in the enter function:
class Bathroom(Room):
def __init__(self):
super(Bathroom, self).__init__("bathroom")
def enter(self, world, player):
super(Bathroom, self).enter(world, player)
But, when I use this, it does:
class Bathroom(Room):
def __init__(self):
super(Bathroom, self).__init__("bathroom")
Are they not the same thing?
The full script I've written (not finished btw) is below. When I enter 'y' after being asked 'Do you want to leave', the program finishes when I use 'super' to inherit the enter function. If I don't, the program works:
while player and self.name != "corridor":
response = self._ask_question("Do you want to leave? (y/n) ", "y", "n")
if response == "y":
return world.corridor
elif response == "n" and self.enemy:
print("The", self.enemy, "kills you. You didn't even put up a\
fight")
return world.death
Full script:
import random
import time
# bad from sys import exit
class Character(object):
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
def __str__(self):
return str(self.health) + " health and " + str(self.attack) + " attack."
class Room(object):
def __init__(self, name):
self.name = name
self.enemy = self._getRandEnemy()
def enter(self, world, player):
print(player.name + ",", "you are in the", self.name + ". You have\
" + str(player))
if self.enemy: # you may have killed it
print("But, wait! There's a", self.enemy.name, "with " + str(\
self.enemy))
response = self._ask_question("Do you stay and fight?(y/n)\
", "n", "y")
if response == "n":
pass
if response == "y":
self.combat(player, self.enemy)
else:
print("No enemies here.")
# check if player has no health after potential fight
if player.health < 1:
return world.death
while player and self.name != "corridor":
response = self._ask_question("Do you want to leave? (y/n) ", "y", "n")
if response == "y":
return world.corridor
elif response == "n" and self.enemy:
print("The", self.enemy, "kills you. You didn't even put up a\
fight")
return world.death
def _getRandEnemy(self):
names = ["Troll", "Witch", "Ogre", "Jeremy Corbyn"]
return Character(random.choice(names), random.randint(4, 6),\
random.randint(2, 3))
def _ask_question(self, question, a, b):
response = None
while response not in(a, b):
response = input(question)
return response
def combat(self, player, enemy):
while player.health > 0 and enemy.health > 0:
time.sleep(1)
print("You attack and deal", player.attack, "damage")
enemy.health -= player.attack
if enemy.health >= 1:
print("The enemy has " + str(self.enemy))
time.sleep(1)
print("The", self.enemy.name, "attacks and deals you",\
self.enemy.attack, "\
damage.")
player.health -= enemy.attack
print("You have " + str(player))
if player.health < 1:
pass
if enemy.health < 1:
print("Ha! Got him!")
self.enemy = None
class Corridor(Room):
def __init__(self):
self.name = "corridor"
self.enemy = None
def enter(self, world, player):
super(Corridor, self).enter(world, player)
room = self._ask_question("Which room: bathroom, bedroom ",\
"bedroom", "bathroom", "Library", "study")
if room == "bedroom":
return world.bedroom
if room == "bathroom":
return world.bathroom
class Bathroom(Room):
def __init__(self):
super(Bathroom, self).__init__("bathroom")
def enter(self, world, player):
super(Bathroom, self).enter(world, player)
class Bedroom(Room):
def __init__(self):
super(Bedroom, self).__init__("bedroom")
class Death(Room):
def __init__(self):
super(Death, self).__init__("death")
def enter(self, world, player):
time.sleep(1)
responses = ["Off to the man in sky. You are dead", "You died,\
no-one cried.", "Lolz. You're dead!"]
print(random.choice(responses))
return None
class World(object):
def __init__(self):
self.corridor = Corridor()
self.bathroom = Bathroom()
self.death = Death()
self.bedroom = Bedroom()
self.start = self.corridor
def play_game(world, player):
room = world.start
while room:
room = room.enter(world, player)
play_game(World(), Character("Bob", 12, 2))
I know I must be missing something obvious.
Thanks, Dave.
You forgot to return the result of the super().enter() call. You are swallowing the return value, so you never returned the new room. The following would be correct:
class Bathroom(Room):
def enter(self, world, player):
return super(Bathroom, self).enter(world, player)
Not that there is a point in defining a new Bathroom().enter() method if all you do is call the original version with super(). You may as well remove the whole enter() method (as I've done for the __init__ method, above).

Categories

Resources