def debugFormicMetaGraph(fmg, mazeLong):
    """
    Format a output for pyplot that renders the formic meta graph
    """

    # import
    try:
        import matplotlib.pyplot as plt
    except:
        api.debug("Matplotlib not found")
        return

    # plot
    for i in fmg:
        for j in fmg[i]:
            dotY = [-i[0], -j[0]]
            dotX = [i[1], j[1]]
            plt.plot(dotX, dotY, "o:")

            if (i[0] - mazeLong) ** 2 + i[1] ** 2 > (j[0] - mazeLong) ** 2 + j[1] ** 2:
                plt.annotate(
                    str(j) + "<-" + str(i) + " " + str(fmg[i][j][0]) + " " + str(fmg[i][j][1]),
                    ((i[1] + j[1]) / 2.0 - 0.4, -((i[0] + j[0]) / 2.0 - 0.1)),
                )
            else:
                plt.annotate(
                    str(i) + "->" + str(j) + " " + str(fmg[i][j][0]) + " " + str(fmg[i][j][1]),
                    ((i[1] + j[1]) / 2.0 - 0.4, -((i[0] + j[0]) / 2.0 + 0.1)),
                )

    # render
    plt.axis((-0.5, mazeLong - 0.5, -mazeLong + 0.5, 0.5))
    plt.show()
Esempio n. 2
0
def initializationCode (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :
    global METAGRAPH
    global BESTPATHS
    iniTime = time.time()
    METAGRAPH, BESTPATHS = th.generateMetaGraph(mazeMap, playerLocation, coins)
    api.debug(time.time() - iniTime)
    return "Everything seems fine, let's start !"
Esempio n. 3
0
def determineNextMove (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :
    global MOVING
    global METAGRAPH
    global BESTPATHS
    global EATENCOINS
    global PATH
    global CURRENTCOIN
    
    EATENCOINS = ut.updateCoins(METAGRAPH, EATENCOINS, coins)
    

    if MOVING :
        if not PATH :
            MOVING = False
        
        if (opponentLocation == CURRENTCOIN and playerLocation != CURRENTCOIN) or ():
            PATH = th.findNearestCoin(mazeMap, playerLocation, coins)
            PATH.pop()
            api.debug("BITE")
    
    if not MOVING :
        CURRENTCOIN = chooseCoin(METAGRAPH, playerLocation, EATENCOINS)

        PATH = BESTPATHS[playerLocation][CURRENTCOIN]
        PATH.pop()
        
        MOVING = True
    
    nextPos = PATH.pop()

    return ut.convertPosesToDir(nextPos, playerLocation, mazeMap)
Esempio n. 4
0
def initializationCode(mazeWidth, mazeHeight, mazeMap, timeAllowed,
                       playerLocation, opponentLocation, coins):
    global METAGRAPH
    global BESTPATHS
    iniTime = time.time()
    METAGRAPH, BESTPATHS = th.generateMetaGraph(mazeMap, playerLocation, coins)
    api.debug(time.time() - iniTime)
    return "Everything seems fine, let's start !"
Esempio n. 5
0
def determineNextMove (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :

    t0 = time.time ()

    # Travel heuristics variables
    global METAGRAPH
    global FORMICMETAGRAPH
    global BESTPATHES

    # Pathes variables
    global GLOBALPATH
    global ACTUALPATH
    global GOALLOCATION

    # General variables
    global MOVING    
    global EATENCOINS

    
    # We update eatenCoins except playerLocation
    EATENCOINS = ut.updateCoinsWoPlayerLoc (METAGRAPH, EATENCOINS, coins, playerLocation)

    if GOALLOCATION in EATENCOINS:
        ACTUALPATH = th.findNearestCoin(mazeMap, playerLocation, coins)
        GOALLOCATION = ACTUALPATH[0]
        api.debug("Thief ! We go there : "+str(GOALLOCATION))
        ACTUALPATH.pop ()

    newMetaGraph = ut.metaGraphWithoutEaten (METAGRAPH, EATENCOINS)


    # Let's send some ant. Not too much
    t1 = time.time ()
    FORMICMETAGRAPH = aco.generateFormicMetaGraph (newMetaGraph, GOALLOCATION, (timeAllowed-(t1-t0)-ESTIMATEDTIMEMAIN)*PERCENTTIMEALLOWEDFORANTS, FORMICMETAGRAPH)

    if MOVING :
        # Plus de chemin ou pièce bouffée, on s'arrete.
        if not ACTUALPATH :
            MOVING = False
            EATENCOINS.append (playerLocation)
    
    if not MOVING :
        # We choose the next coin with aco :
        GOALLOCATION = chooseNextCoins(FORMICMETAGRAPH, playerLocation)[0][0]
        
        # Get next path
        try :
            ACTUALPATH = list (BESTPATHES[playerLocation][GOALLOCATION])
        except KeyError: # The path doesn't exist, let's calculate one:
            ACTUALPATH = sp.shortestWay (mazeMap, playerLocation, GOALLOCATION)
         

        ACTUALPATH.pop () # Get rid of the first position wich should be actualPosition
        MOVING = True

    # Let's go !
    nextPos = ACTUALPATH.pop()
    return ut.convertPosesToDir(nextPos, playerLocation, mazeMap)
Esempio n. 6
0
def initializationCode (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :

    api.debug("\n" + "mazeWidth = " + str(mazeWidth) + "\n"
               + "mazeHeight = " + str(mazeHeight) + "\n"
               + "mazeMap = " + str(mazeMap) + "\n"
               + "timeAllowed = " + str(timeAllowed) + "\n"
               + "playerLocation = " + str(playerLocation) + "\n"
               + "opponentLocation = " + str(opponentLocation) + "\n"
               + "coins = " + str(coins))
Esempio n. 7
0
def initializationCode(mazeWidth, mazeHeight, mazeMap, timeAllowed,
                       playerLocation, opponentLocation, coins):

    api.debug("\n" + "mazeWidth = " + str(mazeWidth) + "\n" + "mazeHeight = " +
              str(mazeHeight) + "\n" + "mazeMap = " + str(mazeMap) + "\n" +
              "timeAllowed = " + str(timeAllowed) + "\n" +
              "playerLocation = " + str(playerLocation) + "\n" +
              "opponentLocation = " + str(opponentLocation) + "\n" +
              "coins = " + str(coins))
Esempio n. 8
0
def handler (signum, frame):
    api.debug ("Sir, someone's trying to kill me !")
Esempio n. 9
0
def initializationCode (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :

    api.debug("\n" + "mazeWidth = " + str(mazeWidth) + "\n"
               + "mazeHeight = " + str(mazeHeight) + "\n"
               + "mazeMap = " + str(mazeMap) + "\n"
               + "timeAllowed = " + str(timeAllowed) + "\n"
               + "playerLocation = " + str(playerLocation) + "\n"
               + "opponentLocation = " + str(opponentLocation) + "\n"
               + "coins = " + str(coins))



def determineNextMove (mazeWidth, mazeHeight, mazeMap, timeAllowed, playerLocation, opponentLocation, coins) :

    return api.UP



if __name__ == "__main__" :

    # We let technical stuff happen
    (mazeWidth, mazeHeight, mazeMap, preparationTime, turnTime, playerLocation, opponentLocation, coins, gameIsOver) = api.initGame(BOT_NAME)


    initializationCode(mazeWidth, mazeHeight, mazeMap, preparationTime, playerLocation, opponentLocation, coins)

    # Here magic happens
    api.mainLoop (determineNextMove, mazeWidth, mazeHeight, mazeMap, turnTime)

Esempio n. 10
0
              "timeAllowed = " + str(timeAllowed) + "\n" +
              "playerLocation = " + str(playerLocation) + "\n" +
              "opponentLocation = " + str(opponentLocation) + "\n" +
              "coins = " + str(coins))


def determineNextMove(mazeWidth, mazeHeight, mazeMap, timeAllowed,
                      playerLocation, opponentLocation, coins):

    return api.UP


if __name__ == "__main__":

    # We let technical stuff happen
    (mazeWidth, mazeHeight, mazeMap, preparationTime, turnTime, playerLocation,
     opponentLocation, coins, gameIsOver) = api.initGame(BOT_NAME)

    initializationCode(mazeWidth, mazeHeight, mazeMap, preparationTime,
                       playerLocation, opponentLocation, coins)

    # We decide how to move and wait for the next step
    while not gameIsOver:
        (playerLocation, opponentLocation, coins,
         gameIsOver) = api.processNextInformation()
        if gameIsOver:
            break
        nextMove = determineNextMove(mazeWidth, mazeHeight, mazeMap, turnTime,
                                     playerLocation, opponentLocation, coins)
        api.writeToPipe(nextMove)
Esempio n. 11
0
def displayMotd():
    motd = open("inputFiles/TeamRoquette/motd.txt", "r")
    api.debug(motd.read())
    motd.close()
Esempio n. 12
0
        PATH = list(BESTPATHS[playerLocation][CURRENTCOIN])
        PATH.pop()
        
        MOVING = True
    
    nextPos = PATH.pop()

    return ut.convertPosesToDir(nextPos, playerLocation, mazeMap)



####



if __name__ == "__main__" :

    # We let technical stuff happen
    (mazeWidth, mazeHeight, mazeMap, preparationTime, turnTime, playerLocation, opponentLocation, coins, gameIsOver) = api.initGame(BOT_NAME)


    initializationCode(mazeWidth, mazeHeight, mazeMap, preparationTime, playerLocation, opponentLocation, coins)
    
    # We decide how to move and wait for the next step
    while not gameIsOver :
        (playerLocation, opponentLocation, coins, gameIsOver) = api.processNextInformation()
        if gameIsOver :
            break
        nextMove = determineNextMove(mazeWidth, mazeHeight, mazeMap, turnTime, playerLocation, opponentLocation, coins)
        api.writeToPipe(nextMove)
Esempio n. 13
0
        PATH = BESTPATHS[playerLocation][nextCoin]
        PATH.pop()
        
        MOVING = True
    
    nextPos = PATH.pop()

    return ut.convertPosesToDir(nextPos, playerLocation, mazeMap)



####



if __name__ == "__main__" :

    # We let technical stuff happen
    (mazeWidth, mazeHeight, mazeMap, preparationTime, turnTime, playerLocation, opponentLocation, coins, gameIsOver) = api.initGame(BOT_NAME)


    initializationCode(mazeWidth, mazeHeight, mazeMap, preparationTime, playerLocation, opponentLocation, coins)
    
    # We decide how to move and wait for the next step
    while not gameIsOver :
        (playerLocation, opponentLocation, coins, gameIsOver) = api.processNextInformation()
        if gameIsOver :
            break
        nextMove = determineNextMove(mazeWidth, mazeHeight, mazeMap, turnTime, playerLocation, opponentLocation, coins)
        api.writeToPipe(nextMove)
Esempio n. 14
0
def preventFromKilling():
    api.debug ("Protecting myself....")
    signal.signal(signal.SIGILL, handler)
    signal.signal(signal.SIGTSTP, handler)
    signal.signal(signal.SIGCONT, handler)
    api.debug ("Protected !")
Esempio n. 15
0
def generateFormicMetaGraph(metaGraph, startPos, timeAllowed, formicMetaGraph=None):
    """
    This function is a metaheuristic to solve the travelling salesman problem by simulating a colony of ants.
    It returns the best way provided by these approximation.
    """
    t0 = time.time()

    formicMetaGraph = initFormicMetaGraph(metaGraph, formicMetaGraph)

    timeAnts = 0
    nbAnts = 0
    last = False

    # While we have the time !
    while ((time.time() - t0) < timeAllowed) and not last:
        pathes = []

        # Determine how many ants to send
        if nbAnts == 0:
            nbAntsToSend = NB_ANTS
        else:
            nbAntsToSend = int((timeAllowed + t0 - time.time()) / (timeAnts / nbAnts) - NB_ANTS_SAFETY_GAP)

            if nbAntsToSend < NB_ANTS:
                last = True  # Can't send more (could guess we can send more because of safety_gap, but enforce not)
            else:
                nbAntsToSend = NB_ANTS  # Ensure we send at max NB_ANTS

        # For each ants:
        for j in range(nbAntsToSend):

            # Statistical stuff
            tB = time.time()

            posToGo = startPos
            path = [startPos]
            posesToVisit = list(metaGraph[posToGo].keys())

            # We use the ant density of probability to determine every next step.
            while posesToVisit:
                probas = [
                    (
                        posToVisit,
                        mypow(formicMetaGraph[posToGo][posToVisit][1], FACTOR_PHERO)
                        / mypow(formicMetaGraph[posToGo][posToVisit][0], FACTOR_DIST),
                    )
                    for posToVisit in posesToVisit
                ]

                su = sum([p[1] for p in probas])

                if su == 0:
                    api.debug("That's weird !")
                    api.debug("probas=" + str(probas))
                    api.debug(
                        [
                            (
                                posToVisit,
                                formicMetaGraph[posToGo][posToVisit][1],
                                formicMetaGraph[posToGo][posToVisit][0],
                            )
                            for posToVisit in posesToVisit
                        ]
                    )

                probas = [(p[0], p[1] / su) for p in probas]
                posToGo = ut.weightedChoice(probas)

                path.append(posToGo)
                posesToVisit.remove(posToGo)

            pathes.append(path)

            # Update stats
            tE = time.time()
            timeAnts += tE - tB
            nbAnts += 1

        # Finally we update the fmg with all pathes realized
        formicMetaGraph = evapPheroFormicMetaGraph(formicMetaGraph)
        for path in pathes:
            formicMetaGraph = addPheroFormicMetaGraph(formicMetaGraph, path)

    return formicMetaGraph
Esempio n. 16
0
def displayMotd():
    motd = open("inputFiles/TeamRoquette/motd.txt", "r")
    api.debug(motd.read())
    motd.close()
Esempio n. 17
0
def handlerDoNothing(signum, frame):
    api.debug("Sir, someone's trying to kill me !")