Пример #1
0
 def applyHeuristic(self, game: Game):
     self.stepstoWin += 1
     q = PriorityQueue()
     bonusSoldiers = game.bonusSoldiers(self.isRed)
     cityListId = game.citiesOf(self.isRed)
     game = self.bonusArmyPlacing(bonusSoldiers, game, self.isRed)
     randomId = random.choice(cityListId)
     canAttack = False
     for cityId in cityListId:
         for neighbourId in game.map.graph[cityId]:
             neighbour = game.cityList[neighbourId]
             city = game.cityList[cityId]
             if (city.armyCount > neighbour.armyCount + 1
                     and city.isRedArmy != neighbour.isRedArmy):
                 canAttack = True
                 q.put((self.GreedyHeurictic(city, neighbour,
                                             game), city, neighbour))
     if (canAttack == False):
         return game
     if (q.not_empty):
         next_item = q.get()
         fromCity = next_item[1]
         toCity = next_item[2]
         print(fromCity)
         print(toCity)
         self.attack(fromCity.id, toCity.id, fromCity.armyCount - 1, game)
     self.evaluate()
     return game
Пример #2
0
 def applyHeuristic(self, game: Game) -> Game:
     cityListId = game.citiesOf(self.isRedPlayer)
     bonusArmy = game.bonusSoldiers(self.isRedPlayer)
     minimumTerritor = self.calculateMinimumTerritory(cityListId, game)
     if minimumTerritor != None:
         game.addSoldiersToCity(minimumTerritor.id, bonusArmy)
     return game
Пример #3
0
 def __init__(self,
              isSimulation,
              game: Game,
              redPlayer: Agent = None,
              greenPlayer: Agent = None):
     self.isRedPlayerTurn = True
     self.game = game
     self.players = {False: greenPlayer, True: redPlayer}
     self.isSimulationMode = isSimulation
     self.isPlayingMode = not isSimulation
     self.gamePlayCounts = 0
     game.prepare()
Пример #4
0
        def renderSimulationMode(self, game: Game):
            cityList = game.getCityList()
            screen = pygame.display.set_mode((self.gameimage.get_width(), self.gameimage.get_height()))
            screen.blit(self.gameimage, (0, 0))

            Quit = pygame.draw.rect(screen, (0, 0, 255), [0, 0, 140, 40])
            text = pygame.font.Font('freesansbold.ttf', 30)
            textsurf, textrect = text_objects("Quit", text, (0, 0, 0))  # get city.armyCount
            textrect.center = (Quit.center)
            screen.blit(textsurf, textrect)
            if self.chosenimage == "USmap.txt":
                map = game.map.USmap
            else:
                map = game.map.worldMap
            self.rendermap(map, cityList, screen, game)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
                # if event.type == pygame.MOUSEMOTION:
                #     for city in range(0, len(map), 1):
                #         if pygame.mouse.get_pos() == map[str(city)]:
                #             text = pygame.font.Font('freesansbold.ttf', 30)
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if 140 > pygame.mouse.get_pos()[0] > 0 and 40 > pygame.mouse.get_pos()[1] > 0:
                        self.state = "intro"
                    # crosshair.shoot()
            # loop over the cities to check the color with city is the index (or id) of the city

            # crosshairgroup.draw(screen)
            # crosshairgroup.update()
            pygame.display.update()
Пример #5
0
 def terminalState(self, curDepth: int, maxDepth: int, game: Game) -> bool:
     """
     :param curDepth: current state depth
     :param maxDepth: maximum allowed state depth
     :param game:
     :return: true if the current state is terminal state, false otherwise
     """
     if (curDepth == maxDepth or game.isFinished()):
         self.cnt += 1
         return True
     return False
Пример #6
0
 def __onConflictingPairs(self, isRedPlayer: bool, game: Game,
                          calculate) -> int:
     result: int = 0
     myCities: [int] = game.citiesOf(isRedPlayer)
     for myCityId in myCities:
         for adjCityId in game.map.graph[myCityId]:
             if game.cityList[adjCityId].isRedArmy != isRedPlayer:
                 enemyCityId: int = adjCityId
                 result += calculate(isRedPlayer, game, myCityId,
                                     enemyCityId)
     return result
Пример #7
0
    def heuristicFromCity(self, maxIsRed, myCityId: int, game: Game):
        result = 0
        myCity = game.cityList[myCityId]

        if (myCity.isRedArmy == maxIsRed):
            bonusSoldiers = game.bonusSoldiers(not maxIsRed)
            maxCityId = myCityId
            for minCityId in game.map.graph[maxCityId]:
                if (game.cityList[minCityId].isRedArmy !=
                        game.cityList[maxCityId].isRedArmy):
                    if (game.canAttack2(maxCityId, 0, minCityId, 0)):
                        result += 1
                    if (game.canAttack2(maxCityId, 0, minCityId,
                                        bonusSoldiers)):
                        result += 2
                    if (not game.canAttack2(minCityId, 0, maxCityId, 0)):
                        result += 3
                    if (not game.canAttack2(minCityId, bonusSoldiers,
                                            maxCityId, 0)):
                        result += 4

        else:
            bonusSoldiers = game.bonusSoldiers(maxIsRed)
            minCityId = myCityId
            for maxCityId in game.map.graph[minCityId]:
                if (game.cityList[minCityId].isRedArmy !=
                        game.cityList[maxCityId].isRedArmy):
                    if (game.canAttack2(maxCityId, bonusSoldiers, minCityId,
                                        0)):
                        result += 1
                    if (game.canAttack2(maxCityId, 0, minCityId, 0)):
                        result += 2
                    if (not game.canAttack2(minCityId, 0, maxCityId,
                                            bonusSoldiers)):
                        result += 3
                    if (not game.canAttack2(minCityId, 0, maxCityId, 0)):
                        result += 4
        return result
Пример #8
0
    def adjacentStates(self, game: Game):
        bonusArmyPossibilities = list()
        cityListId = game.citiesOf(self.isRedPlayer)
        bonusArmy = game.bonusSoldiers(self.isRedPlayer)

        for cityId in cityListId:
            gameCopy = deepcopy(game)
            gameCopy.addSoldiersToCity(cityId, bonusArmy)
            bonusArmyPossibilities.append(gameCopy)

        attackingPossibilities = list()
        for gameStatee in bonusArmyPossibilities:
            cityListId = gameStatee.citiesOf(self.isRedPlayer)
            for cityId in cityListId:
                city = gameStatee.cityList[cityId]
                for neighbourId in gameStatee.map.graph[cityId]:
                    neighbour = gameStatee.cityList[neighbourId]
                    if city.armyCount > neighbour.armyCount + 1 and city.isRedArmy != neighbour.isRedArmy:
                        gameCopy = deepcopy(gameStatee)
                        gameCopy.move(cityId, neighbourId,
                                      neighbour.armyCount + 1)
                        attackingPossibilities.append(gameCopy)

        return attackingPossibilities
Пример #9
0
 def applyHeuristic(self, game: Game) -> Game:
     cityListId = game.citiesOf(self.isRedPlayer)
     bonusArmy = game.bonusSoldiers(self.isRedPlayer)
     maxCity = self.calculateMaxCity(cityListId, game)
     if maxCity != None:
         game.addSoldiersToCity(maxCity.id, bonusArmy)
     # attack all neighbour cities with most armies
     for cityId in cityListId:
         for neighbourId in game.map.graph[cityId]:
             neighbour = game.cityList[neighbourId]
             city = game.cityList[cityId]
             if neighbour.armyCount < city.armyCount - 1 and neighbour.isRedArmy != city.isRedArmy:
                 game.move(city.id, neighbour.id, city.armyCount - 1)
     return game
Пример #10
0
 def applyHeuristic(self, game: Game) -> Game:
     """
         the actions taken are:
             1. place all bonus army in my city with minimum number of soldiers
             2. attack enemy city with minimum number of soldiers that can be attacked
     """
     myCities = game.citiesOf(self.isRedPlayer)
     myMinArmyCityId = self.minArmyCityId(game, myCities)
     game.placeBonusSoldiers(myMinArmyCityId,
                             game.bonusSoldiers(self.isRedPlayer))
     bestUId, bestVId = self.hisMinArmyCityToAttack(game, myCities)
     if bestUId != -1 and bestVId != -1:
         game.move(bestUId, bestVId, game.cityList[bestVId].armyCount + 1)
     return game
Пример #11
0
 def start(self):
     # assets = GUI()
     gameState = GUI.GameState()
     gameState.start(
     )  # start the first two scenes to get the required parameters (tuple)
     isSimulation, redAgentString, greenAgentString, gameimage = gameState.returnTuple(
     )
     redAgent = self.getAgent(redAgentString, True)
     greenAgent = self.getAgent(greenAgentString, False)
     print(gameimage)
     map = Map(gameimage)  # for now just read the USmap
     game = Game(map)
     gameEngine = GameEngine(isSimulation, game, redAgent, greenAgent)
     if self.humanAgent is False:
         print("msh human agent")
         while not gameEngine.gameEnded():
             gameState.modesmanager(gameEngine.game)
             sleep(0.5)
             gameEngine.play()
     else:
         print("human agent")
         while not gameEngine.gameEnded():
             while gameState.ready is False:
                 gameState.modesmanager(gameEngine.game)
             army = gameState.withArmy
             print("army is  : ", army)
             if (
                     gameState.attackingCity.armyCount > int(army)
                     and int(army) > 1
             ) and gameState.defendingCity.armyCount < gameState.attackingCity.armyCount:
                 gameEngine.game.move(gameState.attackingCity.id,
                                      gameState.defendingCity.id, int(army))
                 gameEngine.playvsHuman()
             gameState.defendingCity = ''
             gameState.attackingCity = ''
             gameState.withArmy = ''
             gameState.bonusAttack = False
             gameState.ready = False
Пример #12
0
    def applyHeuristic(self, initialGame: Game):
        if (initialGame.isFinished()):
            return initialGame
        pq = PriorityQueue()
        visited = {}
        isFirstMove = True
        #           value, g, currentState, firstMoveThatLedToThisState, parent
        curTuple = (0, initialGame, initialGame, None)

        while True:
            value, curGame, firstMoveInPath, parent = curTuple
            if (self.isGoalState(curGame, initialGame)):
                ansGame = firstMoveInPath
                break
            adjacentStates = self.adjacentStates(curGame)
            if (parent != None):
                adjacentStates.append(parent)
            for nextGameState in adjacentStates:
                value: int
                newG: int
                if (nextGameState in visited.keys()):
                    value = visited[nextGameState][0] + 1

                else:
                    newG = 1
                    value = (newG + self.calculateHeuristic(nextGameState))
                if (isFirstMove):
                    pq.put((value, nextGameState, nextGameState, curGame))
                else:
                    pq.put((value, nextGameState, firstMoveInPath, curGame))

            frontTuple = pq.get()
            curState = frontTuple[1]
            visited[curState] = pq.get()
            curTuple = frontTuple
            isFirstMove = False
        return ansGame
Пример #13
0
 def __mySecuredCityWeightCalculator(self, isRedPlayer: bool, game: Game,
                                     myCityId: int, enemyCityId: int):
     hisBonus = game.bonusSoldiers(not isRedPlayer)
     return MY_STRONG_CITY_WEIGHT if (game.cityList[myCityId].armyCount >=
                                      game.cityList[enemyCityId].armyCount +
                                      hisBonus) else MY_WEAK_CITY_WEIGHT
Пример #14
0
 def placeBonusArmy(self, army, city):
     Game.placeBonusSoldiers(city.id, army)
Пример #15
0
 def apply(self, game: Game):
     self.defenders = game.cityList[self.toId].armyCount
     game.move(self.fromId, self.toId, self.attackers)
Пример #16
0
 def rollBack(self, game: Game):
     game.addSoldiersToCity(self.toId, -self.attackers)
     game.addSoldiersToCity(self.fromId, self.attackers)
     game.changeCityOwner(self.toId)
     game.addSoldiersToCity(self.toId, self.defenders)
Пример #17
0
 def apply(self, game: Game):
     game.addSoldiersToCity(self.cityId, self.soldiers)
Пример #18
0
 def rollBack(self, game: Game):
     game.addSoldiersToCity(self.cityId, -self.soldiers)