def test_end_to_end_parallel_pipeline_using_a_threadpool(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = [e['shape'] for e in _KNOWN_COLLECTION] def run_task(x: Any) -> Any: # sleep between 1/5 (200ms) to 1/10 (100ms) time.sleep(1.0 / random.randrange(5, 10)) return x['shape'] start_time = time.time() # act actual = (Pipes(iterator.gen()).lz_map(run_task).apply()) actual_exec_time = time.time() - start_time start_time = time.time() with Pipes(iterator.gen(), num_threads=8) as pipes: threaded_actual = (pipes.lz_map(run_task).apply()) threaded_actual_exec_time = time.time() - start_time # assert assert actual == expected assert threaded_actual == expected assert actual_exec_time > threaded_actual_exec_time
def __init__(self): self.blinks_detector = BlinkDetector() self.blinks_detector.start() pygame.init() pygame.event.set_allowed([ QUIT, KEYDOWN, KEYUP, Pipes.SPAWN_PIPE_EVENT, Bird.BIRD_FLAP_EVENT ]) self.active = True self.score = 0 self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), DOUBLEBUF) self.screen.set_alpha(None) self.clock = pygame.time.Clock() self.font = pygame.font.Font('fonts/04B_19.ttf', 40) # Game objects self.bg_surface = pygame.transform.scale2x( pygame.image.load("assets/background-day.png").convert()) self.gameover_surface = pygame.transform.scale2x( pygame.image.load("assets/gameover.png").convert_alpha()) self.gameover_rect = self.gameover_surface.get_rect( center=(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)) self.floor = Floor() self.bird = Bird() self.bird.start_flapping() self.pipes = Pipes() self.pipes.start_spawning()
def mainLoop(clock, window, sprites, audio): run = True status = Status.inMenu tick = 0 drawer = Drawer(window) hitBoxe = HitBoxe(audio.hitSound, audio.dieSound, audio.pointSound) base = Base(sprites.base) bird = Bird(sprites.bird, audio.wingSound, hitBoxe) pipes = Pipes(sprites.pipe, hitBoxe) score = Score(sprites.numbers) while run: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): run = False if status == Status.inMenu and event.type == pygame.KEYUP and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): status = Status.inGame if status == Status.inGame and event.type == pygame.KEYDOWN and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): bird.jump() if status == Status.inGameOver and event.type == pygame.KEYUP and ( event.key == pygame.K_SPACE or event.key == pygame.K_UP): status = Status.inMenu tick = 0 base = Base(sprites.base) bird = Bird(sprites.bird, audio.wingSound, hitBoxe) pipes = Pipes(sprites.pipe, hitBoxe) score = Score(sprites.numbers) if status == Status.inGame: hitBase = hitBoxe.birdHitBase(bird, base) hitPipe = hitBoxe.birdHitPipes(bird, pipes) hitBoxe.birdPassPipe(bird, pipes.pipes, score) if hitBase or hitPipe: status = Status.inGameOver bird.die() if status == Status.inMenu: drawer.drawInMenu(sprites.background, sprites.message, base, bird, tick) elif status == Status.inGame: drawer.drawInGame(sprites.background, base, bird, pipes, score, tick) else: drawer.drawInGameOver(sprites.background, sprites.gameOver, base, bird, pipes, score, tick) if tick < FPS: tick += 1 else: tick = 0
def _create_pipes(self): if self.bird.rect.x >= 100: # Create pipe in the top pipe = Pipes(self, "top") self.pipes.add(pipe) current_bottom = pipe.rect.bottom # Create pipe in the bottom pipe = Pipes(self, "down", current_bottom) self.pipes.add(pipe)
class State: def __init__(self): self.player = Player() self.pipes = Pipes() def update(self, dirr): self.player.update(dirr, self.pipes) self.pipes.update() def draw(self, surface): self.pipes.draw(surface) self.player.draw(surface)
def __init__(self, info, player): self.nombre = info['name'] self.posicion = info['position'] self.game_name = info['game']['name'] self.player = player # Inicializo los juegos dependiendo del objeto if self.game_name == 'Adivinanzas': self.game = Adivinanza(info['game'], player) elif self.game_name == 'sopa_letras': self.game = Sopita(info['game'], player) elif self.game_name == 'Preguntas sobre python': self.game = PreguntaPython(info['game'], player) elif self.game_name == 'ahorcado': self.game = Ahorcado(info['game'], player) elif self.game_name == 'Preguntas matemáticas': self.game = PregMate(info['game'], player) elif self.game_name == 'Criptograma': self.game = Criptograma(info['game'], player) elif self.game_name == 'Encuentra la lógica y resuelve': self.game = LogicaE(info['game'], player) elif self.game_name == 'Quizizz Cultura Unimetana': self.game = Quizizz(info['game'], player) elif self.game_name == 'memoria con emojis': self.game = Memoria(info['game'], player) elif self.game_name == 'Lógica Booleana': self.game = LogicaB(info['game'], player) elif self.game_name == 'Juego Libre': self.game = Pipes(info['game'], player) elif self.game_name == 'Palabra mezclada': self.game = PalabrasMezcladas(info['game'], player) elif self.game_name == 'escoge un número entre': self.game = EscogeNumero(info['game'], player)
def test_map_with_exception_handling(): # arrange error = 'expected error' value = 5 new_value = value * 100 iterator = _CountableIterator(_KNOWN_RANGE) expected = [new_value if i == value else i * 2 for i in _KNOWN_RANGE] def raise_exception(x: Any) -> Any: if x == value: raise ValueError(error) return x * 2 captured_errors = {} def error_log_fn(exc: Exception, v: Any, nv: Any) -> None: captured_errors['error'] = f'{exc}' captured_errors['value'] = v captured_errors['new_value'] = nv # act actual = (Pipes(iterator.gen()).lz_map(fn=raise_exception, error_val_fn=lambda v: v * 100, error_log_fn=error_log_fn).apply()) # assert assert actual == expected assert captured_errors['error'] == error assert captured_errors['value'] == value assert captured_errors['new_value'] == new_value _assert_linear_performance(iterator, _KNOWN_RANGE)
def create_pipes(self): for pipes in range(100): random_size = self.s.pipes_sizes[random.randrange( len(self.s.pipes_sizes))] self.distance += 200 self.pipes.append( Pipes(self.window, random_size[0], random_size[1], self.distance))
def test_map_reduce(): # arrange iterator = _CountableIterator(_KNOWN_RANGE) expected = sum([i for i in _KNOWN_RANGE]) # act actual = (Pipes(iterator.gen()).reduce(lambda a, b: a + b, init_val=0)) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_RANGE)
def test_map_apply(): # arrange iterator = _CountableIterator(_KNOWN_RANGE) expected = [i * 2 for i in _KNOWN_RANGE] # act actual = (Pipes(iterator.gen()).lz_map(lambda x: x * 2).apply()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_RANGE)
def example4(): """Demonstrates group_by, pair. """ result = (Pipes(_EXAMPLE_COLLECTION).lz_map( lambda x: Pair(L=x['shape'], R=x['color'])).lz_filter( lambda pair: pair.L == 'square').group_by( lambda pair: pair.R, group_fn=lambda group: len(list(group)))) print(f'group by result = {result}')
def pipe_controls(self): """create, remove, and move the pipes""" pipe_width = 85 pipe_speed = 8 # bird speed basically for pipe in self.pipegroup.sprites(): pipe.rect.left -= pipe_speed for pipe in self.pipegroup.sprites(): if pipe.rect.left <= -pipe_width: self.pipegroup.remove(pipe) if len(self.pipegroup.sprites()) == 2: if self.pipegroup.sprites()[0].rect.left <= self.screen_width // 2: # for adjusting pipes space = random.randint(200, 300) top_height = random.randint(50, self.screen_height - space) # no need to modify below color = self.getrandomcolor() x = self.screen_width bottom_y = top_height + space bottom_height = self.screen_height - top_height - space top_rect = pygame.Rect(x, 0, pipe_width, top_height) bottom_rect = pygame.Rect(x, bottom_y, pipe_width, bottom_height) self.pipegroup.add(Pipes(self.screen, top_rect, color)) self.pipegroup.add(Pipes(self.screen, bottom_rect, color)) elif not self.pipegroup.sprites(): # for adjusting pipes space = random.randint(200, 300) top_height = random.randint(50, self.screen_height - space) # no need to modify below color = self.getrandomcolor() x = self.screen_width bottom_y = top_height + space bottom_height = self.screen_height - top_height - space top_rect = pygame.Rect(x, 0, pipe_width, top_height) bottom_rect = pygame.Rect(x, bottom_y, pipe_width, bottom_height) self.pipegroup.add(Pipes(self.screen, top_rect, color)) self.pipegroup.add(Pipes(self.screen, bottom_rect, color))
def test_map_filter_map_apply(): # arrange iterator = _CountableIterator(_KNOWN_RANGE) expected = [(i * 10) + 1 for i in _KNOWN_RANGE if (i * 10) % 2 == 0] # act actual = (Pipes(iterator.gen()).lz_map(lambda x: x * 10).lz_filter( lambda x: x % 2 == 0).lz_map(lambda x: x + 1).apply()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_RANGE)
def test_multi_filter_apply(): # arrange iterator = _CountableIterator(_KNOWN_RANGE) expected = [i for i in _KNOWN_RANGE if (i % 3 == 0) and (i % 9 == 0)] # act actual = (Pipes(iterator.gen()).lz_filter(lambda x: x % 3 == 0).lz_filter( lambda x: x % 9 == 0).apply()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_RANGE)
def test_sort_apply(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = sorted([e['color'] for e in _KNOWN_COLLECTION]) # act actual = (Pipes( iterator.gen()).lz_map(lambda x: x['color']).sort().apply()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def example1(): def has_blue_color(item): return item['color'] == 'blue' def has_square_shape(item): return item['shape'] == 'square' num_blue_squares = (Pipes(_EXAMPLE_COLLECTION).lz_filter( has_blue_color).lz_filter(has_square_shape).count()) print(f'Number of blue squares = {num_blue_squares}')
def test_map_uniq_count(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = len(list(dict.fromkeys([e['color'] for e in _KNOWN_COLLECTION]))) # act actual = (Pipes( iterator.gen()).lz_map(lambda x: x['color']).uniq().count()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def test_stream(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = [e['color'] for e in _KNOWN_COLLECTION] # act actual = [] for e in Pipes(iterator.gen()).lz_map(lambda x: x['color']).stream(): actual.append(e) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def test_reverse_sort_with_custom_hash_fn(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = sorted([e['color'] for e in _KNOWN_COLLECTION], reverse=True) # act actual = (Pipes(iterator.gen()).sort( fn=lambda x: x['color'], reverse=True).lz_map(lambda x: x['color']).apply()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def test_uniq_with_custom_hash(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = len(list(dict.fromkeys([e['color'] for e in _KNOWN_COLLECTION]))) # act actual = (Pipes( iterator.gen()).uniq(hash_fn=lambda x: hash(x['color'])).count()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def example2(): """Demonstrates, flatmap, sort, uniq, and parallel processing """ def has_red_color(item): return item['color'] == 'red' with Pipes(_EXAMPLE_COLLECTION, num_threads=4) as p: sorted_unique_red_items = (p.lz_filter(has_red_color).flat_map( lambda x: x['items']).sort().uniq().apply()) print(f'Number of items for red circles = {sorted_unique_red_items}')
def get_data_from_sensor(sensor_name): FIFO_NAME = Pipes.FIFO_REQUEST FIFO_NAME_ANSWER = Pipes.FIFO_ANSWER my_answer_pipe = Pipes() fifo_writer = os.open(FIFO_NAME, os.O_WRONLY) ret_val = "NOK", 400 try: my_answer_thread = Thread(target=my_answer_pipe.listening_pipe, args=(FIFO_NAME_ANSWER, )) my_answer_thread.start() message = create_msg(b"Hello sensor") os.write(fifo_writer, message) my_answer_thread.join() my_answer_pipe.kill_all_threads() ret_val = jsonify({"message": str(decode_value(my_answer_pipe.get_received_data()))}) except KeyboardInterrupt as kdb_ex: print('Closing...') finally: os.close(fifo_writer) return ret_val
def main(): pygame.display.set_caption(TITLE) crashed = False while not crashed: if GAMESTATE.changed(): if GAMESTATE.get() == 0: backgroundGroup = Backgrounds() groundGroup = Grounds() menuGroup = pygame.sprite.Group(Menu(0)) GROUPS.add(backgroundGroup, groundGroup, menuGroup) elif GAMESTATE.get() == 1: birdGroup = Birds() backgroundGroup = Backgrounds() pipeGroup = Pipes(birdGroup.getBird()) groundGroup = Grounds() scoreGroup = Scores() GROUPS.add(backgroundGroup, pipeGroup, groundGroup, birdGroup, scoreGroup) elif GAMESTATE.get() == 2: menuGroup = pygame.sprite.Group(Menu(1)) GROUPS.add(menuGroup) else: crashed = True for event in pygame.event.get(): if event.type == pygame.QUIT: crashed = True elif event.type == pygame.KEYDOWN or event.type == pygame.MOUSEBUTTONDOWN: if GAMESTATE.get() == 0: GAMESTATE.set(1) elif GAMESTATE.get() == 1: birdGroup.getBird().bounce() elif GAMESTATE.get() == 2: GAMESTATE.set(0) else: crash = True GROUPS.update() GROUPS.draw(DISPLAY) pygame.display.update() CLOCK.tick(TICKRATE) pygame.quit() quit()
def test_map_group_by(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = { key: len(list(group)) for key, group in groupby([e for e in _KNOWN_COLLECTION], lambda x: x['color']) } # act actual = (Pipes(iterator.gen()).lz_map(lambda x: x).group_by( lambda x: x['color'], group_fn=lambda group: len(list(group)))) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def main(): global log, port, pipes, db, test_mode # Be sure we have root privileges if os.geteuid() != 0: exit("You need to have root privileges. Exiting.") # Ctrl-C and SIGTERM handler signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # Parse arguments, use file docstring as a parameter definition args = docopt.docopt(__doc__, version='0.1a') # Create directory if it doesn't exist futil = FileUtil(".opendoord") print("Path: %s, args: %s" % (futil.path, args)) # Create a logger if args["--console"]: log = Logger.get(verbose=True) else: log = Logger.get(futil.path + "/opendoor.log", verbose=args["--verbose"]) log.info("*** Start OpenDoor ***") # Get access to the database handler db = Sqlite(futil.path + "/opendoor.db", log) if not db.exist(): log.info("No database found. Will create one.") db.create_tables() # if not already created db.reset_tables() # and initialize if args["--test"]: test_mode = True # Let's initialize the gpio's port = Port(log, test_mode) # Open the pipes pipes = Pipes(log, port, db) if args["--resetdb"]: db.reset_tables() log.info("Database has been reset.") else: log.info("Watch door events in an endless loop.") opendoor_endless_loop()
def test_map_flat_map_count(): # arrange iterator = _CountableIterator(_KNOWN_COLLECTION) expected = len([ x for x in [ e.upper() for e in chain.from_iterable( [e['items'] for e in _KNOWN_COLLECTION]) ] if x == 'A' ]) # act actual = ( Pipes( iterator.gen()).lz_map(lambda x: x).flat_map(lambda x: x['items']). lz_map(lambda x: x.upper()).lz_filter(lambda x: x == 'A').count()) # assert assert actual == expected _assert_linear_performance(iterator, _KNOWN_COLLECTION)
def example3(): """Demonstrates exception handling, peek, reduce. """ def square_and_raise_on_3(x): if x == 3: raise ValueError('unaccepted value') return x**2 result = (Pipes(_EXAMPLE_COLLECTION).lz_map(lambda x: x['size']).lz_peek( lambda x: LOG.debug(f'value={x}')).lz_filter( square_and_raise_on_3, error_log_fn=lambda x, v, nv: LOG.error( f'Error: "{x}" for val = {v}, defaulting to {nv}'), error_val_fn=lambda x: x * 100, ).reduce(lambda a, b: a + b, init_val=0)) print(f'map/reduce result = {result}')
def example5(): """Demonstrates streams. """ def gen(): for i in range(1000): yield i items = [] with Pipes(gen(), num_threads=8) as pipes: generator = pipes.lz_map(lambda x: x**2).stream() while True: try: v = next(generator) items.append(v) except StopIteration: break print(f'total items = {len(items)}')
RESET = 4 QUIT = 5 pygame.init() game_display = pygame.display.set_mode((config.WIDTH, config.HEIGHT)) pygame.display.set_caption('Flappy bird') clock = pygame.time.Clock() crashed = False game_state = GameState.NOT_START bird = Bird() pipes = Pipes() monitor = Monitor() count = 0 while game_state != GameState.QUIT: if game_state == GameState.RESET: bird.reset() pipes.reset() monitor.reset() count = 0 game_state = GameState.NOT_START for event in pygame.event.get(): if event.type == pygame.QUIT:
Walls.placeWalls(brd) l = brd.length Brick_coordinates = [[12,28,1],[12,40,1],[12,56,1],[12,48,1],[12,52,2],[12,44,1],[6,48,1],[12,264,1],[12,268,1],[12,272,2],[6,276,1],[6,280,1],[6,284,1],[6,288,1],[6,292,1],[6,304,1],[6,308,1],[6,312,1],[6,316,1],[12,316,1],[12,324,1],[12,328,1],[12,338,1],[12,348,1],[12,358,1],[6,348,1],[12,370,1],[6,374,1],[6,378,1],[6,381,1],[6,393,1],[6,397,1],[6,401,1],[6,405,1],[12,397,1],[12,401,1],[12,522,1],[12,526,1],[12,530,1],[12,534,1]] Pipe_coordinates = [[brd.length-8,68],[brd.length-8,110],[brd.length-8,152],[brd.length-8,200],[l-8,510],[l-8,550]] Holes_coordinates = [[brd.length-2,248],[brd.length-2,290],[l-2,486],[l-2,488]] Stair_coordinates = [[brd.length-4,418],[brd.length-4,422],[brd.length-4,426],[brd.length-4,430],[brd.length-6,422],[l-6,426],[l-6,430],[l-8,426],[l-8,430],[l-10,430],[brd.length-4,454],[brd.length-4,450],[brd.length-4,446],[brd.length-4,442],[brd.length-6,450],[l-6,446],[l-6,442],[l-8,446],[l-8,442],[l-10,442],[l-4,466],[l-4,470],[l-4,474],[l-4,478],[l-4,482],[l-6,470],[l-6,474],[l-6,478],[l-6,482],[l-8,474],[l-8,478],[l-8,482],[l-10,478],[l-10,482],[l-4,492],[l-4,496],[l-4,500],[l-4,504],[l-6,492],[l-6,496],[l-6,500],[l-8,492],[l-8,496],[l-10,492],[l-4,554],[l-4,558],[l-4,562],[l-4,566],[l-4,570],[l-4,574],[l-6,558],[l-6,562],[l-6,566],[l-6,570],[l-6,574],[l-8,562],[l-8,566],[l-8,570],[l-8,574],[l-10,566],[l-10,570],[l-10,574],[l-12,570],[l-12,574],[l-14,574]] Enem_coordinates = [[l-4,120],[l-4,208],[l-4,124,-1],[l-4,240],[l-4,255,-1],[l-4,270,1],[l-4,305],[l-4,310],[l-4,370,-1],[l-4,520]] Cloud_coordinates = [[0,10],[0,75],[0,100],[0,150],[0,230],[0,350],[0,400],[0,450],[0,500],[0,550]] for cord in Brick_coordinates: bricks = Bricks(2,4,cord[2]) bricks.setPosition(cord[0],cord[1]) bricks.placebrick(brd) Rem.lis.append(bricks) for cord in Pipe_coordinates: bricks = Pipes(6,4) bricks.setPosition(cord[0],cord[1]) bricks.placebrick(brd) for cord in Holes_coordinates: bricks = Holes(2,4) bricks.setPosition(cord[0],cord[1]) bricks.placebrick(brd) for cord in Stair_coordinates: bricks = Stair(2,4) bricks.setPosition(cord[0],cord[1]) bricks.placebrick(brd) for cord in Cloud_coordinates: bricks = Clouds(4,6)