Exemple #1
0
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))
Exemple #2
0
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
Exemple #3
0
    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())
Exemple #4
0
    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()
Exemple #5
0
'''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)
Exemple #6
0
from agent import Agent
from flock import Flock

culture = Flock(num_agents = 5, run_time = 100000, show_every = 10)
culture.run()
Exemple #7
0
                    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)
    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)
Exemple #10
0
def main():
    flock = Flock(n, width, height)
    game_loop(flock, width, height, delay)
Exemple #11
0
### 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
Exemple #12
0
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()
Exemple #13
0
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()