Can you put new if statements into a child class from a parent class (probably phrased wrong) - python

So I want to have 'if Battle_Option == "E", do this in the Battle() class, but if its in the Wizard_Battle() class I want it to do something different, is there any way to do it?
I deleted the code a bit to only show important lines
class Battle():
Battle_Option = input("What will you do? \n W.Attack \n E.Special
Move \n R.Guard \n T.Wait").upper()
if Battle_Option == "E":
print("You pick up your magical spear and yes")
class Wizard_Battle(Battle):
def __init__(self):
Battle.__init__(self)
def Yourturn(self):
global Battle_Option
if Battle_Option == "E":
print("You wizarded")

You can access it through Battle:
class Wizard_Battle(Battle):
def __init__(self):
Battle.__init__(self)
def Yourturn(self):
if Battle.Battle_Option == "E":
print("You wizarded")
Here you have the live example

If something is to be specialized in a subclass, it should be a method that is overriden in the subclass:
class Battle():
...
Battle_Option = input("What will you do? \n W.Attack \n E.Special
Move \n R.Guard \n T.Wait").upper()
if Battle_Option == "E":
self.e_battle()
...
def e_battle(self):
print("You pick up your magical spear and yes")
class Wizard_Battle(Battle):
...
def e_battle(self):
print("You wizarded")

Related

Adding a combat system to a text adventure game; confused by the structure of the code I'm using

Through some educational materials I've been tasked to use the below structure (the classes) for a text adventure game and am required to add a simple combat system for battle between a hero and an enemy.
Currently I am able to have an enemy created in each room and move between the start room(corridor) to the bathroom and back, but at this point I'm stuck. I can't determine where I should be creating my 'hero' or how I'd communicate the changes I'd need to make to the health attributes etc.
If I could structure the code in another way, I would be able to complete the game, but as it is there is a gap in my understanding of how to enable various sections of code communicate with each other.
Thanks,
Dave
# text based adventure game
import random
import time
from sys import exit
class Game(object):
def __init__(self, room_map):
self.room_map = room_map
def play(self):
current_room = self.room_map.opening_room()
while True:
next_room_name = current_room.enter()
current_room = self.room_map.next_room(next_room_name)
class Character(object):
def __init__(self, name, health, attack):
self.name = name
self.health = health
self.attack = attack
class Hero(Character):
def __init__(self, name):
super(Hero, self).__init__(name, 10, 2)
def __str__(self):
rep = "You, " + self.name + ", have " + str(self.health) + " health and " + \
str(self.attack) + " attack."
return rep
class Enemy(Character):
ENEMIES = ["Troll", "Witch", "Ogre", "Jeremy Corbyn"]
def __init__(self):
super(Enemy, self).__init__(random.choice(self.ENEMIES),
random.randint(4, 6), random.randint(2, 4))
def __str__(self):
rep = "The " + self.name + " has " + str(self.health) + \
" health, and " + str(self.attack) + " attack."
return rep
class Room(object):
def __init__(self):
self.commands = ["yes", "no"]
self.rooms = ["\'corridor\'", "\'bathroom\'", "\'bedroom\'"]
self.enemy = Enemy()
def command_list(self):
print("Commands: ", ", ".join(self.commands))
def enter_room_question(self):
print("Which room would you like to enter?")
print("Rooms:", ", ".join(self.rooms))
def leave_room_question(self):
print("Do you want to leave this room?")
print("Commands:", ", ".join(self.commands))
class Bathroom(Room):
def enter(self):
print("You enter the bathroom. But, wait! There is an", \
self.enemy.name, "!")
print(self.enemy)
print("You are in the bathroom. Need to take a dump? ")
self.command_list()
response = input("> ")
while response not in self.commands:
print("Sorry I didn't recognise that answer")
print("You are in the bathroom. Need to take a dump?")
self.command_list()
response = input("> ")
if response == "yes":
print("Not while I'm here!")
return "death"
elif response == "no":
print("Good.")
self.leave_room_question()
response = input("> ")
if response == "yes":
return "corridor"
else:
return "death"
class Bedroom(Room):
def enter(self):
pass
class Landing(Room):
def enter(self):
pass
class Corridor(Room):
def enter(self):
print("You are standing in the corridor. There are two rooms available to enter.")
self.enter_room_question()
response = input("> ")
if response == "corridor":
print("You're already here silly.")
else:
return response
class Death(Room):
QUIPS = ["Off to the man in sky. You are dead",
"You died, no-one cried.",
"Lolz. You're dead!"]
def enter(self):
time.sleep(1)
print(random.choice(Death.QUIPS))
exit()
class Map(object):
ROOMS = {"corridor": Corridor(),
"bathroom": Bathroom(),
"death": Death(),
"landing": Landing(),
"bedroom": Bedroom()}
def __init__(self, start_room):
self.start_room = start_room
self.hero = hero
def next_room(self, room_name):
return Map.ROOMS.get(room_name)
def opening_room(self):
return self.next_room(self.start_room)
a_hero = Hero("Dave")
a_map = Map("corridor")
a_game = Game(a_map, a_hero)
a_game.play()
If I were you, I would set out a game schema. You could find out asking yourself questions like this:
What are the really important entities?
In your case, as you have done, I would consider Character, Enemy, Room and Map, inheriting when it would be appropiate, like Character-> Hero and Enemy, and several types of room from Room as Bathroom, Corridor, ...
If I were you a consider using a data structure to represent the Map. For example, if you are considering do a text game adventure, you could think in different rooms as different states in your game. If you are in the bathroom, you could be attacked by an enemy and if you are in the bedroom, you can retrieve your hitpoints (life) so these places can be thought as different states.
As an example, you would an array for group all your different rooms (states)
rooms = ["bedroom", "bathroom", "corridor", "kitchen", "living_room"]
and other rooms that you can think about.
(there is probably a better example, more efficient and so on, so this example is to help you about not giving up when you gets stuck about an problem.
According to this example, if you use an array, you can assign a value to each room (equal to each position in the array)
Moreover, you will need to know the hero's position, so you could assign a random value to it using rand(). You can read links below for more information:
random docs python
stackoverflow answer
At last, you also would find useful to compare the hero's position, which would have a random assigned value previously with every position of your array or rooms
In this cases, you could use a if... elif.. elif... to compare those values and do something according to the room where your hero would be.
I hope this answer will be useful for you.
Let me know if you have any doubt about my answer.
Cheers

How to compare 2 objects from a class

I have created a class called Dog_card. With this, I created player_card and computer_card. I am trying to compare the same attribute from both of these objects. There are more values to each than friendliness, but I have removed them so it is easier to test. I keep getting the error:
NameError: name 'player_card' is not defined
Here is my code:
class Dog_card:
def __init__(self):
self.name = ""
self.friendliness = ""
def printing_card(self):
prnt_str = "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
return prnt_str
def printing_player_card():
player_card = Dog_card()
player_card.name = dogs_list_player[0]
player_card.friendliness = random.randint(1,101)
def printing_computer_card():
computer_card = Dog_card()
computer_card.name = dogs_list_computer[0]
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")
Any help would be appreciated
The problem is as it's stated in the error. Basically you are trying to use player_card when it is not defined inside the definition of choose_category(). I suggest you pass the value of player_card to the function like the following
def choose_category(player_card):
or you can define it as an attribute so that it can be accessed by the methods of the same class.
you need to initialize play_card before using it. Maybe you call printing_player_card in order to intnialize before, but as you don't return anything from that function, the created object and the variable player_card only lives in scope of the function. When that function finished, player_card object variable is unknown and the object is destroyed.
if you want player_card (as well as computer_card) survice its function, you need to return it an save it to a variable outside the function code.
Furthermore your function name "printing" is bad, as you don't print anything. You just initialize your object.
Maybe that's what you are aiming at.
class Dog_card:
def __init__(self, name, friendliness=1):
self.name = name
self.friendliness = friendliness
def __str__(self):
return "Name: %s \nIntelligence: %s" %(self.name, self.friendliness)
player_card = Dog_card(dogs_list_player[0], random.randint(1,101))
computer_card = Dog_card(dogs_list_copmuter[0])
def choose_category():
user_choice_category = input("Please choose a category: ")
if user_choice_category not in ["1", "2", "3", "4"]:
print("Please choose from the options above")
choose_category()
else:
if user_choice_category == "1":
if player_card.friendliness > computer_card.friendliness:
print("Player has won the round!")
elif player_card.friendliness == computer_card.friendliness:
print("It is a Draw!")

Attribute in a Class immediately runs at the wrong time?

I am fairly new to Python and I am learning how classes and methods interact by creating a text-based game. The code runs great, however, my question lies in the Name(object) class. Wherever I put it in the code, (in the beginning or in the middle as shown below) I will always be prompted with an input. I suspect it may be because of the attribute name_new that prompts raw_input("> "), however, I was wondering if there was a way to prevent or change when the Class Name() is prompted.
class Character(object):
def __init__(self, name, weapon, spec_ability, health):
self.name = name
self.weapon = weapon
self.spec_ability = spec_ability
self.health = 100
def special_ability(self):
special = False
rand_num = str(random.choice(rdm))
if '1' in rand_num or '2' in rand_num or '3' in rand_num:
special = True
if special:
print "Your special ability is ready."
return True
else:
return
else:
print "Your special ability is not ready."
def Critical_Chance(self):
crit = False
rand_num = str(random.choice(rdm))
if '1' in rand_num or '2' in rand_num or '3' in rand_num:
crit = True
if crit:
print "Critical hit incoming."
return True
else:
return
class Warrior(Character):
def __init__(self, name, weapon, spec_ability, health, armor):
super(Warrior, self).__init__(name, weapon, spec_ability, health)
self.armor = armor
class Mage(Character):
def __init__(self, name, weapon, spec_ability, health, cloak):
super(Mage, self).__init__(name, weapon, spec_ability, health)
self.cloak = cloak
class Rogue(Character):
def __init__(self, name, weapon, spec_ability, health, boots):
super(Rogue, self).__init__(name, weapon, spec_ability, health)
class Name(object):
name_new = raw_input("> ")
def start():
print """\nWelcome to the world of _______. \n
You are a young hero or heroine
in search of the gold that hides within the Mountains of _____.
In order to obtain the gold and treasure that lies within the
mountains, you must battle great monsters and face dangerous
perils."""
print "Will you pursue such adventure? Or will you refuse?"
choice = raw_input("> ")
if "Yes" in choice or "yes" in choice:
Introduction()
elif "No" in choice or "no" in choice:
sys.exit()
else:
print "You typed: %s. \nPlease try again." % choice
start()
def Introduction():
print "Thank you for joining in on this adventure..."
print "Well, welcome to your adventure for the gold."
print "You will encounter dangerouse quests and enemies, but you will be\
rewarded in the end."
print "Now, what class will you be?\n\
Warrior Mage Rogue"
char_choice = raw_input("> ")
verynew_name = Name()
name_choice = Name.name_new
if "Warrior" in char_choice or "warrior" in char_choice:
name_choice = Warrior(name_choice, None, None, None, None)
print name_choice.name
print name_choice.weapon
print name_choice.spec_ability
print name_choice.health
print name_choice.armor
elif "Mage" in char_choice or "mage" in char_choice:
name_choice = Mage(name_choice, None, None, None, None)
print name_choice.name
print name_choice.weapon
print name_choice.spec_ability
print name_choice.health
print name_choice.cloak
elif "Rogue" in char_choice or "rogue" in char_choice:
name_choice = Rogue(name_choice, None, None, None, None)
print name_choice.name
print name_choice.weapon
print name_choice.spec_ability
print name_choice.health
print name_choice.boots
else:
print "You must pick a class."
start()
print "Our story starts in the town of Larton."
#super(Larton, self).enter()
start()
When you run your program, the module-level code is executed. This includes your Name class.
class Name(object):
name_new = raw_input("> ")
This creates the class Name and also executes the code within the class. Which is why you're prompted to enter a name.
If you want to be able to prompt the user for a name like this
verynew_name = Name()
you have to change your Name class so that raw_input is executed when you instantiate the class (because that's what Name() does, it creates an instance of Name):
class Name(object):
def __init__(self):
self.name_new = raw_input("> ")
(Note that instead of name_choice = Name.name_new you'll have to use name_choice = verynew_name.name_new.)
define constructors for your Character class and subclasses that don't take a name as a paramter:
e.g.
class Warrior(Character):
def __init__(self, weapon, spec_ability, health, armor):
super(Warrior, self).__init__(weapon, spec_ability, health)
self.armor = armor
and in character class, you can define self.name to be None by default
You can always assign the name later on in the logic, by using something like
character.name = Name.name_new
As long as you do that before you actually read the value of name, you will be fine

Class selector for a beginning of a game

Why wont it work.
Its a simple selection code that lets you select a character
import random
def Number():
print ("1:Warrior")
print ("2:Ninja")
print ("3:Wizard")
print ("4:Terrorist")
print ("5:Sniper")
print ()
ClassNo = input("Pick you class:\n")
return ClassNo
def Class(ClassNo):
Class = ""
if ClassNo == 1:
Class = "Warrior"
print ("you picked" ,Class)
elif ClassNo == 2:
Class = "Ninja"
print ("you picked Ninja")
elif ClassNo == 3:
Class = "Wizard"
print ("you picked" ,Class)
elif ClassNo == 4:
Class = "Terrorist"
print ("you picked" ,Class)
elif ClassNo == 5:
Class = "Sniper"
print ("you picked" ,Class)
return Class
Number()
Class(ClassNo)
print (Class)
It keeps saying that ClassNo inst defined but then when I define it is come up with and error
plz help
You need to catch the return value of the Number function, ie:
classNo = Number();
playerClass = Class(classNo)
print playerClass
A few other pointers. By convention, we use lower_case or camelCase for variable and function names and we use Capital letters for Class names. Also, if you're using a lot of elif in a row you probably want a dictionary. Here is an example:
possibleClasses = {1:"Warrior",
2:"Ninja",
3:"Wizard",
4:"Terrorist",
5:"Sniper"}
def pickClass():
for number, playerClass in possibleClasses.items():
print number, ":", playerClass
classNo = raw_input("Pick you class:\n")
classNo = int(classNo)
return classNo
playerClass = pickClass()
className = possibleClasses[playerClass]
print className
My first comment here, Im also pretty noob at python but I believe that the only input you have is within a single function, therefore that input is discarded when you get out of that function.
You should prompt for the class input outside of the function so it can be used globally in your code.
If I am wrong, I'd be happy for someone to whack me over the head...

Problems accessing a class's variable in Python

New learner here. I tried the methods indicated here but was unsuccessful. Can you please help me out with the following code. I can't seem to get the Escape Pod class to access the gothonlife variable in the Central Corridor class. Keep getting this error message "type object 'CentralCorridor' has no attribute 'gothonlife'? Thank you!
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self, scene_map):
print "On the floor you find a map with the following options. \n 1) Central Corridor \n 2) Laser Weapon Armory \n 3) The Bridge \n 4) Escape Pod. \n Where do you want to go?"
door = raw_input("> ")
count = 0
while (count < 1):
if door == "Central Corridor":
count = count + 1
object1 = CentralCorridor()
object1.enter()
elif door == "Laser Weapon Armory":
count = count + 1
elif door == "The Bridge":
count = count + 1
elif door == "Escape Pod":
count = count + 1
object5 = EscapePod()
object5.enter()
else:
print "Erm... where exactly do you want to go again?"
door = raw_input("> ")
class Death(Scene):
def enter(self):
print "You die, thanks for playing. Hope you had fun."
class CentralCorridor(Scene):
def enter(self):
print "There stands a Gothon. What do you want to do with him? \n 1) Offensive attack \n 2) Defensive attack \n 3) Suicide"
gothonlife = 10
herolife = 10
def __init__(self):
self.gothonlife = gothonlife
while (gothonlife > 0 and herolife > 0):
action = raw_input("What now? Offensive attack, defensive attack or suicide?")
if action == "Offensive attack":
gothonlife = gothonlife -3
herolife = herolife -2
print "your life stands at %s, the enemy life be at %s" % (herolife, gothonlife)
elif action == "Defensive attack":
gothonlife = gothonlife -2
herolife = herolife -0
print "your life stands at %s, the enemy life be at %s" % (herolife, gothonlife)
elif action == "Suicide":
herolife = herolife -11
print "your life stands at %s, the enemy life be at %s" % (herolife, gothonlife)
else:
print "Erm... where exactly do you want to go again?"
if herolife <0:
object2 = Death()
object2.enter()
elif herolife >0:
print "You defeated the Gothon, where do you want to go next?"
object3 = EscapePod()
object3.enter()
class LaserWeaponArmory(Scene):
def enter(self):
pass
class TheBridge(Scene):
def enter(self):
pass
class EscapePod(CentralCorridor):
def enter(self):
if CentralCorridor.gothonlife > 0:
print "A gothon stands guarding the escape pod."
object4 = CentralCorridor()
object4.enter()
elif CentralCorridor.gothonlife < 0:
print "You escape from Gothon! Congrats!"
class Map(object):
def __init__(self, start_scene):
print "You are at the entrance, there is a Gothon in front of you"
def next_scene(self, scene_name):
pass
def opening_scene(self):
pass
a_map = Map('central_corridor')
a_game = Engine(a_map)

Resources