CSCI 110, Spring 2011
Home | | Course Schedule | | Assignments | | Lecture NotesHomework 6 solution
#Program: puzzle.py
#Author: Brenda Student
#Section: CSCI 110, Section 1
#Date: 3/18/11
#Assignment: Homework 6, Problem 1
#Purpose: Solve Tower of Hanoi puzzle
def moveRing(ring, fromPeg, toPeg):
print "Move ring", ring, "from peg", fromPeg, "to peg", toPeg + "."
def Hanoi(n, source, destination, spare):
if n == 1:
moveRing(1, source, destination)
else:
Hanoi(n - 1, source, spare, destination)
moveRing(n, source, destination)
Hanoi(n - 1, spare, destination, source)
#begin program
number = input("How many rings are in the tower? ")
Hanoi(number, "A", "B", "C")
#Program: hero.py
#Author: Brenda Student
#Class: CSCI 110
#Date: 3/18/11
#Assignment: Homework 6, problem 2
#Purpose: Create a hero class to keep track of an inventory and health.
# Also allows the hero to attack a troll.
class Hero:
inventory = []
health = 10
def __init__(self, name):
self.name = name
def __str__(self):
return "I am the hero, " + self.name
def print_inventory(self):
print "The following items are in the inventory: "
for x in self.inventory:
print x
def add_inventory(self, item):
self.inventory.append(item)
def attack_troll(self):
print self.name + " has attacked a troll."
self.health = self.health - 2
print self.name + " now has", self.health, "health points."
def heal(self):
for x in self.inventory:
if x == "potion":
print "The healing potion heals " + self.name + "."
self.health = 10
#Alternate solution:
#if x in inventory:
# print "The healing potion heals " + self.name + "."
# self.health = 10
print self.name + " now has", self.health, "health points."
heroName = raw_input("Please enter the hero's name: ")
myHero = Hero(heroName)
print myHero
myHero.add_inventory("sword")
myHero.add_inventory("potion")
myHero.add_inventory("armor")
myHero.print_inventory( )
myHero.attack_troll( )
myHero.heal( )