Ejemplo n.º 1
0
def runTest(Inventory):
  import Ant
  import Construction 
  ant1 = Ant.Ant((2,3), Ant.QUEEN, 1)
  ant2 = Ant.Ant((4,5), Ant.WORKER, 1)
  construction1 = Construction.Construction((3,4), Construction.TUNNEL)
  construction2 = Construction.Construction((1,2), Construction.ANTHILL)
  testInventory = Inventory.Inventory(1,[ant1, ant2], [construction1, construction2], 3)
  testQueen = testInventory.getQueen()
  if testQueen == None:
    raise Exception("getQueen method is not returning existing Queen Ant")
  testAntHill = testInventory.getAnthill()
  if testAntHill == None:
    raise Exception("getAnthill method is not returning existing Ant Hill")
  testInventoryClone = testInventory.clone()
  if testInventoryClone == testInventory:
    raise Exception("The cloned inventory is equal to the original")
  if testInventoryClone.player != testInventory.player:
    raise Exception("The cloned inventory does not have the same player as the original Inventory")
  if testInventoryClone.ants != testInventory.ants:
    raise Exception("The cloned inventory does not have the same set of ants as the original Inventory")
  if testInventoryClone.constructions != testInventory.constructions:
    raise Exception("The cloned inventory does not have the same set of constructions as the original Inventory")
  if testInventoryClone.foodCount != testInventory.foodCount:
    raise Exception("The cloned inventory does not have the same number of food pieces as the original Inventory")
  testInventoryClone.foodCount = 5
  if testInventoryClone.foodCount == testInventory.foodCount:
    raise Exception("The changed cloned inventory food count is the same as the original")
Ejemplo n.º 2
0
def test( ):
    a = Ant.Ant( 0, x = 200, y = 100 )
    b = Ant.Ant( 0, x = 100, y = 200 )
    while True:
        a.angle = 0
        b.angle = PI / 3.0
        show_img( grid_ )

        draw_ant( a, grid_  )
        draw_ant( b, grid_  )
        show_img( grid_ )
Ejemplo n.º 3
0
    def expandNode(self, currentState, move):
        gameState = currentState.fastclone()
        # ourInventory = gameState.inventories[self.playerId]
        ourId = gameState.whoseTurn
        ourInventory = gameState.inventories[gameState.whoseTurn]
        if (move.moveType == MOVE_ANT):
            antToMove = None
            for ant in ourInventory.ants:
                if ant.coords == move.coordList[0]:
                    antToMove = ant
            if antToMove is not None:
                antToMove.coords = move.coordList[-1]
                antToMove.hasMoved = True

                # check if other ants near by for attack
                opponentId = self.getOpponentId(gameState.whoseTurn)
                enemyInv = gameState.inventories[opponentId]
                ## Checks if can attack.
                self.attackSequence(enemyInv, antToMove)

        elif (move.moveType == BUILD):
            # just worried about building Ants and Tunnel
            if (move.buildType == WORKER):
                # add ant
                ourInventory.ants.append(Ant(move.coordList[-1], WORKER,
                                             ourId))
                # subtract food
                ourInventory.foodCount -= 1
            elif (move.buildType == DRONE):
                ourInventory.ants.append(Ant(move.coordList[-1], DRONE, ourId))
                ourInventory.foodCount -= 1
            elif (move.buildType == SOLDIER):
                ourInventory.ants.append(
                    Ant(move.coordList[-1], SOLDIER, ourId))
                ourInventory.foodCount -= 2
            elif (move.buildType == R_SOLDIER):
                ourInventory.ants.append(
                    Ant(move.coordList[-1], R_SOLDIER, ourId))
                ourInventory.foodCount -= 2
            elif (move.buildType == TUNNEL):
                ourInventory.constrs.append(
                    Building(move.coordList[-1], TUNNEL, ourId))
                ourInventory.foodCount -= 3
        else:
            self.pickUpFood(gameState, ourInventory)
            self.dropOffFood(gameState, ourInventory)
            return gameState

        return gameState
Ejemplo n.º 4
0
 def initAnts(self):
     ratio = self.population_size / self.node_count
     if (ratio < 1):
         set_selected_nodes = sample(list(range(self.node_count)),
                                     self.population_size)
         for node in set_selected_nodes:
             self.population.append(Ant(node))
     else:
         if (ratio != int(ratio)):
             exit(
                 'If the population is bigger than the number of nodes, the population size must be divisible by the number of nodes.'
             )
         for j in range(int(ratio)):
             for i in range(self.node_count):
                 self.population.append(Ant(i))
Ejemplo n.º 5
0
    def solve_problem(self):
        print("\nSTARTING ITERATIONS\n")
        # print("Number of iterations: "+ str(self.number_iterations))

        for it in range(self.number_iterations):
            print("Current iteration: " + str(it))

            ant = Ant(self.number_jobs,self.number_machines,self.graph,self.pheromone_trails,self.best_seq) # Only one ant per iteration

            ant.build_sequence()
            self.ant_results.append(ant.z_graph) # Save result to plot
            self.ant_results_ls.append(ant.z_ls_graph)
            self.update_best_solution(ant)


            self.update_trail_intensities(ant)

            #print(self.pheromone_trails)

        # Job-index-based swap scheme
        self.before_swap_seq, self.before_swap_z = self.best_seq,self.z_best
        self.best_seq,self.z_best = job_index_based_swap_scheme(self.before_swap_seq,self.before_swap_z,self.graph,self.number_machines)

        self.show_solution()
        self.show_graphics()
Ejemplo n.º 6
0
    def do_turn(self, ants):
        ants.orders.clear()
        ants.destinations.clear()
        # update ant list - my ants should be updated to reflect
        # where they were ordered to go last turn.
        # so any ants not in the ant_list are new.

        if len(ants.my_ants()) != len(self.ant_list):
            expected_locs = []
            for ant in self.ant_list:
                expected_locs.append(ant.loc)
        
            for loc in ants.my_ants():
                if loc not in expected_locs:
                    self.ant_list.append(Ant(ants, loc))

            # likewise, any dead ants should be removed.
            for loc in ants.dead_list:
                for ant in self.ant_list:            
                    if loc == ant.loc:
                        self.ant_list.remove(loc)

        sys.stderr.write('ants: ' + str(len(self.ant_list)) + '\n')                        
        # connect previously invisible ants.nodes to the graph
        # and remove ants.nodes that have all neighbors mapped from unfinished
        for node in ants.unfinished_nodes[:]:
            if ants.visible(node.loc):
                finished = True
                for neighbor_loc in ants.neighbors(node.loc):
                    if ants.visible(neighbor_loc):
                        neighbor_node = ants.nodes[neighbor_loc]
                        if not node in ants.graph.keys():
                            ants.graph[node] = set([neighbor_node])
                        else:
                            ants.graph[node].add(neighbor_node)
                    else:
                        finished = False
                if finished:
                    ants.unfinished_nodes.remove(node)

        # add all ants.destinations
        for food_loc in ants.food():
            ants.destinations.add(food_loc)
        for hill_loc, hill_owner in ants.enemy_hills():
            ants.destinations.add(hill_loc)
        for unseen_loc in self.unseen:
            ants.destinations.add(unseen_loc)
            
        ant_dist = []
        for dest in ants.destinations:
            for ant in self.ant_list:
                dist = ants.distance(ant.loc, dest)
                ant_dist.append((dist, ant, dest))
        ant_dist.sort()
        for dist, ant, dest in ant_dist:
            ant.do_move_location(dest)

        # move all ants to their next locitions
        for ant in self.ant_list:
            ant.moveToNext() 
Ejemplo n.º 7
0
    def genState(self, currentState, moveAction):
        simpleState = currentState.fastclone()

        opponentId = 0
        if self.playerId == 0:
            opponentId = 1

        if moveAction.moveType == MOVE_ANT:
            #move the ant.
            movingAnt = getAntAt(simpleState, moveAction.coordList[0])
            if movingAnt == None:
                return None

            movingAnt.coords = moveAction.coordList[len(moveAction.coordList) -
                                                    1]

            #assume we attack an ant nearby
            # (in the case of multiple targets this may be inaccurate)
            for coord in listAdjacent(movingAnt.coords):
                ant = getAntAt(simpleState, coord)
                if ant != None and ant.player != self.playerId:
                    ant.health -= UNIT_STATS[movingAnt.type][ATTACK]
                    #an ant has died
                    if ant.health <= 0:
                        simpleState.inventories[opponentId].ants.remove(ant)
                    break

            #worker ants pick up food if they end turn on a food
            foods = getConstrList(simpleState, None, [(FOOD)])
            for food in foods:
                if movingAnt.type == WORKER and food.coords == movingAnt.coords:
                    movingAnt.carrying = True

            #worker ants drop food if they end turn on the goals
            goals = getConstrList(simpleState, None, types=(ANTHILL, TUNNEL))
            for goal in goals:
                if movingAnt.type == WORKER and goal.coords == movingAnt.coords and movingAnt.carrying:
                    movingAnt.carrying = False
                    simpleState.inventories[self.playerId].foodCount += 1

        elif moveAction.moveType == BUILD:
            # decrease the food amount for the player
            simpleState.inventories[self.playerId].foodCount -= UNIT_STATS[
                moveAction.buildType][COST]
            if simpleState.inventories[self.playerId].foodCount < 0:
                return None

            #add the appropriate ant to the player's inventory
            newAnt = Ant(moveAction.coordList[0], moveAction.buildType,
                         self.playerId)
            simpleState.inventories[self.playerId].ants.append(newAnt)

        # elif moveAction.moveType == END:
        # we made no change

        return simpleState
Ejemplo n.º 8
0
 def populate(self):
     for i in range(self.population):
         found_unused_cell = False
         while not found_unused_cell:
             x, y = random.randint(0, self.world_size - 1), random.randint(
                 0, self.world_size - 1)
             if self.map[y][x] is None:
                 found_unused_cell = True
                 self.map[y][x] = Ant(pos=(x, y),
                                      world=self,
                                      ant_type=WORKER_ANT,
                                      change_factor=self.change_factor)
Ejemplo n.º 9
0
    def addAnt(self):
        colony = self.getTile(self.colony)

        newAnt = None

        if not colony.getAnt():
            newAnt = Ant.Ant(self.colony, self.antNumber)
            self.antNumber = self.antNumber + 1
            self.newAntCount = self.newAntCount - 1
            self.ants.append(newAnt)
            colony.setAnt(newAnt)

        return newAnt
Ejemplo n.º 10
0
def runTest(Location):
    import Ant
    import Construction
    ant1 = Ant.Ant((2, 3), Ant.QUEEN, 1)
    ant2 = Ant.Ant((5, 6), Ant.WORKER, 1)
    construction1 = Construction.Construction((3, 4), Construction.TUNNEL)
    testLocation = Location.Location((2, 3))
    testLocation2 = Location.Location((4, 5))
    testLocation.ant = ant1
    testLocation.constr = construction1
    if (testLocation.ant == None):
        raise Exception(
            "Ant is not found at a location where there should be an Ant")
    if (testLocation.constr == None):
        raise Exception(
            "Construction is not found at a location where they should be a Construction"
        )
    if (testLocation2.ant != None):
        raise Exception("Ant is found at a location where there is no Ant")
    if (testLocation2.constr != None):
        raise Exception(
            "Construction is found at a location where there is not Construction"
        )
    locationClone = testLocation.clone()
    if locationClone == testLocation:
        raise Exception("The cloned location is equal to the original")
    if locationClone.ant != testLocation.ant:
        raise Exception(
            "The cloned location does not have the same ant object as the original location"
        )
    if locationClone.constr != testLocation.constr:
        raise Exception(
            "The cloned location does not have the same construction as the original location"
        )
    locationClone.ant = ant2
    if locationClone.ant == testLocation.ant:
        raise Exception(
            "The ant on the cloned location has been changed but is not recognized as different from the original location"
        )
Ejemplo n.º 11
0
    def __init__(self, num_ant=10, w_heuristic=2, w_pheromone_vapor=0.1, q0=0.9, p=0.1, max_gen=2500, city_name=""):
        self.m = num_ant                                        # 蚂蚁数目
        self.b = w_heuristic                                    # 启发式信息权重
        self.a = w_pheromone_vapor                              # 信息素挥发因子
        self.t0 = 0.0                                           # 初始信息素
        self.q0 = q0                                            # 伪随机因子
        self.p = p                                              # 信息素局部挥发因子
        self.gen = max_gen                                      # 最大进化代数

        self.ant = np.zeros(self.m, dtype=Ant)                  # 蚁群
        self.best = Ant()                                       # 历史最优蚂蚁
        self.city = City(city_name)                             # 城市对象
        self.dis_matrix = self.city.get_dis_matrix()            # 距离矩阵
        self.num_city = self.city.num_city                      # 城市数量
        self.pheromone_matrix = np.zeros((self.num_city, self.num_city),
                                         dtype=float)           # 信息素矩阵
Ejemplo n.º 12
0
def unitTest1():
    board = [[Location((col, row)) for row in range(0, BOARD_LENGTH)]
             for col in range(0, BOARD_LENGTH)]
    p1Inventory = Inventory(PLAYER_ONE, [], [], 10)
    p2Inventory = Inventory(PLAYER_TWO, [], [], 0)
    neutralInventory = Inventory(NEUTRAL, [], [], 0)

    state = GameState(board, [p1Inventory, p2Inventory, neutralInventory],
                      MENU_PHASE, PLAYER_ONE)

    #Add an ant to move
    ant = Ant((0, 0), WORKER, 0)
    board[0][0].ant = ant
    p1Inventory.ants.append(ant)

    player = AIPlayer(0)
    newState = player.hypotheticalMove(
        state, Move(MOVE_ANT, ((0, 0), (0, 1), (0, 2)), None))
    if tuple(newState.inventories[0].ants[0].coords) != (0, 2):
        print "didn't move ant"
        return False

    #test adding a building
    newState = player.hypotheticalMove(state, Move(BUILD, ((3, 3), ), TUNNEL))

    if len(newState.inventories[0].constrs) == 0:
        print "didn't create construction"
        return False

    if newState.inventories[0].constrs[0].type != TUNNEL:
        print "created wrong type of construction"
        return False

    if tuple(newState.inventories[0].constrs[0].coords) != (3, 3):
        print "created construction at wrong place"
        return False

    if newState.inventories[0].foodCount != 7:
        print "didn't subtract food cost"
        return False

    return True
Ejemplo n.º 13
0
def start(scene, city):
    global cities, numberOfCities

    resultFile = open("results", "w")

    cities = city
    numberOfCities = len(cities)

    tau0 = 1 / (len(cities) * nearestNeighbor(list(cities), resultFile)
                )  # copying cities list and send nn algorithm

    # tau0 = (n * Cnn )^-1

    # create Ants
    for i in range(0, numberOfAnts):
        ants.append(Ant(i))

    systemStart(scene, iteration, cities, ants, pheromoneMatrix,
                numberOfCities, numberOfAnts, beta, q0, rho, ksi, tau0,
                resultFile)
Ejemplo n.º 14
0
 def iteration(self):
     antSet = [Ant(self.n, self.lst) for i in range(self.noAnts)]
     for i in range(self.n * self.n):
         for x in antSet:
             x.addMove(self.q0, self.trace, self.alpha, self.beta)
     dTrace = [
         1.0 / intermediate_fitness(antSet[i].path, antSet[i])
         for i in range(len(antSet))
     ]
     for i in range(self.n * self.n):
         for j in range(self.n * self.n):
             self.trace[i][j] = (1 - self.rho) * self.trace[i][j]
     for i in range(len(antSet)):
         for j in range(len(antSet[i].path) - 1):
             x = int(antSet[i].pheromones[j])
             y = int(antSet[i].pheromones[j + 1])
             self.trace[x][y] = self.trace[x][y] + dTrace[i]
     f = [[intermediate_fitness(antSet[i].path, antSet[i]), i]
          for i in range(len(antSet))]
     f = min(f)
     return antSet[f[1]].path
Ejemplo n.º 15
0
def loadingFile():
    """
    load the file with the last saved data, makes a split method that puts you located in the file lists the position
    as 0 and 1 at position 1 are all values ​​suggar, poison, wine Clod and the size of the matrix, equals the globals
     variables to change the value of the same
    """

    global wineCount
    global poisonCount
    global sugarCount
    global nameAntFile
    global sizeMatrixGlobals
    global antInstance

    file = open("Settings.txt", "r")

    dataLines = file.readlines()

    for line in dataLines:

        info = line.split(",")

        if info[0] == "wineClod":
            wineCount = int(info[1])

        if info[0] == "poisonClod":
            poisonCount = int(info[1])

        if info[0] == "sugarClod":
            sugarCount = int(info[1])

        if info[0] == "sizeMatrix":
            sizeMatrixGlobals = int(info[1])

        if info[0] == "nameAnt":
            nameAntFile = info[1]
            antInstance = Ant(info[1])

    file.close()
Ejemplo n.º 16
0
    def init(self):
        # 初始化所有蚂蚁
        for i in range(self.m):
            self.ant[i] = Ant()
            self.ant[i].path.resize(self.num_city)

        # 信息素初始化 (贪婪选择一条道路)
        seq = np.zeros(self.num_city, dtype=int)
        flag = np.zeros(self.num_city, dtype=int)
        seq[0] = np.random.randint(self.num_city)
        flag[seq[0]] = 1

        # 创建下一个城市的信息数组
        next_city = np.zeros(shape=self.num_city, dtype=NextCityInit)
        for i in range(self.num_city):
            next_city[i] = NextCityInit()

        # 贪婪选择
        s = 0.0
        for i in range(self.num_city - 1):
            for j in range(self.num_city):
                next_city[j].dis = self.dis_matrix[seq[i]][j]
                next_city[j].id = j
            next_city.sort()
            for j in range(1, self.num_city):
                if flag[next_city[j].id] == 0:
                    seq[i + 1] = next_city[j].id
                    s = s + next_city[j].dis
                    flag[next_city[j].id] = 1
                    break
        s = s + self.dis_matrix[0][seq[self.num_city - 1]]

        # 计算信息素
        self.t0 = 1.0 / (self.num_city * s)
        for i in range(self.num_city):
            for j in range(self.num_city):
                self.pheromone_matrix[i][j] = self.t0
Ejemplo n.º 17
0
x = 300
colony_ = (x,x)
source_ = map(lambda a: a - x, grid_.shape) 


pp1_ = [ colony_, (200,200), (300,150), (500,100), (800, 200), (850,400), source_ ]
pp2_ = [ colony_, (400,400), (550,800), source_ ]
pp3_ = [ colony_, (400,800), (800,800), source_ ]

p1_ = spline_fit( pp1_ )
p2_ = spline_fit( pp2_ )
p3_ = spline_fit( pp3_ )
paths_ = [ p1_, p2_, p3_ ]

# Initially all ants are colony
ants_ = [ Ant.Ant(i, x=colony_[0], y=colony_[1]) for i in range( 10000 ) ]

def show_img( img ):
    cv2.imshow( "grid", img )
    cv2.waitKey( 10 )

def show_path( path, img, weight = 1 ):
    cv2.polylines( img, [path], False, weight, 1)

def updateAnts(  ):
    global ants_
    # Scan in neighbouring direction and select the best direction to
    [ a.scanAndMove( ) for a in ants_ ]

def show_ants( length = 5 ):
    global grid_
Ejemplo n.º 18
0
    # This agent doens't learn
    #
    def registerWin(self, hasWon):
        #method templaste, not implemented
        pass


# UNIT TEST
# Here we test the methods we wrote for Homework 2

# First we check our getValue function, this function evaluates a state
# Case 1 (simple)
# Check state with AI has only queen as ant and 0 food, with the enemy having a worker ant
# The AI has lost, so function should return -1
basicState = GameState(0, 0, 0, 0).getBasicState()
randomAnt = Ant((0, 1), WORKER, 1)
basicState.inventories[1].ants.append(randomAnt)
AIplayer = AIPlayer(1)
value = AIplayer.getValue(basicState)
rightValue = -1
if not math.isclose(value, rightValue):
    print("Error, the getValue function gives the value ", value, \
        "instead of the value ", rightValue, ".")
# Case 2 (complex)
# Check state with queen, one soldier ant and 5 food for the AI
# versus queen and one ant and one food for the opponent
randomSoldierAnt = Ant((0, 1), R_SOLDIER, 1)
basicState.inventories[0].ants.append(randomSoldierAnt)
basicState.inventories[0].foodCount = 5
enemyWorkerAnt = Ant((0, 2), WORKER, 1)
basicState.inventories[1].ants.append(enemyWorkerAnt)
Ejemplo n.º 19
0
    def hypotheticalMove(self, state, move):
        newState = state.fastclone()

        if move.moveType == END:
            newState.whoseTurn = 1 - state.whoseTurn
            return newState

        elif move.moveType == MOVE_ANT:
            ant = getAntAt(newState, move.coordList[0])
            ant.coords = move.coordList[-1]

            #check if ant is depositing food
            if ant.carrying:
                if tuple(ant.coords) in self.buildingCoords[self.playerId]:
                    ant.carrying = False
                    newState.inventories[self.playerId].foodCount += 1

            #check if ant is picking up food
            if not ant.carrying:
                if tuple(ant.coords) in self.foodCoords:
                    ant.carrying = True

            #check if ant can attack
            targets = []  #coordinates of attackable ants
            range = UNIT_STATS[ant.type][RANGE]

            for ant in newState.inventories[1 - self.playerId].ants:
                dist = math.sqrt((ant.coords[0] - ant.coords[0])**2 +
                                 (ant.coords[1] - ant.coords[1])**2)
                if dist <= range:
                    #target is in range and may be attacked
                    targets.append(ant.coords)

            if targets:
                #Attack the ant chosen by the AI
                target = self.getAttack(newState, ant, targets)
                targetAnt = getAntAt(newState, target)
                targetAnt.health -= UNIT_STATS[ant.type][ATTACK]

                if targetAnt.health <= 0:
                    #Remove the dead ant
                    newState.inventories[1 -
                                         self.playerId].ants.remove(targetAnt)

            ant.hasMoved = True

        else:  #Move type BUILD
            if move.buildType in (WORKER, DRONE, SOLDIER, R_SOLDIER):
                #Build ant on hill
                ant = Ant(move.coordList[0], move.buildType, self.playerId)
                newState.inventories[self.playerId].ants.append(ant)

                newState.inventories[self.playerId].foodCount -= UNIT_STATS[
                    move.buildType][COST]
            else:
                #build new building
                building = Building(move.coordList[0], move.buildType,
                                    self.playerId)
                newState.inventories[self.playerId].constrs.append(building)

                newState.inventories[self.playerId].foodCount -= CONSTR_STATS[
                    move.buildType][BUILD_COST]

        return newState
Ejemplo n.º 20
0
                continue

        return round(eval, 8)


##
# UNIT TESTING SECTION
##

aiPlayer = AIPlayer(PLAYER_ONE)

### Test 1 ###
# Build a Drone

# build a test board
antCarrying = Ant((3, 3), WORKER, PLAYER_ONE)
antCarrying.carrying = True
inventory1 = Inventory(PLAYER_ONE, [
    Ant((4, 2), WORKER, PLAYER_ONE), antCarrying,
    Ant((7, 0), SOLDIER, PLAYER_ONE),
    Ant((0, 0), QUEEN, PLAYER_ONE)
], [
    Building((2, 2), ANTHILL, PLAYER_ONE),
    Building((3, 4), TUNNEL, PLAYER_ONE)
], 1)
inventory2 = Inventory(PLAYER_TWO, [
    Ant((0, 9), SOLDIER, PLAYER_TWO),
    Ant((1, 9), WORKER, PLAYER_TWO),
    Ant((7, 2), WORKER, PLAYER_TWO),
    Ant((9, 9), QUEEN, PLAYER_TWO)
], [
Ejemplo n.º 21
0
def getNextState(currentState, move):
    # variables I will need
    myGameState = currentState.fastclone()
    myInv = getCurrPlayerInventory(myGameState)
    me = myGameState.whoseTurn
    myAnts = myInv.ants
    myTunnels = myInv.getTunnels()
    myAntHill = myInv.getAnthill()

    # If enemy ant is on my anthill or tunnel update capture health
    ant = getAntAt(myGameState, myAntHill.coords)
    if ant is not None:
        if ant.player != me:
            myAntHill.captureHealth -= 1

    # If an ant is built update list of ants
    antTypes = [WORKER, DRONE, SOLDIER, R_SOLDIER]
    if move.moveType == BUILD:
        if move.buildType in antTypes:
            ant = Ant(myInv.getAnthill().coords, move.buildType, me)
            myInv.ants.append(ant)
            # Update food count depending on ant built
            myInv.foodCount -= UNIT_STATS[move.buildType][COST]
        # ants are no longer allowed to build tunnels, so this is an error
        elif move.buildType == TUNNEL:
            print("Attempted tunnel build in getNextState()")
            return currentState

    # If an ant is moved update their coordinates and has moved
    elif move.moveType == MOVE_ANT:
        newCoord = move.coordList[-1]
        startingCoord = move.coordList[0]
        for ant in myAnts:
            if ant.coords == startingCoord:
                ant.coords = newCoord
                # TODO: should this be set true? Design decision
                ant.hasMoved = False
                # If an ant is carrying food and ends on the anthill or tunnel drop the food
                if ant.carrying and ant.coords == myInv.getAnthill().coords:
                    myInv.foodCount += 1
                    ant.carrying = False
                for tunnels in myTunnels:
                    if ant.carrying and (ant.coords == tunnels.coords):
                        myInv.foodCount += 1
                        ant.carrying = False
                # If an ant doesn't have food and ends on the food grab food
                if not ant.carrying and ant.type == WORKER:
                    foods = getConstrList(myGameState, 2, [FOOD])
                    for food in foods:
                        if food.coords == ant.coords:
                            ant.carrying = True
                # If my ant is close to an enemy ant attack it
                attackable = listAttackable(ant.coords,
                                            UNIT_STATS[ant.type][RANGE])
                for coord in attackable:
                    foundAnt = getAntAt(myGameState, coord)
                    if foundAnt is not None:  # If ant is adjacent my ant
                        if foundAnt.player != me:  # if the ant is not me
                            foundAnt.health = foundAnt.health - UNIT_STATS[
                                ant.type][ATTACK]  # attack
                            # If an enemy is attacked and looses all its health remove it from the other players
                            # inventory
                            if foundAnt.health <= 0:
                                myGameState.inventories[1 - me].ants.remove(
                                    foundAnt)
                            # If attacked an ant already don't attack any more
                            break
    return myGameState
Ejemplo n.º 22
0
def putTheirInventory(inventory):
    inventory.constrs.append(Construction((0, 7), ANTHILL))
    inventory.constrs.append(Construction((1, 7), TUNNEL))
    queen = Ant((0, 7), QUEEN, PLAYER_TWO)
    queen.health = 1
    inventory.ants.append(queen) # Queen
Ejemplo n.º 23
0
    def getFutureState(self, currentState, move):
        # create a bare-bones copy of the state to modify
        newState = currentState.fastclone()

        # get references to the player inventories
        playerInv = newState.inventories[newState.whoseTurn]
        enemyInv = newState.inventories[1 - newState.whoseTurn]

        if move.moveType == BUILD:
            # BUILD MOVE
            if move.buildType < 0:
                # building a construction
                playerInv.foodCount -= CONSTR_STATS[move.buildType][BUILD_COST]
                playerInv.constrs.append(
                    Construction(move.coordList[0], move.buildType))
            else:
                # building an ant
                playerInv.foodCount -= UNIT_STATS[move.buildType][COST]
                playerInv.ants.append(
                    Ant(move.coordList[0], move.buildType, newState.whoseTurn))

        elif move.moveType == MOVE_ANT:
            # MOVE AN ANT
            # get a reference to the ant
            ant = getAntAt(newState, move.coordList[0])

            # update the ant's location after the move
            ant.coords = move.coordList[-1]
            ant.hasMoved = True

            # get a reference to a potential construction at the destination coords
            constr = getConstrAt(newState, move.coordList[-1])

            # check to see if a worker ant is on a food or tunnel or hill and act accordingly
            if constr and ant.type == WORKER:
                # if destination is food and ant can carry, pick up food
                if constr.type == FOOD:
                    if not ant.carrying:
                        ant.carrying = True
                # if destination is dropoff structure and and is carrying, drop off food
                elif constr.type == TUNNEL or constr.type == ANTHILL:
                    if ant.carrying:
                        ant.carrying = False
                        playerInv.foodCount += 1

            # get a list of the coordinates of the enemy's ants
            enemyAntCoords = [enemyAnt.coords for enemyAnt in enemyInv.ants]

            # contains the coordinates of ants that the 'moving' ant can attack
            validAttacks = []

            # go through the list of enemy ant locations and check if
            # we can attack that spot, and if so add it to a list of
            # valid attacks (one of which will be chosen at random)
            for coord in enemyAntCoords:
                if UNIT_STATS[ant.type][RANGE]**2 >= abs(
                        ant.coords[0] - coord[0])**2 + abs(ant.coords[1] -
                                                           coord[1])**2:
                    validAttacks.append(coord)

            # if we can attack, pick a random attack and do it
            if validAttacks:
                enemyAnt = getAntAt(newState, random.choice(validAttacks))
                attackStrength = UNIT_STATS[ant.type][ATTACK]

                if enemyAnt.health <= attackStrength:
                    # just to be safe, set the health to 0
                    enemyAnt.health = 0
                    # remove the enemy ant from their inventory
                    enemyInv.ants.remove(enemyAnt)
                else:
                    # lower the enemy ant's health because they were attacked
                    enemyAnt.health -= attackStrength

        # return the modified copy of the original state
        return newState
Ejemplo n.º 24
0
        for ant in antList:
            ant.hasMoved = False
        gameState.whoseTurn = playerId


class Node:
    def __init__(self, move, state, parent, eval):
        self.move = move
        self.state = state
        self.parent = parent
        self.eval = eval


#Unit Test #1: Tests whether an ant correctly moves to a space
#create a worker ant on the board
ant = Ant((0, 0), WORKER, 0)

#initialize the parameters needed to create a gamestate
board = [[Location((col, row)) for row in xrange(0, BOARD_LENGTH)]
         for col in xrange(0, BOARD_LENGTH)]
p1Inventory = Inventory(PLAYER_ONE, [ant], [], 0)
p2Inventory = Inventory(PLAYER_TWO, [], [], 0)
neutralInventory = Inventory(NEUTRAL, [], [], 0)
state = GameState(board, [p1Inventory, p2Inventory, neutralInventory],
                  MENU_PHASE, PLAYER_ONE)

#ant will move two spaces down
move = Move(MOVE_ANT, [(0, 0), (0, 1), (0, 2)], None)

#create new AI instance and use next move algorithm
player = AIPlayer(0)
Ejemplo n.º 25
0
def main(neuralNetwork):
    ##########
    global GEN_NUM, food_storage
    food_storage = []
    for i in range(100):
        food_storage.append((random.randrange(0, GRID_WIDTH), random.randrange(0, GRID_HEIGHT)))
    ants = {}
    GEN_NUM += 1
    # nets = []
    # ge = []
    ge = {}
    nets = {}
    ant_id = 0
    for net in neuralNetwork:
        nets[ant_id] = net
        ants[ant_id] = Ant(10, 10)
        ge[ant_id] = 0
        ant_id += 1
    ##########
    QUIT = False
    while QUIT == False:
        if gui:
            clock.tick(FPS)
        rem_ants = set()
        for ant_id, ant in ants.items():
            brainInput = ant.createVision()
            brainInput = brainInput.reshape(brainInput.shape[0], 1)
            brainOutput = nets[ant_id].forward_propagation(brainInput)
            performance, isIn = ant.move(brainOutput)
            if isIn ==False:
                rem_ants.add(ant_id)
                ge[ant_id] += performance
            else:
                ge[ant_id] += performance
            if ant.num_moves > ant.allowed_moves:
                rem_ants.add(ant_id)
        if gui:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    QUIT = True
                    pygame.quit()
                    quit()
                # elif event.type == pygame.KEYDOWN:
                #     if event.key == pygame.K_LEFT:
                #         output[2] = 1
                #     elif event.key == pygame.K_UP:
                #         output[3] = 1
                #     elif event.key == pygame.K_RIGHT:
                #         output[4] = 1
                #     elif event.key == pygame.K_DOWN:
                #         output[0] = 1
                #     for ant in ants:
                #         valid = ant.move(output)
                #         if not valid:
                #             rem_ants.add(ant)
            
        
        for ant_id in rem_ants:
            ants.pop(ant_id)
        if len(ants) == 0:
            QUIT = True


        if gui:
            WIN.fill((255, 255, 255))
            for ant_id, ant in ants.items():
                ant.draw(WIN, ANT_IMAGE)
                # ant.move(np.random.rand(5))
            pygame.display.update()

    return ge 
Ejemplo n.º 26
0
 def addAnt(self):
     self.ants.append(a.Ant(self.frame, self.width, self.height, self.x, self.y,
                            self.land[self.startx][self.starty]))
Ejemplo n.º 27
0
def putOurInventory(inventory):
    inventory.constrs.append(Construction((0,3), ANTHILL))
    inventory.constrs.append(Construction((1,3), TUNNEL))
    inventory.ants.append(Ant((0,3), QUEEN, PLAYER_ONE)) # Queen
    inventory.ants.append(Ant((0,6), DRONE, PLAYER_ONE)) # Queen
Ejemplo n.º 28
0
    def getFutureState(self, currentState, nextMove):
        """
        :type currentState: GameState
        :type nextMove: Move
        :rtype: GameState
        """

        # for ending turns, there is no change to the board
        if nextMove.moveType == END:
            return currentState

        futureState = currentState.fastclone()
        """:type : GameState"""

        playerId = currentState.whoseTurn
        enemyId = playerId * (-1) + 1

        if nextMove.moveType == BUILD:
            if nextMove.buildType == TUNNEL:
                futureState.inventories[playerId].foodCount -= CONSTR_STATS[
                    TUNNEL][BUILD_COST]
                futureState.inventories[playerId].constrs.append(
                    Construction(nextMove.coordList[0], nextMove.buildType))
            else:
                # build an ant
                futureState.inventories[playerId].foodCount -= UNIT_STATS[
                    nextMove.buildType][COST]
                futureState.inventories[playerId].ants.append(
                    Ant(nextMove.coordList[0], nextMove.buildType, playerId))

        else:
            # the move is a MOVE_ANT move, so
            # find the ant and move it to the target
            ant = getAntAt(futureState, nextMove.coordList[0])
            """:type : Ant"""
            ant.coords = nextMove.coordList[-1]

            # see if it moved onto a structure
            constr = getConstrAt(futureState, nextMove.coordList[-1])

            if constr and ant.type == WORKER:
                # pickup/dropoff food
                if ant.carrying and (constr.type == ANTHILL
                                     or constr.type == TUNNEL):
                    ant.carrying = False
                    futureState.inventories[playerId].foodCount += 1
                elif not ant.carrying and constr.type == FOOD:
                    ant.carrying = True

            # search for possible attacks and execute one
            for coords in listAdjacent(ant.coords):

                targetAnt = getAntAt(futureState, coords)
                """:type : Ant"""

                # verify that the targetAnt is an enemy
                if targetAnt and targetAnt.player == playerId:
                    targetAnt = None

                if targetAnt:
                    targetAnt.health -= UNIT_STATS[ant.type][ATTACK]
                    # remove from board if enemy is killed
                    if targetAnt.health < 1:
                        futureState.inventories[enemyId].ants.remove(targetAnt)
                    continue

        return futureState
Ejemplo n.º 29
0
def getNextState(currentState, move):
    # variables I will need
    myGameState = currentState.fastclone()
    myInv = getCurrPlayerInventory(myGameState)
    me = myGameState.whoseTurn
    myAnts = myInv.ants

    # If enemy ant is on my anthill or tunnel update capture health
    myTunnels = myInv.getTunnels()
    myAntHill = myInv.getAnthill()
    for myTunnel in myTunnels:
        ant = getAntAt(myGameState, myTunnel.coords)
        if ant is not None:
            opponentsAnts = myGameState.inventories[not me].ants
            if ant in opponentsAnts:
                myTunnel.captureHealth -= 1
    if getAntAt(myGameState, myAntHill.coords) is not None:
        ant = getAntAt(myGameState, myAntHill.coords)
        opponentsAnts = myGameState.inventories[not me].ants
        if ant in opponentsAnts:
            myAntHill.captureHealth -= 1

    # If an ant is built update list of ants
    antTypes = [WORKER, DRONE, SOLDIER, R_SOLDIER]
    if move.moveType == BUILD:
        if move.buildType in antTypes:
            ant = Ant(myInv.getAnthill().coords, move.buildType, me)
            myInv.ants.append(ant)
            # Update food count depending on ant built
            if move.buildType == WORKER:
                myInv.foodCount -= 1
            elif move.buildType == DRONE or move.buildType == R_SOLDIER:
                myInv.foodCount -= 2
            elif move.buildType == SOLDIER:
                myInv.foodCount -= 3

    # If a building is built update list of buildings and the update food count
    if move.moveType == BUILD:
        if move.buildType == TUNNEL:
            building = Construction(move.coordList[0], move.buildType)
            myInv.constrs.append(building)
            myInv.foodCount -= 3

    # If an ant is moved update their coordinates and has moved
    if move.moveType == MOVE_ANT:
        newCoord = move.coordList[len(move.coordList) - 1]
        startingCoord = move.coordList[0]
        for ant in myAnts:
            if ant.coords == startingCoord:
                ant.coords = newCoord
                ant.hasMoved = False
                # If an ant is carrying food and ends on the anthill or tunnel drop the food
                if ant.carrying and ant.coords == myInv.getAnthill().coords:
                    myInv.foodCount += 1
                    ant.carrying = False
                for tunnels in myTunnels:
                    if ant.carrying and (ant.coords == tunnels.coords):
                        myInv.foodCount += 1
                        ant.carrying = False
                # If an ant doesn't have food and ends on the food grab food
                if not ant.carrying:
                    foods = getConstrList(myGameState, None, (FOOD, ))
                    for food in foods:
                        if food.coords == ant.coords:
                            ant.carrying = True
                # If my ant is close to an enemy ant attack it
                adjacentTiles = listAdjacent(ant.coords)
                for adj in adjacentTiles:
                    if getAntAt(myGameState,
                                adj) is not None:  # If ant is adjacent my ant
                        closeAnt = getAntAt(myGameState, adj)
                        if closeAnt.player != me:  # if the ant is not me
                            closeAnt.health = closeAnt.health - UNIT_STATS[
                                ant.type][ATTACK]  # attack
                            # If an enemy is attacked and looses all its health remove it from the other players
                            # inventory
                            if closeAnt.health <= 0:
                                enemyAnts = myGameState.inventories[
                                    not me].ants
                                for enemy in enemyAnts:
                                    if closeAnt.coords == enemy.coords:
                                        myGameState.inventories[
                                            not me].ants.remove(enemy)
                            # If attacked an ant already don't attack any more
                            break
    return myGameState
    def initial(self):

        job0 = Job.Job(0, 120, 1)
        job1 = Job.Job(1, 120, 1)
        job2 = Job.Job(2, 120, 1)
        job3 = Job.Job(3, 120, 1)
        job4 = Job.Job(4, 120, 1)
        job5 = Job.Job(5, 120, 1)
        job6 = Job.Job(6, 120, 1)
        job7 = Job.Job(7, 120, 1)
        job8 = Job.Job(8, 120, 1)
        job9 = Job.Job(9, 120, 1)

        job10 = Job.Job(10, 150, 1)
        job11 = Job.Job(11, 150, 1)
        job12 = Job.Job(12, 150, 1)
        job13 = Job.Job(13, 150, 1)
        job14 = Job.Job(14, 150, 1)
        job15 = Job.Job(15, 150, 1)
        job16 = Job.Job(16, 150, 1)
        job17 = Job.Job(17, 150, 1)
        job18 = Job.Job(18, 150, 1)
        job19 = Job.Job(19, 150, 1)

        job20 = Job.Job(20, 170, 1)
        job21 = Job.Job(21, 170, 1)
        job22 = Job.Job(22, 170, 1)
        job23 = Job.Job(23, 170, 1)
        job24 = Job.Job(24, 170, 1)
        job25 = Job.Job(25, 170, 1)
        job26 = Job.Job(26, 170, 1)
        job27 = Job.Job(27, 170, 1)
        job28 = Job.Job(28, 170, 1)
        job29 = Job.Job(29, 170, 1)

        self.jobs.append(job0)
        self.jobs.append(job1)
        self.jobs.append(job2)
        self.jobs.append(job3)
        self.jobs.append(job4)
        self.jobs.append(job5)
        self.jobs.append(job6)
        self.jobs.append(job7)
        self.jobs.append(job8)
        self.jobs.append(job9)
        self.jobs.append(job10)
        self.jobs.append(job11)
        self.jobs.append(job12)
        self.jobs.append(job13)
        self.jobs.append(job14)
        self.jobs.append(job15)
        self.jobs.append(job16)
        self.jobs.append(job17)
        self.jobs.append(job18)
        self.jobs.append(job19)
        self.jobs.append(job20)
        self.jobs.append(job21)
        self.jobs.append(job22)
        self.jobs.append(job23)
        self.jobs.append(job24)
        self.jobs.append(job25)
        self.jobs.append(job26)
        self.jobs.append(job27)
        self.jobs.append(job28)
        self.jobs.append(job29)

        cluster0 = Cluster.Cluster(0, 1000, 64)
        cluster1 = Cluster.Cluster(1, 1000, 64)
        cluster2 = Cluster.Cluster(2, 1000, 64)
        cluster3 = Cluster.Cluster(3, 1000, 64)
        cluster4 = Cluster.Cluster(4, 1000, 64)

        self.clusters.append(cluster0)
        self.clusters.append(cluster1)
        self.clusters.append(cluster2)
        self.clusters.append(cluster3)
        self.clusters.append(cluster4)

        self.n = len(self.jobs)
        self.m = len(self.clusters)

        self.bestSolution = [None] * self.n

        self.heuristic = [[None] * (self.m + 1)] * self.n
        for i in range(self.n):
            for j in range(self.m):
                self.heuristic[i][j] = 2

        for i in range(self.n):
            self.heuristic[i][self.m] = 0.1

        self.pheromone = [[None] * (self.m + 1)] * self.n
        for i in range(self.n):
            for j in range(self.m + 1):
                self.pheromone[i][j] = self.pheremoneInitialVal

        for i in range(self.numOfAnts):
            self.ants.append(Ant.Ant(self.n, self.m))