Question

I need help with this problem. Using Python please. Thanks Construct a class “Monster” with the...

I need help with this problem. Using Python please. Thanks

Construct a class “Monster” with the following attributes:

  1. self.name (a string)
  2. self.type (a string, default is ‘Normal’)
  3. self.current_hp (int, starts out equal to max_hp)
  4. self.max_hp (int, is given as input when the class instance is created, default is 20)
  5. self.exp (int, starts at 0, is increased by fighting)
  6. self.attacks (a dict of all known attacks)
  7. self.possible_attacks (a dictionary of all possible attacks

The dictionary of possible_attacks will map the name of an attack (the key) to how many points of damage the attack does. These are all the possible attacks with their corresponding damage points.

  1. sneak_attack: 1
  2. slash: 2
  3. ice_storm: 3
  4. fire_storm: 3
  5. whirlwind: 3
  6. earthquake: 2
  7. double_hit: 4
  8. wait: 0

Every monster will start out with only the “wait” attack within self.attacks, but you will need to construct the method add_attacks and method remove_attacks. Both methods will take in an attack_name as a parameter.

A monster can only to have a max of four attacks at a time. If you add an attack when the monster already has four, the weakest one should be dropped automatically. If there is a tie for weakest attack, drop the attack that comes first alphabetically. If adding the attack ended successfully return True if you try to add an invalid attack return False.

If all of a monster’s attacks are removed, “wait” should automatically be added again, so that every monster always has at least 1 attack. If removing an attack ended successfully return True if you try to remove an invalid or an attack which has not been learned return False.

Sample Input 1:

car = Monster("carina", 3)
mat = Monster("matthew", 3)
print(car.name)
print(mat.name)

Sample Output 1:

carina
matthew

Sample Input 2:

bob = Monster("bob", 2)
print(bob.add_attack("ice_storm"))
print(bob.add_attack("ice_storm2"))

Sample Output 2:

True
False

Sample Input 3:

mark = Monster("mark", 3)
print(mark.remove_attack("wait"))
print(mark.add_attack("fire_storm"))
print(mark.attacks)

Sample Output 3:

True
True
{'wait': 0, 'fire_storm': 3}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Python Code:

'''
Constructing Monster class with following attributes
* self.name (a string)
* self.type (a string, default is 'Normal')
* self.current_hp (int, starts out equal to max_hp)
* self.max_hp (int, is given as input when the class instance is created, default is 20)
* self.exp (int, starts at 0, is increased by fighting)
* self.attacks (a dict of all known attacks)
* self.possible_attacks (a dictionary of all possible attacks)
The dictionary of possible_attacks will map the name of an attack (the key) to how many
points of damage the attack does. These are all the possible attacks with their
corresponding damage points.

   sneak_attack: 1
   slash: 2
   ice_storm: 3
   fire_storm: 3
   whirlwind: 3
   earthquake: 2
   double_hit: 4
   wait: 0
'''
class Monster(object):
   def __init__(self,name,max_hp=20,type_ = 'Normal',debug):
       self.debug = debug
       self.name = name
       self.max_hp = max_hp
       self.type = type_
       self.current_hp = max_hp
       self.exp = 0
       self.attacks = {'wait':0}
       self.possible_attacks = {   'sneak_attack': 1,
                           'slash': 2,
                           'ice_storm': 3,
                           'fire_storm': 3,
                           'whirlwind': 3,
                           'earthquake': 2,
                           'double_hit': 4,
                           'wait': 0}
   def add_attack(self,attack_name):
       if self.debug:
           print("current attacks: ")
           print(self.attacks)
           print("To add: "+attack_name)

       if (attack_name in self.possible_attacks) and (attack_name not in self.attacks):
           if len(self.attacks.keys())==4:
               # the monster object has 4 attacks already

               # finding the min attack power among the current set of attacks
               min_attack_power = 10000000
               for key in sorted(self.attacks.keys()):
                   if self.attacks[key]<min_attack_power:
                       min_attack_power = self.attacks[key]
                       idx = key

               # checking       
               if self.possible_attacks[attack_name]>=min_attack_power:
                   # lowest power in current attack is less than this new attack
                   self.attacks.pop(idx) # remove the attack with the lowest attack
                   self.attacks[attack_name] = self.possible_attacks[attack_name] # add new attack
                   return True  
               else:
                   return False  
           else: # less than 4 attacks available
               self.attacks[attack_name] = self.possible_attacks[attack_name]
               return True
       else: # attack not present in the dict of possible attacks
           return False

   def remove_attack(self, attack_name):
       if self.debug:
           print("current attacks: ")
           print(self.attacks)
           print("To remove: "+attack_name)

       if attack_name in self.attacks:
           self.attacks.pop(attack_name)
           # if the dict becomes empty after remove operation then add the wait attack
           if len(self.attacks.keys())==0:
               self.attacks = {'wait':0}
           return True
       else: # attack not present in the dict of possible attacks
           return False                                  

if __name__ == '__main__':

   # print("Sample output 1:")
   # car = Monster("carina", 3)
   # mat = Monster("matthew", 3)
   # print(car.name)
   # print(mat.name)
   # print("-----------------------")

   # print("Sample output 2:")
   # bob = Monster("bob", 2)
   # print(bob.add_attack("ice_storm"))
   # print(bob.add_attack("ice_storm2"))
   # print("-----------------------")

   # print("Sample output 3:")
   # mark = Monster("mark", 3)
   # print(mark.remove_attack("wait"))
   # print(mark.add_attack("fire_storm"))
   # print(mark.attacks)  
   # print("-----------------------")

   debug = True
   a = Monster("a", 20,debug) # running in debug mode,
   # to run in normal mode, set debug = False
   print(a.add_attack("fire_storm"))
   print("-----------------------")
   print(a.add_attack("whirlwind"))
   print("-----------------------")
   print(a.add_attack("slash"))
   print("-----------------------")
   print(a.add_attack("slash"))
   print("-----------------------")
   print(a.add_attack("sneak_attack"))
   print("-----------------------")
   print(a.add_attack("double_hit"))
   print("-----------------------")
   print(a.add_attack("earthquake"))
   print("-----------------------")
   print(a.add_attack("whirlwind"))
   print("-----------------------")
   print(a.add_attack("ice_storm"))
   print("-----------------------")
   print(a.add_attack("wait"))
   print("-----------------------")
   print(a.add_attack("wait"))  
   print("-----------------------")

   print(a.remove_attack("wait"))
   print("-----------------------")
   print(a.add_attack("whirlwind"))
   print("-----------------------")
   print(a.remove_attack("earthquake"))
   print("-----------------------")
   print(a.remove_attack("whirlwind"))
   print("-----------------------")
   print(a.remove_attack("double_hit"))
   print("-----------------------")
   print(a.remove_attack("sneak_attack"))
   print("-----------------------")
   print(a.remove_attack("ice_storm"))
   print("-----------------------")
   print(a.remove_attack("wait"))
   print("-----------------------")
   print(a.attacks)  

Code Screenshot:

Result:

Add a comment
Know the answer?
Add Answer to:
I need help with this problem. Using Python please. Thanks Construct a class “Monster” with the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Problem 5: Monster Factory (10 points) (Game Dev) Create a Monster class that maintains a count...

    Problem 5: Monster Factory (10 points) (Game Dev) Create a Monster class that maintains a count of all monsters instantiated and includes a static method that generates a new random monster object. In software engineering, a method that generates new instances of classes based on configuration information is called the Factory pattern. UML Class Diagram: Monster - name: String - health: int - strength: int - xp: int + spawn(type:String): Monster + constructor (name: String, health: int, strength: int, xp:...

  • C++ Inheritance Problem Step a: Suppose you are creating a fantasy role-playing game. In this game...

    C++ Inheritance Problem Step a: Suppose you are creating a fantasy role-playing game. In this game we have four different types of Creatures: Humans, Cyberdemons, Balrogs, and elves. To represent one of these Creatures we might define a Creature class as follows: class Creature { private: int type; // 0 Human, 1 Cyberdemon, 2 Balrog, 3 elf int strength; // how much damage this Creature inflicts int hitpoints; // how much damage this Creature can sustain string getSpecies() const; //...

  • HIGHEST SUBMISSION Vlew All Submissions Submission 17 Submitted on 6/10/2019 12 35 PM by Jenna Saleh...

    HIGHEST SUBMISSION Vlew All Submissions Submission 17 Submitted on 6/10/2019 12 35 PM by Jenna Saleh DESCRIPTION Objectives To write a classes based on sets of specifications To write a main class to be used in a multi-class Java program To use inheritance to extend a class (optional, EC) To override methods in subclasses (optional, EC) Groups You may work with a partner on this assignment. A header comment (In every Java file) should include authors (group members) and collaborators...

  • [3] In python, please help me write the functions needed for this problem: Another Way to do Parentheses: For this probl...

    [3] In python, please help me write the functions needed for this problem: Another Way to do Parentheses: For this problem, you will be given a string that contains parentheses, brackets, and curly braces ( (, ), [, ], {,} ) and other characters. As a human you are given a string of any characters, determine if the parentheses, brackets, and braces match. (No trailing or leading parentheses). The function called on an empty string will return True. Parentheses must...

  • Python 3, nbgrader, pandas 0.23.4 Q2 Default Value Functions (1 point) a) Sort Keys Write a function called sort_keys, which will return a sorted version of the keys from an input dictionary Input(s...

    Python 3, nbgrader, pandas 0.23.4 Q2 Default Value Functions (1 point) a) Sort Keys Write a function called sort_keys, which will return a sorted version of the keys from an input dictionary Input(s): dictionary :dictionary reverse boolean, default: False Output(s): .sorted_keys: list Procedure(s) Get the keys from the input dictionary using the keys()method (this will return a list of keys) Use the sorted function to sort the list of keys. Pass in reverse to sorted to set whether to reverse...

  • use python IDEL Please highlight the answer Problem 2 Dictionary. Read the following code and answer...

    use python IDEL Please highlight the answer Problem 2 Dictionary. Read the following code and answer the next five questions about it. book1 = ("Alice":"arts", "Bob": "botany" "Clara": "chemistry", "Dasha": "digital media") book2 = {"Eve": "electronics", "Forest": "finances". "George": "geology", "Harry": "history". "Ivan": "Italian", "Joanna": "Japanese Arts") mybook=0 condition 1 = ? condition2 - ? condition3 = ? for key in book 1.keys(): mybook[key] =book 1.get(key) mybook.update(book 2) #first print statement print (mybook) if condition 1: mybook["Bob"] = "biochemistry" mybook["Eve"]...

  • I need help with this python programming exercise, please! thanks in advance Create a Python script...

    I need help with this python programming exercise, please! thanks in advance Create a Python script file called hw4.py. Add your name at the top as a comment, along with the class name and date. Both exercises should be in this file, with a comment before each of them to mark it. Ex. 1. Write a program that inputs an integer number from the user, then prints a letter "O" in ASCII art using a width of 5 and the...

  • Using python 3.6 How do I incorporate 0 or negative input to raise an error and...

    Using python 3.6 How do I incorporate 0 or negative input to raise an error and let the user try again? like <=0 #loop to check valid input option. while True: try: choice = int(input('Enter choice: ')) if choice>len(header): print("Invalid choice!! Please try again and select value either:",end=" ") for i in range(1,len(header)+1): print(i,end=",") else: break choice = int(input('\nEnter choice: ')) except ValueError as ve:print('Invalid response, You need to select the number choice from the option menu') # Catch your...

  • Base Class enum HeroType {WARRIOR, ELF, WIZARD}; const double MAX_HEALTH = 100.0; class Character { protected:...

    Base Class enum HeroType {WARRIOR, ELF, WIZARD}; const double MAX_HEALTH = 100.0; class Character { protected: HeroType type; string name; double health; double attackStrength; public: Character(HeroType type, const string &name, double health, double attackStrength); HeroType getType() const; const string & getName() const; /* Returns the whole number of the health value (static_cast to int). */ int getHealth() const; void setHealth(double h); /* Returns true if getHealth() returns an integer greater than 0, otherwise false */ bool isAlive() const; virtual void...

  • [Python] Construct Tree Using Inorder and Preorder Given Preorder and Inorder traversal of a binary tree,...

    [Python] Construct Tree Using Inorder and Preorder Given Preorder and Inorder traversal of a binary tree, create the binary tree associated with the traversals.You just need to construct the tree and return the root. Note: Assume binary tree contains only unique elements. Input format : Line 1 : n (Total number of nodes in binary tree) Line 2 : Pre order traversal Line 3 : Inorder Traversal Output Format : Elements are printed level wise, each level in new line...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT