def setup(): global myflock size(600, 600) #myboid = Boid(400,400) myflock = Flock() for i in range(2): myflock.addBoid(Boid(width / 2, height / 2))
class Controller: def __init__(self): #self.flock = Flock() self.flockb = Flock() def draw(self): background(230, 230, 230) #self.flock.draw() self.flockb.draw()
def spawnEnemy(position, angle, behavior, formation, image, aimage, target): enemygroup = Flock(1.2, formation) anchor = Anchor(position, aimage, behavior, target) for slot in formation: p = position + slot.spatialOffset.rotate(angle) a = angle + slot.angularOffset w = slot.weapon b = Boid(position=p, aim=a, image=image, weap=w) enemygroup.addSquad(b) enemygroup.addAnchor(anchor) return enemygroup
def process(): parser = ArgumentParser(description = \ "Simulate the motion of a flock of birds") # Parameters parser.add_argument('--file', '-f', dest = 'configFile') # Print help message even if no flag is provided if len(sys.argv) == 1: parser.print_help() sys.exit(1) args = parser.parse_args() # Catch exception if file does not exist try: # Create object boids = Flock(args.configFile) # Plot figures animator = FlockAnimator((-500,1500), (-500,1500), "The Boids!", boids) animator.animate_flock() except IOError: print "The file you provided does not exist.\n" parser.print_help() except: print "Unexpected error.", sys.exc_info()[0], "\n" raise
def __init__(self, perimeter_points, num_boids=30): self.perimeter = Perimeter(perimeter_points) self.minx, self.miny, self.maxx, self.maxy = self.perimeter.get_bounds() self.num_boids = num_boids self.flock = Flock(num_boids, self.perimeter) self.static_obstacles = [] self.dynamic_obstacles = [] self.goals = [] self.agents = [] self.set_static_obstacles()
def __init__(self, game): self.game = game self.canvas = game.canvas self.background = pygame.image.load( os.path.join('images', self.name.lower(), 'background.png')) self.console_image = pygame.image.load( os.path.join('images', self.name.lower(), 'console.png')) self.attractors = [] self.flock = None self.flock = Flock(self) self.has_visited = False self._level_complete = False if self.exit_gate_position: self.attractors.append( Attractor(self.exit_gate_position, 500, Settings.gate_radius * 2)) # 'Attractors': AttractorsRule(self, 1, [Attractor((300, 300), 50)]), self.flowers = [] self.init_level()
class World(object): """ contains flock, perimeter and obstacles. doesn't have ros stuff other serialization to messages. """ def __init__(self, perimeter_points, num_boids=30): self.perimeter = Perimeter(perimeter_points) self.minx, self.miny, self.maxx, self.maxy = self.perimeter.get_bounds() self.num_boids = num_boids self.flock = Flock(num_boids, self.perimeter) self.static_obstacles = [] self.dynamic_obstacles = [] self.goals = [] self.agents = [] self.set_static_obstacles() def update(self): for agent in self.agents: agent.update() self.flock.update(self.static_obstacles + self.dynamic_obstacles, self.goals, self.agents) def set_dynamic_obstacles(self, polygon_perimeters): self.dynamic_obstacles = [Obstacle(p) for p in polygon_perimeters] def set_static_obstacles(self): corners = [[self.minx, self.miny], [self.minx, self.maxy], [self.maxx, self.maxy], [self.maxx, self.miny]] self.static_obstacles = [obstacle_from_point(c) for c in corners] world_barrier_points = [[-65, 190], [55, 190], [55, 210], [-65, 230]] world_barrier = Obstacle(world_barrier_points) self.static_obstacles.append(world_barrier) def set_goals(self, xys): self.goals = [Goal(*xy) for xy in xys]
def __init__(self, screen): """ your app starts here""" State.__init__(self, screen) #create game objects self.playerFlock = Flock(1.2) #sprite groups must be added to the screen to be drawn image = loadsurface("small2.png") pimage = loadsurface("anchor.png") #game object list creation and registration self.allyList = [] self.enemyList = [] self.screen.add(self.allyList) self.screen.add(self.enemyList) #player stuff self.register(self.allyList, self.playerFlock) p = Anchor(Vector2D(0,0),pimage) for i in range(9): b = Boid(Vector2D(0,0),image, weap=machinegun()) self.playerFlock.addSquad(b) self.playerFlock.addAnchor(p) #create an enemy enemy = spawnEnemy(Vector2D(100,100), 0, defaultBehavior, enemyformation(), image, pimage, p) self.register(self.enemyList, enemy)
from flock import Flock f = Flock(100,100,100) f.draw() f.draw() f.draw() f.draw()
from flock import Flock import numpy as np import argparse as argparse; parser = argparse.ArgumentParser(prog="python main.py", description = "Main.py handles everything. Use python main.py -h to see your options."); parser.add_argument('-m', '--mode', help='Set the simulation mode.', default = 3, action='store', type = int); starlings = Flock() args = parser.parse_args(); flocksim = args.mode if flocksim == 0: starlings.mode = 1 starlings.number = 40 starlings.tau = 0.1 starlings.eta = 0.25 starlings.speed = 25.0 starlings.boxSize = 100.0 starlings.habitatSize = 200.00 starlings.habitatStrength = 20.0 starlings.initBoids() starlings.velocities = np.ones((starlings.number,3), dtype=np.float) starlings.positions[ int(starlings.number/2):,:] += 0.8 * starlings.habitatSize / (2.0**0.5) starlings.sensitivities *= 30.00 starlings.display = 1 starlings.length = 10.0
from agent import Agent from flock import Flock culture = Flock(num_agents = 5, run_time = 100000, show_every = 10) culture.run()
def main(): pygame.init() display = pygame.display.set_mode((600, 600)) random.seed(time.time()) flock = Flock(60) clock = pygame.time.Clock() useTree = True showTree = True useCohesion = True useSeperation = True useAlignment = True instructions = """ Click Mouse to add Boid. Press 1 to toggle use Quad-tree. Press 2 to toggle show Quad-tree. Press 3 to toggle Cohesion between Boids. Press 4 to toggle Seperation between Boids. Press 5 to toggle Alignment between Boids. """ print(instructions) while True: #limit to 30 fps clock.tick(30) fps = clock.get_fps() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: flock.insertBoid((pygame.mouse.get_pos())) if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: #toggle using Quadtree useTree = not useTree if event.key == pygame.K_2: #toggle showing tree showTree = not showTree if event.key == pygame.K_3: #toggle Cohesion useCohesion = not useCohesion if event.key == pygame.K_4: #toggle Seperation useSeperation = not useSeperation if event.key == pygame.K_5: #toggle Alignment useAlignment = not useAlignment if event.key == pygame.K_BACKSPACE: flock.removeBoid() flockLen = len(flock.flock) pygame.display.set_caption( "Boids Simulation - Boids: {0} - FPS: {1}".format( flockLen, int(fps))) #very basic menu, will implement buttons later. states = '\r # of Boids: {0},' \ ' Use Qtree: {1},' \ ' Show Qtree: {2},' \ ' Cohesion: {3},' \ ' Seperation: {4},' \ ' Alignment: {5} '.\ format(flockLen, useTree, showTree, useCohesion, useSeperation, useAlignment) print(states, end="") display.fill((10, 10, 60)) flock.draw(useTree, showTree, useCohesion, useSeperation, useAlignment) pygame.display.flip()
type=int) parser.add_argument('-s', '--snapshots', help='Set the number of frames for the video', default=1200, action='store', type=int) parser.add_argument('-f', '--filename', help='Set the simulation mode.', default="default", action='store') starlings = Flock() args = parser.parse_args() flocksim = args.mode filename = args.filename + ".mp4" snapshots = args.snapshots #number of frames if flocksim == 0: starlings.mode = 1 starlings.number = 40 starlings.tau = 0.1 starlings.eta = 0.25 starlings.speed = 25.0 starlings.boxSize = 100.0 starlings.habitatSize = 200.00 starlings.habitatStrength = 20.0
def lock(self): try: return Flock(os.open(self.get_repo_dir(), 0), LOCK_EX) except FileNotFoundError: os.makedirs(self.get_repo_dir()) return Flock(os.open(self.get_repo_dir(), 0), LOCK_EX)
### most recent from boid import Boid from flock import Flock from player import Player from tileMap import Map flock = Flock() #### ------------- Julie: constants to create map ------------- #### TILE_SIZE_PIXELS = 50 MAP_SIZE_TILES = 11 MAP_SIZE_PIXELS = MAP_SIZE_TILES * TILE_SIZE_PIXELS PASSABLE_TILE = 0 #### ------------- Julie: to switch from start screen to gameplay ------------- #### stage = 1 def setup(): global spriteList global flatLand global winSize global time global score score = 0 global gameFont global startFont
import numpy as np import argparse as argparse parser = argparse.ArgumentParser( prog="python main.py", description= "Main.py handles everything. Use python main.py -h to see your options.") parser.add_argument('-m', '--mode', help='Set the simulation mode.', default=3, action='store', type=int) starlings = Flock() args = parser.parse_args() flocksim = args.mode if flocksim == 0: starlings.mode = 1 starlings.number = 40 starlings.tau = 0.1 starlings.eta = 0.25 starlings.speed = 25.0 starlings.boxSize = 100.0 starlings.habitatSize = 200.00 starlings.habitatStrength = 20.0 starlings.initBoids()
from flock import Flock import numpy as np import argparse as argparse; parser = argparse.ArgumentParser(prog="python main.py", description = "Main.py handles everything. Use python main.py -h to see your options."); parser.add_argument('-m', '--mode', help='Set the simulation mode.', default = 3, action='store', type = int); parser.add_argument('-s', '--snapshots', help='Set the number of frames for the video', default = 1200, action='store', type = int); parser.add_argument('-f', '--filename', help='Set the simulation mode.', default = "default", action='store'); starlings = Flock() args = parser.parse_args(); flocksim = args.mode filename = args.filename + ".mp4" snapshots = args.snapshots #number of frames if flocksim == 0: starlings.mode = 1 starlings.number = 40 starlings.tau = 0.1 starlings.eta = 0.25 starlings.speed = 25.0 starlings.boxSize = 100.0 starlings.habitatSize = 200.00 starlings.habitatStrength = 20.0 starlings.initBoids()
def main(): flock = Flock(n, width, height) game_loop(flock, width, height, delay)
class Level(abc.ABC): entrance_gate_position = None exit_gate_position = None new_events = [] landing_zone_top = 820 maximum_plant_level = landing_zone_top minimum_plant_level = 600 exit_gate_open = True name = None extra_help_lines = [] def __init__(self, game): self.game = game self.canvas = game.canvas self.background = pygame.image.load( os.path.join('images', self.name.lower(), 'background.png')) self.console_image = pygame.image.load( os.path.join('images', self.name.lower(), 'console.png')) self.attractors = [] self.flock = None self.flock = Flock(self) self.has_visited = False self._level_complete = False if self.exit_gate_position: self.attractors.append( Attractor(self.exit_gate_position, 500, Settings.gate_radius * 2)) # 'Attractors': AttractorsRule(self, 1, [Attractor((300, 300), 50)]), self.flowers = [] self.init_level() @abc.abstractmethod def init_level(self): pass @abc.abstractmethod def level_complete_check(self): pass def on_first_entry(self): pass def leader_enters(self): if not self.has_visited: self.game.event_handler.activate(self.new_events) self.game.help_lines += self.extra_help_lines self.on_first_entry() self.game.state = GameState.READ_INTRO # def first_visitor(self): # """First time any boid visits this level""" # # def visit(self): # if not self.has_visited: # self.first_visitor() # self.has_visited = True @property def level_complete(self): if logger.getEffectiveLevel() <= logging.DEBUG: return True # Once passed, a level stays done, even if the test starts failing again if self._level_complete: return True if self.level_complete_check(): self._level_complete = True return self._level_complete @property def contains_leader(self): return self.flock.leader is not None def update(self, duration): self.flock.update(duration) [flower.update(duration) for flower in self.flowers] def draw(self): self.canvas.blit(self.background, (0, 0)) # [ # item.draw(self.canvas) # for item in self.flowers # ] [flower.draw() for flower in self.flowers] self.flock.draw() if self.entrance_gate_position: pygame.draw.circle(self.canvas, pygame.Color('green'), self.entrance_gate_position, Settings.gate_radius, 2) if self.exit_gate_position: if not self.exit_gate_open: colour = pygame.Color('red') elif not self.level_complete: colour = pygame.Color('blue') else: colour = pygame.Color('green') pygame.draw.circle(self.canvas, colour, self.exit_gate_position, Settings.gate_radius, 2) self.canvas.blit(self.console_image, (0, 0))
def __init__(self): #self.flock = Flock() self.flockb = Flock()
from agent import Agent from flock import Flock import cPickle as pickle import time t0 = time.clock() culture = Flock(num_agents = 15, run_time = 1000, show_every = 10, animation = 'off') trajectories, details = culture.run() t1 = time.clock() print 'python took ', t1-t0 f = open('trajectories.pkl', 'wb') pickle.dump([trajectories, details], f) f.close()
'''Simple script for running the program''' from flock import Flock # Parameters time_steps = 200 number_of_birds = 150 is_predator_present = True # Initialize flock myFlock = Flock(number_of_birds, predator=is_predator_present) # Run simulation for m in range(0, time_steps): myFlock.update() myFlock.drawPlot(m)
def sync(self, timeout=None): with self.lock: # create repos config repos_config = [ '[main]\nreposdir=\ncachedir={cache_root}\nkeepcache=0\n'.format(cache_root=self.get_cache_root()) ] last_modified = None download_count = 0 all_repos = [] for copr in self.all_coprs: if copr.last_modified: if last_modified: last_modified = max(last_modified, copr.last_modified) else: last_modified = copr.last_modified for repo in self.repos.filter(copr=copr): if repo.name not in copr.yum_repos: # delete old repos repo.delete() else: # update existing repos repo.copr_url = copr.yum_repos[repo.name] repo.save() repos_config.append( '[{name}]\nname={name}\nbaseurl={url}\ngpgcheck=0\n'.format( name = repo.name, url = repo.copr_url, ) ) all_repos.append(repo) download_count += repo.download_count # save repos config with open(self.get_repos_config(), 'w') as f: f.write('\n'.join(repos_config)) # despite expectations the file is empty # if I do not call explicitly flush f.flush() # scl.all_repos are expected to be sorted by name all_repos.sort(key=lambda repo: repo.name) # store newly computed values self.all_repos = all_repos self.last_modified = last_modified self.download_count = download_count # unfortunately reposync can not run parallel with Flock(os.open(settings.REPOS_ROOT, 0), LOCK_EX): log = open(os.path.join(self.get_repos_root(), 'reposync.log'), 'w') # workaround BZ 1079387 call('rm -rf /var/tmp/yum-*', shell=True) # remove cache_root try: shutil.rmtree(self.get_cache_root()) except FileNotFoundError: pass # run reposync # TODO replace reposync with another tool, # which is capable of parallel run and preserves *-relese.rpm args = [ 'reposync', '--source', '-c', self.get_repos_config(), '-p', self.get_repos_root(), ] for repo in self.all_repos: args += ['-r', repo.name] check_call_log(args, stdout=log, stderr=log, timeout=timeout) self.last_synced = datetime.now().replace(tzinfo=utc) self.check_repos_content(timeout)
class MainGame(State): def __init__(self, screen): """ your app starts here""" State.__init__(self, screen) #create game objects self.playerFlock = Flock(1.2) #sprite groups must be added to the screen to be drawn image = loadsurface("small2.png") pimage = loadsurface("anchor.png") #game object list creation and registration self.allyList = [] self.enemyList = [] self.screen.add(self.allyList) self.screen.add(self.enemyList) #player stuff self.register(self.allyList, self.playerFlock) p = Anchor(Vector2D(0,0),pimage) for i in range(9): b = Boid(Vector2D(0,0),image, weap=machinegun()) self.playerFlock.addSquad(b) self.playerFlock.addAnchor(p) #create an enemy enemy = spawnEnemy(Vector2D(100,100), 0, defaultBehavior, enemyformation(), image, pimage, p) self.register(self.enemyList, enemy) def register(self,list,entity): list.append(entity) def f(): list.remove(entity) entity.unregister = f def run(self): #deal with eventlist for i in pygame.event.get(): if i.type == pl.QUIT: exit() self.checkCollisions() (thrustDirection, boost, rotation, shooting, changeState) = getInputActions() if changeState: statemanager.switch("fe", self.playerFlock.formation) self.playerFlock.anchor.playerInput(thrustDirection, boost, rotation, shooting) for ally in self.allyList: ally.update() for enemy in self.enemyList: enemy.update() self.screen.update(self.playerFlock.anchor.position) #center camera on player pygame.event.pump() def checkCollisions(self): #player/enemy bullet collisions playerShipsHit = {} for ally in self.allyList: for enemy in self.enemyList: playerShipsHit = pygame.sprite.groupcollide(ally, enemy.shotgroup, False, False, pygame.sprite.collide_circle) enemyShipsHit = pygame.sprite.groupcollide(enemy, ally.shotgroup, False, False, pygame.sprite.collide_circle) for ship in playerShipsHit.iterkeys(): for shot in playerShipsHit[ship]: shot.impact(ship) for ship in enemyShipsHit.iterkeys(): for shot in enemyShipsHit[ship]: shot.impact(ship) def switchin(self, *args): """args should be a tuple of exactly 1 element, a Formation object""" State.switchin(self) if len(args) > 1: raise ValueError("MainGame.switchin() should take 1 or fewer arguments!") if len(args) == 1: if not isinstance(args[0],Formation): raise ValueError("MainGame.switchin() needs a Formation object!") if len(args) == 1: self.playerFlock.changeFormation(args[0]) #register sprites self.screen.add(self.playerFlock) #no widgets to register #switch camera self.screen.cam = roughTrack(self.playerFlock.anchor.position) def switchout(self): #unregister sprites self.screen.remove(self.playerFlock)
def simulate(self, duckFactory): # type: (AbstractDuckFactory) -> None mallardDuck = duckFactory.createMallardDuck() redheadDuck = duckFactory.createRedheadDuck() duckCall = duckFactory.createDuckCall() rubberDuck = duckFactory.createRubberDuck() gooseDuck = GooseAdapter(Goose()) flockOfDucks = Flock() flockOfDucks.add(mallardDuck) flockOfDucks.add(redheadDuck) flockOfDucks.add(rubberDuck) flockOfDucks.add(gooseDuck) flockOfMallards = Flock() mallardDuck1 = duckFactory.createMallardDuck() mallardDuck2 = duckFactory.createMallardDuck() mallardDuck3 = duckFactory.createMallardDuck() mallardDuck4 = duckFactory.createMallardDuck() flockOfMallards.add(mallardDuck1) flockOfMallards.add(mallardDuck2) flockOfMallards.add(mallardDuck3) flockOfMallards.add(mallardDuck4) flockOfDucks.add(flockOfMallards) # print "\nDuck simulator: Whole Flock Simulation" # self.__simulate(flockOfDucks) # # print "\nDuck simulator: Mallard Flock Simulation" # self.__simulate(flockOfMallards) print "\nDuck simulator: With Observer" quackologist = Quackologist() flockOfDucks.registerObserver(quackologist) self.__simulate(flockOfDucks) print "Number of quacks: " + str(QuackCounter.getQuacks())