2021 cs61a fall ants


網址 https://inst.eecs.berkeley.edu/~cs61a/fa21/proj/ants/#introduction

problem1:

修改兩個ant類的food_cost,並且HarvesterAnt可以每回合加一個gamestate.food

    class HarvesterAnt(Ant):
        """HarvesterAnt produces 1 additional food per turn for the colony."""

        name = 'Harvester'
        implemented = True
        # OVERRIDE CLASS ATTRIBUTES HERE
        food_cost = 2

        def action(self, gamestate):
            """Produce 1 additional food for the colony.

            gamestate -- The GameState, used to access game state information.
            """
            # BEGIN Problem 1
            "*** YOUR CODE HERE ***"
            gamestate.food = gamestate.food + 1
            # END Problem 1


    class ThrowerAnt(Ant):
        """ThrowerAnt throws a leaf each turn at the nearest Bee in its range."""

problem2:

這個小題就是給一個格子添加走進這個格子的前一個位置和進入了這個格子后面改走哪里,即entrance和exit(都是相對於這個格子而言)
class Place:
"""A Place holds insects and has an exit to another Place."""
is_hive = False

        def __init__(self, name, exit=None):
            """Create a Place with the given NAME and EXIT.

            name -- A string; the name of this Place.
            exit -- The Place reached by exiting this Place (may be None).
            """
            self.name = name
            self.exit = exit
            self.bees = []        # A list of Bees
            self.ant = None       # An Ant
            self.entrance = None  # A Place
            # Phase 1: Add an entrance to the exit
            # BEGIN Problem 2
            "*** YOUR CODE HERE ***"
            if exit != None:
                exit.entrance = self
            # END Problem 2
        name = 'Thrower'
        implemented = True
        damage = 1
        # ADD/OVERRIDE CLASS ATTRIBUTES HERE
        food_cost = 3

        def nearest_bee(self):
            """Return the nearest Bee in a Place that is not the HIVE, connected to
            the ThrowerAnt's Place by following entrances.

            This method returns None if there is no such Bee (or none in range).
            """
            # BEGIN Problem 3 and 4
            return random_bee(self.place.bees)  # REPLACE THIS LINE
            # END Problem 3 and 4

        def throw_at(self, target):
            """Throw a leaf at the TARGET Bee, reducing its health."""
            if target is not None:
                target.reduce_health(self.damage)

        def action(self, gamestate):
            """Throw a leaf at the nearest Bee in range."""
            self.throw_at(self.nearest_bee())

problem3:

這個函數是找到里當前ant所在位置的最近的bee(如果有的話,在hive不算)

    def nearest_bee(self):
            """Return the nearest Bee in a Place that is not the HIVE, connected to
            the ThrowerAnt's Place by following entrances.

            This method returns None if there is no such Bee (or none in range).
            """
            # BEGIN Problem 3 and 4
            pos = self.place #先獲取當前的位置
            while pos.entrance is not None:#如果這個位置還有右邊的位置,因為只能攻擊右邊的bee
                if not pos.is_hive:#並且右邊不是hive
                    if len(pos.bees) > 0:#右邊的位置有bee pos.bees是一個列表,里面有所有的一個格子里面包含的bee
                        return random_bee(pos.bees)#隨機返回一個bee
                pos = pos.entrance#如果沒有則找下一個格子
            return None#如果都沒有就返回None
            # REPLACE THIS LINE
            # END Problem 3 and 4

problem4:

有兩種新的ant,一種只能攻擊三個格子之內的(0-3)一種只能攻擊5個格子以外的(>=5),其他條件和ThrowerAnt一樣
class ThrowerAnt(Ant):
"""ThrowerAnt throws a leaf each turn at the nearest Bee in its range."""

        name = 'Thrower'
        implemented = True
        damage = 1
        # ADD/OVERRIDE CLASS ATTRIBUTES HERE
        food_cost = 3
        min_range = -1
        max_range = float('inf')
        def nearest_bee(self):
            """Return the nearest Bee in a Place that is not the HIVE, connected to
            the ThrowerAnt's Place by following entrances.

            This method returns None if there is no such Bee (or none in range).
            """
            # BEGIN Problem 3 and 4
            pos = self.place
            sept = 0
            while pos.entrance is not None:
                if not pos.is_hive:
                    if len(pos.bees) > 0 and sept >= self.min_range and sept <= self.max_range:
                        return random_bee(pos.bees)
                pos = pos.entrance
                sept += 1
            return None
            # REPLACE THIS LINE
            # END Problem 3 and 4

        def throw_at(self, target):
            """Throw a leaf at the TARGET Bee, reducing its health."""
            if target is not None:
                target.reduce_health(self.damage)

        def action(self, gamestate):
            """Throw a leaf at the nearest Bee in range."""
            self.throw_at(self.nearest_bee())

    def random_bee(bees):
        """Return a random bee from a list of bees, or return None if bees is empty."""
        assert isinstance(bees, list), "random_bee's argument should be a list but was a %s" % type(bees).__name__
        if bees:
            return random.choice(bees)

    ##############
    # Extensions #
    ##############


    class ShortThrower(ThrowerAnt):
        """A ThrowerAnt that only throws leaves at Bees at most 3 places away."""

        name = 'Short'
        food_cost = 2
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 4
        implemented = True   # Change to True to view in the GUI
        max_range = 3
        # END Problem 4


    class LongThrower(ThrowerAnt):
        """A ThrowerAnt that only throws leaves at Bees at least 5 places away."""

        name = 'Long'
        food_cost = 2
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 4
        implemented = True   # Change to True to view in the GUI
        min_range = 5
        # END Problem 4

problem5:

不管這個ant的health有沒有為零,在這個格子上的bee都要承受amount的傷害,然后如果ant的health為零了,bee還需要多承受一次damage

    class FireAnt(Ant):
        """FireAnt cooks any Bee in its Place when it expires."""

        name = 'Fire'
        damage = 3
        food_cost = 5
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 5
        implemented = True   # Change to True to view in the GUI
        # END Problem 5

        def __init__(self, health=3):
            """Create an Ant with a HEALTH quantity."""
            super().__init__(health)

        def reduce_health(self, amount):
            """Reduce health by AMOUNT, and remove the FireAnt from its place if it
            has no health remaining.

            Make sure to reduce the health of each bee in the current place, and apply
            the additional damage if the fire ant dies.
            """
            # BEGIN Problem 5
            "*** YOUR CODE HERE ***"
            pos = self.place
            for i in pos.bees[:]:
                i.reduce_health(amount)
            if amount >= self.health:
                for i in pos.bees[:]:
                    i.reduce_health(self.damage)
                super().reduce_health(amount)
            else:
                super().reduce_health(amount)
            # END Problem 5

problem6:

這個就注意health需要用init函數就好了

    class WallAnt(Ant):
        name = 'Wall'
        implemented = True 
        food_cost = 4
        def __init__(self, health=4):
            """Create an Ant with a HEALTH quantity."""
            super().__init__(health)

problem7:

chew_countdown和chew_duration都是數字

    class HungryAnt(Ant):
        name = 'Hungry'
        implemented = True 
        food_cost = 4
        chew_duration = 3
        def __init__(self, health=1):
            """Create an Ant with a HEALTH quantity."""
            super().__init__(health)
            self.chew_countdown = 0
        def action(self,gamestate):
            if self.chew_countdown != 0:
                self.chew_countdown -= 1
            else:
                pos =  self.place
                if len(pos.bees) > 0 :
                    self.chew_countdown = self.chew_duration
                    bee = random_bee(pos.bees)
                    bee.reduce_health(bee.health)

problem8:

這小問就是修改在ant類里面不能在同一個格子里面不能放兩個ant的限制,然后對格子里面的已經存在的ant做出判斷。
class Ant里面的一個需要修改的

        def add_to(self, place):
            if place.ant is None:
                place.ant = self
            else:
                assert (
                    (place.ant is None)
                    or self.can_contain(place.ant)
                    or place.ant.can_contain(self) 
                ), 'Two ants in {0}'.format(place)
                # BEGIN Problem 8
                if place.ant.is_container and place.ant.can_contain(self):
                    place.ant.store_ant(self)
                elif self.is_container and self.can_contain(place.ant):
                    self.store_ant(place.ant)
                    place.ant = self
                # END Problem 8
            Insect.add_to(self, place)

然后就是ContainerAnt類和BodyguardAnt類

      class ContainerAnt(Ant):
          """
          ContainerAnt can share a space with other ants by containing them.
          """
          is_container = True

          def __init__(self, *args, **kwargs):
              super().__init__(*args, **kwargs)
              self.ant_contained = None

          def can_contain(self, other):
              # BEGIN Problem 8
              "*** YOUR CODE HERE ***"
              if self.ant_contained is None and not other.is_container:
                  return True
              # END Problem 8

          def store_ant(self, ant):
              # BEGIN Problem 8
              "*** YOUR CODE HERE ***"
              self.ant_contained = ant
              # END Problem 8

          def remove_ant(self, ant):
              if self.ant_contained is not ant:
                  assert False, "{} does not contain {}".format(self, ant)
              self.ant_contained = None

          def remove_from(self, place):
              # Special handling for container ants (this is optional)
              if place.ant is self:
                  # Container was removed. Contained ant should remain in the game
                  place.ant = place.ant.ant_contained
                  Insect.remove_from(self, place)
              else:
                  # default to normal behavior
                  Ant.remove_from(self, place)

          def action(self, gamestate):
              # BEGIN Problem 8
              "*** YOUR CODE HERE ***"
              if self.ant_contained is not None:
                  return self.ant_contained.action(gamestate)
              # END Problem 8


      class BodyguardAnt(ContainerAnt):
          """BodyguardAnt provides protection to other Ants."""

          name = 'Bodyguard'
          food_cost = 4
          implemented = True  
          # OVERRIDE CLASS ATTRIBUTES HERE
          # BEGIN Problem 8
          def __init__(self, health = 2):
              super().__init__(health)
           # Change to True to view in the GUI
          # END Problem 8

problem9:

在ContainAnt的基礎上加一個action造成傷害就好了

    class TankAnt(ContainerAnt):
        name = 'Tank'
        damage = 1
        food_cost = 6
        implemented = True
        def __init__(self, health = 2):
            super().__init__(health)
        def action(self,gamestate):
            if self.ant_contained is not None:
                self.ant_contained.action(gamestate)
            for i in self.place.bees[:]:
                i.reduce_health(self.damage)

problem10:

新增加一個地形,水,就是在insect的增加一個屬性is_waterproof,ant默認False,bee默認True(會飛)

    class Water(Place):
        """Water is a place that can only hold waterproof insects."""

        def add_insect(self, insect):
            """Add an Insect to this place. If the insect is not waterproof, reduce
            its health to 0."""
            # BEGIN Problem 10
            "*** YOUR CODE HERE ***"
            super().add_insect(insect)
            if not insect.is_waterproof:
                insect.reduce_health(insect.health)
            # END Problem 10

problem11:

就繼承就好了

    class ScubaThrower(ThrowerAnt):
        food_cost = 6
        name = 'ScubaThrower'
        is_waterproof = True
        def _init_(self, health = 1):
            super().__init__(health)

problem12:

主要是完成queen這個類,在其他地方也有做修改,增加了一些屬性,has_queen,is_doubled,還修改了buff()函數

    class QueenAnt(ScubaThrower):  # You should change this line
    # END Problem 12
        """The Queen of the colony. The game is over if a bee enters her place."""

        name = 'Queen'
        food_cost = 7
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 12
        implemented = True   # Change to True to view in the GUI
        # END Problem 12

        @classmethod
        def construct(cls, gamestate):
            """
            Returns a new instance of the Ant class if it is possible to construct, or
            returns None otherwise. Remember to call the construct() method of the superclass!
            """
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            if cls.food_cost > gamestate.food:
                print('Not enough food remains to place ' + cls.__name__)
                return
            if not gamestate.has_queen:
                gamestate.has_queen = True
                return super().construct(gamestate)
            else:
                return None
            # END Problem 12

        def action(self, gamestate):
            """A queen ant throws a leaf, but also doubles the damage of ants
            in her tunnel.
            """
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            super().action(gamestate)
            pos = self.place.exit
            while pos:
                if pos.ant is not None:
                    if not pos.ant.is_doubled:
                        pos.ant.is_doubled = True
                        pos.ant.buff()
                    if pos.ant.is_container and pos.ant.ant_contained is not None:
                        # the pos.ant.ant_contained may change
                        if not pos.ant.ant_contained.is_doubled:
                            pos.ant.ant_contained.buff()
                            pos.ant.ant_contained.is_doubled = True
                pos = pos.exit
            # END Problem 12

        def reduce_health(self, amount):
            """Reduce health by AMOUNT, and if the QueenAnt has no health
            remaining, signal the end of the game.
            """
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            if self.health <= amount:
                ants_lose()
            # END Problem 12
        def remove_from(self, place):
            None

extra credit:

這道題一開始忘記寫那兩個ant類了一直過不去,然后直接抄了別人代碼(代碼是這位大佬的:https://www.cnblogs.com/MartinLwx/p/15997085.html)發現還是過不去后來發現這兩個ant有單獨的類
寫了就好了
這道題思路就幾種情況考慮清楚
第一種是被減速,第二種是被嚇第三種就是二者都有
被嚇到決定前進的方向所以先寫
被減速決定是否前進,
然后在被減速的情況下,如果被嚇並且gamestate.time是奇數就不動,並且由於先前scared_turns被減了一這里動就需要加回來

    class Bee(Insect):
        """A Bee moves from place to place, following exits and stinging ants."""

        name = 'Bee'
        damage = 1
        is_waterproof = True
        # 2 flags
        is_slow = False
        is_scared = False
        # turns remained
        slow_turns = 0
        scared_turns = 0
        # we can't scare a bee twice
        has_been_scared = False

        def sting(self, ant):
            """Attack an ANT, reducing its health by 1."""
            ant.reduce_health(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."""
            if self.place.ant is None: 
                return False
            if not self.place.ant.blocks_path:
                return False
            return True

        def action(self, gamestate):
            """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.
            gamestate -- The GameState, used to access game state information.
            """
            if self.is_scared:
                destination = self.place.entrance
                self.scared_turns -= 1
            else:
                destination = self.place.exit

            if self.is_slow:
                self.slow_turns -= 1
                if self.slow_turns == 0:
                    self.is_slow = False
                if gamestate.time % 2 == 0 and self.health > 0 and destination is not None:
                    self.move_to(destination)
                elif self.is_scared:
                    # is_slow + is_scared, we need to cancel `self.scared_turns -= 1`  \
                    # if we didn't move
                    self.scared_turns += 1
            else:
                if self.blocked():
                    self.sting(self.place.ant)
                elif self.health > 0 and destination is not None:
                    self.move_to(destination)

            # we can't put this in side `if self.is_scared`, why?
            # because only when we run if self.is_slow we can know
            # should we cancel it or not
            if self.scared_turns == 0:
                self.is_scared = False

            # Extra credit: Special handling for bee direction

        def add_to(self, place):
            place.bees.append(self)
            Insect.add_to(self, place)

        def remove_from(self, place):
            place.bees.remove(self)
            Insect.remove_from(self, place)

        def slow(self, length):
            """Slow the bee for a further LENGTH turns."""
            self.is_slow = True
            self.slow_turns += length

        def scare(self, length):
            """
            If this Bee has not been scared before, cause it to attempt to
            go backwards LENGTH times.
            """
            # a bee can't be scared twice
            if self.has_been_scared:
                return
            else:
                self.is_scared = True
                self.scared_turns += length
                self.has_been_scared = True
    class SlowThrower(ThrowerAnt):
        """ThrowerAnt that causes Slow on Bees."""

        name = 'Slow'
        food_cost = 4
        # BEGIN Problem EC
        implemented = True   # Change to True to view in the GUI
        # END Problem EC

        def throw_at(self, target):
            if target:
                target.slow(3)


    class ScaryThrower(ThrowerAnt):
        """ThrowerAnt that intimidates Bees, making them back away instead of advancing."""

        name = 'Scary'
        food_cost = 6
        # BEGIN Problem EC
        implemented = True   # Change to True to view in the GUI
        # END Problem EC

        def throw_at(self, target):
            # BEGIN Problem EC
            "*** YOUR CODE HERE ***"
            if target:
                target.scare(2)
            # END Problem EC

option1:

這個ant會攻擊每一個他這個格子里面的bee並且不會阻攔bee(不會被攻擊)

    class NinjaAnt(Ant):
        """NinjaAnt does not block the path and damages all bees in its place.
        This class is optional.
        """

        name = 'Ninja'
        damage = 1
        food_cost = 5
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem Optional 1
        implemented = True   # Change to True to view in the GUI
        blocks_path = False
        # END Problem Optional 1

        def action(self, gamestate):
            # BEGIN Problem Optional 1
            "*** YOUR CODE HERE ***"
            for bee in self.place.bees[:]:
                bee.reduce_health(self.damage)
            # END Problem Optional 1

option2:

這道題就是計算清楚laserant的右邊有多少insect和距離laser的位置
這個ant的特性就是每遠一個格子減少0.25傷害,然后每對一個insect造成一次傷害自己因為電池有限就傷害減少0.0625,
他會攻擊包括自己格子在內(包括container)的所有右邊insect,不會攻擊自己

    class LaserAnt(ThrowerAnt):
        # This class is optional. Only one test is provided for this class.

        name = 'Laser'
        food_cost = 10
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem Optional 2
        implemented = True   # Change to True to view in the GUI
        damage = 2
        # END Problem Optional 2

        def __init__(self, health=1):
            super().__init__(health)
            self.insects_shot = 0
            self.damage = LaserAnt.damage

        def insects_in_front(self):
            # BEGIN Problem Optional 2
            pos = self.place
            distance = {}
            dis = 0
            while pos:
                if not pos.is_hive:
                    for bee in pos.bees:
                        distance[bee] = dis
                    if pos.ant is not None and pos.ant is not self:# 如果有container這個slef.place.ant應該會是container
                        distance[pos.ant] = dis
                        if pos.ant.is_container and pos.ant.ant_contained is not None:
                        # 在problem8里面提到Important: If there are two ants in a specific Place, 
                        # the ant attribute of the Place instance should refer to the container ant, 
                        # and the container ant should contain the non-container ant.
                            if dis != 0:#如果在本格就不需要對ant_contained進行攻擊
                                distance[pos.ant.ant_contained]  = dis
                dis += 1
                pos = pos.entrance
            return distance
            # END Problem Optional 2

        def calculate_damage(self, distance):
            # BEGIN Problem Optional 2
            damage_result = self.damage - 0.0625 * self.insects_shot - 0.25 * distance
            return damage_result if damage_result > 0 else 0
            # END Problem Optional 2

        def action(self, gamestate):
            insects_and_distances = self.insects_in_front()
            for insect, distance in insects_and_distances.items():
                damage = self.calculate_damage(distance)
                insect.reduce_health(damage)
                if damage:
                    self.insects_shot += 1

全部代碼

    """CS 61A presents Ants Vs. SomeBees."""

    import random
    from sys import implementation
    from ucb import main, interact, trace
    from collections import OrderedDict

    ################
    # Core Classes #
    ################


    class Place:
        """A Place holds insects and has an exit to another Place."""
        is_hive = False

        def __init__(self, name, exit=None):
            """Create a Place with the given NAME and EXIT.

            name -- A string; the name of this Place.
            exit -- The Place reached by exiting this Place (may be None).
            """
            self.name = name
            self.exit = exit
            self.bees = []        # A list of Bees
            self.ant = None       # An Ant
            self.entrance = None  # A Place
            # Phase 1: Add an entrance to the exit
            # BEGIN Problem 2
            "*** YOUR CODE HERE ***"
            if exit is not None:
                self.exit.entrance = self
            # END Problem 2

        def add_insect(self, insect):
            """
            Asks the insect to add itself to the current place. This method exists so
                it can be enhanced in subclasses.
            """
            insect.add_to(self)

        def remove_insect(self, insect):
            """
            Asks the insect to remove itself from the current place. This method exists so
                it can be enhanced in subclasses.
            """
            insect.remove_from(self)

        def __str__(self):
            return self.name


    class Insect:
        """An Insect, the base class of Ant and Bee, has health and a Place."""

        damage = 0
        # ADD CLASS ATTRIBUTES HERE
        is_waterproof = False

        def __init__(self, health, place=None):
            """Create an Insect with a health amount and a starting PLACE."""
            self.health = health
            self.place = place  # set by Place.add_insect and Place.remove_insect

        def reduce_health(self, amount):
            """Reduce health by AMOUNT, and remove the insect from its place if it
            has no health remaining.

            >>> test_insect = Insect(5)
            >>> test_insect.reduce_health(2)
            >>> test_insect.health
            3
            """
            self.health -= amount
            if self.health <= 0:
                self.death_callback()
                self.place.remove_insect(self)

        def action(self, gamestate):
            """The action performed each turn.

            gamestate -- The GameState, used to access game state information.
            """

        def death_callback(self):
            # overriden by the gui
            pass

        def add_to(self, place):
            """Add this Insect to the given Place

            By default just sets the place attribute, but this should be overriden in the subclasses
                to manipulate the relevant attributes of Place
            """
            self.place = place

        def remove_from(self, place):
            self.place = None

        def __repr__(self):
            cname = type(self).__name__
            return '{0}({1}, {2})'.format(cname, self.health, self.place)


    class Ant(Insect):
        """An Ant occupies a place and does work for the colony."""

        implemented = False  # Only implemented Ant classes should be instantiated
        food_cost = 0
        is_container = False
        is_doubled = False
        blocks_path = True
        # ADD CLASS ATTRIBUTES HERE

        def __init__(self, health=1):
            """Create an Insect with a HEALTH quantity."""
            super().__init__(health)

        @classmethod
        def construct(cls, gamestate):
            """Create an Ant for a given GameState, or return None if not possible."""
            if cls.food_cost > gamestate.food:
                print('Not enough food remains to place ' + cls.__name__)
                return
            return cls()

        def can_contain(self, other):
            return False

        def store_ant(self, other):
            assert False, "{0} cannot contain an ant".format(self)

        def remove_ant(self, other):
            assert False, "{0} cannot contain an ant".format(self)

        def add_to(self, place):
            if place.ant is None:
                place.ant = self
            else:
                assert (
                    (place.ant is None)
                    or self.can_contain(place.ant)
                    or place.ant.can_contain(self) 
                ), 'Two ants in {0}'.format(place)
                # BEGIN Problem 8
                if place.ant.is_container and place.ant.can_contain(self):
                    place.ant.store_ant(self)
                elif self.is_container and self.can_contain(place.ant):
                    self.store_ant(place.ant)
                    place.ant = self
                # END Problem 8
            Insect.add_to(self, place)

        def remove_from(self, place):
            if place.ant is self:
                place.ant = None
            elif place.ant is None:
                assert False, '{0} is not in {1}'.format(self, place)
            else:
                place.ant.remove_ant(self)
            Insect.remove_from(self, place)

        def buff(self):
            """Double this ants's damage, if it has not already been buffed."""
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            self.damage *= 2
            # END Problem 12


    class HarvesterAnt(Ant):
        """HarvesterAnt produces 1 additional food per turn for the colony."""

        name = 'Harvester'
        implemented = True
        # OVERRIDE CLASS ATTRIBUTES HERE
        food_cost = 2

        def action(self, gamestate):
            """Produce 1 additional food for the colony.

            gamestate -- The GameState, used to access game state information.
            """
            # BEGIN Problem 1
            "*** YOUR CODE HERE ***"
            gamestate.food = gamestate.food + 1
            # END Problem 1


    class ThrowerAnt(Ant):
        """ThrowerAnt throws a leaf each turn at the nearest Bee in its range."""

        name = 'Thrower'
        implemented = True
        damage = 1
        # ADD/OVERRIDE CLASS ATTRIBUTES HERE
        food_cost = 3
        min_range = -1
        max_range = float('inf')
        def nearest_bee(self):
            """Return the nearest Bee in a Place that is not the HIVE, connected to
            the ThrowerAnt's Place by following entrances.

            This method returns None if there is no such Bee (or none in range).
            """
            # BEGIN Problem 3 and 4
            pos = self.place
            sept = 0
            while pos.entrance is not None:
                if not pos.is_hive:
                    if len(pos.bees) > 0 and sept >= self.min_range and sept <= self.max_range:
                        return random_bee(pos.bees)
                pos = pos.entrance
                sept += 1
            return None
            # REPLACE THIS LINE
            # END Problem 3 and 4

        def throw_at(self, target):
            """Throw a leaf at the TARGET Bee, reducing its health."""
            if target is not None:
                target.reduce_health(self.damage)

        def action(self, gamestate):
            """Throw a leaf at the nearest Bee in range."""
            self.throw_at(self.nearest_bee())

    def random_bee(bees):
        """Return a random bee from a list of bees, or return None if bees is empty."""
        assert isinstance(bees, list), "random_bee's argument should be a list but was a %s" % type(bees).__name__
        if bees:
            return random.choice(bees)

    ##############
    # Extensions #
    ##############


    class ShortThrower(ThrowerAnt):
        """A ThrowerAnt that only throws leaves at Bees at most 3 places away."""

        name = 'Short'
        food_cost = 2
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 4
        implemented = True   # Change to True to view in the GUI
        max_range = 3
        # END Problem 4


    class LongThrower(ThrowerAnt):
        """A ThrowerAnt that only throws leaves at Bees at least 5 places away."""

        name = 'Long'
        food_cost = 2
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 4
        implemented = True   # Change to True to view in the GUI
        min_range = 5
        # END Problem 4


    class FireAnt(Ant):
        """FireAnt cooks any Bee in its Place when it expires."""

        name = 'Fire'
        damage = 3
        food_cost = 5
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 5
        implemented = True   # Change to True to view in the GUI
        # END Problem 5

        def __init__(self, health=3):
            """Create an Ant with a HEALTH quantity."""
            super().__init__(health)

        def reduce_health(self, amount):
            """Reduce health by AMOUNT, and remove the FireAnt from its place if it
            has no health remaining.

            Make sure to reduce the health of each bee in the current place, and apply
            the additional damage if the fire ant dies.
            """
            # BEGIN Problem 5
            "*** YOUR CODE HERE ***"
            pos = self.place
            for i in pos.bees[:]:
                i.reduce_health(amount)
            if amount >= self.health:
                for i in pos.bees[:]:
                    i.reduce_health(self.damage)
                super().reduce_health(amount)
            else:
                super().reduce_health(amount)
            # END Problem 5

    # BEGIN Problem 6
    # The WallAnt class
    class WallAnt(Ant):
        name = 'Wall'
        implemented = True 
        food_cost = 4
        def __init__(self, health=4):
            """Create an Ant with a HEALTH quantity."""
            super().__init__(health)
    # END Problem 6

    # BEGIN Problem 7
    # The HungryAnt Class
    class HungryAnt(Ant):
        name = 'Hungry'
        implemented = True 
        food_cost = 4
        chew_duration = 3
        def __init__(self, health=1):
            """Create an Ant with a HEALTH quantity."""
            super().__init__(health)
            self.chew_countdown = 0
        def action(self,gamestate):
            if self.chew_countdown != 0:
                self.chew_countdown -= 1
            else:
                pos =  self.place
                if len(pos.bees) > 0 :
                    self.chew_countdown = self.chew_duration
                    bee = random_bee(pos.bees)
                    bee.reduce_health(bee.health)

    # END Problem 7


    class ContainerAnt(Ant):
        """
        ContainerAnt can share a space with other ants by containing them.
        """
        is_container = True

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.ant_contained = None

        def can_contain(self, other):
            # BEGIN Problem 8
            "*** YOUR CODE HERE ***"
            if self.ant_contained is None and not other.is_container:
                return True
            # END Problem 8

        def store_ant(self, ant):
            # BEGIN Problem 8
            "*** YOUR CODE HERE ***"
            self.ant_contained = ant
            # END Problem 8

        def remove_ant(self, ant):
            if self.ant_contained is not ant:
                assert False, "{} does not contain {}".format(self, ant)
            self.ant_contained = None

        def remove_from(self, place):
            # Special handling for container ants (this is optional)
            if place.ant is self:
                # Container was removed. Contained ant should remain in the game
                place.ant = place.ant.ant_contained
                Insect.remove_from(self, place)
            else:
                # default to normal behavior
                Ant.remove_from(self, place)

        def action(self, gamestate):
            # BEGIN Problem 8
            "*** YOUR CODE HERE ***"
            if self.ant_contained is not None:
                return self.ant_contained.action(gamestate)
            # END Problem 8


    class BodyguardAnt(ContainerAnt):
        """BodyguardAnt provides protection to other Ants."""

        name = 'Bodyguard'
        food_cost = 4
        implemented = True  
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 8
        def __init__(self, health = 2):
            super().__init__(health)
         # Change to True to view in the GUI
        # END Problem 8

    # BEGIN Problem 9
    # The TankAnt class
    class TankAnt(ContainerAnt):
        name = 'Tank'
        damage = 1
        food_cost = 6
        implemented = True
        def __init__(self, health = 2):
            super().__init__(health)
        def action(self,gamestate):
            if self.ant_contained is not None:
                self.ant_contained.action(gamestate)
            for i in self.place.bees[:]:
                i.reduce_health(self.damage)

    # END Problem 9


    class Water(Place):
        """Water is a place that can only hold waterproof insects."""

        def add_insect(self, insect):
            """Add an Insect to this place. If the insect is not waterproof, reduce
            its health to 0."""
            # BEGIN Problem 10
            "*** YOUR CODE HERE ***"
            super().add_insect(insect)
            if not insect.is_waterproof:
                insect.reduce_health(insect.health)
            # END Problem 10

    # BEGIN Problem 11
    # The ScubaThrower class
    class ScubaThrower(ThrowerAnt):
        food_cost = 6
        name = 'ScubaThrower'
        is_waterproof = True
        def _init_(self, health = 1):
            super().__init__(health)
        
    # END Problem 11

    # BEGIN Problem 12


    class QueenAnt(ScubaThrower):  # You should change this line
    # END Problem 12
        """The Queen of the colony. The game is over if a bee enters her place."""

        name = 'Queen'
        food_cost = 7
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem 12
        implemented = True   # Change to True to view in the GUI
        # END Problem 12

        @classmethod
        def construct(cls, gamestate):
            """
            Returns a new instance of the Ant class if it is possible to construct, or
            returns None otherwise. Remember to call the construct() method of the superclass!
            """
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            if cls.food_cost > gamestate.food:
                print('Not enough food remains to place ' + cls.__name__)
                return
            if not gamestate.has_queen:
                gamestate.has_queen = True
                return super().construct(gamestate)
            else:
                return None
            # END Problem 12

        def action(self, gamestate):
            """A queen ant throws a leaf, but also doubles the damage of ants
            in her tunnel.
            """
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            super().action(gamestate)
            pos = self.place.exit
            while pos:
                if pos.ant is not None:
                    if not pos.ant.is_doubled:
                        pos.ant.is_doubled = True
                        pos.ant.buff()
                    if pos.ant.is_container and pos.ant.ant_contained is not None:
                        # the pos.ant.ant_contained may change
                        if not pos.ant.ant_contained.is_doubled:
                            pos.ant.ant_contained.buff()
                            pos.ant.ant_contained.is_doubled = True
                pos = pos.exit
            # END Problem 12

        def reduce_health(self, amount):
            """Reduce health by AMOUNT, and if the QueenAnt has no health
            remaining, signal the end of the game.
            """
            # BEGIN Problem 12
            "*** YOUR CODE HERE ***"
            if self.health <= amount:
                ants_lose()
            # END Problem 12
        def remove_from(self, place):
            None


    class AntRemover(Ant):
        """Allows the player to remove ants from the board in the GUI."""

        name = 'Remover'
        implemented = False

        def __init__(self):
            super().__init__(0)


    class Bee(Insect):
        """A Bee moves from place to place, following exits and stinging ants."""

        name = 'Bee'
        damage = 1
        is_waterproof = True
        # 2 flags
        is_slow = False
        is_scared = False
        # turns remained
        slow_turns = 0
        scared_turns = 0
        # we can't scare a bee twice
        has_been_scared = False

        def sting(self, ant):
            """Attack an ANT, reducing its health by 1."""
            ant.reduce_health(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."""
            if self.place.ant is None: 
                return False
            if not self.place.ant.blocks_path:
                return False
            return True

        def action(self, gamestate):
            """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.
            gamestate -- The GameState, used to access game state information.
            """
            if self.is_scared:
                destination = self.place.entrance
                self.scared_turns -= 1
            else:
                destination = self.place.exit

            if self.is_slow:
                self.slow_turns -= 1
                if self.slow_turns == 0:
                    self.is_slow = False
                if gamestate.time % 2 == 0 and self.health > 0 and destination is not None:
                    self.move_to(destination)
                elif self.is_scared:
                    # is_slow + is_scared, we need to cancel `self.scared_turns -= 1`  \
                    # if we didn't move
                    self.scared_turns += 1
            else:
                if self.blocked():
                    self.sting(self.place.ant)
                elif self.health > 0 and destination is not None:
                    self.move_to(destination)

            # we can't put this in side `if self.is_scared`, why?
            # because only when we run if self.is_slow we can know
            # should we cancel it or not
            if self.scared_turns == 0:
                self.is_scared = False

            # Extra credit: Special handling for bee direction

        def add_to(self, place):
            place.bees.append(self)
            Insect.add_to(self, place)

        def remove_from(self, place):
            place.bees.remove(self)
            Insect.remove_from(self, place)

        def slow(self, length):
            """Slow the bee for a further LENGTH turns."""
            self.is_slow = True
            self.slow_turns += length

        def scare(self, length):
            """
            If this Bee has not been scared before, cause it to attempt to
            go backwards LENGTH times.
            """
            # a bee can't be scared twice
            if self.has_been_scared:
                return
            else:
                self.is_scared = True
                self.scared_turns += length
                self.has_been_scared = True



    ############
    # Optional #
    ############

    class NinjaAnt(Ant):
        """NinjaAnt does not block the path and damages all bees in its place.
        This class is optional.
        """

        name = 'Ninja'
        damage = 1
        food_cost = 5
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem Optional 1
        implemented = True   # Change to True to view in the GUI
        blocks_path = False
        # END Problem Optional 1

        def action(self, gamestate):
            # BEGIN Problem Optional 1
            "*** YOUR CODE HERE ***"
            for bee in self.place.bees[:]:
                bee.reduce_health(self.damage)
            # END Problem Optional 1

    ############
    # Statuses #
    ############


    class SlowThrower(ThrowerAnt):
        """ThrowerAnt that causes Slow on Bees."""

        name = 'Slow'
        food_cost = 4
        # BEGIN Problem EC
        implemented = True   # Change to True to view in the GUI
        # END Problem EC

        def throw_at(self, target):
            if target:
                target.slow(3)


    class ScaryThrower(ThrowerAnt):
        """ThrowerAnt that intimidates Bees, making them back away instead of advancing."""

        name = 'Scary'
        food_cost = 6
        # BEGIN Problem EC
        implemented = True   # Change to True to view in the GUI
        # END Problem EC

        def throw_at(self, target):
            # BEGIN Problem EC
            "*** YOUR CODE HERE ***"
            if target:
                target.scare(2)
            # END Problem EC


    class LaserAnt(ThrowerAnt):
        # This class is optional. Only one test is provided for this class.

        name = 'Laser'
        food_cost = 10
        # OVERRIDE CLASS ATTRIBUTES HERE
        # BEGIN Problem Optional 2
        implemented = True   # Change to True to view in the GUI
        damage = 2
        # END Problem Optional 2

        def __init__(self, health=1):
            super().__init__(health)
            self.insects_shot = 0
            self.damage = LaserAnt.damage

        def insects_in_front(self):
            # BEGIN Problem Optional 2
            pos = self.place
            distance = {}
            dis = 0
            while pos:
                if not pos.is_hive:
                    for bee in pos.bees:
                        distance[bee] = dis
                    if pos.ant is not None and pos.ant is not self:# 如果有container這個slef.place.ant應該會是container
                        distance[pos.ant] = dis
                        if pos.ant.is_container and pos.ant.ant_contained is not None:
                        # 在problem8里面提到Important: If there are two ants in a specific Place, 
                        # the ant attribute of the Place instance should refer to the container ant, 
                        # and the container ant should contain the non-container ant.
                            if dis != 0:#如果在本格就不需要對ant_contained進行攻擊
                                distance[pos.ant.ant_contained]  = dis
                dis += 1
                pos = pos.entrance
            return distance
            # END Problem Optional 2

        def calculate_damage(self, distance):
            # BEGIN Problem Optional 2
            damage_result = self.damage - 0.0625 * self.insects_shot - 0.25 * distance
            return damage_result if damage_result > 0 else 0
            # END Problem Optional 2

        def action(self, gamestate):
            insects_and_distances = self.insects_in_front()
            for insect, distance in insects_and_distances.items():
                damage = self.calculate_damage(distance)
                insect.reduce_health(damage)
                if damage:
                    self.insects_shot += 1


    ##################
    # Bees Extension #
    ##################

    class Wasp(Bee):
        """Class of Bee that has higher damage."""
        name = 'Wasp'
        damage = 2


    class Hornet(Bee):
        """Class of bee that is capable of taking two actions per turn, although
        its overall damage output is lower. Immune to statuses.
        """
        name = 'Hornet'
        damage = 0.25

        def action(self, gamestate):
            for i in range(2):
                if self.health > 0:
                    super().action(gamestate)

        def __setattr__(self, name, value):
            if name != 'action':
                object.__setattr__(self, name, value)


    class NinjaBee(Bee):
        """A Bee that cannot be blocked. Is capable of moving past all defenses to
        assassinate the Queen.
        """
        name = 'NinjaBee'

        def blocked(self):
            return False


    class Boss(Wasp, Hornet):
        """The leader of the bees. Combines the high damage of the Wasp along with
        status immunity of Hornets. Damage to the boss is capped up to 8
        damage by a single attack.
        """
        name = 'Boss'
        damage_cap = 8
        action = Wasp.action

        def reduce_health(self, amount):
            super().reduce_health(self.damage_modifier(amount))

        def damage_modifier(self, amount):
            return amount * self.damage_cap / (self.damage_cap + amount)


    class Hive(Place):
        """The Place from which the Bees launch their assault.

        assault_plan -- An AssaultPlan; when & where bees enter the colony.
        """
        is_hive = True

        def __init__(self, assault_plan):
            self.name = 'Hive'
            self.assault_plan = assault_plan
            self.bees = []
            for bee in assault_plan.all_bees:
                self.add_insect(bee)
            # The following attributes are always None for a Hive
            self.entrance = None
            self.ant = None
            self.exit = None

        def strategy(self, gamestate):
            exits = [p for p in gamestate.places.values() if p.entrance is self]
            for bee in self.assault_plan.get(gamestate.time, []):
                bee.move_to(random.choice(exits))
                gamestate.active_bees.append(bee)


    class GameState:
        """An ant collective that manages global game state and simulates time.

        Attributes:
        time -- elapsed time
        food -- the colony's available food total
        places -- A list of all places in the colony (including a Hive)
        bee_entrances -- A list of places that bees can enter
        """

        def __init__(self, strategy, beehive, ant_types, create_places, dimensions, food=2):
            """Create an GameState for simulating a game.

            Arguments:
            strategy -- a function to deploy ants to places
            beehive -- a Hive full of bees
            ant_types -- a list of ant classes
            create_places -- a function that creates the set of places
            dimensions -- a pair containing the dimensions of the game layout
            """
            self.time = 0
            self.food = food
            self.strategy = strategy
            self.beehive = beehive
            self.ant_types = OrderedDict((a.name, a) for a in ant_types)
            self.dimensions = dimensions
            self.active_bees = []
            self.configure(beehive, create_places)
            self.has_queen = False

        def configure(self, beehive, create_places):
            """Configure the places in the colony."""
            self.base = AntHomeBase('Ant Home Base')
            self.places = OrderedDict()
            self.bee_entrances = []

            def register_place(place, is_bee_entrance):
                self.places[place.name] = place
                if is_bee_entrance:
                    place.entrance = beehive
                    self.bee_entrances.append(place)
            register_place(self.beehive, False)
            create_places(self.base, register_place, self.dimensions[0], self.dimensions[1])

        def simulate(self):
            """Simulate an attack on the ant colony (i.e., play the game)."""
            num_bees = len(self.bees)
            try:
                while True:
                    self.beehive.strategy(self)         # Bees invade
                    self.strategy(self)                 # Ants deploy
                    for ant in self.ants:               # Ants take actions
                        if ant.health > 0:
                            ant.action(self)
                    for bee in self.active_bees[:]:     # Bees take actions
                        if bee.health > 0:
                            bee.action(self)
                        if bee.health <= 0:
                            num_bees -= 1
                            self.active_bees.remove(bee)
                    if num_bees == 0:
                        raise AntsWinException()
                    self.time += 1
            except AntsWinException:
                print('All bees are vanquished. You win!')
                return True
            except AntsLoseException:
                print('The ant queen has perished. Please try again.')
                return False

        def deploy_ant(self, place_name, ant_type_name):
            """Place an ant if enough food is available.

            This method is called by the current strategy to deploy ants.
            """
            ant_type = self.ant_types[ant_type_name]
            ant = ant_type.construct(self)
            if ant:
                self.places[place_name].add_insect(ant)
                self.food -= ant.food_cost
                return ant

        def remove_ant(self, place_name):
            """Remove an Ant from the game."""
            place = self.places[place_name]
            if place.ant is not None:
                place.remove_insect(place.ant)

        @property
        def ants(self):
            return [p.ant for p in self.places.values() if p.ant is not None]

        @property
        def bees(self):
            return [b for p in self.places.values() for b in p.bees]

        @property
        def insects(self):
            return self.ants + self.bees

        def __str__(self):
            status = ' (Food: {0}, Time: {1})'.format(self.food, self.time)
            return str([str(i) for i in self.ants + self.bees]) + status


    class AntHomeBase(Place):
        """AntHomeBase at the end of the tunnel, where the queen resides."""

        def add_insect(self, insect):
            """Add an Insect to this Place.

            Can't actually add Ants to a AntHomeBase. However, if a Bee attempts to
            enter the AntHomeBase, a AntsLoseException is raised, signaling the end
            of a game.
            """
            assert isinstance(insect, Bee), 'Cannot add {0} to AntHomeBase'
            raise AntsLoseException()


    def ants_win():
        """Signal that Ants win."""
        raise AntsWinException()


    def ants_lose():
        """Signal that Ants lose."""
        raise AntsLoseException()


    def ant_types():
        """Return a list of all implemented Ant classes."""
        all_ant_types = []
        new_types = [Ant]
        while new_types:
            new_types = [t for c in new_types for t in c.__subclasses__()]
            all_ant_types.extend(new_types)
        return [t for t in all_ant_types if t.implemented]


    class GameOverException(Exception):
        """Base game over Exception."""
        pass


    class AntsWinException(GameOverException):
        """Exception to signal that the ants win."""
        pass


    class AntsLoseException(GameOverException):
        """Exception to signal that the ants lose."""
        pass


    def interactive_strategy(gamestate):
        """A strategy that starts an interactive session and lets the user make
        changes to the gamestate.

        For example, one might deploy a ThrowerAnt to the first tunnel by invoking
        gamestate.deploy_ant('tunnel_0_0', 'Thrower')
        """
        print('gamestate: ' + str(gamestate))
        msg = '<Control>-D (<Control>-Z <Enter> on Windows) completes a turn.\n'
        interact(msg)

    ###########
    # Layouts #
    ###########


    def wet_layout(queen, register_place, tunnels=3, length=9, moat_frequency=3):
        """Register a mix of wet and and dry places."""
        for tunnel in range(tunnels):
            exit = queen
            for step in range(length):
                if moat_frequency != 0 and (step + 1) % moat_frequency == 0:
                    exit = Water('water_{0}_{1}'.format(tunnel, step), exit)
                else:
                    exit = Place('tunnel_{0}_{1}'.format(tunnel, step), exit)
                register_place(exit, step == length - 1)


    def dry_layout(queen, register_place, tunnels=3, length=9):
        """Register dry tunnels."""
        wet_layout(queen, register_place, tunnels, length, 0)


    #################
    # Assault Plans #
    #################

    class AssaultPlan(dict):
        """The Bees' plan of attack for the colony.  Attacks come in timed waves.

        An AssaultPlan is a dictionary from times (int) to waves (list of Bees).

        >>> AssaultPlan().add_wave(4, 2)
        {4: [Bee(3, None), Bee(3, None)]}
        """

        def add_wave(self, bee_type, bee_health, time, count):
            """Add a wave at time with count Bees that have the specified health."""
            bees = [bee_type(bee_health) for _ in range(count)]
            self.setdefault(time, []).extend(bees)
            return self

        @property
        def all_bees(self):
            """Place all Bees in the beehive and return the list of Bees."""
            return [bee for wave in self.values() for bee in wave]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM