Пример #1
0
    def test_intimidation(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(4))
        robbers = agentFactory.copyAgents(agentFactory.buildRobbers(4))

        totalDiggerStrength = encounter.getTotalStrength(diggers)
        totalRobberStrength = encounter.getTotalStrength(robbers)

        oldRobberGold = {}
        for robber in robbers:
            robber.addGold(100)
            oldRobberGold[robber] = robber.getGold()

        oldDiggerGold = {}
        for digger in diggers:
            digger.addGold(100)
            oldDiggerGold[digger] = digger.getGold()

        encounter.intimidation(aggressiveAgents=robbers, passiveAgents=diggers)

        if totalRobberStrength >= 2 * totalDiggerStrength:
            pass
        # TODO continue making the test

        pass
Пример #2
0
    def test_collectiveDigging(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        goldResource = GoldResource(1000)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        totalDiggingPower = 0
        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        _ = encounter.collectiveDigging(diggers, goldResource)

        assert goldResource.getQuantity() == 1000 - totalDiggingPower

        goldResource = GoldResource(1)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        encounter.priorityDigging(diggers, goldResource)

        totalDiggingPower = 0
        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        assert goldResource.getQuantity() == 0
Пример #3
0
    def test_priorityDigging(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        goldResource = GoldResource(1000)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        totalDiggingPower = 0
        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        totalAmountCollected = encounter.priorityDigging(diggers, goldResource)

        assert goldResource.getQuantity(
        ) == 1000 - totalDiggingPower or goldResource.getQuantity() == 0
        assert totalAmountCollected < totalDiggingPower

        goldResource = GoldResource(1)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(100))
        lastAgent = diggers[len(diggers) - 1]
        originalLastAgentGold = lastAgent.getGold()

        encounter.priorityDigging(diggers, goldResource)

        totalDiggingPower = 0
        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        assert goldResource.getQuantity() == 0
        assert lastAgent.getGold() == originalLastAgentGold
Пример #4
0
    def test_getAllEncounters(self):

        encounterEngine = GoldHunterEncounter()

        encounters = encounterEngine.getAllEncounters()

        actualEncounters = encounterEngine.passiveEncounters + encounterEngine.robbingEncounters + encounterEngine.aggressiveEncounters

        assert encounters == actualEncounters
Пример #5
0
    def test_addTuples(self):

        encounterEngine = GoldHunterEncounter()

        tuple1 = (5, 7)
        tuple2 = (8, 1)

        addedTuple = encounterEngine.addTuples(tuple1, tuple2)
        actualAddedTuple = (13, 8)

        assert addedTuple == actualAddedTuple
Пример #6
0
    def test_getStrongestAgent(self):

        agentFactory = GHAgentFactory()
        encounterEngine = GoldHunterEncounter()

        agents = agentFactory.copyAgents(agentFactory.buildRobbers(9))
        agents[0].strength = 1000000

        strongestAgent = encounterEngine.getStrongestAgent(agents)
        actualStrongestAgent = agents[0]

        assert actualStrongestAgent == strongestAgent
Пример #7
0
    def test_getTotalGoldOwned(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))
        actualTotalGold = 90

        for digger in diggers:
            digger.addGold(10)

        testTotalGold = encounter.getTotalGoldOwned(diggers)

        assert actualTotalGold == testTotalGold
Пример #8
0
    def test_getTotalMaxGoldPerTurn(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))
        actualMaxGold = 0

        for digger in diggers:
            actualMaxGold += digger.getMaxGoldPerTurn()

        testMaxGold = encounter.getTotalMaxGoldPerTurn(diggers)

        assert actualMaxGold == testMaxGold
Пример #9
0
    def test_getTotalStrength(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))
        actualTotalStrength = 0

        for digger in diggers:
            actualTotalStrength += digger.getStrength()

        testTotalStrength = encounter.getTotalStrength(diggers)

        assert actualTotalStrength == testTotalStrength
    def __init__(self, worldSize=(3, 3), encounterEngine=None):

        self.agents = []
        self.world = None
        self.resources = []
        self.encounterEngine = encounterEngine
        if self.encounterEngine is None:
            logging.warning(
                "creating the default encounter engine as none is supplied")
            self.encounterEngine = GoldHunterEncounter()

        self.actionsHandler = GHAgentActions()
        self.init(worldSize)

        pass
Пример #11
0
    def test_philanthropy(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        goldResource = GoldResource(1000)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        totalDiggingPower = 0

        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        encounter.philanthropy(passiveAgents=diggers,
                               goldResource=goldResource)

        assert goldResource.getQuantity() == 1000 - totalDiggingPower
Пример #12
0
    def test_collaboration(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        goldResource = GoldResource(1000)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        totalDiggingPower = 0
        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        encounter.collaboration(passiveAgents=diggers,
                                goldResource=goldResource)

        print(f"current in resource: {goldResource.getQuantity()}")
        print(f"total lost: {totalDiggingPower}")

        assert goldResource.getQuantity() == 1000 - totalDiggingPower
Пример #13
0
    def test_monopoly(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        goldResource = GoldResource(1000)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        totalDiggingPower = 0

        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        encounter.monopoly(passiveAgents=diggers, goldResource=goldResource)

        assert goldResource.getQuantity() == 1000 - totalDiggingPower

        goldResource = GoldResource(1)

        for digger in diggers:
            digger.setGold(0)

        diggers[0].strength = 10000000

        encounter.monopoly(passiveAgents=diggers, goldResource=goldResource)

        self.assertEqual(1, diggers[0].getGold())
Пример #14
0
    def test_competition(self):

        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        goldResource = GoldResource(1000)
        diggers = agentFactory.copyAgents(agentFactory.buildDiggers(9))

        totalDiggingPower = 0
        for digger in diggers:
            totalDiggingPower += digger.getDiggingRate()

        encounter.competition(passiveAgents=diggers, goldResource=goldResource)

        assert goldResource.getQuantity() == 1000 - totalDiggingPower

        goldResource = GoldResource(100)

        oldGoldValues = {}
        for digger in diggers:
            oldGoldValues[digger] = digger.getGold()

        encounter.competition(passiveAgents=diggers, goldResource=goldResource)

        for digger in oldGoldValues.keys():
            oldGoldValue = oldGoldValues[digger]
            assert digger.getGold() - oldGoldValue <= digger.getMaxGoldPerTurn(
            )
Пример #15
0
    def test_getPossibleNearbyLocations(self):
        world = GridWorld()
        # agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()

        assert world.size == (10, 10)
        locationOfEncounter = (5, 5)
        nearByLocations = encounter.getPossibleNearbyLocations(
            locationOfEncounter, world)
        assert nearByLocations[0] == (4, 4)

        locationOfEncounter = (0, 0)
        nearByLocations = encounter.getPossibleNearbyLocations(
            locationOfEncounter, world)
        assert nearByLocations[0] == (0, 0)

        locationOfEncounter = (9, 9)
        nearByLocations = encounter.getPossibleNearbyLocations(
            locationOfEncounter, world)
        print(len(nearByLocations))
        assert nearByLocations[0] == (8, 8)
        assert len(nearByLocations) == 4
    def test_takeAction(self):

        actionsHandler = test_GHAgentActions.actionsHandler
        agentFactory = test_GHAgentActions.agentFactory
        world = test_GHAgentActions.world
        agent = agentFactory.buildDigger()
        encounterEngine = GoldHunterEncounter(actionsHandler)

        world.addAgentToLocation((5, 5), agent)
        agent.updateAgentLocation((5, 5))

        actionsHandler.takeAction(agent, world, encounterEngine)

        assert agent.getNextAction().name == 'MoveUp'
class GoldHunters(Game):
    def __init__(self, worldSize=(3, 3), encounterEngine=None):

        self.agents = []
        self.world = None
        self.resources = []
        self.encounterEngine = encounterEngine
        if self.encounterEngine is None:
            logging.warning(
                "creating the default encounter engine as none is supplied")
            self.encounterEngine = GoldHunterEncounter()

        self.actionsHandler = GHAgentActions()
        self.init(worldSize)

        pass

    def init(self, worldSize=(3, 3)):

        # 1. Create a gridworld
        self.world = GridWorld(size=worldSize)
        # 2. Create some agents
        self.createAgents()
        # 3. Put agents in the world (you will need to remove them from previous node, move the agent to the location and also add them to the corresponding node in the world)
        self.putAgentsInWorld()
        # 4. Create some gold resources
        self.createGoldResources()
        # 5. Put gold resources in the world.
        self.putGoldResourcesInWorld()
        # 6. do not Run the game loop.
        # self.run()

        pass

    def createAgents(self):
        factory = GHAgentFactory(self.actionsHandler)
        self.agents = [factory.buildDigger(), factory.buildRobber()]
        # self.agents = factory.buildDiggers(2)
        pass

    def putAgentsInWorld(self):

        for agent in self.agents:
            randomXLocation = randint(0, self.world.size[0] - 1)
            randomYLocation = randint(0, self.world.size[1] - 1)
            self.moveAgent(agent, (randomXLocation, randomYLocation))
        pass

    def moveAgent(self, agent, newLocation):

        # TODO do not move if the there is no change in the location.

        oldLocation = agent.getLocation()
        logging.info(
            f"moving agent {agent.id} from {oldLocation} to {newLocation}")

        if oldLocation[0] == newLocation[0] and oldLocation[1] == newLocation[
                1]:
            return

        self.removeAgentFromOldLocation(agent)

        agent.updateAgentLocation(newLocation)

        # logging.info(f"adding agent {agent} to location {newLocation}")
        self.world.addAgentToLocation(newLocation, agent)

        pass

    def removeAgentFromOldLocation(self, agent):

        try:
            oldLocation = agent.getLocation()
            if self.world.hasLocation(oldLocation) is False:
                return

            # logging.info(f"removing agent {agent} from location {oldLocation}")
            self.world.removeAgentFromLocation(oldLocation, agent)
        except NotFoundInTheWorld as e:
            pass
        except Exception as e:
            raise e

        pass

    def addAgent(self, agent, newLocation):
        self.agents.append(agent)

    def getAgents(self):
        return self.agents

    def createGoldResources(self, count=5):

        for _ in range(count):
            self.resources.append(GoldResource(500))
        pass

    def putGoldResourcesInWorld(self):
        for resource in self.resources:
            randomXLocation = randint(0, self.world.size[0] - 1)
            randomYLocation = randint(0, self.world.size[1] - 1)
            location = (randomXLocation, randomYLocation)
            resource.setLocation(location)
            logging.info(f"adding gold [{resource}] to {location}")
            self.world.addResourceToLocation(location, resource)
        pass

    def changeState(self):
        self.updateGame()

    def updateGame(self):
        #for each agent:
        #check next action
        #if its move then call removeAgentFromOldLocation() and call moveAgentToNewLocation()
        #if agent digs, use a dig encounter with the agent by itself
        #if agent robs, use sabotage encounter?

        for agent in self.agents:
            action = agent.getNextAction()
            # TODO do whatever you want to do.

            # 1 if the action is a move event.
            if isinstance(action, GHMoveAction):
                newLocation = self.actionsHandler.aLocationNearby(
                    agent, action.direction, self.world)
                self.moveAgent(agent, newLocation)

        self.doEncounters()

        pass

    def doEncounters(self):

        encounterResults = []
        for location in self.world.locations():
            result = self.doEncounterAtLocation(location)
            if result is None:
                # TODO less than one agent here. DIG DIG.
                agents = self.world.getAgentsAtLocation(location)
                resources = self.world.getResourcesAtLocation(location)

                if len(agents) > 0 and len(resources) > 0:
                    logging.info(
                        f"agent {agents[0].id} is digging gold at {location}")
                    amount = self.actionsHandler.dig(agents[0], resources[0])
                    agents[0].addGold(amount)
                    # TODO update it to handle arrays)

            else:
                encounterResults.append(result)
                self.updateAgentsAndResourcesFromEncounterResult(result)

        logging.debug(encounterResults)
        pass

    def updateAgentsAndResourcesFromEncounterResult(self, encounterResult):
        """
        { agent1Object: changedObject,
          agent2Object: changedObject,
          goldResource1: changed...
        }
        """

        for originalObject in encounterResult:
            changedObject = encounterResult[originalObject]
            if isinstance(originalObject, GoldResource):
                # TODO changed resource.
                self.updateResource(originalObject, changedObject)

            else:
                # this is an agent.
                self.updateAgent(originalObject, changedObject)

        pass

    def updateResource(self, originalObject, changedObject):
        #1. copy properties
        logging.info(
            f"updating resource: {originalObject.getQuantity()} to {changedObject.getQuantity()}"
        )
        originalObject.setQuantity(changedObject.getQuantity())
        pass

    def updateAgent(self, originalObject, changedObject):
        #1. copy properties getPayoffFromEncounterResults
        logging.info(
            f"updating agent: {originalObject.getGold()} to {changedObject.getGold()}"
        )
        originalObject.setGold(changedObject.getGold())

        pass

    def doEncounterAtLocation(self, location):

        agents = self.world.getAgentsAtLocation(location)
        if len(agents) < 2:
            return None  # no encounter

        resources = self.world.getResourcesAtLocation(location)

        if len(resources) == 0:
            return self.encounterEngine.getEncounterResults(agents)

        else:
            # TODO encounter method does not handle more than one resource.
            return self.encounterEngine.getEncounterResults(
                agents, resources[0])

    def run(self, timesToRun=1, interactive=False):
        # run the loop for timesToRun times

        for turn in range(timesToRun):

            logging.info(f"turn: {turn + 1}")
            self.runGameLoop(turn)
            for agent in self.agents:
                logging.info(agent.getResourceStats())

            if interactive is True:
                _ = input("press any key to continue")

        pass

    def runGameLoop(self, turn):

        for agent in self.agents:
            self.actionsHandler.takeTurn(
                agent, self.world, self.encounterEngine
            )  # it updates nextAction property in an agent.
        self.updateGame()
Пример #18
0
    def test_simulateMultipleEncounters(self):
        # TODO continue
        agentFactory = GHAgentFactory()
        encounter = GoldHunterEncounter()
        originalGoldQuantity = 1000
        goldResource = GoldResource(originalGoldQuantity)

        diggers = agentFactory.buildDiggers(5)
        robbers = agentFactory.buildRobbers(4)

        # single passive encounter
        allEncounterResults = encounter.simulateMultipleEncounters(
            [encounter.collaboration],
            passiveAgents=diggers,
            goldResource=goldResource)

        for encounterResults in allEncounterResults:
            self.assertIsNotNone(encounterResults.get(goldResource))
            for digger in diggers:
                self.assertIsNotNone(encounterResults.get(digger))

        self.assertEqual(originalGoldQuantity, goldResource.getQuantity())

        # all passive encounters
        allEncounterResults = encounter.simulateMultipleEncounters(
            encounter.passiveEncounters,
            passiveAgents=diggers,
            goldResource=goldResource)

        for encounterResults in allEncounterResults:
            self.assertIsNotNone(encounterResults.get(goldResource))
            for digger in diggers:
                self.assertIsNotNone(encounterResults.get(digger))

        self.assertEqual(originalGoldQuantity, goldResource.getQuantity())

        # single robbing encounter
        allEncounterResults = encounter.simulateMultipleEncounters(
            [encounter.intimidation],
            passiveAgents=diggers,
            aggressiveAgents=robbers)

        for encounterResults in allEncounterResults:
            for digger in diggers:
                self.assertIsNotNone(encounterResults.get(digger))

            for robber in robbers:
                self.assertIsNotNone(encounterResults.get(robber))

        # all robbing encounters
        allEncounterResults = encounter.simulateMultipleEncounters(
            encounter.robbingEncounters,
            passiveAgents=diggers,
            aggressiveAgents=robbers)

        for encounterResults in allEncounterResults:
            for digger in diggers:
                self.assertIsNotNone(encounterResults.get(digger))

            for robber in robbers:
                self.assertIsNotNone(encounterResults.get(robber))

        # single aggressive encounter
        allEncounterResults = encounter.simulateMultipleEncounters(
            [encounter.combat], aggressiveAgents=robbers)

        for encounterResults in allEncounterResults:
            for robber in robbers:
                self.assertIsNotNone(encounterResults.get(robber))

        # all aggressive encounters
        allEncounterResults = encounter.simulateMultipleEncounters(
            encounter.aggressiveEncounters, aggressiveAgents=robbers)

        for encounterResults in allEncounterResults:
            for robber in robbers:
                self.assertIsNotNone(encounterResults.get(robber))

        pass