CMU 15-112 Spring 2019: Fundamentals of Programming and Computer Science
Check 8.5


  1. Check 8.5
    Write a new subclass of monster called MontyMonster. Add a method called boost that multiplies the strength by a factor f passed in to boost. Also, overwrite defend to reduce health by twice the damage. Finally, your subclass MontyMonster should create a new property in __init__ called lockedHealth which starts out at 0.
    # This is our base class class Monster(object): def __init__(self, strength, defense): self.strength = strength self.defense = defense self.health = 10 def attack(self): # returns damage to be dealt if self.health > 0: return self.strength def defend(self, damage): # does damage to self self.health -= damage class MagicMonster(Monster): def __init__(self, strength, defense): super().__init__(strength, defense) # most properties are the same self.health = 5 # but they start out weaker def heal(self): # only magic monsters can heal themselves! if 0 < self.health < 5: self.health += 1 class NecroMonster(Monster): def attack(self): # NecroMonsters can attack even when 'killed' return self.strength #Add your class here! def testMontyMonster(): mm = MontyMonster(5, 10) assert(mm.lockedHealth == 0) mm.boost(2) assert(mm.strength == 10) mm.defend(5) assert(mm.health == 0) testMontyMonster() import sys def set_certificate(certificate_div_id, certificate): document[certificate_div_id].textContent = certificate def get_student_code(student_code_div_id): raw_student_code = document[student_code_div_id].textContent return window.patchCodeToCheckTimeout(raw_student_code, 'check_timeout();'); class captureIO: def __init__(self): self.captured = [] def get_output(self): out = "" for c in self.captured: out += str(c) return out def write(self, data): self.captured.append(data) def flush(self): pass def make_certificate(student_code_div_id, certificate_div_id): student_code = get_student_code(student_code_div_id) certificate = [] try: execCapture = captureIO() sys.stdout = execCapture sys.stderr = execCapture exec(student_code) mm = MontyMonster(10, 110) factor, damage1, damage2 = 22, 7, 9 mm.boost(factor) certificate.append((mm.strength, type(mm.strength))) mm.boost(0) certificate.append((mm.strength, type(mm.strength))) mm.defend(damage1) certificate.append((mm.health, type(mm.health))) mm.defend(damage2) certificate.append((mm.health, type(mm.health))) certificate.append((mm.lockedHealth, type(mm.lockedHealth))) except: set_certificate(certificate_div_id, "error") set_certificate(certificate_div_id, str(certificate))

  2. Back to notes