Beispiel #1
0
 def createDot(self):
     positionValid = False
     reservedPositions = []
     reservedPositions.append(
         [self.player.position[0], self.player.position[1]])
     for tailPart in self.player.tail:
         reservedPositions.append(
             [tailPart.position[0], tailPart.position[1]])
     while not positionValid:
         dotPosition = [
             random.randint(0, self.worldSize - 1),
             random.randint(0, self.worldSize - 1)
         ]
         for position in reservedPositions:
             if dotPosition[0] != position[0] and dotPosition[
                     1] != position[1]:
                 positionValid = True
             else:
                 positionValid = False
                 break
     self.dot = Dot(dotPosition[0], dotPosition[1], Window.tileSize)
     self.dot.setShape(
         self.window.canvas.create_rectangle(
             self.dot.position[0] * self.dot.size,
             self.dot.position[1] * self.dot.size,
             self.dot.position[0] * self.dot.size + self.dot.size,
             self.dot.position[1] * self.dot.size + self.dot.size,
             fill="blue",
             outline=""))
     self.objectHandler.add(self.dot)
Beispiel #2
0
def getDots(state):
    dots = []
    for x, i in enumerate(state):
        for y, j in enumerate(state[x]):
            if j is '.':
                dots.append(d.Dot(x, y, False))
            if j is 'o':
                dots.append(d.Dot(x, y, True))
    return dots
Beispiel #3
0
 def select_parent(self):
     avg = self.total_fitness / pop_size
     rand = random.uniform(0.0, self.total_fitness)
     curr_sum = 0.0
     for dot in self.dots:
         curr_sum += dot.fitness
         if dot.fitness > avg and curr_sum > rand:
             return dot
     best = Dot()
     best.dir = self.best_dot_dir.copy()
     return best
Beispiel #4
0
    def naturalSelection(self):
        self.newDots = 0
        self.newDots = [
            Dot(self.dotSize, self.boxSize, self.screen, self.goal)
            for i in xrange(len(self.dots))
        ]
        # newDots = Dot[dots.length] #next gen
        self.setBestDot()
        self.calculateFitnessSum()

        # the champion lives on

        i = 0
        for doti in self.newDots:
            # select parent based on fitness
            parent = self.selectParent()

            # get baby from them
            self.newDots[i] = parent.gimmeBaby()
            i = i + 1

        self.newDots[0] = self.dots[self.bestDot].gimmeBaby()
        self.newDots[0].isBest = True
        self.dots = self.newDots
        self.gen = self.gen + 1
Beispiel #5
0
def spawnDots(window):
    dotList = []
    dotMoveHistory = []
    for i in range(100):  # Need more automation to do more than 100 exact dots
        dotList.append(Dot(400, 0, window))
        dotList[i].draw()
        dotMoveHistory.append([])
    return (dotList, dotMoveHistory)
 def __init__(self, size):
     self.fitnessSum = 0
     self.dots = []
     self.gen = 1
     self.bestDot = 0
     self.minStep = 3000
     self.increment = 100
     self.bestDotsSteps = 0
     for i in range(size):
         self.dots.append(Dot.Dot())
Beispiel #7
0
 def __init__(self):
     self.dots = []
     for i in range(pop_size):
         s = Dot()
         self.dots.append(s)
         all_sprites.add(s)
         pop_sprites.add(s)
     self.total_fitness = 0.0
     self.generation = 1
     self.best_dot_dir = []
     self.best_dot = Dot
Beispiel #8
0
 def __init__(self, size, dotSize, boxSize, screen, goal):
     self.dotSize = dotSize
     self.boxSize = boxSize
     self.screen = screen
     self.goal = goal
     self.dots = [Dot(dotSize, boxSize, screen, goal) for i in xrange(size)]
     self.fitnessSum = 0
     self.gen = 1
     self.bestDot = 0  # the index of the best dot in the dots set
     self.minStep = 10000
     self.newDots = 0
Beispiel #9
0
    def __init__(self, screen, goal, size):
        self.screen = screen
        self.goal = goal
        self.size = size
        self.dots = []

        self.fitnessSum = 0.0
        self.gen = 1
        self.bestDot = 0
        self.minStep = 400

        self.first2reach = True

        for i in range(self.size):
            self.dots.append(Dot.Dot(self.screen, self.goal))
Beispiel #10
0
def setup_maze(file_name, dot_list):
    """ Function that sets up maze by populating maze_list, dot_list and start_pos
    Args:
        file_name: name of file that contains the unsolved maze
        dot_list: list containing the positions of the dots
    Returns:
        Tuple containing
        maze_list: the 2-D maze that stores the maze  
        start_pos: the starting position of the maze
    """
    with open(file_name) as text_file:
        maze_list = [[str(c) for c in line.rstrip()] for line in text_file]

    for i in range(len(maze_list)):
        for j in range(len(maze_list[i])):
            if (maze_list[i][j] == 'P'):
                start_pos = Position(i, j)
            elif (maze_list[i][j] == '.'):
                dot_list.append(Dot(Position(i, j)))
    return maze_list, start_pos
Beispiel #11
0
 def boost_fitness(self):
     best_steps = self.best_dot.curr_step
     fixed_direction = best_steps
     new_dots = []
     for i in range(pop_size):
         if i < 50:  #  for the first 50 keep evolving normally
             baby = self.select_parent().get_baby()
             new_dots.append(baby)
         elif best_steps < n_steps and not self.best_dot.has_reached_goal:  #  the best crushed somewhere
             baby = Dot()
             if i < pop_size / 2:
                 explosion = 50
             else:
                 explosion = 15
             for j in range(fixed_direction - explosion):
                 baby.dir[j] = self.best_dot_dir[j]
             new_dots.append(baby)
             baby.add(all_sprites)
             baby.add(pop_sprites)
         else:
             baby = Dot()
             remainder = i % 50
             if remainder == 0:
                 fixed_direction -= 15
                 baby.dir = cardinal_dir[remainder].copy()
             elif remainder < 4:
                 baby.dir = cardinal_dir[remainder].copy()
             for j in range(fixed_direction):
                 baby.dir[j] = self.best_dot_dir[j]
             new_dots.append(baby)
             baby.add(all_sprites)
             baby.add(pop_sprites)
     self.dots = new_dots.copy()
     self.keep_best()
     self.generation += 1
Beispiel #12
0
class GameHandler:
    worldSize = 30
    delay = 100
    obstacles = Enum('obstacles', 'dot tail wall')
    directions = {
        37: Player.movement.left,
        38: Player.movement.up,
        39: Player.movement.right,
        40: Player.movement.down
    }

    def __init__(self):
        self.player = Player(math.ceil((self.worldSize - 1) / 2),
                             math.ceil((self.worldSize - 1) / 2),
                             Window.tileSize)
        self.window = Window(self.worldSize)
        self.window.master.bind("<KeyPress>", self.keyDown)
        self.player.setShape(
            self.window.canvas.create_rectangle(
                self.player.position[0] * self.player.size,
                self.player.position[1] * self.player.size,
                self.player.position[0] * self.player.size + self.player.size,
                self.player.position[1] * self.player.size + self.player.size,
                fill="black",
                outline=""))
        self.objectHandler = ObjectHandler(self.window.canvas)

    def start(self):
        self.createDot()
        self.objectHandler.add(self.player)
        self.process()
        self.window.open()

    def process(self):
        if self.isCollidingWith() == self.obstacles.dot:
            self.objectHandler.remove(self.dot)
            self.player.grow()
            self.createDot()
        elif self.isCollidingWith() == self.obstacles.tail or \
             self.isCollidingWith() == self.obstacles.wall:
            print("game over")
            self.window.close()
        while len(self.player.tail) < self.player.tailLength:
            if len(self.player.tail) == 0:
                previous = self.player
            else:
                previous = self.player.tail[len(self.player.tail) - 1]
            self.player.tail.append(self.player.TailPart(previous))
            self.objectHandler.joinList(self.player.tail)
            newTailPart = self.player.tail[len(self.player.tail) - 1]
            newTailPart.setShape(
                self.window.canvas.create_rectangle(
                    newTailPart.position[0] * newTailPart.size,
                    newTailPart.position[1] * newTailPart.size,
                    newTailPart.position[0] * newTailPart.size +
                    newTailPart.size,
                    newTailPart.position[1] * newTailPart.size +
                    newTailPart.size,
                    fill="black",
                    outline=""))
            print("extend tail - current length:", len(self.player.tail))
        self.objectHandler.update()
        self.objectHandler.render()
        self.window.canvas.after(self.delay, self.process)

    def createDot(self):
        positionValid = False
        reservedPositions = []
        reservedPositions.append(
            [self.player.position[0], self.player.position[1]])
        for tailPart in self.player.tail:
            reservedPositions.append(
                [tailPart.position[0], tailPart.position[1]])
        while not positionValid:
            dotPosition = [
                random.randint(0, self.worldSize - 1),
                random.randint(0, self.worldSize - 1)
            ]
            for position in reservedPositions:
                if dotPosition[0] != position[0] and dotPosition[
                        1] != position[1]:
                    positionValid = True
                else:
                    positionValid = False
                    break
        self.dot = Dot(dotPosition[0], dotPosition[1], Window.tileSize)
        self.dot.setShape(
            self.window.canvas.create_rectangle(
                self.dot.position[0] * self.dot.size,
                self.dot.position[1] * self.dot.size,
                self.dot.position[0] * self.dot.size + self.dot.size,
                self.dot.position[1] * self.dot.size + self.dot.size,
                fill="blue",
                outline=""))
        self.objectHandler.add(self.dot)

    def isCollidingWith(self):
        if self.player.position[0] == self.dot.position[0] and \
           self.player.position[1] == self.dot.position[1]:
            print("collides with dot")
            return self.obstacles.dot
        elif self.player.position[0] >= self.worldSize or \
             self.player.position[1] >= self.worldSize or \
             self.player.position[0] < 0 or \
             self.player.position[1] < 0:
            print("collides with wall")
            return self.obstacles.wall
        else:
            for tailPart in self.player.tail:
                if self.player.position[0] == tailPart.position[0] and \
                   self.player.position[1] == tailPart.position[1]:
                    print("collides with tail")
                    return self.obstacles.tail
        return None

    def keyDown(self, event):
        self.player.setMoveDirection(
            self.directions.get(event.keycode, self.directions.get(38)))
        print("key down:", event.keycode, "- direction:",
              self.player.direction)
Beispiel #13
0
 def __init__(self):
     for i in range(1000):
         self.dots.append((Dot.Dot()))
Beispiel #14
0
import Brain
import Dot
import random as ra

DotObj = Dot.Dot()  # get an instance of the class


class Population:
    dots = []
    fitnessSum = 0
    generation = 1
    bestDot = 0
    minStep = 400

    def __init__(self):
        for i in range(1000):
            self.dots.append((Dot.Dot()))

    def show(self):
        for i in range(len(self.dots)):
            self.dots[i].show()

    def update(self):
        for i in range(len(self.dots)):
            #if self.dots[i].brain.step > self.minStep:
            #self.dots[i].dead = bool(1)
            self.dots[i].update()

    def calculateFitness(self):
        for i in range(len(self.dots)):
            self.dots[i].calculateFitness()
Beispiel #15
0
            else:
                last_good = node
        for edge in get_edges(node):
            tail = get_tail(edge)
            if last_good is not node:
                orphans.add((last_good, tail))
            if tail not in visited:
                visited.add(tail)
                stack.append((last_good, tail))

    orphans = [(last_good, tail) for (last_good, tail) in orphans if tail not in removes]

    return visited, removes, orphans



if __name__ == '__main__':

    import Dot

    g = generate_scale_free_graph(steps=10, growth_num=4)

    d = Dot.Dot(g)

    d.all_node_style(width=1, shape='circle', style='filled', fillcolor='white')

    d.display()
    d.save_img()

    print g