本实例为用python语言编写,以python的面向对象、列表、局部变量等部分知识为基础,内容类似于popcap的植物大战僵尸的游戏项目本实例为UC berkeley课程CS61A的project,代码框架由CS61A课程提供,其余部分由上传者独立完成,详见https://inst.eecs.berkeley.edu/~cs61a/sp18/proj/ants/
class Insect(object): """An Insect, the base class of Ant and Bee, has armor and a Place.""" is_ant = False damage = 0 watersafe = False def __init__(self, armor, place=None): """Create an Insect with an ARMOR amount and a starting PLACE.""" self.armor = armor self.place = place # set by Place.add_insect and Place.remove_insect def reduce_armor(self, amount): """Reduce armor by AMOUNT, and remove the insect from its place if it has no armor remaining. >>> test_insect = Insect(5) >>> test_insect.reduce_armor(2) >>> test_insect.armor 3 """ self.armor -= amount if self.armor <= 0: self.place.remove_insect(self) def action(self, colony): """The action performed each turn. colony -- The AntColony, used to access game state information. """ def __repr__(self): cname = type(self).__name__ return '{0}({1}, {2})'.format(cname, self.armor, self.place)class Bee(Insect): """A Bee moves from place to place, following exits and stinging ants.""" name = 'Bee' damage = 1 watersafe = True def sting(self, ant): """Attack an ANT, reducing its armor by 1.""" ant.reduce_armor(self.damage) def move_to(self, place): """Move from the Bee's current Place to a new PLACE.""" self.place.remove_insect(self) place.add_insect(self) def blocked(self): """Return True if this Bee cannot advance to the next Place.""" # Phase 4: Special handling for NinjaAnt # BEGIN Problem 7 return (self.place.ant is not None) and self.place.ant.blocks_path # END Problem 7 def action(self, colony): """A Bee's action stings the Ant that blocks its exit if it is blocked, or moves to the exit of its current place otherwise. colony -- The AntColony, used to access game state information. """ if self.blocked(): self.sting(self.place.ant) elif self.armor > 0 and self.place.exit is not None: self.move_to(self.place.exit)class Ant(Insect): """An Ant occupies a place and does work for the colony.""" is_ant = True implemented = False # Only implemented Ant classes should be instantiated food_cost = 0 blocks_path = True container = False def __init__(self, armor=1): """Create an Ant with an ARMOR quantity.""" Insect.__init__(self, armor) def can_contain(self, other): # BEGIN Problem 9 "*** YOUR CODE HERE ***" if self.container and not other.container and self.ant==None: return True return False # END Problem 9
评论