Exemplo n.º 1
0
def frayedThreadRand(G, fN, elemLimit, sonLimit):
    """
    Sfilacciato-Random è una forma particolare che in ogni nodo mette dei figli foglia di numero variabile al fine di aumentare il confine
    Crea una pila che all'inizio contiene solo fN, e gli collega altri nodi in numero variabile. Questi saranno poi
    i punti di partenza per generarne altri, finchè non viene raggiunto elemLimit. Il comando "del pila" serve per
    deallocare lo spazio precedentemente occupato dalla pila.

    :param G: grafo contenente fN
    :param fN: è il fistNode creato in mkGraph
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :param sonLimit: numero massimo di figli per nodo, è lo stesso di mkGraph
    :return:
    """
    pila = stack()
    pila.push(fN)

    count = 1
    while (count <= elemLimit - 1):
        if (not pila.isEmpty()):
            node = pila.pop()  # prendo nodo già inserito
        for k in range(rInt(
                0, sonLimit)):  # gli aggiungo un numero casuale di figli
            if (count > elemLimit - 1):
                break
            son = G.addNode(rInt(-10, 10))
            notOriented(G, node, son)
            pila.push(son)
            count += 1  # tengo traccia dell'aumento dei nodi
    del pila  # eliminiamo la pila
Exemplo n.º 2
0
def asterisk(G, fN, elemLimit, sonLimit):
    """
    Creazione di un grafico simile a lineare, ma a partire da un nodo centrale fa partire un numero sonLimit di rami,
    sempre con un numero globale di elemLimit nodi; la forma variera' tra linear (sL = 2) e star (sL = n-1); per
    questi casi, preferire gli algoritmi appositamente creati (meno istruzioni --> piu' rapidi).

    :param G: grafo contenente fN
    :param fN: è il fistNode creato in mkGraph
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :param sonLimit: numero rami dipanati dal nodo centrale, è lo stesso di mkGraph
    :return:
    """
    node = fN
    count = 1

    coda = queue()

    # abbozziamo i rami per definire la forma del grafo
    for k in range(sonLimit):
        if (sonLimit <= (count - 1) or elemLimit <= (count - 1)):
            #print("ERROR: not enough elements chosen")
            return
        son = G.addNode(rInt(-10, 10))
        notOriented(G, node, son)
        coda.enqueue(son)
        count += 1

    # sviluppiamo i rami dei grafi
    while (count <= elemLimit - 1):
        if (not coda.isEmpty()):
            node = coda.dequeue()  # prendo nodo già inserito
        son = G.addNode(rInt(-10, 10))
        notOriented(G, node, son)
        coda.enqueue(son)
        count += 1  # tengo traccia dell'aumento dei nodi
Exemplo n.º 3
0
def key_generator():
    import string
    from random import randint as rInt

    generalPurposeStr = (string.ascii_letters + string.punctuation).replace(
        "`", "").replace("-", "")

    used = list()

    theKey = ""

    keySections = list()

    ct = 10

    while ct > 0:
        integerWeNeed_1 = rInt(0, (len(generalPurposeStr) - 1))
        charWeNeed = generalPurposeStr[integerWeNeed_1]

        control_flag = False
        for i in used:
            if i == charWeNeed:
                control_flag = True

        if control_flag:
            continue

        integerWeNeed_2 = rInt(0, 99)

        for i in used:
            if i == integerWeNeed_2:
                control_flag = True

        if control_flag:
            continue

        keySection = "{}{}".format(charWeNeed, integerWeNeed_2)
        keySections.append(keySection)

        #appends useds to a list to dont use they again
        used.append(charWeNeed)
        used.append(integerWeNeed_2)

        ct -= 1

    theKey = "-".join(keySections)

    return theKey
Exemplo n.º 4
0
def mkGraph(elem, mod="rand", son=5):
    """
    Chiama le funzioni che creano il grafo; di default mod="rand" e son=5.

    :param elem: numero massimo di elementi da aggiungere al grafo
    :param mod: modalità: "rand", "star", "linear", "fractal", "sfilacciatoRand", "sfilacciato"
    :param son: numero massimo di figli per nodo, al massimo per rand, fissato per fractal
    :return: grafico sotto forma di lista di adiacenza
    """
    newGr = GraphAdjacencyList()
    firstNode = newGr.addNode(rInt(-10, 10))  # nodo con valore casuale

    if mod == "asterisco":
        asterisk(newGr, firstNode, elem, son)

    if mod == "sfilacciatoRand":
        frayedThreadRand(newGr, firstNode, elem, son)

    if mod == "sfilacciato":
        frayedThread(newGr, firstNode, elem, son)

    if mod == "star":
        starGraph(newGr, firstNode, elem)

    if mod == "linear":
        linearGraph(newGr, firstNode, elem)

    if mod == "fractal":
        fractalGraph(newGr, firstNode, elem, son)

    if mod == "rand":
        randomGraph(newGr, elem)

    return newGr
Exemplo n.º 5
0
def frayedThread(G, fN, elemLimit, sonLimit):
    """
    Sfilacciato è una forma particolare che in ogni nodo mette dei figli foglia al fine di aumentare il confine
    Crea una pila che all'inizio contiene solo fN, e gli collega altri nodi in numero variabile. Questi saranno poi
    i punti di partenza per generarne altri, finchè non viene raggiunto elemLimit. Il comando "del pila" serve per
    deallocare lo spazio precedentemente occupato dalla pila.

    :param G: grafo contenente fN
    :param fN: è il fistNode creato in mkGraph
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :param sonLimit: numero massimo di figli per nodo, è lo stesso di mkGraph
    :return:
    """
    node = fN
    count = 1
    while (count <= elemLimit - 1):
        for k in range(
                sonLimit + 1
        ):  # aggiungo un numero definito di figli foglia, e l'ultimo che sarà il nuovo nodo
            if (count > elemLimit - 1):
                break
            son = G.addNode(rInt(-10, 10))
            notOriented(G, node, son)
            count += 1
        node = son  # prendo l'ulimo nodo aggiunto e su di esso ripeto il procedimento
Exemplo n.º 6
0
def fractalGraph(G, fN, elemLimit, sonLimit):
    """
    Crea una coda che inizialmente contiene solo fN, e poi aggiunge i figli nel numero stabilito da sonLimit ad
    ogni nodo, come per un d-Heap. Se elemLimit-count (gli elementi rimanenti da inserire nel grafo) è minore di
    sonLimit, allora l'inserimento dei nodi nel grafo si ferma all'iterazione precedente.

    :param G: grafo contenente fN
    :param fN: è il firstNode creato in mkGraph
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :param sonLimit: numero massimo di figli per nodo, è lo stesso di mkGraph
    :return:
    """
    coda = queue()
    coda.enqueue(fN)

    count = 1
    while (count <= elemLimit - 1):
        if (not coda.isEmpty()):
            node = coda.dequeue()  # prendo nodo già inserito
        for k in range(sonLimit):  # gli aggiungo un numero definito di figli
            if (count > elemLimit - 1):
                break
            son = G.addNode(rInt(-10, 10))
            notOriented(G, node, son)
            coda.enqueue(son)
            count += 1  # tengo traccia dell'aumento dei nodi
    del coda  # eliminiamo la coda
Exemplo n.º 7
0
    def handle(self, *args, **options):
        f = open("branches.json", "r")
        thing = json.load(f)
        f.close()

        for i in range(len(thing)):
            b = Branch(br_id=thing[i]["_id"], width=rInt(80, 240))
            b.save()
Exemplo n.º 8
0
 def appleChangePosition(self):
     validPos = False
     while not validPos:
         validPos = True
         self.appleSeed += 1
         random.seed(self.appleSeed)
         self.applePosition = [
             rInt(1, self.boundary[0] - 1),
             rInt(1, self.boundary[1] - 1)
         ]
         if (self.xPos == self.applePosition[0]
                 and self.xPos == self.applePosition[1]):
             validPos = False
         else:
             for t in self.body:
                 if self.applePosition == t:
                     validPos = False
Exemplo n.º 9
0
def keyGenerator():
    generalPurposeStr = (string.ascii_letters + string.punctuation).replace(
        "`", "").replace("-", "")

    used = list()

    theKey = ""

    keySections = list()

    ct = 10

    while ct > 0:
        integerWeNeed_1 = rInt(0, (len(generalPurposeStr) - 1))
        charWeNeed = generalPurposeStr[integerWeNeed_1]

        control_flag = False
        for i in used:
            if i == charWeNeed:
                control_flag = True

        if control_flag:
            continue

        integerWeNeed_2 = rInt(0, 99)

        for i in used:
            if i == integerWeNeed_2:
                control_flag = True

        if control_flag:
            continue

        keySection = "{}{}".format(charWeNeed, integerWeNeed_2)
        keySections.append(keySection)

        #appends useds to a list to dont use they again
        used.append(charWeNeed)
        used.append(integerWeNeed_2)

        ct -= 1

    theKey = "-".join(keySections)

    print("-\n--\n---\nyour key is ready below:\n{}\n=================".format(
        theKey))
Exemplo n.º 10
0
def starGraph(G, fN, elemLimit):
    """
    Genera tanti nodi che, con la funzione notOriented, saranno collegati a firstNode.

    :param G: grafo contenente fN
    :param fN: è il fistNode creato in mkGraph
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :return:
    """
    node = fN
    for k in range(elemLimit - 1):
        son = G.addNode(rInt(-10, 10))
        notOriented(G, node, son)
Exemplo n.º 11
0
def randomGraph(G, elemLimit):
    """
    Genera un grafo in maniera random. Il comando "del l" finale serve a deallocare lo spazio precedentemente occupato
    dalla lista l.

    :param G: grafo contenente fN
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :return:
    """

    count = 1
    # oldNode = fN
    l = []
    while (count <= elemLimit - 1):
        newNode = G.addNode(rInt(-10, 10))
        l = G.getNodes()
        oldNode = l[rInt(0, len(l) - 1)]
        while (oldNode == newNode):
            oldNode = l[rInt(0, len(l) - 1)]
        notOriented(G, newNode, oldNode)
        count += 1
    del l
Exemplo n.º 12
0
def linearGraph(G, fN, elemLimit):
    """
    Genera un grafo lineare.

    :param G: grafo contenente fN
    :param fN: è il firstNode creato in mkGraph
    :param elemLimit: numero massimo di elementi da aggiungere al grafo, è lo stesso di mkGraph
    :return:
    """
    node = fN
    for k in range(elemLimit - 1):
        # prendo nodo già inserito
        son = G.addNode(rInt(-10, 10))
        notOriented(G, node, son)
        node = son
Exemplo n.º 13
0
 def __init__(self, xPos, yPos, colour, maxEnergy, wBoundary, hBoundary,
              bodyLength):
     self.xPos = xPos
     self.yPos = yPos
     random.seed(Snake.seed)
     i = rInt(1, 4)
     self.direction = i
     self.body = []
     self.createBody(bodyLength)
     self.applesEaten = 0
     self.colour = colour
     self.dead = False
     self.increaseLength = False
     #
     self.score = 0
     #
     self.decisionScore = 0
     self.sumDecisionScore = 0
     self.maxEnergy = maxEnergy
     self.energy = maxEnergy
     self.boundary = [wBoundary, hBoundary]
     #
     self.framesAlive = 0
     self.appleChangePosition()
Exemplo n.º 14
0
#import random
#import random as rand
from random import choice as ch, randint as rInt

print(ch(['apple', 'banana', 'cherry', 'durian']))
print(rInt(1, 100))
Exemplo n.º 15
0
class Snake:
    seed = rInt(1, 10000)
    appleSeed = rInt(1, 10000)
    maxEnergy = 100

    def __init__(self, xPos, yPos, colour, maxEnergy, wBoundary, hBoundary,
                 bodyLength):
        self.xPos = xPos
        self.yPos = yPos
        random.seed(Snake.seed)
        i = rInt(1, 4)
        self.direction = i
        self.body = []
        self.createBody(bodyLength)
        self.applesEaten = 0
        self.colour = colour
        self.dead = False
        self.increaseLength = False
        #
        self.score = 0
        #
        self.decisionScore = 0
        self.sumDecisionScore = 0
        self.maxEnergy = maxEnergy
        self.energy = maxEnergy
        self.boundary = [wBoundary, hBoundary]
        #
        self.framesAlive = 0
        self.appleChangePosition()

    def createBody(self, bodyLength):
        if self.direction == Direction.LEFT:
            [
                self.body.append([self.xPos + bodyLength - i, self.yPos])
                for i in range(bodyLength)
            ]
        elif self.direction == Direction.RIGHT:
            [
                self.body.append([self.xPos - bodyLength + i, self.yPos])
                for i in range(bodyLength)
            ]
        elif self.direction == Direction.UP:
            [
                self.body.append([self.xPos, self.yPos + bodyLength - i])
                for i in range(bodyLength)
            ]
        elif self.direction == Direction.DOWN:
            [
                self.body.append([self.xPos, self.yPos - bodyLength + i])
                for i in range(bodyLength)
            ]

    def updateBody(self, direction):
        self.body.append([self.xPos, self.yPos])
        if not self.increaseLength:
            del self.body[0]
        else:
            self.increaseLength = False
        if (direction
                == Direction.LEFT) and not (self.direction == Direction.RIGHT):
            self.direction = Direction.LEFT
        elif (direction
              == Direction.RIGHT) and not (self.direction == Direction.LEFT):
            self.direction = Direction.RIGHT
        elif (direction
              == Direction.UP) and not (self.direction == Direction.DOWN):
            self.direction = Direction.UP
        elif (direction
              == Direction.DOWN) and not (self.direction == Direction.UP):
            self.direction = Direction.DOWN

    def checkCollision(self):
        # out of bounds
        if (self.xPos <= 0 or self.xPos >= self.boundary[0] or self.yPos <= 0
                or self.yPos >= self.boundary[1]):
            self.dead = True
            self.firstDeathFrame = True
        else:
            # check for self collision
            for t in self.body:
                if self.xPos == t[0] and self.yPos == t[1]:
                    self.dead = True
                    self.firstDeathFrame = True
                    break
        # check for apple collision
        if self.xPos == self.applePosition[
                0] and self.yPos == self.applePosition[1]:
            self.appleChangePosition()
            self.increaseLength = True
            self.applesEaten += 1
            self.energy = self.maxEnergy
        else:
            self.energy -= 1
            if self.energy <= 0:
                self.dead = True

    def senses(self):
        self.collisionDistance = [
            self.xPos, self.boundary[0] - self.xPos, self.yPos,
            self.boundary[1] - self.yPos
        ]
        self.appleDistance = [1000, 1000, 1000, 1000]
        self.appleDistance2 = [
            self.xPos - self.applePosition[0],
            self.yPos - self.applePosition[1]
        ]
        #
        self.framesAlive += 1
        #
        if self.xPos - self.applePosition[0] >= 0:
            self.appleDistance[0] = self.xPos - self.applePosition[0]
        else:
            self.appleDistance[1] = self.applePosition[0] - self.xPos

        if self.yPos - self.applePosition[1] >= 0:
            self.appleDistance[2] = self.yPos - self.applePosition[1]
        else:
            self.appleDistance[3] = self.applePosition[1] - self.yPos

        for block in self.body:
            if block[0] == self.xPos:
                distance = block[1] - self.yPos
                if distance > 0:
                    if distance < self.collisionDistance[2]:
                        self.collisionDistance[3] = distance
                else:
                    if abs(distance) < self.collisionDistance[3]:
                        self.collisionDistance[2] = abs(distance)
            elif block[1] == self.yPos:
                distance = block[0] - self.xPos
                if distance > 0:
                    if distance < self.collisionDistance[0]:
                        self.collisionDistance[1] = distance
                else:
                    if abs(distance) < self.collisionDistance[1]:
                        self.collisionDistance[0] = abs(distance)

        # for x in range(0, self.xPos):# from left wall to snake
        #     for block in self.body:
        #         if block == [x,self.yPos] :
        #             self.collisionDistance[0] = self.xPos - x

        # for x in range(self.boundary[0], self.xPos, -1):
        #     for block in self.body:
        #         if block == [x,self.yPos]:
        #             self.collisionDistance[1] = x - self.xPos

        # for y in range(0, self.yPos):
        #     for block in self.body:
        #         if block == [self.xPos,y]:
        #             self.collisionDistance[2] = self.yPos - y

        # for y in range(self.boundary[1], self.yPos, -1):
        #     for block in self.body:
        #         if block == [self.xPos,y]:
        #             self.collisionDistance[3] = y - self.yPos

        self.collisionDistance = list(map(NORMALISE, self.collisionDistance))

        def getDecisionScore(self):
            self.decisionScore = -1
            if self.appleDistance2[0] < 0:
                if self.direction == Direction.RIGHT:
                    self.decisionScore += 2
            elif self.appleDistance2[0] > 0:
                if self.direction == Direction.LEFT:
                    self.decisionScore += 2
            if self.appleDistance2[1] > 0:
                if self.direction == Direction.UP:
                    self.decisionScore += 2
            elif self.appleDistance2[1] < 0:
                if self.direction == Direction.DOWN:
                    self.decisionScore += 2

        def getDecisionArray(self):
            self.decisionArray = [0, 0, 0, 0]
            if self.appleDistance2 == [1, 0]:
                self.decisionArray[0] += 1
            elif self.appleDistance2 == [-1, 0]:
                self.decisionArray[1] += 1
            elif self.appleDistance2 == [0, 1]:
                self.decisionArray[2] += 1
            elif self.appleDistance2 == [0, -1]:
                self.decisionArray[3] += 1
            else:
                if self.appleDistance2[0] < 0:
                    self.decisionArray[1] += 1
                elif self.appleDistance2[0] > 0:
                    self.decisionArray[0] += 1
                if self.appleDistance2[1] > 0:
                    self.decisionArray[2] += 1
                elif self.appleDistance2[1] < 0:
                    self.decisionArray[3] += 1

        getDecisionScore(self)
        getDecisionArray(self)

    def move(self):
        if self.direction == Direction.LEFT:
            self.xPos -= 1
        elif self.direction == Direction.RIGHT:
            self.xPos += 1
        elif self.direction == Direction.UP:
            self.yPos -= 1
        elif self.direction == Direction.DOWN:
            self.yPos += 1

    def getScore(self, game):
        self.sumDecisionScore += self.decisionScore
        if self.sumDecisionScore < 0:
            self.sumDecisionScore = 0
        self.score = (self.framesAlive / 100)**2 + (
            self.sumDecisionScore / 10)**2 + (2 * (self.applesEaten))**2

    def appleChangePosition(self):
        validPos = False
        while not validPos:
            validPos = True
            self.appleSeed += 1
            random.seed(self.appleSeed)
            self.applePosition = [
                rInt(1, self.boundary[0] - 1),
                rInt(1, self.boundary[1] - 1)
            ]
            if (self.xPos == self.applePosition[0]
                    and self.xPos == self.applePosition[1]):
                validPos = False
            else:
                for t in self.body:
                    if self.applePosition == t:
                        validPos = False
Exemplo n.º 16
0
def grafoEsempio():
    """
    funzione che genera il grafo in Fig1 sulla relazione
    :return: grafoFig1
    """
    fig1 = GraphAdjacencyList()
    n0 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n1 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n2 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n3 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n4 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n5 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n6 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n7 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n8 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n9 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    n10 = fig1.addNode(rInt(-10, 10))  # nodo con valore casuale
    notOriented(fig1, n8, n4)
    notOriented(fig1, n7, n4)
    notOriented(fig1, n9, n4)
    notOriented(fig1, n1, n4)
    notOriented(fig1, n5, n1)
    notOriented(fig1, n0, n1)
    notOriented(fig1, n0, n2)
    notOriented(fig1, n0, n3)
    notOriented(fig1, n6, n3)
    notOriented(fig1, n6, n10)
    return fig1
Exemplo n.º 17
0
            backupi2 = i2
        except:
            print("#this input must be integer.#")
            continue


        if i2  > 1000:
            print("-----\nwhy did you do this..just..\n-----\ni didn't understand\n-----\ntry something less.\ndon't be a paranoid.")
            continue
        
        time1 = time()
        while timesinp > 0:
            i2 = backupi2
            newpassword = ""
            while i2 > 0:
                r_int = rInt(1,len(secki))-1
                new_char = secki[r_int]
                newpassword = newpassword + new_char
                i2 = i2 - 1
            if timesinp == 1:
                print("{}\n".format(newpassword))
                passwords += "{}\n\n".format(newpassword)
                print("----------\nyour new passwords are above.")
                
                time2 = time()
                
                break

            print("{}\n".format(newpassword))
            passwords += "{}\n\n".format(newpassword)
            timesinp -= 1