class Main: def __init__(self): pg.init() pg.display.set_caption("gravity") self.win = pg.display.set_mode((WIDTH, HEIGHT)) self.clock = pg.time.Clock() self.running = True self.universe = Universe() # Key press and close button functionality def checkEvents(self): for event in pg.event.get(): if event.type == pg.QUIT: self.running = False # Update things def update(self, dt): self.universe.update(dt) # Draw things def render(self): self.win.fill(BLACK) self.universe.render(self.win) pg.display.update() # The main loop def loop(self): while self.running: dt = self.clock.tick(FPS) / 1000 self.checkEvents() self.update(dt) self.render() pg.quit() sys.exit()
def run(self): self._status = SimState.INITIALIZING self._report_state() stats = Stats() universe = Universe(ConfigSimulator.RACES, stats) self._status = SimState.RUNNING self._report_state() while self._status == SimState.RUNNING and universe.pass_time(): stats.accumulate_step_stats(universe) printing.print_step_stats(stats) self._report(stats) stats.initialize_inter_step_stats() if universe.get_time() % ConfigSimulator.LOGGING_BATCH_SIZE == 0: stats.accumulate_epoch_stats(universe) printing.print_epoch_stats(stats) if ConfigSimulator.CSV_LOGGING: printing.dataframe2csv( stats.step_stats_df, ConfigSimulator.CSV_FILE_PATH.format( time.strftime("%Y%m%d-%H%M%S"))) self._status = SimState.IDLE self._report_state()
def __init__(self): """A basic test where Alice puts objects in a box.""" alice = UAgent( 'Alice', ['move', 'take', 'put', 'place_in_box', 'fetch_from_box'], [(('know', 'Alice', ('location', 'pipo', 'pipobox')), ), (('know', 'Alice', ('location', 'pipo2', 'pipobox')), )], knowledge=[ ('know', 'Alice', ('location', 'pipo', 1)), ('know', 'Alice', ('location', 'pipo2', 1)), ('know', 'Alice', ('location', 'pipobox', 2)), ('know', 'Alice', ('full', 'pipobox', False)), ], max_length_plan=9) pipo = UObject('pipo') pipo2 = UObject('pipo2') pipobox = Box('pipobox', 2) uni = Universe(3) uni.add(alice, 0) uni.add(pipo, 1) uni.add(pipobox, 2) uni.add(pipo2, 1) self.agents = [alice] self.objects = [pipo, pipo2, pipobox] self.universe = uni self.nb_iteration_max = 9 self.test_name = 'Test with Alice putting 2 objects in the box'
def main(): fraction_malicious = 50 fraction_exposing = 50 universe = Universe(30, fraction_malicious, fraction_exposing) coordinates = universe.coordinates earth = universe.civilizations[0] earth.broadcasts = True if earth.broadcasts: earth.send_broadcast() neighbours = universe.find_neighbours(earth) for i in range(len(neighbours)): print( f'{neighbours[i].name} was found. Malicious = {neighbours[i].malicious}' ) if neighbours[i].malicious: print(f'{neighbours[i].name} destroys {earth.name}') elif neighbours[i].broadcasts: print(f'{neighbours[i].name} says, "Hi Neighbour!"') else: print(f'{neighbours[i].name} remains silent') # print(coordinates) create_plt(coordinates)
def __init__(self): """A basic test where Alice wants to move an item and then move to another position.""" alice = UAgent( 'Alice', ['move', 'take', 'put'], [ ( ('know', 'Alice', ('location', 'pipo',0)), ('know', 'Alice', ('location', 'Alice', 2)) ), ], [('know', 'Alice', ('location', 'pipo', 1))] ) pipo = UObject('pipo') uni = Universe(3) uni.add(alice, 0) uni.add(pipo, 1) self.agents = [alice] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 5 self.test_name = 'Test with Alice moving an item and moving.'
def main(): print(ss.earth.grav_force(ss.sun)) dt = 60 # a minute simple = [ss.sun, ss.earth] u = Universe(dt, simple) u.init_velocities() print("------------------- init speeds --------------------") for o in u.oschis: print(o.name, np.linalg.norm(o.velocity)) print() counter = 0 while u.simulate(): if counter > (370 * 24 * 60): break # after a year if counter % (31 * 24 * 60) == 0: # each month print('') for o in u.oschis: print( '{:10} | {:15e} {:15e} {:15e} | {:15f} {:15f} {:15f} | {:15e} | {:15f}' .format(o.name, o.position[0], o.position[1], o.position[2], o.velocity[0], o.velocity[1], o.velocity[2], np.linalg.norm(o.position), np.linalg.norm(o.velocity))) counter += 1 print() print("------------------- After a Year --------------------") print(u.oschis)
def test_single_agent(): print("### test_single_agent() ###") universe = Universe(1, 5, 0.0, debug=False) counter = 0 while not universe.is_finished(): universe.update() counter += 1 assert counter == 0
def __init__(self): pg.init() pg.display.set_caption("gravity") self.win = pg.display.set_mode((WIDTH, HEIGHT)) self.clock = pg.time.Clock() self.running = True self.universe = Universe()
def test_center_of_mass(self): sun = Oschi("Sun", (0, 0, 0), 1, (0, 0, 0), 0.2) earth = Oschi("Earth", (1, 1, 1), 27 * 10**11, (0, 0, 0), 0.1) universe = Universe(60, [sun, earth]) u = universe.center_of_mass(earth) self.assertTrue((universe.center_of_mass(earth) == (0, 0, 0)).all())
def start_game(self, name, skill_points, credit): self.universe = Universe() rand_int = random.randint(0, len(self.universe.region_list) - 1) self.player = Player(name, skill_points, credit, self.universe.region_list[rand_int]) self.net_worth_data.append(self.player.credit) self.universe.insert_win(self.player.name) utility.bprice_calc(self.player, self.player.curr_region) utility.sprice_calc(self.player, self.player.curr_region)
def __init__(self): self.agents = [] self.objects = [] self.universe = Universe(1) # nb_iteration_max is here to refrain some cases to computer for # too long... self.nb_iteration_max = 1 self.test_name = 'default_test_name' self.finished = False
def main(): a = Body((DIST, 0, 0), (0, VEL, 0), mass=M, color=(0.8, 0.8, 1)) b = Body((-DIST, 0, 0), (0, -VEL, 0), mass=M, color=(1, 0.8, 0.8)) bodies = [a, b] universe = Universe(bodies, G=G, dt=DT) #universe.draw() #print(universe.bodyList) while True: #(universe.bodyList) universe.update()
def test_two_agents(): print("### test_two_agents() ###") universe = Universe(2, 5, 0.0, debug=False) stats = Statistics() counter = 0 while not universe.is_finished(): universe.update(stats) counter += 1 assert counter <= 10
def __init__(self): """A basic test where Alice puts objects in a box.""" alice = UAgent( 'Alice', ['move', 'take', 'put', 'place_in_box', 'fetch_from_box'], [ (('know', 'Alice', ('location', 'pipo', 'pipobox')),), (('know', 'Alice', ('location', 'pipo2', 'pipobox')),) ], knowledge = [ ('know', 'Alice', ('location', 'pipo', 1)), ('know', 'Alice', ('location', 'pipo2', 1)), ('know', 'Alice', ('location', 'pipobox', 2)), ('know', 'Alice', ('full', 'pipobox', False)), ], max_length_plan = 9 ) pipo = UObject('pipo') pipo2 = UObject('pipo2') pipobox = Box('pipobox', 2) uni = Universe(3) uni.add(alice, 0) uni.add(pipo, 1) uni.add(pipobox, 2) uni.add(pipo2, 1) self.agents = [alice] self.objects = [pipo, pipo2, pipobox] self.universe = uni self.nb_iteration_max = 9 self.test_name = 'Test with Alice putting 2 objects in the box'
def __init__(self, actions: List[int], figure: Figure, runtime: float = 8.6, fps: float = 1.0 / 30): self.actions = actions self.universe = Universe() self.universe.add_figure(figure) self.runtime = runtime self.fps = fps
def __init__( self, actions: List[int], figure: Figure, label: Text = '', runtime: float = 8.2 ): super().__init__(width=1000, height=400, caption='Jumping over the ball', resizable=False) self.actions = actions self.universe = Universe() self.universe.add_figure(figure) self.current_action = 1 self.current_time = 0.0 self.fps = 1.0/30 self.add_label(label) self.runtime = runtime
def test_simulation_run(): print("### test_simulation_run() ###") universe = Universe(2, 5, 0.4, debug=True) stats = Statistics() print("Start:") print_environment(universe) print("Agent stats:") for agent in universe.agents: agent.print_stats() while not universe.is_finished(): universe.update(stats) print_environment(universe)
def add_player(): print(request.form.to_dict()) playerDict = request.form.to_dict() isValid = True sum = 0 for key, value in playerDict.items(): print(sum) if value == '': flash('Name is empty') isValid = False if key == 'pilot': sum += int(value) elif key == 'fighter': sum += int(value) elif key == 'trader': sum += int(value) elif key == 'engineer': sum += int(value) if sum != 16: flash('Skills must add to 16') isValid = False #print(playerDict) if isValid is True: playerDict['spaceship'] = 'gnat' playerDict['credits'] = 1000 u = Universe() universe = u.makeUniverse() playerDict['universe'] = universe db.users.insert_one(playerDict) # p = db.users.find_one({}) player = Player() print(universe) player.setPlayer(playerDict['name'], playerDict['pilot'], playerDict['fighter'], playerDict['trader'], playerDict['engineer'], playerDict['difficulty'], playerDict['spaceship'], playerDict['credits'], playerDict['universe']) return "Success!" else: return "Try again!"
def __init__(self): self.screen = Screen() self.window = pygame.display.set_mode( (self.screen.width, self.screen.height)) self.universe = Universe(self.window, 10, 10) self.population_record = 0 self.hungry_deaths = 0 self.age_deaths = 0 self.food_wait = 10 self.extinction = False pygame.display.set_caption("Evolution") pygame.init()
def __init__(self): """A basic test where Alice can only order and wants to move the item. Bob can move and take/put items. Expected result : Alice orders Bob to move, take the item, move, put the item.""" alice = UAgent('Alice', can_do=['order'], goals=[('know', 'Alice', ('location', 'pipo', 0))], knowledge=[ ('know', 'Alice', ('location', 'pipo', 2)), ('know', 'Alice', ('location', 'Bob', 1)), ('know', 'Alice', ('free', 'Bob', True)), ]) bob = UAgent('Bob', ['move', 'take', 'put'], goals=[], knowledge=[('know', 'Bob', ('location', 'pipo', 2))]) pipo = UObject('pipo') uni = Universe(3) uni.add(alice, 0) uni.add(bob, 1) uni.add(pipo, 2) self.agents = [alice, bob] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 6 self.test_name = 'Test with Alice ordering Bob to move the object.'
def __init__(self): """A basic test where Alice wants to give the object to Bob. Expected result : Alice moves to take the object and gives it to Bob.""" alice = UAgent( 'Alice', ['move', 'take', 'give'], goals = [('know', 'Alice', ('location', 'pipo', 'Bob'))], knowledge = [ ('know', 'Alice', ('location', 'pipo', 2)), ('know', 'Alice', ('location', 'Bob', 1)), ('know', 'Alice', ('free', 'Bob', True)), ] ) bob = UAgent( 'Bob', ['move', 'put'], [('know', 'Bob', ('location', 'pipo', 0))], knowledge = [ ] ) pipo = UObject('pipo') uni = Universe(3) uni.add(alice, 0) uni.add(bob, 1) uni.add(pipo, 2) self.agents = [alice, bob] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 6 self.test_name = 'Test with Alice giving an object to Bob and Bob putting it somewhere else'
def __init__(self): """ Trivial test Alice is at location 0, can move, and wants herself to be in location 1. Expected result : Alice moves from 0 to 1.""" alice = UAgent('Alice', ['move'], [('know', 'Alice', ('location', 'Alice', 1))]) uni = Universe(2) uni.add(alice, 0) self.agents = [alice] self.objects = [] self.universe = uni self.nb_iteration_max = 2 self.test_name = 'Test of the move action.'
def main(): MODE = "random" fig = plt.figure() ax = plt.subplot(111) ax.set_title(MODE) if MODE == "random": N = 3 stars = [] randomvals = np.random.rand(N, 6) while any( any((impossiblepos(val1, val2) and val1 is val2) for val2 in randomvals) for val1 in randomvals): randomvals = np.random.rand(N, 4) print("apprehended") for vals in randomvals: mass = 4 color = np.random.rand(3) stars += [ Star((WIDTH * 0.5 * (vals[0] - 0.5), HEIGHT * 0.5 * (vals[1] - 0.5)), (0.00 * vals[2], 0.00 * vals[3]), mass=mass, facecolor=color) ] universe = Universe(stars, ax, dt=5e-3, trace=TRACE) mov = anim.FuncAnimation(fig, universe.update, frames=100, interval=1000 * universe.dt, blit=True) try: plt.show() except AttributeError: print("AtrributeError")
def __init__(self): """ Trivial test Alice is at location 0, can move, and wants herself to be in location 1. Expected result : Alice moves from 0 to 1.""" alice = UAgent( 'Alice', ['move'], [('know', 'Alice', ('location', 'Alice', 1))] ) uni = Universe(2) uni.add(alice, 0) self.agents = [alice] self.objects = [] self.universe = uni self.nb_iteration_max = 2 self.test_name = 'Test of the move action.'
def initialize(): dt = 60*60*24*7 # a minute # simple = [ss.sun, ss.earth, ss.mars] simple = [ss.sun, ss.mercury, ss.venus, ss.earth, ss.mars, ss.jupiter, ss.saturn, ss.uranus, ss.neptune] u = Universe(dt, simple) #u.init_velocities() return u
def __init__(self): """A basic test where Alice can only order and wants to move the item. Bob can move and take/put items. Expected result : Alice orders Bob to move, take the item, move, put the item.""" alice = UAgent( 'Alice', can_do = ['order'], goals = [('know', 'Alice', ('location', 'pipo',0))], knowledge = [ ('know', 'Alice', ('location', 'pipo',2)), ('know', 'Alice', ('location', 'Bob', 1)), ('know', 'Alice', ('free', 'Bob', True)), ] ) bob = UAgent( 'Bob', ['move', 'take', 'put'], goals = [], knowledge = [('know', 'Bob', ('location', 'pipo',2))] ) pipo = UObject('pipo') uni = Universe(3) uni.add(alice, 0) uni.add(bob, 1) uni.add(pipo, 2) self.agents = [alice, bob] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 6 self.test_name = 'Test with Alice ordering Bob to move the object.'
def __init__(self): """A basic test where Alice asks Bob about the object she wants to take.""" alice = UAgent( 'Alice', ['take', 'ask_if', 'ask_ref'], [ (('know', 'Alice', ('location', 'pipo', 'Alice')),), ], [], max_length_plan = 3 ) bob = UAgent( 'Bob', ['move', 'inform_if', 'inform_ref'], [], [ ('know', 'Bob', ('location', 'pipo', 0)) ] ) pipo = UObject('pipo') uni = Universe(3) uni.add(alice, 0) uni.add(bob, 2) uni.add(pipo, 0) self.agents = [alice, bob] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 6 self.test_name = 'Test with Alice asking Bob about the object.'
def generateUniverses(self): result = [] for assignment in next_permutation( sorted(expandrolelist(self.rolelist))): assignedroles = dict(zip(self.players, assignment)) result.append(Universe(assignedroles, self)) numUniverses = int(self.toKeep * len(result)) filteredUniverses = random.sample(result, numUniverses) return filteredUniverses
def run_until(max_time, settings, display=True): universe = Universe(settings) if display: displayer = Display(universe) running = True while running: if display: inp = displayer.show() if inp == 'quit': running = False universe.tick() if universe.time > max_time: running = False if display: displayer.quit() return universe
def VisualLoop(self): self.universe = Universe() self.universe.LoadNew("basic.config") self.restartLoop = False playing = True while (playing): for currentEntity in self.universe.entities: command = [] self.PlayerShow(command, currentEntity) while ((len(command) == 0 or not (command[0] in ("d", "done"))) and playing): command = raw_input("> ").lower().split(" ") ## '?': ShowHelp, _ ## 'help': ShowHelp, _ try: playing = { 'quit': lambda a, b: False, 'exit': lambda a, b: False, 'q': lambda a, b: False, 'd': lambda a, b: True, # done 'done': lambda a, b: True, 'move': self.PlayerMove, 'split': self.PlayerSplit, 'show': self.PlayerShow, 'budget': self.BudgetShow, 'debug': self.PlayerDebug, 'save': self.PlayerSave, 'load': self.PlayerLoad, 'ashow': self.AdvancementsShow, 'discover': self.PlayerDiscover, 'teach': self.PlayerTeach, }[command[0]](command, currentEntity) except KeyError: print "unknown command" if not (playing): break if not (playing): if self.restartLoop: self.restartLoop = False playing = True else: self.universe.DoTimeStep() print "=" * 10, "time:", self.universe.t, "=" * 10
def __init__(self, loop=None, config=False, showfps=False): self.loop = loop or asyncio.get_event_loop() self.cbg = CBG(showfps=showfps) if self.cbg.width < 320 or self.cbg.height < 240: print("Screen is too small.") print("Please resize your terminal to minimal 160x60 characters.") self.cbg.exit(2) ctrl = Control(self.cbg) if config: ctrl.edit_controls() else: ctrl.load_mapping() self.inputdev = ctrl.get_evdev() self.universe = Universe() self.commander = Commander() self.commander.load_game() self.market = Market() if self.commander.data.current_market is None: self.set_pricelist() self.ships = AllShips("all_ships.ship").ships
def GetUniverseFromServer(self): conn = httplib.HTTPConnection(self.serverAddress, port=self.port) conn.request("GET", "/universeState/" + str(self.t)) response = conn.getresponse() if response.status != 200: print response.status print response.reason print response.read() raise "out of sync?" jsonString = response.read() self.universe = Universe.FromJson(jsonString)
def main(options): parsed_options = validate_options (options) log.info("Options: " + str(parsed_options)) univ = Universe() provider = Provider(log) for stock in univ.universe(): if(stock['name'] != parsed_options['instrument']): continue log.info("Processing: " + stock['name']) price = provider.get_last_trade_data(stock['name'], stock['exchange'], parsed_options['lookback']) instruments = Instruments(log, price.to_dict()) if(instruments is not None): driver = Driver(log, parsed_options['file']) driver.create_tabs(stock['tab']) driver.insert_data(instruments.get_instruments(), stock['tab'], 2) driver.save()
def main(): size = 100 # HEADS UP! Enabling vsync on Linux will cause the app to freeze. window = pyglet.window.Window(width=size * 8, height=size * 8, vsync=False) universe = Universe(size, CONTENDERS) event_loop = asyncio.get_event_loop() event_loop.call_soon(run_pyglet, event_loop) event_loop.call_soon(universe_tick, universe, event_loop, window) event_loop.run_forever() event_loop.close()
def collect_stats(toVary, values, args, N=100): win_counts_list = [] for j in range(len(values)): print("\tSimulating", toVary, "=", values[j]) args[toVary] = values[j] win_counts = [0 for i in range(21)] for i in range(N): stats = Statistics() universe = Universe(num_agents=args["num_agents"], env_size=args["env_size"], resource_prob=args["resource_prob"], metabolic_rate=args["metabolic_rate"], field_of_vision=args["field_of_vision"], seed=i, debug=False) while not universe.is_finished(): universe.update(stats) win_counts[int(stats.avg_win_strategy) + 10] += 1 win_counts_list.append(win_counts) return win_counts_list
def main(): # Parse arguments argparser = argparse.ArgumentParser() argparser.add_argument('-g', '--graphics', action="store_true") flags = argparser.parse_args() # Let there be light! (create an N-particle universe) universe = Universe(N_PARTICLES) print universe # Create graphics if flags.graphics and graphics_imported: graph = Graphics(universe, GRAPHICS_DIR) graph.save_plot() # Incremenent time for i in xrange(50): print 'Computing step', i+1 universe.increment_time() if flags.graphics and graphics_imported: graph.save_plot()
def __init__(self): """A basic test where Alice can move, take and put and wants to change the location of an object. Expected result : Alice moves to the item, takes it and moves it.""" alice = UAgent( 'Alice', ['move', 'take', 'put'], [('know', 'Alice', ('location', 'pipo', 0)),], [('know', 'Alice', ('location', 'pipo', 1)),], ) pipo = UObject('pipo') uni = Universe(2) uni.add(alice, 0) uni.add(pipo, 1) self.agents = [alice] self.objects = [pipo] self.universe = uni self.nb_iteration_max = 4 self.test_name = 'Test with Alice changing an object\'s position.'
def __init__(self): """Basic test where Alice can only order and Bob can only move. Alice wants Bob to change his location. Expected result : Alice orders Bob to move.""" alice = UAgent( 'Alice', ['order'], [('know', 'Alice', ('location', 'Bob', 2))], [('know', 'Alice', ('location', 'Bob', 1))] ) bob = UAgent( 'Bob', ['move'], [] ) uni = Universe(3) uni.add(alice, 0) uni.add(bob, 1) self.agents = [alice, bob] self.objects = [] self.universe = uni self.nb_iteration_max = 3 self.test_name = 'Test of Alice ordering moving to Bob.'
class FFT(Show): def __init__(self, *args, **kwargs): self.bands = 12 super(FFT, self).__init__(*args, **kwargs) self.colorConfig = { 'blue':{ 'start':0, 'end':.8 }, 'red':{ 'start':.8, 'end':1 } } def getFixtures(self): return self.fixtureList.filter(lambda f : f.hasTag('rgb')) def run(self): self.universe = Universe(self.bands) for channel in self.universe: channel.addListener(self) fixtures = self.getFixtures() self.outputs = [] self.ratio = float(len(fixtures)) / self.bands start = 0 for i in range(self.bands): end = int((i+1) * self.ratio) self.outputs.append(VUOutput(fixtures[start:end], self.colorConfig)) start = end self.reader = FFTReader(AudioReader.instance("hw:1,0"), self.universe, self.bands) self.reader.start() self.endEvent.wait() def onValueChange(self, channel, value): index = self.universe.channelIndex(channel) value = float(value) / 255 self.outputs[index].update(value) def stop(self): self.reader.stop() self.reader.endEvent.wait() for output in self.outputs: output.stop() self.endEvent.set() super(FFT, self).stop()
def run(self): self.universe = Universe(self.bands) for channel in self.universe: channel.addListener(self) fixtures = self.getFixtures() self.outputs = [] self.ratio = float(len(fixtures)) / self.bands start = 0 for i in range(self.bands): end = int((i+1) * self.ratio) self.outputs.append(VUOutput(fixtures[start:end], self.colorConfig)) start = end self.reader = FFTReader(AudioReader.instance("hw:1,0"), self.universe, self.bands) self.reader.start() self.endEvent.wait()
def render_prelude(self, eye): Universe.render_prelude(self, eye) glClearColor(1, 1, 1, 1) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
__author__ = 'elemental' # This project is using python v3 from universe import Universe from world import World from path import * from car import Car from road import * w = World(20, 20) i1 = Two_by_Two(2, 2) i2 = Two_by_Two(13, 2) i3 = Two_by_Two(13, 14) i4 = Two_by_Two(2, 14) r1 = Two_Lane_Road(i1, i2) r2 = Two_Lane_Road(i2, i3) r3 = Two_Lane_Road(i3, i4) r4 = Two_Lane_Road(i4, i1) w.add_roads([r1, r2, r3, r4]) w.add_intersections([i1, i2, i3, i4]) c = Car(r1.paths[1], w) d = Car(r1.paths[0], w, 'left') e = Car(r2.paths[0], w) u = Universe(w) u.start()
def main(): dx = dy = jump = 0 screen = pygame.display.set_mode((600,600)) start_image = pygame.image.load("start.png") screen.blit(start_image, start_image.get_rect()) pygame.display.flip() while True: event = pygame.event.poll() if event.type == KEYUP and event.key == K_SPACE: break for level in levels: universe = Universe(level) player = Player(universe) running = True pygame.mixer.music.load("music.flac") pygame.mixer.music.play(-1) while running: # Process events for event in pygame.event.get(): if event.type == QUIT: running = False break elif event.type == KEYDOWN and event.key == K_ESCAPE: running = False break elif event.type == KEYDOWN: if event.key == K_d: dx = 10 if event.key == K_a: dx = -10 if event.key == K_w: if jump == 0: dy = 350 jump = 35 elif event.type == KEYUP: if event.key == K_d or event.key == K_a: dx = 0 if event.key == K_w: dy = 0 # Make player move player.act(dx, dy) # Jump limiting dy = 0 if jump > 0: jump -= 1 # SIMULATE! universe.tick() if universe.won: running = False pygame.mixer.music.stop() screen = pygame.display.set_mode((600,600)) done_image = pygame.image.load("done.png") screen.blit(done_image, start_image.get_rect()) pygame.display.flip() while True: event = pygame.event.poll() if event.type == KEYUP and event.key == K_SPACE: break all_done_image = pygame.image.load("alldone.png") screen.blit(all_done_image, start_image.get_rect()) pygame.display.flip() while True: event = pygame.event.poll() if event.type == KEYUP and event.key == K_SPACE: break
from universe import Universe, World, Element, Attribute import defaultphysics import customphysics def f(x,y): if x['value'] == 1: return y else: return set() u = Universe() efilter = {'filter' : f, 'value' : 1} elems = u.getInitialElements(defaultphysics.ugetinitialelements, efilter) reachelems = u.getReachables(defaultphysics.ugetreachables, elems, efilter) w2 = World(reachelems) w2.printElements() altelems = u.getInitialElements(customphysics.custominitials, None) for e in altelems: print e.attr[0].name + ' (' +str(e.getOutputs(customphysics.customoutputs, None)[0].dblval) + ')' reachelems = u.getReachables(defaultphysics.ugetreachables, set([e]), None) strg ='\t' for ee in reachelems: strg+=str(ee.attr[0].dblval) + ' --> ' print strg
args = [] if 'args' in config: args = config['args'][:] getattr(self.modules[config['module']], config['method'])(*tuple(args)) if __name__ == '__main__': Messenger.addOutput(ConsoleOutput()) Messenger.addOutput(LCDOutput()) Messenger.addOutput(Messaging()) receiver = UDPReceiver() receiver.start() remoteServer = RemoteServer() remoteServer.start() universe = Universe() output = Output.factory('LPD8806Output', 180) output.addFilter(AlphaFilter()) #output = Output.factory('WebsocketOutput') universe.setOutput(output) for i in range(60): fixture = RGBFixture() fixture.mapToUniverse(universe, i * 3) fixture.addTags(['lpd8806', 'strip']) universe = Universe() universe.setOutput(Output.factory('SerialOutput', 0, 32)) for i in range(4): fixture = RGBFixture()
import sys sys.path.append('../vendors/adafruit/Adafruit_PWM_Servo_Driver/') from output import Output from filter import ScalingAlphaFilter from input import SocketInput from universe import Universe if __name__ == '__main__': output = Output.factory('AdafruitPWMOutput', address=0x40, bus=1) output.addFilter(ScalingAlphaFilter(4095)) universe = Universe(16) universe.setOutput(output) input = SocketInput(universe, '192.168.4.2', 'pwm')
class Test: """The mother class of the actual tests.""" def __init__(self): self.agents = [] self.objects = [] self.universe = Universe(1) # nb_iteration_max is here to refrain some cases to computer for # too long... self.nb_iteration_max = 1 self.test_name = 'default_test_name' self.finished = False def run(self): """Run the test""" # First we print some info about the test. self.print_test() self.print_launching() # Initialization for the loop. self.finished = False i = 0 while not self.finished and i < self.nb_iteration_max: print 'Iteration %d' % i self.universe.step() self.finished = self.universe.all_satisfied i += 1 if i == self.nb_iteration_max: self.print_nbiter_atteint() if self.finished: self.print_test_successful() if not self.finished: self.print_test_failed() return self.finished def print_test(self): print '#####' print '# Test : %s' % (self.test_name) print '# Agents : %s' % ([agent.name for agent in self.agents]) print '# Capacities : %s' % ([agent.can_do for agent in self.agents]) print '# Objects : %s' % ([o.name for o in self.objects]) print '# Universe size : %s' % (self.universe.locations[-1]) print '# Max nb of iterations : %s' % (self.nb_iteration_max) print '#####' def print_launching(self): self.print_separator(19) print '>>> Launching %s ...' % (self.test_name) self.print_separator(19) print(self.universe) def print_nbiter_atteint(self): print '>>> Maximum number of iterations reached.' def print_separator(self, magic_number): """F**k magic numbers""" print '#' * (magic_number + len(self.test_name)) def print_test_successful(self): self.print_separator(19) print '>>> ...%s SUCCESSFUL.' % (self.test_name) self.print_separator(19) def print_test_failed(self): self.print_separator(19) print '>>> ...%s FAILED.' %(self.test_name) self.print_separator(19)
import sys sys.path.append('../vendors/usbdmx/') from control import ControlServer, Controllable from universe import Universe from output import Output from fixture import FixtureManager, RGBFixture, StairvillePAR from module import SubMaster from filter import AlphaFilter from show import ShowManager if __name__ == '__main__': subMaster = SubMaster(['red', 'green', 'blue'], 3) universe = Universe() output = Output.factory('WS2801Output', channels=150) output.addFilter(AlphaFilter()) universe.setOutput(output) for i in range(50): fixture = RGBFixture(channelSequence='RGB') fixture.mapToUniverse(universe, i * 3) fixture.addTags(['ws2801', 'pixel']) universe = Universe() universe.setOutput(Output.factory('DEOutput', '0000000000001337')) for i in range(2): fixture = StairvillePAR() fixture.mapToUniverse(universe, i * 5) fixture.addTags(['dmx']) for i in reversed(range(2)): fixture = RGBFixture(channelSequence='RGB')
knowledge=[], max_length_plan = 3 ) bob = UAgent( name='Bob', can_do=['move', 'inform_if', 'inform_ref'], goals=[], knowledge= [ ('know', 'Bob', ('location', 'pipo', 0)) ] ) pipo = UObject('pipo') uni = Universe(3) uni.add(alice, 0) uni.add(bob, 2) uni.add(pipo, 0) print(uni) finished = False i = 0 nb_iteration_max = 5 while not finished and i < nb_iteration_max: print 'Itération %d' % i uni.step() i += 1 finished = uni.all_satisfied