Question

In: Computer Science

Python Clean up the code Recall that once a subclass inherits from a parent class, it...

Python

Clean up the code

Recall that once a subclass inherits from a parent class, it automatically has access to all of the parents' methods. Sometimes, the subclass needs to do extra things within a method which the parent does not do. For example, both UserPlayer and BasicMonster have their specialized __init__ methods which override the one from Player. Discuss the following question with your partner: What are the other methods that are being overridden by a subclass in the set of classes you've been given?

Some of these methods are not necessary to override. Clean up your classes by moving the methods that could just be put in the Player class up into the Player class

and remove any unneeded repetition of these methods within subclasses.

import random
import time

class Player:
'''
The Player class includes things that every player has,
which is name and hp (health points).
'''

def __init__(self, name: str, hp: int, strength: int) -> None:
self.name = name
self.hp = hp
self.strength = strength
  
class UserPlayer(Player):
'''
UserPlayer inherits from Player, because it is a more specific
type of Player. This type of Player is controlled by the user.
'''
  
def __init__(self, name: str) -> None:
'''
Construct a UserPlayer with the given name, and a set
hp and strength. Also define mp for magic, a list
of possible moves they can make, and an inventory
dictionary of items they can use.
'''

super().__init__(name, 50, 10) # assign attributes name, hp, strength
  
self.mp = 50
self.moves = ['attack', 'magic attack', 'defend']
self.inventory = {'potion': 1, 'ether': 1} # potion should restore hp, ether restores mp

def attack(self, other: 'Player') -> None:
'''
Attack the Player <other> by calling that Player's take_hit method.
The attack power is based on your own strength.
'''
  
other.take_hit(self.strength)

def take_hit(self, strength: int) -> None:
'''
Lose some hp based on the <strength> given.
Print message about how much hp you lost.
'''
  
power = random.randint(strength//2, strength)
print("{} was attacked, and lost {} hp.".format(self.name, power))
self.hp = self.hp - power

def magic_attack(self, other):
pass

def defend(self):
pass
  
def make_move(self, opponent: 'Player') -> None:
'''
Make a move based on user input.
'''
  
not_valid = True
while not_valid:
move = input("What move do you want to take? a: attack, m: magic, d: defend\n")
not_valid = False
if move == "a":
self.attack(opponent)
elif move == "m":
self.magic_attack(opponent)
elif move == "d":
self.defend()
else:
print("Invalid input. Try again.")
not_valid = True

class Monster(Player):
'''
Monster class represents a Computer controlled player.
The make_move method is thus different for the Monster,
where the move is randomly chosen based on a randomly
generated number, rather than through user input.
'''
  
def make_move(self, opponent):
move = self.moves[random.randint(0, len(self.moves)-1)]
if move == "basic attack":
self.attack(opponent)
elif move == "special attack":
self.special_attack(opponent)
  
class BasicMonster(Monster):
'''
BasicMonster class represents a basic type of Monster.
We inherit the make_move from the Monster class, and this
BasicMonster only has those two moves, so we don't need
to add the make_move method here again.
'''
  
def __init__(self) -> None:
'''
Construct a BasicMonster with a name, hp, strength
and list of moves.
'''
  
super().__init__('Basic Monster', 50, 10) # assign attributes name, hp, strength
# the super call above uses the original Player class's init method

self.moves = ['basic attack']

# Question: What does the following code do?
if self.hp < 25:
self.moves.append = ['special attack']

def attack(self, other: 'Player') -> None:
'''
Attack the Player <other> by calling that Player's take_hit method.
The attack power is based on your own strength.
'''
  
other.take_hit(self.strength)

def take_hit(self, strength: int) -> None:
'''
Lose some hp based on the <strength> given.
Print message about how much hp you lost.
'''
  
power = random.randint(strength//2, strength)
print("{} was attacked, and lost {} hp.".format(self.name, power))
self.hp = self.hp - power
  
def special_attack(self, other):
'''
Attack the Player <other> with a special attack that exceeds
your usual strength.
'''

power = random.randint(strength, strength*2)
other.take_hit(40)
  
class Game:

def __init__(self, p1: 'Player', p2: 'Player') -> None:
'''
Construct a Game with the given players.
'''
self.players = (p1, p2)
self.turn = 0 # keep track of whose turn it is out of the two players

def whose_turn(self, count: int) -> 'Player':
'''
Return the Player whose turn it is.
'''
if count % 2 == 0:
next_player = self.players[0]
else:
next_player = self.players[1]
return next_player

def play_game(self) -> None:
'''
Play the game, with each player taking turns making a move, until
one player runs out of hp.
'''
  
# print out the starting state of the game
print(self)
print('------------')
  
winner = None
while (not winner):
if (self.players[0].hp <= 0):
winner = self.players[1]
elif (self.players[1].hp <= 0):
winner = self.players[0]
else:
# if no one has won yet, play one turn of the game (one player makes one move)
self.play_one_turn()
  
print('And {} is the winner!!!'.format(winner.name))

def play_one_turn(self) -> None:
'''
Play one turn of the game based on which player's turn it is.
Print state of game that results from this turn.
'''
  
current_player = self.whose_turn(self.turn) # get the Player whose turn it currently is
other_player = self.whose_turn(self.turn-1) # get the other Player in the game

print("{}'s TURN".format(current_player.name))

# if the player is the computer, wait 2 seconds before
# showing the player's move to make the gameflow feel more natural
if (isinstance(current_player,Monster)):
time.sleep(1)
  
current_player.make_move(other_player)
  
# print current state of game
print(self)
print('------------')
  
self.turn += 1

def __str__(self) -> str:
'''
Return string representation of state of game.
'''
  
return "Player 1 hp: {}, Player 2 hp: {}".format(self.players[0].hp, self.players[1].hp)

def main():
'''Prompt the user to configure and play the game.'''

name = input("What is p1's name? ")
  
p1 = UserPlayer(name) # make the first player a User at position (0,0)

p2 = BasicMonster()
  
g = Game(p1, p2)
g.play_game()

if __name__ == '__main__':
main()
  

Solutions

Expert Solution

Solution:

import random
import time

class Player:
def __init__(self, name: str, hp: int, strength: int) -> None:
self.name = name
self.hp = hp
self.strength = strength
def attack(self, other: 'Player') -> None:
other.take_hit(self.strength)

def take_hit(self, strength: int) -> None:
power = random.randint(strength//2, strength)
print("{} was attacked, and lost {} hp.".format(self.name, power))
self.hp = self.hp - power
  
class UserPlayer(Player):
def __init__(self, name: str) -> None:
super().__init__(name, 50, 10) # assign attributes name, hp, strength
  
self.mp = 50
self.moves = ['attack', 'magic attack', 'defend']
self.inventory = {'potion': 1, 'ether': 1} # potion should restore hp, ether restores mp

def magic_attack(self, other):
pass

def defend(self):
pass
  
def make_move(self, opponent: 'Player') -> None:
not_valid = True
while not_valid:
move = input("What move do you want to take? a: attack, m: magic, d: defend\n")
not_valid = False
if move == "a":
self.attack(opponent)
elif move == "m":
self.magic_attack(opponent)
elif move == "d":
self.defend()
else:
print("Invalid input. Try again.")
not_valid = True

class Monster(Player):
def make_move(self, opponent):
move = self.moves[random.randint(0, len(self.moves)-1)]
if move == "basic attack":
self.attack(opponent)
elif move == "special attack":
self.special_attack(opponent)
  
class BasicMonster(Monster):
def __init__(self) -> None:
super().__init__('Basic Monster', 50, 10) # assign attributes name, hp, strength
self.moves = ['basic attack']

# Question: What does the following code do?
if self.hp < 25:
self.moves.append = ['special attack']

  
  
def special_attack(self, other):

power = random.randint(strength, strength*2)
other.take_hit(40)
  
class Game:

def __init__(self, p1: 'Player', p2: 'Player') -> None:
self.players = (p1, p2)
self.turn = 0 # keep track of whose turn it is out of the two players

def whose_turn(self, count: int) -> 'Player':

if count % 2 == 0:
next_player = self.players[0]
else:
next_player = self.players[1]
return next_player

def play_game(self) -> None:
print(self)
print('------------')
  
winner = None
while (not winner):
if (self.players[0].hp <= 0):
winner = self.players[1]
elif (self.players[1].hp <= 0):
winner = self.players[0]
else:
# if no one has won yet, play one turn of the game (one player makes one move)
self.play_one_turn()
  
print('And {} is the winner!!!'.format(winner.name))

def play_one_turn(self) -> None:

current_player = self.whose_turn(self.turn) # get the Player whose turn it currently is
other_player = self.whose_turn(self.turn-1) # get the other Player in the game

print("{}'s TURN".format(current_player.name))

# if the player is the computer, wait 2 seconds before
# showing the player's move to make the gameflow feel more natural
if (isinstance(current_player,Monster)):
time.sleep(1)
  
current_player.make_move(other_player)
  
# print current state of game
print(self)
print('------------')
  
self.turn += 1

def __str__(self) -> str:
return "Player 1 hp: {}, Player 2 hp: {}".format(self.players[0].hp, self.players[1].hp)

def main():
name = input("What is p1's name? ")
  
p1 = UserPlayer(name) # make the first player a User at position (0,0)

p2 = BasicMonster()
  
g = Game(p1, p2)
g.play_game()

if __name__ == '__main__':
main()

  
Screenshots:

The screenshots are attached below for reference.
Please follow them for proper indentation.

As you have attached the code please follow indentation from your code that you attached.
The attack() and take_hit() methods have been repeated.
So these two methods are placed in the parent class and avoided repetitive code in the program.


Related Solutions

Write a c++ code: 2.2.1 Vehicle Class The vehicle class is the parent class of a...
Write a c++ code: 2.2.1 Vehicle Class The vehicle class is the parent class of a derived class: locomotive. Their inheritance will be public inheritance so react that appropriately in their .h les. The description of the vehicle class is given in the simple UML diagram below: vehicle -map: char** -name: string -size:int -------------------------- +vehicle() +setName(s:string):void +getName():string +getMap():char** +getSize():int +setMap(s: string):void +getMapAt(x:int, y:int):char +vehicle() +operator--():void +determineRouteStatistics()=0:void The class variables are as follows: map: A 2D array of chars, it will...
C++ Code Vehicle Class The vehicle class is the parent class of a derived class: locomotive....
C++ Code Vehicle Class The vehicle class is the parent class of a derived class: locomotive. Their inheritance will be public inheritance so reflect that appropriately in their .h files. The description of the vehicle class is given in the simple UML diagram below: vehicle -map: char** -name: string -size:int -------------------------- +vehicle() +setName(s:string):void +getName():string +getMap():char** +getSize():int +setMap(s: string):void +getMapAt(x:int, y:int):char +~vehicle() +operator−−():void +determineRouteStatistics()=0:void The class variables are as follows: • map: A 2D array of chars, it will represent the...
C++ Code Vehicle Class The vehicle class is the parent class of the derived class: dieselLocomotive....
C++ Code Vehicle Class The vehicle class is the parent class of the derived class: dieselLocomotive. Their inheritance will be public inheritance so reect that appropriately in their .h les. The description of the vehicle class is given in the simple UML diagram below: vehicle -map: char** -name: string -size:int -------------------------- +vehicle() +getSize():int +setName(s:string):void +getName():string +getMap():char** +setMap(s: string):void +getMapAt(x:int, y:int):char +~vehicle() +operator--():void +determineRouteStatistics()=0:void The class variables are as follows: map: A 2D array of chars, it will represent the map...
Python Explain Code #Python program class TreeNode:
Python Explain Code   #Python program class TreeNode:    def __init__(self, key):        self.key = key        self.left = None        self.right = Nonedef findMaxDifference(root, diff=float('-inf')):    if root is None:        return float('inf'), diff    leftVal, diff = findMaxDifference(root.left, diff)    rightVal, diff = findMaxDifference(root.right, diff)    currentDiff = root.key - min(leftVal, rightVal)    diff = max(diff, currentDiff)     return min(min(leftVal, rightVal), root.key), diff root = TreeNode(6)root.left = TreeNode(3)root.right = TreeNode(8)root.right.left = TreeNode(2)root.right.right = TreeNode(4)root.right.left.left = TreeNode(1)root.right.left.right = TreeNode(7)print(findMaxDifference(root)[1])
This is using Python, it is utilizing code from a Fraction class to create a Binary...
This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this. Instruction for Binary Class: Exercise 6.18: Design an immutable class BinaryNumber, in the style of our Fraction class. Internally, your only instance variable should be a text string that represents the binary value, of the form '1110100'. Implement a constructor that takes a string parameter that specifies the original binary value....
In Java, create an abstract vehicle class. Create a Truck Class that Inherits from Vehicle Class....
In Java, create an abstract vehicle class. Create a Truck Class that Inherits from Vehicle Class. The vehicle class should contain at least 2 variables that could pertain to ANY vehicle and two methods. The truck class should contain 2 variables that only apply to trucks and one method. Create a console program that will instantiate a truck with provided member information then call one method from the truck and one method contained from the inherited vehicle class. Have these...
Simple Java class. Create a class Sportscar that inherits from the Car class includes the following:...
Simple Java class. Create a class Sportscar that inherits from the Car class includes the following: a variable roof that holds type of roof (ex: convertible, hard-top,softtop) a variable doors that holds the car's number of doors(ex: 2,4) implement the changespeed method to add 20 to the speed each time its called add exception handling to the changespeed method to keep soeed under 65 implement the sound method to print "brooom" to the screen. create one constructor that accepts the...
C++ Code (I just need the dieselLocomotive Class) Vehicle Class The vehicle class is the parent...
C++ Code (I just need the dieselLocomotive Class) Vehicle Class The vehicle class is the parent class of the derived class: dieselLocomotive. Their inheritance will be public inheritance so reflect that appropriately in their .h files. The description of the vehicle class is given in the simple UML diagram below: vehicle -map: char** -name: string -size:int -------------------------- +vehicle() +getSize():int +setName(s:string):void +getName():string +getMap():char** +setMap(s: string):void +getMapAt(x:int, y:int):char +~vehicle() +operator--():void +determineRouteStatistics()=0:void The class variables are as follows: map: A 2D array of...
JAVA CODING PLEASE Create a class SportsCar that inherits from the Car class (CAR CLASS LISTED...
JAVA CODING PLEASE Create a class SportsCar that inherits from the Car class (CAR CLASS LISTED BELOW THIS QUESTION). Include the following: A variable Roof that holds the type of roof (Ex: Convertible, Hard-Top, Soft-Top) A variable Doors that holds the car’s number of doors (Ex: 2, 4) Implement the ChangeSpeed method to add 20 to the speed each time it is called. Add exception handling to the ChangeSpeed method to keep the speed under 65. Implement the sound method...
From the MNIST dataset introduced in class, write code in Python that a) Splits the 42000...
From the MNIST dataset introduced in class, write code in Python that a) Splits the 42000 training images into a training set (50% of all the data) and a test set (the rest). The labels should also be split accordingly. (PLEASE ONLY SOLVE 2 & 3) 2) Basically repeat Part 1, but now use 80% of the images for training and the other 20% for testing. Report scores. [10 points] 3) Use the SVM model from part 2 to print...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT