Exemple #1
0
def new_prey():
	if (len(preyList) < 9):
		x = random.randrange((window_size[0] - 40))
		y = random.randrange((window_size[1] - 40))
		while (y > 300):
			y = random.randrange(window_size[1])
		preyList.append(Prey(pygame.image.load("images/prey.png").convert(), [x, y]))	
def initialize_animats(initial_list, object_list, scale, number, speed, kind):
    for i in range(0, number):
        if (kind == 'prey'):
            animat = Prey(prey_path, scale, speed, RL.QLearn)
            overlap = False
            for j in range(0, len(initial_list)):
                if (doRectsOverlap(animat.get_rect(),
                                   initial_list[j].get_rect())):
                    overlap = True
                    break
            if (overlap):
                i = i - 1
            else:
                object_list.append(animat)
                all_sprites.add(animat)
                initial_list.append(animat)
        else:
            animat = Predator(predator_path, scale, speed, RL.QLearn)
            overlap = False
            for j in range(0, len(initial_list)):
                if (doRectsOverlap(animat.get_rect(),
                                   initial_list[j].get_rect())):
                    overlap = True
                    break
            if (overlap):
                i = i - 1
            else:
                object_list.append(animat)
                all_sprites.add(animat)
                initial_list.append(animat)
Exemple #3
0
def single_sim():

    width = 1000
    height = 1000
    n_flock = 1000
    n_pred = 10
    elapsed = 0

    flock = [
        Prey(*np.random.rand(2) * 1000, width, height, np.mod(_, 2))
        for _ in range(n_flock)
    ]
    predators = [
        Predator(*np.random.rand(2) * 1000, width, height, np.mod(_, 2))
        for _ in range(n_pred)
    ]

    while flock and predators and len(flock) < 1500 and elapsed < 10:

        pointmap = create_map(flock)

        locations = np.array(list(pointmap.keys()))
        tree = spatial.KDTree(locations, 15)
        all = flock + predators

        for boid in all:
            boid.apply_behaviour(flock, tree, locations, pointmap, predators,
                                 elapsed)

        for boid in all:
            boid.update()
            boid.edges()

        print(len(flock), ",", len(predators), ",", elapsed)
        elapsed += 1
Exemple #4
0
def single_sim(value):

    a_list = []
    n_pred_vec = []
    n_prey_vec = []
    time_vec = []

    width = 1000
    height = 1000
    n_flock = 600
    n_pred = 25

    elapsed = 0

    flock = [
        Prey(*np.random.rand(2) * 1000, width, height) for _ in range(n_flock)
    ]
    predators = [
        Predator(*np.random.rand(2) * 1000, width, height)
        for _ in range(n_pred)
    ]

    _thread.start_new_thread(input_thread, (a_list, ))

    while flock and predators and len(
            flock) < 2000 and elapsed < len_sim and not a_list:

        pointmap = create_map(flock)

        locations = np.array(list(pointmap.keys()))
        tree = spatial.KDTree(locations, 15)
        all = flock + predators

        for boid in all:
            boid.apply_behaviour(flock, tree, locations, pointmap, predators)

        for boid in all:
            boid.update()
            boid.edges()

        print(len(flock), ",", len(predators), ",", elapsed)
        n_prey_vec.append(len(flock))
        n_pred_vec.append(len(predators))
        time_vec.append(elapsed)

        elapsed += 1

    #plt.title("Populations vs time")
    #plt.xlabel("Elapsed time (#)")
    #plt.ylabel("# of individuals")
    #plt.plot(time_vec,n_prey_vec, label='Preys')
    #plt.plot(time_vec,n_pred_vec, label='Predators')

    #plt.legend()
    #plt.savefig('sim_{}.pdf'.format(value))
    #plt.close()
    return n_prey_vec, n_pred_vec
Exemple #5
0
def main():
    '''main execution func'''
    game = SteeringBehavioursGame("SteeringBehaviours")

    for _ in range(1):
        pos = Vector2(randrange(0, 800), randrange(0, 800))
        vel = Vector2(randrange(0, 800), randrange(0, 800)).normalized
        agent0 = Prey("max", pos, vel)
        pos = Vector2(randrange(0, 800), randrange(0, 800))
        vel = Vector2(randrange(0, 800), randrange(0, 800)).normalized
        agent1 = Prey("donray", pos, vel)
        pos = Vector2(randrange(0, 800), randrange(0, 800))
        vel = Vector2(randrange(0, 800), randrange(0, 800))
        agent2 = Predator("trent", pos, vel, [agent0, agent1])

        agent0.set_target(agent2)
        agent1.set_target(agent2)

        game.addtobatch(agent0)
        game.addtobatch(agent1)
        game.addtobatch(agent2)
    game.run()
Exemple #6
0
    def Start_Evaluation(self, pp, pb):
        #run simulator without pausing
        self.sim = pyrosim.Simulator(eval_time=c.evalTime,
                                     play_blind=pb,
                                     play_paused=pp)

        #create instance of the robot class
        #sends a random value between -1 and 1 for each iteration
        self.predator = Predator(self.sim, self.predatorGenome)
        self.prey = Prey(self.sim, self.preyGenome)

        #start the simulator
        self.sim.start()
    def Start_Evaluation(self, env, pp, pb):
        #run simulator without pausing
        self.sim = pyrosim.Simulator(eval_time=c.evalTime,
                                     play_blind=pb,
                                     play_paused=pp)

        env.Send_To(self.sim)
        #create instance of the robot class
        #sends a random value between -1 and 1 for each iteration
        self.robot = Prey(self.sim, self.genome)

        self.collided = self.sim.assign_collision(self.robot, env.source)
        #start the simulator
        self.sim.start()
    def start(self):
        prev = ""
        while 1:
            resp = self.s.recv(1024) + prev

            if '\n' not in resp:
                prev = resp
                continue

            resp = resp.split('\n')

            currResp = resp[0]
            resp.pop(0)

            prev = '\n'.join(resp)
            # print currResp

            if 'done' in currResp:
                break

            if 'sendname' in currResp:
                self.sendOutput(self.teamname)
                continue

            if 'hunter' in currResp:
                self.playerType = 'hunter'
                self.flag = 0
                continue
            elif 'prey' in currResp:
                self.playerType = 'prey'
                self.flag = 0
                continue

            currResp = currResp.split(' ')

            currResp = self.parseInput(currResp)

            if self.flag == 0:
                self.flag = 1
                self.player = Hunter(
                    currResp) if self.playerType == 'hunter' else Prey(
                        currResp)

            self.sendOutput(self.parseOutput(self.player.move(currResp)))

        self.s.close()
Exemple #9
0
def main(WIDTH=21, HEIGHT=10, PREDATORS=8):
    mygame = Kernel()

    myscheduler = DummyScheduler()
    mygame.addAgent(myscheduler, "Scheduler")

    mymesh = Mesh(WIDTH, HEIGHT)
    mygame.addAgent(mymesh, "Mesh")

    anAgent = Prey()
    mygame.addAgent(anAgent, "Prey")
    mymesh.addAgent(mygame.getAgentId(anAgent))

    for i in range(PREDATORS):
        anAgent = Predator()
        mygame.addAgent(anAgent, "Predator%s" % i)
        mymesh.addAgent(mygame.getAgentId(anAgent))

    while (Kernel.instance != None):
        time.sleep(3)
Exemple #10
0
 def __init__(self, x, y):
     self._image = PhotoImage(file='ufo.gif')
     ball = Prey(x, y, 10, 10, 1, 5)
     ball.randomize_angle()
     ang = ball.get_angle()
     Prey.__init__(self, x, y, 10, 10, ang, 5)
Exemple #11
0
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    # needed so that egi knows where to draw
    egi.InitWithPyglet(win)
    # prep the fps display
    fps_display = clock.ClockDisplay()
    # register key and mouse event handlers
    win.push_handlers(on_key_press)
    win.push_handlers(on_mouse_release)
    win.push_handlers(on_resize)

    # create a world for agents
    world = World(500, 500)
    # add one agent
    world.hunter = Hunter(world)
    world.agents.append(Prey(world))
    # add HideObjects
    for _ in range(5):
        obj = HideObject(world)
        world.hideObjects.append(obj)
    # unpause the world ready for movement
    world.paused = False

    while not win.has_exit:
        win.dispatch_events()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        # show nice FPS bottom right (default)
        delta = clock.tick()
        world.update(delta)
        world.render()
        fps_display.draw()
Exemple #12
0
def photoshoot():

    n_sim = 1
    for value in range(n_sim):

        width = 1000
        height = 1000
        n_flock = 1000
        #n_pred = int(n_flock/25)
        n_pred = 5
        elapsed = 0

        flock = [
            Prey(*np.random.rand(2) * 1000, width, height)
            for _ in range(n_flock)
        ]
        predators = [
            Predator(*np.random.rand(2) * 1000, width, height)
            for _ in range(n_pred)
        ]

        fig = plt.figure()
        camera = Camera(fig)

        while flock and predators and len(flock) < 1100 and elapsed < 300:

            start = time.perf_counter()
            color = []
            radius = []

            x = np.empty(len(flock + predators))
            y = np.empty(len(flock + predators))
            u = np.empty(len(flock + predators))
            v = np.empty(len(flock + predators))

            pointmap = create_map(flock)

            locations = np.array(list(pointmap.keys()))
            tree = spatial.KDTree(locations, 15)
            all = flock + predators

            for boid in all:
                boid.apply_behaviour(flock, tree, locations, pointmap,
                                     predators, elapsed)

            count = 0
            for boid in all:
                boid.update()
                boid.edges()

                x[count], y[count] = get_pos(boid.position)
                u[count], v[count] = get_vel(boid.velocity)

                color.append(boid.color)
                radius.append(boid.radius)
                count += 1

            plt.quiver(x, y, u, v, color=color)
            plt.scatter(x, y, c=color, s=radius)
            camera.snap()
            end = time.perf_counter()
            print(len(flock), len(predators), elapsed)
            print(end - start)
            elapsed += 1

        anim = camera.animate()
        anim.save("simulation_{}.mp4".format(value), writer='imagemagick')
 def __init__(self, x, y):
     ball = Prey(x, y, 10, 10, 1, 5)
     ball.randomize_angle()
     ang = ball.get_angle()
     Prey.__init__(self, x, y, 10, 10, ang, 5)
Exemple #14
0
 def __init__(self, x, y):
     aPrey = Prey(x, y, 10, 10, 1, 5)
     aPrey.randomize_angle()
     Prey.__init__(self, x, y, 10, 10, aPrey.get_angle(), 5)
     self._color = 'blue'
Exemple #15
0
def main():
    numberOfRuns = 3
    maximumLengthOfRun = 30000

    initialNumberOfPreys = 400
    initialNumberOfPredators = 10
    initialNumberOfClusters = 30
    gridSize = 512
    clusterSpawnRate = 0.02  # The probability of generating a new cluster for each generation
    clusterDistributionParameter = 40  # A higher value will tend to create the clusters more evenly spread.
    # In the limit that the parameter is 1 the clusters will spawn completely random.
    clusterSizeParameter = 30  # The amount of plants per cluster (SHOULD THIS BE THE UPPER LIMIT OR MEAN?!?!?!?!?!)
    clusterStandardDeviation = 9  # The standard deviation used to generate the plants which make up the cluster.

    # Initializes "graphics"
    plt.ioff()
    plt.show()
    plt.axis([-1, gridSize, -1, gridSize])
    preyPlotHandle = plt.plot([], [], '.', markersize=3,
                              color=(0.2, 0.3, 0.8))[0]
    predatorsPlotHandle = plt.plot([], [],
                                   '.',
                                   markersize=5,
                                   color=(0.9, 0.1, 0.1))[0]
    plantPlotHandle = plt.plot([], [],
                               '.',
                               markersize=2,
                               color=(0.3, 0.9, 0.1))[0]
    clusterPlotHandle = plt.plot([], [],
                                 'o',
                                 markersize=10,
                                 color=(0.3, 0.5, 0.7),
                                 alpha=0.5)[0]

    file = open("run_data", "w")
    file.write("Initial number of preys = %i \n" % initialNumberOfPreys)
    file.write("Initial number of predators = %i \n" %
               initialNumberOfPredators)
    file.write("Initial number of plant clusters = %i \n" %
               initialNumberOfClusters)
    file.write("Grid size = %i \n" % gridSize)
    file.write("cluster spawn rate = %f \n" % clusterSpawnRate)
    file.write("cluster distribution parameter = %i \n" %
               clusterDistributionParameter)
    file.write("cluster size parameter = %i \n" % clusterSizeParameter)
    file.write("cluster standard deviation %f \n" % clusterStandardDeviation)

    for iRun in range(0, numberOfRuns, 1):
        file.write(
            "\n========================================================== \n")
        clusterObjects, plantObjects = plant_module.InitializePlants(
            initialNumberOfClusters, gridSize, clusterDistributionParameter,
            clusterSizeParameter, clusterStandardDeviation)
        clusterObjects[0].setClusterCheckRadius(
            clusterStandardDeviation *
            math.sqrt(-2 * math.log(0.001 * clusterStandardDeviation *
                                    math.sqrt(2 * math.pi))) + 40)

        preys = [
            Prey(gridSize, visibilityRadius=27, reproductionRate=0.1)
            for i in range(initialNumberOfPreys)
        ]
        predators = [
            Predator(gridSize, visibilityRadius=22, reproductionRate=0.2)
            for j in range(initialNumberOfPredators)
        ]
        for prey in preys:
            prey.update_pointers(preys, predators, plantObjects,
                                 clusterObjects)
        for predator in predators:
            predator.update_pointers(preys, predators)

        number_of_preys = []
        number_of_predators = []
        number_of_plants = []
        number_of_preys.append(np.size(preys))
        number_of_predators.append(10 * np.size(predators))
        number_of_plants.append(np.size(plantObjects))
        i = 0
        while preys and predators and i < maximumLengthOfRun:
            i += 1
            clusterObjects, plantObjects = plant_module.PlantGrowth(
                clusterObjects, plantObjects, gridSize, clusterSpawnRate,
                clusterDistributionParameter, clusterSizeParameter,
                clusterStandardDeviation)

            if np.size(clusterObjects) == 1:
                plantObjects[0].UpdatePointers(
                    plantObjects, clusterObjects
                )  # Needed when new plants grow when before there
                for prey in preys:  # were no plants. Without this code the preys
                    prey.update_pointers(
                        preys, predators, plantObjects,
                        clusterObjects)  # seem to lose track of the plants

            for prey in preys:
                prey()
            for predator in predators:
                predator()
            plt.title("Prey = {}, Predators = {}, Iteration = {}".format(
                np.size(preys), np.size(predators), i))

            #if i%100 == 0:
            #    print("i = %i\n# of preys = %i\n# of plants = %i\n# of predators = %i" %(i,np.size(preys),np.size(plantObjects),np.size(predators)))
            #if i%1 == 0:
            #    plt.axis([-1, gridSize, -1, gridSize])
            #    plot(preys, predators, plantObjects, clusterObjects, preyPlotHandle, plantPlotHandle, clusterPlotHandle,
            #         predatorsPlotHandle)
            #    plt.savefig('pictures/pic{:04}.png'.format(i), format='png')
            number_of_preys.append(np.size(preys))
            number_of_predators.append(10 * np.size(predators))
            number_of_plants.append(np.size(plantObjects))

        plt.figure(2 + iRun)
        tmpList = [
            max(number_of_plants),
            max(number_of_preys),
            max(number_of_predators)
        ]
        plt.axis([0, i, 0, max(tmpList)])
        plt.plot(range(0, i + 1), number_of_plants, 'g')
        plt.plot(range(0, i + 1), number_of_preys, 'b')
        plt.plot(range(0, i + 1), number_of_predators, 'r')
        plt.title("iRun = %i" % iRun)
        plt.savefig('pictures/aBlood{:04}.png'.format(iRun), format='png')
        #plt.show()

        # Save to text file here
        file.write("Iterations passed = %i\n" % i)
        file.write("number of preys = %i\n" % np.size(preys))
        file.write("number of predators = %i\n" % np.size(predators))
        file.write("number of plant clusters = %i\n" % np.size(clusterObjects))
        file.write("number of plants = %i\n" % np.size(plantObjects))

        print("Run number %i complete\n" % (iRun + 1))
        print(
            "i = %i\n# of preys = %i\n# of plants = %i\n# of predators = %i" %
            (i, np.size(preys), np.size(plantObjects), np.size(predators)))

        # Awful way of deleting all the plants/clusters between runs
        i = 1
        while i > 0:
            for plant in plantObjects:
                plant.PlantGetsEaten()
            i = np.size(plantObjects)

    file.close()
    print("All runs are done")
Exemple #16
0
def main():
    numberOfRuns = 3
    maximumLengthOfRun = 5000

    initialNumberOfPreys = 400
    initialNumberOfPredators = 10
    initialNumberOfClusters = 5
    gridSize = 300
    clusterSpawnRate = 0.005  # The probability of generating a new cluster for each generation
    clusterDistributionParameter = 20  # A higher value will tend to create the clusters more evenly spread.
    # In the limit that the parameter is 1 the clusters will spawn completely random.
    clusterSizeParameter = 100  # The amount of plants per cluster (SHOULD THIS BE THE UPPER LIMIT OR MEAN?!?!?!?!?!)
    clusterStandardDeviation = 12  # The standard deviation used to generate the plants which make up the cluster.

    file = open("run_data", "w")
    file.write("Initial number of preys = %i \n" % initialNumberOfPreys)
    file.write("Initial number of predators = %i \n" %
               initialNumberOfPredators)
    file.write("Initial number of plant clusters = %i \n" %
               initialNumberOfClusters)

    for iRun in range(0, numberOfRuns, 1):
        file.write(
            "\n========================================================== \n")

        clusterObjects, plantObjects = plant_module.InitializePlants(
            initialNumberOfClusters, gridSize, clusterDistributionParameter,
            clusterSizeParameter, clusterStandardDeviation)
        clusterObjects[0].setClusterCheckRadius(
            clusterStandardDeviation *
            math.sqrt(-2 * math.log(0.001 * clusterStandardDeviation *
                                    math.sqrt(2 * math.pi))) + 40)

        preys = [Prey(gridSize) for i in range(initialNumberOfPreys)]
        predators = [
            Predator(gridSize) for j in range(initialNumberOfPredators)
        ]
        for prey in preys:
            prey.update_pointers(preys, predators, plantObjects,
                                 clusterObjects)
        for predator in predators:
            predator.update_pointers(preys, predators)
        i = 0
        while preys and predators and i < maximumLengthOfRun:
            i += 1
            clusterObjects, plantObjects = plant_module.PlantGrowth(
                clusterObjects, plantObjects, gridSize, clusterSpawnRate,
                clusterDistributionParameter, clusterSizeParameter,
                clusterStandardDeviation)
            if np.size(clusterObjects) == 1:
                plantObjects[0].UpdatePointers(
                    plantObjects, clusterObjects
                )  # Needed when new plants grow when before there
                for prey in preys:  # were no plants. Without this code the preys
                    prey.update_pointers(
                        preys, predators, plantObjects,
                        clusterObjects)  # seem to lose track of the plants

            for prey in preys:
                prey()
            for predator in predators:
                predator()

        # Save to text file here
        file.write("Iterations passed = %i\n" % i)
        file.write("number of preys = %i\n" % np.size(preys))
        file.write("number of predators = %i\n" % np.size(predators))
        file.write("number of plant clusters = %i\n" % np.size(clusterObjects))
        file.write("number of plants = %i\n" % np.size(plantObjects))

        # Awful way of deleting all the plants/clusters between runs
        i = 1
        while i > 0:
            for plant in plantObjects:
                plant.PlantGetsEaten()
            i = np.size(plantObjects)

    file.close()
Exemple #17
0
 def __init__(self, x, y):
     aPrey = Prey(x, y, 10, 10, 1, 5)
     aPrey.randomize_angle()
     Prey.__init__(self, x, y, 10, 10, aPrey.get_angle(),
                   random.randint(3, 7))
     self._color = 'red'