コード例 #1
0
 def cohesion(self, others):
     ''' Returns acceleration towards center of mass of nearby others
     '''
     count = 0
     steerx = 0
     steery = 0
     xavg = 0
     yavg = 0
     for n in range(0, len(others)):
         dist = self.distance(others[n])
         if dist < self.nd and dist > 0.0:
             count = count + 1
             xavg = xavg + others[n].x
             yavg = yavg + others[n].y
     if count > 0:
         xavg = xavg / count
         yavg = yavg / count
         # Create ghost boid representing the others
         ghost = Boid()
         ghost.x = xavg
         ghost.y = yavg
         steerx, steery = self.distanceVector(ghost)
         length = sqrt(steerx**2+steery**2)
         steerx = steerx/length*self.maxforce
         steery = steery/length*self.maxforce
         steerx = steerx - self.vx
         steery = steery - self.vy
     return steerx, steery
コード例 #2
0
 def cohesion(self, others):
     ''' Return acceleration towards center of mass of nearby birds
     '''
     count = 0
     steerx = 0
     steery = 0
     xavg = 0
     yavg = 0
     for n in range(0, len(others)):
         dist = self.distance(others[n])
         sx, sy = self.distanceVector(others[n])
         # Add acceleration for any birds within the cone of vision
         if dist < self.nd and dist > 0.0 and \
               (sx*self.vx+sy*self.vy)/(self.vx**2+self.vy**2) > self.alpha:
             count = count + 1
             xavg = xavg + others[n].x
             yavg = yavg + others[n].y
     if count > 0:
         xavg = xavg / count
         yavg = yavg / count
         # Create ghost boid representing the center of mass of the others
         ghost = Boid()
         ghost.x = xavg
         ghost.y = yavg
         steerx, steery = self.distanceVector(ghost)
         length = sqrt(steerx**2 + steery**2)
         steerx = steerx / length * self.maxforce
         steery = steery / length * self.maxforce
         steerx = steerx - self.vx
         steery = steery - self.vy
     return steerx, steery
コード例 #3
0
ファイル: bird.py プロジェクト: pederka/pythonBoids2D
 def cohesion(self, others):
     ''' Return acceleration towards center of mass of nearby birds
     '''
     count = 0
     steerx = 0
     steery = 0
     xavg = 0
     yavg = 0
     for n in range(0, len(others)):
         dist = self.distance(others[n])
         sx, sy = self.distanceVector(others[n])
         # Add acceleration for any birds within the cone of vision
         if dist < self.nd and dist > 0.0 and \
               (sx*self.vx+sy*self.vy)/(self.vx**2+self.vy**2) > self.alpha:
             count = count + 1
             xavg = xavg + others[n].x
             yavg = yavg + others[n].y
     if count > 0:
         xavg = xavg / count
         yavg = yavg / count
         # Create ghost boid representing the center of mass of the others
         ghost = Boid()
         ghost.x = xavg
         ghost.y = yavg
         steerx, steery = self.distanceVector(ghost)
         length = sqrt(steerx**2+steery**2)
         steerx = steerx/length*self.maxforce
         steery = steery/length*self.maxforce
         steerx = steerx - self.vx
         steery = steery - self.vy
     return steerx, steery
コード例 #4
0
    def __init__(self, x, y, width, height):
        Boid.__init__(self, x, y, width, height)

        self.max_force_coe = 3
        self.max_speed = 15

        self.velocity = (np.random.rand(2) - 0.5) * self.max_speed

        self.perception = 30
        self.radius = 5
        self.color = 'r'
        self.eat_counter = 0
コード例 #5
0
def initSimulation():
    State['iter'] = 0

    for i in range(INI_FLORA):
        Flora(canvas)

    for i in range(INI_BOIDS):
        Boid(canvas)

    for i in range(INI_PREDS):
        Predator(canvas)

    Boid.setPredatorGrid(Predator.grid)
コード例 #6
0
ファイル: flock.py プロジェクト: micnil/maya-flocking-boids
def createBoids(numBoids):
	'''create numboids boids and randomize position'''
	boundaryPos = boundary.getPosition()
	boundaryDim = boundary.getSpawnDimensions()
	for i in range(numBoids):
		b = Boid("boid{0}".format(i))
		x = random.uniform(boundaryPos[0]-boundaryDim[0]/2, boundaryPos[0]+boundaryDim[0]/2)
		y = random.uniform(boundaryPos[1]-boundaryDim[1]/2, boundaryPos[1]+boundaryDim[1]/2)
		z = random.uniform(boundaryPos[2]-boundaryDim[2]/2, boundaryPos[2]+boundaryDim[2]/2)
		b.setPosition(x, y, z)
		boids.append(b)

	print 'creating boids done'
コード例 #7
0
    def __init__(self, x, y, width, height):
        Boid.__init__(self, x, y, width, height)

        self.max_force_coe = 0.7
        self.max_force_sep = 1
        self.max_force_esc = 10

        self.max_speed = 7
        self.perception = 50

        self.velocity = (np.random.rand(2) - 0.5)*self.max_speed
        
        self.radius = 2
        self.color = 'b'
コード例 #8
0
    def insertBoid(self, pos=None):

        vel = m.Vector2(random.uniform(-10, 10), random.uniform(-10, 10))
        if pos is not None:
            if type(pos) == tuple:
                boid = Boid(m.Vector2(pos[0], pos[1]), vel)
            elif type(pos) == m.Vector2:
                boid = Boid(pos, vel)
        else:
            x, y = pygame.display.get_surface().get_size()
            x = random.randint(0, x)
            y = random.randint(0, y)
            boid = Boid(m.Vector2(x, y), vel)
        self.flock.append(boid)
        return
コード例 #9
0
def create_enemy_boid(width, height):
    return Boid(
        position=[random.uniform(0, width), random.uniform(0, height)],
        bounds=[width, height],
        velocity=[random.uniform(-50.0, 50.0), random.uniform(-50.0, 50.0)],
        color=[1, 0, 0],
        enemy = True)
コード例 #10
0
def create_random_boid(width, height):
    return Boid(
        position=[random.uniform(0, width), random.uniform(0, height)],
        bounds=[width, height],
        velocity=[random.uniform(-50.0, 50.0), random.uniform(-50.0, 50.0)],
        #color=[random.random(), random.random(), random.random()
        color=[0,1,0])
コード例 #11
0
ファイル: prey.py プロジェクト: mcapassox/SMS
    def __init__(self, x, y, width, height):
        Boid.__init__(self, x, y, width, height)

        self.max_force_coe = 0.7
        self.max_force_sep = 1
        self.max_force_esc = 15

        self.max_speed = 5
        self.perception = 50

        self.radius = 2
        self.lastproc = 0
        self.birthdate = 0
        self.color = 'b'

        self.velocity = (np.random.rand(2) - 0.5)*10
コード例 #12
0
ファイル: main.py プロジェクト: TimTen10/Boids
def main():
    # Initialise the screen
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    screen.fill((255, 255, 255))
    pygame.display.set_caption("Flocking Simulation")

    # Create some Boids
    flock = [Boid(
        random.randint(10, WIDTH - 10), random.randint(10, HEIGHT - 10),
        [random.randint(-5, 5), random.randint(-5, 5)]
    ) for _ in range(100)]

    # Create one "ill" bird
    flock[-1].color = 'green'

    for bird in flock:
        pygame.draw.circle(screen, pygame.Color(bird.color), (bird.x, bird.y), 3)

    # Event (Main) loop
    while True:
        pygame.time.delay(25)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return

        # This line resets the screen after every step; delete to show trails
        screen.fill((255, 255, 255))

        for bird in flock:
            # equals "show"
            pygame.draw.circle(screen, pygame.Color(bird.color), (bird.x, bird.y), 3)

            # "Ill"; if-statement needs readability update
            if any(bird.x - 10 < b.x < bird.x + 10 and bird.y - 10 < b.y < bird.y + 10 and b.color == 'green'
                   for b in flock if b != bird):
                if random.randint(1, 10) == 10:
                    bird.color = 'green'

            bird.update()

            if bird.ill_since > 500:
                flock.remove(bird)

            if bird.x < 0:
                bird.x = WIDTH
            elif bird.x > WIDTH:
                bird.x = 0
            if bird.y < 0:
                bird.y = HEIGHT
            elif bird.y > HEIGHT:
                bird.y = 0

        pygame.display.update()

        FPS_CLOCK.tick(FPS)
コード例 #13
0
 def __init__(self, size, numBoids):
     self.boidList = []
     for i in range(numBoids):
         pos = Vector(
             size[0] * 0.5 + (random.random() - 0.5) * size[0] * 0.5,
             size[1] * 0.5 + (random.random() - 0.5) * size[1] * 0.5)
         vel = Vector(random.random() - 0.5, random.random() - 0.5) * 2
         self.boidList.append(Boid(pos, vel, i))
コード例 #14
0
def random_flock(size: int) -> FLOCK:
    flock: FLOCK = []
    rng = random.Random()
    for i in range(size):
        x_pos = rng.randrange(100, 900)
        y_pos = rng.randrange(100, 900)
        rot = (rng.random() - 0.5) * 3.14
        flock.append(Boid(5, 100, x_pos, y_pos, rot))
    return flock
コード例 #15
0
 def create_starting_flock(self):
     for i in range(10):
         location = pygame.Vector2(random.randint(275, 485),
                                   random.randint(840, 925))
         velocity = pygame.Vector2(0, 0)
         velocity.from_polar((10, random.randint(220, 320)))
         sex = {0: BoidSex.FEMALE, 1: BoidSex.MALE}[i % 2]
         self.flock.boids.append(
             Boid(self.flock, location, velocity, sex,
                  Settings.boid_adult_age))
         self.flock.leader = random.choice(self.flock.boids)
コード例 #16
0
ファイル: main.py プロジェクト: rounsifer/Artificial-Life
    def add_boid(self, x, y):
        """Add a boid

        Adds a boid at the position of the click
        """
        x_vel = random.randrange(-1, 1)
        y_vel = random.randrange(-1, 1)
        x_pos = x
        y_pos = y
        boid = Boid(x_vel, y_vel, x_pos, y_pos)
        self.flock.append(boid)
コード例 #17
0
ファイル: Catzerk.py プロジェクト: jchea95/CatZerk
def setup():
    global spriteList
    global flatLand
    global winSize

    global time
    global score
    score = 0
    global gameFont
    global startFont

    gameFont = createFont("Arial", 16, True)
    startFont = createFont("Arial", 40, True)

    global playerLoc
    global player
    global healthAmt

    healthAmt = 100

    global tileMap
    global playerRow
    global playerCol

    global startScreen

    #### ------------- Julie: Creating Start Screen ------------- ####
    startScreen = loadImage("catzerk_start.png")
    image(startScreen, 0, 0, width, height)

    player = Player(width / 3, height / 3, "Right0000.png")
    playerLoc = player.getLocation()
    projectile = player.projectile
    # Add an initial set of boids into the system
    for i in range(8):
        flock.addBoid(Boid(width / 2, height / 2))

    winSize = 500

    ####------------- Julie: Creating Map -------------  ####

    spriteList = []

    size(MAP_SIZE_PIXELS, MAP_SIZE_PIXELS)

    # these need to be loaded into sketch, just go back in here and look into list like spriteNames[i] w loop
    # Tile values -    0              1
    spriteNames = ["floor.png", "treeTile.png", "Right0000.png"]

    for name in spriteNames:
        img = loadImage(name)
        spriteList.append(img)

    flatLand = Map("zombTile.txt")
コード例 #18
0
ファイル: window.py プロジェクト: XDA-7/boids
 def reflected_velocity(self, delta_time: float,
                        boid: Boid) -> Tuple[float, float]:
     """Returns the x and y movements, if these would take the boid outside of the window
     boundary then (0, 0) is returned and the velocity is reflected"""
     x_velocity = boid.x_velocity
     y_velocity = boid.y_velocity
     delta_x = x_velocity * delta_time
     delta_y = y_velocity * delta_time
     if self.on_border(boid, delta_x, delta_y):
         if self.on_vertical_border(boid, delta_y):
             x_velocity = -x_velocity
         if self.on_horizontal_border(boid, delta_x):
             y_velocity = -y_velocity
         rotation = Vector(x_velocity,
                           y_velocity).rotation_normalized() * 3.14
         if x_velocity < 0:
             boid.rotation = rotation
         else:
             boid.rotation = -rotation
         return (0, 0)
     else:
         return (delta_x, delta_y)
コード例 #19
0
 def make_agents(self):
     """
     Create self.population agents, with random positions and starting headings.
     """
     for i in range(self.population):
         x = self.random.random() * self.space.x_max
         y = self.random.random() * self.space.y_max
         pos = np.array((x, y))
         velocity = np.random.random(2) * 2 - 1
         boid = Boid(i, self, pos, self.speed, velocity, self.vision,
                     self.separation, **self.factors)
         self.space.place_agent(boid, pos)
         self.schedule.add(boid)
コード例 #20
0
ファイル: main.py プロジェクト: rounsifer/Artificial-Life
    def create_flock(self):

        w, h = pygame.display.get_surface().get_size()

        # create the flock
        num_boids = 3
        self.flock = [None] * num_boids
        for i in range(num_boids):
            x_vel = random.randrange(-1, 1)
            y_vel = random.randrange(-1, 1)
            x_pos = int(random.random() * w)
            y_pos = int(random.random() * h)
            self.flock[i] = Boid(x_vel, y_vel, x_pos, y_pos)
コード例 #21
0
def main():
    numBoids = 30
    boids = []
    gui, canvas, canvasSize = createCanvas()
    boidSize = canvasSize // 100

    for i in range(numBoids):
        accx, accy = random.randint(-40, 40), random.randint(-40, 40)
        # accx, accy = random.randint(-40, 40), random.randint(-40, 40)
        boids.append(
            Boid(
                i, [accx, accy],
                [random.randint(0, canvasSize),
                 random.randint(0, canvasSize)], canvasSize))

    ovals = drawBoids(canvas, boids, canvasSize, boidSize)
    windArrow = None
    windSpeed = 0

    windArrowOptions = {'width': 5, 'arrowshape': (25, 30, 13)}
    iterations = 700
    try:
        for i in range(iterations):
            if i > iterations / 2:  # start wind halfway through simulation
                windSpeed = sin(i / 30) * 4  # sin(i / 40) * 2]
                if windArrow is not None:
                    canvas.delete(windArrow)
                canvas.create_text(canvasSize / 2,
                                   70,
                                   fill="black",
                                   font="Times 20 italic bold",
                                   text="WIND")
                windArrow = createWindArrow(canvas, windSpeed, canvasSize / 2,
                                            40, windArrowOptions)

            for boid in boids:
                boid.update_position(boids, windSpeed)
                # canvas.move(ovals[boid.id],boid.velocity[0],boid.velocity[1])
                moveTo(canvas, ovals[boid.id], boid.position[0],
                       boid.position[1])
            time.sleep(.05)
            gui.update()
    except KeyboardInterrupt:  # close canvas in case of program quit
        gui.destroy()
    gui.title("Boid Simulation")
    gui.destroy()
    gui.mainloop()
コード例 #22
0
ファイル: flocking.py プロジェクト: DanielDondorp/flocking
    def __init__(self):
        self.display_width = 800
        self.display_height = 600

        self.display = pygame.display.set_mode(
            (self.display_width, self.display_height))
        pygame.display.set_caption("Simulation")
        self.clock = pygame.time.Clock()
        self.running = True

        self.boids = [
            Boid(display_width=self.display_width,
                 display_height=self.display_height) for x in range(100)
        ]
        self.pboids = [
            Pboid(display_width=self.display_width,
                  display_height=self.display_height) for x in range(4)
        ]
コード例 #23
0
 def init_random_boids(self, num_boids, boid_size=0):
     self.num_boids += num_boids
     positions_list = []
     while len(positions_list)<num_boids:
         position = (random.uniform(0, self.range[0]), random.uniform(0, self.range[1]))
         flag = True
         for obstacle in self.obstacles:
             if obstacle.x[0] < position[0] < obstacle.x[1] and obstacle.y[0] < position[1] < obstacle.y[1]:
                 flag=False
                 break
         if flag:
             positions_list.append(position)
     self.boids += [Boid(
         position=positions_list[key],
         velocity=(random.uniform(-Boid.max_velocity, Boid.max_velocity),
                   random.uniform(-Boid.max_velocity, Boid.max_velocity)),
         color=(random.random(), random.random(), random.random()), size = boid_size)
                 for key,_ in enumerate(range(self.num_boids))]
コード例 #24
0
ファイル: simulation.py プロジェクト: mihneadb/optboid
    def __init__(self, starting_units=100, field_size=800, leaders=0):
        """
        """
        self.swarm = BoidSwarm(field_size+2*40, Boid.influence_range+5)  # /2
        self.field_size = field_size
        self.pad = 40  # use to keep boids inside the play field

        for _ in range(starting_units):
            b = Boid(random.uniform(100, 400),
                     random.uniform(100, 400))
            self.swarm.boids.append(b)

        for _ in range(leaders):
            leader = Leader(random.uniform(100, 400),
                            random.uniform(100, 400))
            self.swarm.boids.append(leader)

        self.swarm.rebuild()
        self._cumltime = 0  # calculation var
コード例 #25
0
    def make_agents(self):
        '''
        Create self.population agents, with random positions and starting headings.
        '''
        for i in range(50):
            x = random.random() * self.space.x_max
            y = random.random() * self.space.y_max
            center_x = self.space.x_max / 2
            center_y = self.space.y_max / 2
            pos = np.array((x, y))
            center = np.array((center_x, center_y))
            velocity = np.random.random(2) * 2 - 1
            velocity = np.zeros(2) + self.space.get_distance(pos, center)
            velocity[0] *= self.target[0]
            velocity[1] *= self.target[1]
            boid = Boid(i, self, pos, self.speed, velocity, self.vision,
                        self.separation, self.collision_separation, "boid.png",
                        10, **self.factors)
            self.space.place_agent(boid, pos)
            self.schedule.add(boid)

        for i in range(4):
            x = random.random() * self.space.x_max
            y = random.random() * self.space.y_max
            pos = np.array((x, y))
            obstacle = Obstacle(i + self.population, self, pos, 30)
            obstacle2 = Obstacle(i + self.population + 5, self, pos, 4)
            self.space.place_agent(obstacle, pos)
            self.space.place_agent(obstacle2, pos)
            self.schedule.add(obstacle)
            self.schedule.add(obstacle2)
        if self.predators:
            x = random.random() * self.space.x_max
            y = random.random() * self.space.y_max
            pos = np.array((x, y))
            velocity = np.random.random(2) * 2 - 1
            predator = Predator(2003, self, pos, self.speed + 0.1, velocity,
                                self.vision + 5, 12, self.collision_separation,
                                "predator.png")
            self.space.place_agent(predator, pos)
            self.schedule.add(predator)
コード例 #26
0
from p5 import setup, draw, size, background, run
import numpy as np
from boid import Boid

width = 1000
heigth = 1000

flock = [Boid(*np.random.rand(2) * 1000, width, heigth) for _ in range(20)]


def setup():
    #once call at RUN
    #set-up: canvas size
    size(width, heigth)


def draw():
    #everytime call event
    background(30, 30, 47)

    for boid in flock:
        boid.show()
        boid.behavir_commit(flock)
        boid.update()
        boid.edges()


#p5 calling: setup(),d draw() ...
run()
コード例 #27
0
ファイル: gui_boid.py プロジェクト: vukk/ope2-boids
 def __init__(self, position=None, velocity=None, orientation=None):
     """ Initialize the GuiBoid graphical representation of the Boid. """
     QtGui.QGraphicsItem.__init__(self)
     Boid.__init__(self, position, velocity, orientation)
     self.color = self.randomColor()
     self.updateOnGui()
コード例 #28
0
ファイル: gui_boid.py プロジェクト: vukk/ope2-boids
 def step(self):
     """ Wraps Boid.step() so the GUI is updated after it. """
     Boid.step(self)
     self.updateOnGui()
コード例 #29
0
import random
import sys

pg.init()
window = pg.display.set_mode((500, 500), SRCALPHA | HWSURFACE)
clock = pg.time.Clock()

# load the target image
target = pg.image.load('images/target.png').convert_alpha()
target_pos = (250, 250)

BOID_NUMBER = 20
boids = []
for i in range(BOID_NUMBER):
    boid = Boid(color=random.choice(['red', 'blue', 'green', 'purple']))
    boid.pos = (random.randint(0, 500), random.randint(0, 500))
    boid.max_speed = random.randint(100, 200)
    boid.seek_target = target_pos
    boid.seek_on()

    boids.append(boid)

frame = 0
while True:
    window.fill(pg.Color('white'))

    for event in pg.event.get():
        if event.type == MOUSEBUTTONUP:
            target_pos = event.pos
            for b in boids:
コード例 #30
0
 def __init__(self, num_boids):
     self.boids = [Boid() for boid in range(num_boids)]
     self.num_boids = num_boids
コード例 #31
0
                  screen_objects, 
                  noise_factor = noise, 
                  always_limit_speed = always_limit_speed, 
                  jitter_factor = jitter)
        boid.draw(screen)

boids = []
for _ in range(num_boids):
    loc = [int(window_size[0] * np.random.random()),
           int(window_size[1] * np.random.random())]
    loc[1] = min(max(300, loc[1]), 860)
    boids += [Boid(loc, 
                   params['max_speed'],
                   params['influence'], 
                   params['min_dist'], 
                   params['obj_margin'],
                   window_size,
                   params['cohesion_factor'],
                   params['separation_factor'], 
                   params['align_factor'])]
    if params['jitter'] > 0:
        boids[-1].__jitter__(np.pi/(4 * params['jitter']))
    
circles = []
for i in range(0, 48):
    circles += [Circle(20, np.array([40*i, 100]), [255, 0, 0]), 
                Circle(20, np.array([40*i, 900]), [255, 0, 0])]

clickables = main_clickables

while True: 
コード例 #32
0
def main():
    pg.init()
    pg.display.set_caption("Swarm")
    # CONFIG
    width = 1200
    height = 700

    clock = pg.time.Clock()
    num_boids = 10

    screen = pg.display.set_mode((width, height))
    background = pg.Surface(screen.get_size()).convert()
    background.fill(pg.Color('black'))
    running = True
    #pg.event.set_allowed([pg.QUIT, pg.KEYDOWN, pg.KEYUP])

    all_sprites = pg.sprite.RenderUpdates()
    obs_sprites = pg.sprite.RenderUpdates()

    boids = [Boid(i) for i in range(num_boids)]
    obs = []
    globalvariables.target.append(Targetpoint((width - 50, height - 50)))
    '''obstacles'''

    for i in range(0, int(height / 4), 5):
        obs.append(Obstacle([0, i]))
    for i in range(int(3 * height / 4), height, 5):
        obs.append(Obstacle([width, i]))
    for i in range(0, int(width / 4), 5):
        obs.append(Obstacle([i, 0]))
    for i in range(int(3 * width / 4), width, 5):
        obs.append(Obstacle([i, height]))

    if len(sys.argv) > 1:
        for i in [
                int(1.5 * height / 4),
                int(1.70 * height / 4),
                int(2.30 * height / 4),
                int(2.5 * height / 4)
        ]:
            # a = i
            for j in range(int(1.5 * width / 4), int(2.5 * width / 4), 5):
                # a-=1
                obs.append(Obstacle([j, i]))
        for i in [
                int(1.5 * width / 4),
                int(1.5 * width / 4 + 2),
                int(2.5 * width / 4),
                int(2.5 * width / 4 + 2)
        ]:
            for j in range(int(1.5 * height / 4), int(1.70 * height / 4), 5):
                obs.append(Obstacle([i, j]))
            for j in range(int(2.30 * height / 4), int(2.5 * height / 4), 5):
                obs.append(Obstacle([i, j]))

    for boid in boids:
        all_sprites.add(boid)
    for ob in obs:
        obs_sprites.add(ob)
    ###################################################################################
    fail_count = 0
    frame_count = 0
    averdist = 0
    filewriter = open('scenario3_no_ob.csv', 'a')
    if len(sys.argv) > 1:
        filewriter.close()
        filewriter = open('scenario3.csv', 'a')
        vel_breakdown_filewriter = open('scenario3_breakdown.csv', 'a')
    b0 = boids[2]  # for logging
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
                pos = pg.mouse.get_pos()
                globalvariables.point = pg.math.Vector2(pos[0], pos[1])
                globalvariables.target.append(Targetpoint(pos))
                globalvariables.click = 1
            if pg.mouse.get_pressed()[2]:
                pos = pg.mouse.get_pos()
                obs.append(Obstacle(pos))
                obs_sprites.add(Obstacle(pos))
            if event.type == pg.KEYDOWN and event.key == pg.K_UP:
                boids.append(Boid(0))
                all_sprites.add(boids[len(boids) - 1])
            if event.type == pg.KEYDOWN and event.key == pg.K_DOWN:
                boid = boids.pop(len(boids) - 1)
                all_sprites.remove(boid)
        #############################################################

        for b in boids:
            if b.checktarget() == True:
                boids.remove(b)
                all_sprites.remove(b)
            elif b.checkcolision_ob(obs) == True:
                boids.remove(b)
                all_sprites.remove(b)
                fail_count += 1
            elif frame_count >= 50 and b.checkcolision_neigh(boids) == True:
                boids.remove(b)
                all_sprites.remove(b)
                fail_count += 1
                for b1 in boids:
                    if b1.checkcolision_neigh([b]) == True:
                        boids.remove(b1)
                        all_sprites.remove(b1)
                        fail_count += 1
            else:
                stat = b.update(boids, obs)
                if b0.id == b.id:
                    if len(sys.argv) > 1:
                        vel_breakdown_filewriter.write(
                            '%f,%f,%f,%f,%f\n' %
                            (stat[0], stat[1], stat[2], stat[3], stat[4]))
        averdist += averagedistance.AverageDistancePerFrame(boids)
        if len(boids) == 0:
            print("average distance: " + str(averdist / frame_count))
            filewriter.write('%f,%d\n' %
                             ((averdist / frame_count), fail_count))
            fail_count = 0
            frame_count = 0
            averdist = 0
            # time.sleep(3)
            boids = [Boid(i) for i in range(num_boids)]
            for boid in boids:
                all_sprites.add(boid)

        # for b in boids:
        #     if b.checktarget() == True:
        #         boids.remove(b)
        #         all_sprites.remove(b)
        #     else:
        #         b.update(boids,obs)
        # averdist += averagedistance.AverageDistancePerFrame(boids)
        # if len(boids) == 0:
        #     print("average distance: "+str(averdist/frame_count))
        #     filewriter.write('%f\n'%(averdist/frame_count))
        #     frame_count = 0
        #     averdist = 0
        #     boids = [Boid(0) for i in range(num_boids)]
        #     for boid in boids:
        #         all_sprites.add(boid)

        globalvariables.target_sprites = pg.sprite.RenderUpdates(
            globalvariables.target)
        all_sprites.clear(screen, background)
        all_sprites.update(boids, obs)
        # if frame_count % 10 ==0:
        dirty = all_sprites.draw(screen)
        pg.display.update(dirty)
        dirty1 = obs_sprites.draw(screen)
        pg.display.update(dirty1)
        globalvariables.target_sprites.clear(screen, background)
        dirty2 = globalvariables.target_sprites.draw(screen)
        pg.display.update(dirty2)
        frame_count += 1
コード例 #33
0
ファイル: steering.py プロジェクト: alex-berman/tforms
 def __init__(self, args):
     Visualizer.__init__(self, args)
     self.boids = []
     boid = Boid(PVector(10, 10), 3.0, 3.0)
     boid.arrive(PVector(400, 200))
     self.boids.append(boid)
コード例 #34
0
def main():
    pg.init()
    pg.display.set_caption("Swarm")
    # CONFIG
    width = 1200
    height = 700

    clock = pg.time.Clock()
    num_boids = 10

    screen = pg.display.set_mode((width, height))
    background = pg.Surface(screen.get_size()).convert()
    background.fill((0, 0, 0))
    running = True
    #pg.event.set_allowed([pg.QUIT, pg.KEYDOWN, pg.KEYUP])

    all_sprites = pg.sprite.RenderUpdates()
    obs_sprites = pg.sprite.RenderUpdates()

    boids = [Boid(0) for i in range(num_boids)]
    obs = []
    globalvariables.target.append(Targetpoint((width - 50, height - 50)))
    '''obstacles'''

    # for i in range(0, int(height/4),10):
    #     for j in[0]:
    #         obs.append(Obstacle([j,i]))
    # for i in range(0, int(width/4),10):
    #     for j in[0]:
    #         obs.append(Obstacle([i,j]))

    for i in range(0, height, 10):
        for j in [0, width]:
            obs.append(Obstacle([j, i]))
    for i in range(0, width, 10):
        for j in [0, height]:
            obs.append(Obstacle([i, j]))

    for i in [
            int(1.5 * height / 4),
            int(1.75 * height / 4),
            int(2.25 * height / 4),
            int(2.5 * height / 4)
    ]:
        for j in range(int(1.5 * width / 4), int(2.5 * width / 4), 5):
            obs.append(Obstacle([j, i]))
    for i in [int(1.5 * width / 4), int(2.5 * width / 4)]:
        for j in range(int(1.5 * height / 4), int(1.75 * height / 4), 5):
            obs.append(Obstacle([i, j]))
        for j in range(int(2.25 * height / 4), int(2.5 * height / 4), 5):
            obs.append(Obstacle([i, j]))

    # for i in [int(1.5*height/4),int(2.5*height/4)]:
    #     for j in range(int(1.5*width/4),int(2.5*width/4),10):
    #         obs.append(Obstacle([j,i]))
    # for j in range(int(2.5*width/4),int(3*width/4),10):
    #     obs.append(Obstacle([j,i]))

    # for i in [int(0.5*width/4),int(1*width/4),int(1.75*width/4),int(2.25*width/4),int(3*width/4),int(3.5*width/4)]:
    #     for j in range(int(0.5*height/4),int(1.5*height/4),10):
    #         obs.append(Obstacle([i,j]))
    #     for j in range(int(2.5*height/4),int(3.5*height/4),10):
    #         obs.append(Obstacle([i,j]))

    for boid in boids:
        all_sprites.add(boid)
    for ob in obs:
        obs_sprites.add(ob)
    ###################################################################################

    frame_count = 0
    averdist = 0
    filewriter = open('scenario1.csv', 'a')
    while running:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
            if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
                pos = pg.mouse.get_pos()
                globalvariables.point = pg.math.Vector2(pos[0], pos[1])
                globalvariables.target.append(Targetpoint(pos))
                globalvariables.click = 1
            if pg.mouse.get_pressed()[2]:
                pos = pg.mouse.get_pos()
                obs.append(Obstacle(pos))
                obs_sprites.add(Obstacle(pos))
            if event.type == pg.KEYDOWN and event.key == pg.K_UP:
                boids.append(Boid(0))
                all_sprites.add(boids[len(boids) - 1])
            if event.type == pg.KEYDOWN and event.key == pg.K_DOWN:
                boid = boids.pop(len(boids) - 1)
                all_sprites.remove(boid)
        # for b in boids:
        #     b.update(boids,obs)
        for b in boids:
            if b.checktarget(obs) == True:
                boids.remove(b)
                all_sprites.remove(b)
            else:
                b.update(boids, obs)
        averdist += averagedistance.AverageDistancePerFrame(boids)
        if len(boids) == 0:
            print("average distance: " + str(averdist / frame_count))
            filewriter.write('%f\n' % (averdist / frame_count))
            frame_count = 0
            averdist = 0
            boids = [Boid(0) for i in range(num_boids)]
            for boid in boids:
                all_sprites.add(boid)

        globalvariables.target_sprites = pg.sprite.RenderUpdates(
            globalvariables.target)
        all_sprites.clear(screen, background)
        all_sprites.update(boids, obs)
        dirty = all_sprites.draw(screen)
        pg.display.update(dirty)
        dirty1 = obs_sprites.draw(screen)
        pg.display.update(dirty1)
        globalvariables.target_sprites.clear(screen, background)
        dirty2 = globalvariables.target_sprites.draw(screen)
        pg.display.update(dirty2)
        frame_count += 1
        clock.tick(120)
コード例 #35
0
 def add_boid(self, position=(100.0, 100.0),
              velocity=(0.0, 0.0),
              size=0,
              color=(1.0, 1.0, 1.0)):
     self.boids.append(Boid(position,velocity,size,color))
     self.num_boids += 1