Ejemplo n.º 1
0
class ColorDemo(Application):
    generators = [gen_random_flashing, gen_sweep_async, gen_sweep_rand, ]

    def __init__(self, parser, animations):
        Application.__init__(self, parser)
        config = animations[self.args.type]
        self.durations = [int(config['dur_min']*config['rate']), int(config['dur_max']*config['rate'])]
        self.rate = Rate(config['rate'])
        self.colors = config['colors']
        self.generator = self.generators[config['generator_id']]

    def run(self):
        # Construct all pixel generators
        generators = []
        for h in xrange(self.height):
            line = []
            for w in xrange(self.width):
                duration = random.randrange(0, self.durations[1]-self.durations[0])
                line.append(self.generator(self.durations[0], int(2./self.rate.sleep_dur), duration, self.colors))
            generators.append(line)

        # Browse all pixel generators at each time
        while True:
            with self.model:
                for h in xrange(self.height):
                    for w in xrange(self.width):
                        try:
                            color = next(generators[h][w])
                        except StopIteration:
                            pass
                        else:
                            self.model.set_pixel(h, w, color)
            self.rate.sleep()
Ejemplo n.º 2
0
    def run(self):
        pa = pyaudio.PyAudio()
        num_bands = self.width if self.args.vertical else self.height
        num_bins = self.height if self.args.vertical else self.width
        self.renderer = Renderer(self.model, self.height, self.width, num_bins, num_bands, self.args.vertical)

        input_device_info = pa.get_default_input_device_info()
        self.framerate = int(input_device_info['defaultSampleRate'])

        stream = pa.open(format=pyaudio.paFloat32,
                         channels=1,
                         rate=self.framerate,
                         output=False,
                         input=True,
                         stream_callback=self.callback)

        stream.start_stream()

        if self.args.scan_devices:
            files = []
            self.get_playable_files('/media/', files)
            print("{} playable files found.".format(len(files)))
            if len(files) > 0:
                self.subprocess = Popen(['mplayer', choice(files), '-novideo'])
                signal(SIGINT, self.signal_handler)
                self.subprocess.wait()
        else:
            rate = Rate(5)
            while stream.is_active():
                rate.sleep()

        stream.close()
        pa.terminate()
Ejemplo n.º 3
0
    def run(self):

        # Update the screen every second.
        rate = Rate(1.0)

        tick_second = False

        while True:
            with self.model:
                # Get the current time.
                now = datetime.datetime.today()
                hour = now.hour
                minute = now.minute

                # Extract the digits of each number in order to draw them
                # separately.
                hour_digits = self.extract_digits(hour)
                minute_digits = self.extract_digits(minute)

                # Display digits on the screen.
                self.draw_row(0, hour_digits)
                self.draw_row(1, minute_digits)

                # Flash the separator every two seconds.
                self.flash_separator(tick_second)
            tick_second = not tick_second

            rate.sleep()
Ejemplo n.º 4
0
    def run(self):
        rate = Rate(self.rate)

        self.model.set_all(self.BG_COLOR)
        self.model.set_pixel(self.HEAD[0], self.HEAD[1], self.PIXEL_COLOR)
        self.spawn_food(self.start_food)
        for x, y in self.FOOD_POSITIONS:
            self.model.set_pixel(x, y, self.FOOD_COLOR)

        while True:
            rate.sleep_dur = 1.0 / self.rate
            with self.model:
                self.process_events()
                new_pos = ((self.HEAD[0] + self.DIRECTION[0]) % self.height,
                           (self.HEAD[1] + self.DIRECTION[1]) % self.width)
                #check
                if new_pos in self.queue:
                    break

                self.HEAD = new_pos
                self.model.set_pixel(new_pos[0], new_pos[1], self.PIXEL_COLOR)
                self.queue.append(new_pos)

                if new_pos not in self.FOOD_POSITIONS:
                    x, y = self.queue.pop(0)
                    self.model.set_pixel(x, y, self.BG_COLOR)
                    self.process_extras(x, y)
                else:
                    del self.FOOD_POSITIONS[new_pos]
                    self.spawn_food(1)
                    self.rate += self.rate_increase
                    self.process_extras()
            rate.sleep()
        self.game_over()
        exit()
Ejemplo n.º 5
0
    def run(self):
        rate = Rate(self.rate)

        self.model.set_all(self.BG_COLOR)
        self.model.set_pixel(self.HEAD[0],self.HEAD[1],self.PIXEL_COLOR)
        self.spawn_food(self.start_food)
        for x,y in self.FOOD_POSITIONS:
            self.model.set_pixel(x, y, self.FOOD_COLOR)

        while True:
            rate.sleep_dur=1.0/self.rate
            with self.model:
                self.process_events()
                new_pos=((self.HEAD[0]+self.DIRECTION[0])%self.height, (self.HEAD[1]+self.DIRECTION[1])%self.width)
                #check
                if new_pos in self.queue:
                    break


                self.HEAD=new_pos
                self.model.set_pixel(new_pos[0],new_pos[1],self.PIXEL_COLOR)
                self.queue.append(new_pos)

                if new_pos not in self.FOOD_POSITIONS:
                    x, y=self.queue.pop(0)
                    self.model.set_pixel(x, y, self.BG_COLOR)
                    self.process_extras(x, y)
                else:
                    del self.FOOD_POSITIONS[new_pos]
                    self.spawn_food(1)
                    self.rate+=self.rate_increase
                    self.process_extras()
            rate.sleep()
        self.game_over()
        exit()
Ejemplo n.º 6
0
    def run(self):

        # Update the screen every second.
        rate = Rate(1.0)

        tick_second = False

        while True:
            with self.model:
                # Get the current time.
                now = datetime.datetime.today()
                hour = now.hour
                minute = now.minute

                # Extract the digits of each number in order to draw them
                # separately.
                hour_digits = self.extract_digits(hour)
                minute_digits = self.extract_digits(minute)

                # Display digits on the screen.
                self.draw_row(0, hour_digits)
                self.draw_row(1, minute_digits)

                # Flash the separator every two seconds.
                self.flash_separator(tick_second)
            tick_second = not tick_second

            rate.sleep()
Ejemplo n.º 7
0
 def run(self):
     # Update the screen every second.
     rate = Rate(2.0)
     for w in range(self.width):
         for h in range(self.height):
             with self.model:
                 self.model.set_pixel(h, w, self.colors[self.color_index])
             rate.sleep()
         self.color_index = (self.color_index +1) % len(self.colors)
Ejemplo n.º 8
0
    def run(self):
        rate = Rate(self.rate)
        self.model.set_all(self.BG_COLOR)
        self.model.set_pixel(self.HEAD1[0],self.HEAD1[1],self.P1COLOR)
        self.model.set_pixel(self.HEAD2[0],self.HEAD2[1],self.P2COLOR)

        self.spawn_food(self.start_food)
        for x,y in self.FOOD_POSITIONS:
            self.model.set_pixel(x, y, self.FOOD_COLOR)

        while True:
            rate.sleep_dur=1.0/self.rate
            with self.model:
                self.process_events()
                new_pos=((self.HEAD1[0]+self.DIRECTION1[0])%self.height, (self.HEAD1[1]+self.DIRECTION1[1])%self.width)
                new_pos2=((self.HEAD2[0]+self.DIRECTION2[0])%self.height, (self.HEAD2[1]+self.DIRECTION2[1])%self.width)

                #check
                if new_pos in self.queue1 or new_pos in self.queue2:
                    gagnant="J2"
                    break

                if new_pos2 in self.queue2 or new_pos2 in self.queue1:
                    gagnant="J1"
                    break

                self.HEAD1=new_pos
                self.HEAD2=new_pos2

                self.model.set_pixel(new_pos[0],new_pos[1],self.P1COLOR)
                self.model.set_pixel(new_pos2[0],new_pos2[1],self.P2COLOR)

                self.queue1.append(new_pos)
                self.queue2.append(new_pos2)

                if new_pos not in self.FOOD_POSITIONS:
                    x, y=self.queue1.pop(0)
                    self.model.set_pixel(x, y, self.BG_COLOR)
                    self.process_extras(x, y)
                else:
                    del self.FOOD_POSITIONS[new_pos]
                    self.spawn_food(1)
                    self.rate+=self.rate_increase
                    self.process_extras()

                if new_pos2 not in self.FOOD_POSITIONS:
                    x, y=self.queue2.pop(0)
                    self.model.set_pixel(x, y, self.BG_COLOR)
                    self.process_extras(x, y)
                else:
                    del self.FOOD_POSITIONS[new_pos2]
                    self.spawn_food(1)
                    self.rate+=self.rate_increase
                    self.process_extras()
            rate.sleep()
        self.game_over(gagnant)
        exit()
Ejemplo n.º 9
0
 def run(self):
     # Update the screen every second.
     rate = Rate(2.0)
     for w in range(self.width):
         for h in range(self.height):
             with self.model:
                 self.model.set_pixel(h, w, self.colors[self.color_index])
             rate.sleep()
         self.color_index = (self.color_index + 1) % len(self.colors)
Ejemplo n.º 10
0
class Bounces(Application):
    def __init__(self, parser, rate):
        Application.__init__(self, parser)
        self.balls = []
        self.rate = Rate(rate)

        def rand():
            return choice([-1, 1]) * uniform(1. / rate, 10. / rate)

        for ball in range(4):
            self.balls.append(
                Ball(ball, randint(0, self.height - 1),
                     randint(0, self.width - 1), self.height, self.width,
                     Ball.colors[ball % len(Ball.colors)], rand(), rand()))

        # Motion control via Leap Motion
        self.swipe = [None]
        self.swipe_lock = RLock()

        if leapmotion:
            self.leap_listener = SampleListener(self.swipe, self.swipe_lock)
            self.controller = Controller()
            self.controller.add_listener(self.leap_listener)

    def close(self, reason='unknown'):
        Application.close(self, reason)
        if leapmotion:
            self.controller.remove_listener(self.leap_listener)

    def render(self):
        with self.model:
            self.model.set_all('black')
            with self.swipe_lock:
                for ball in self.balls:
                    self.model.set_pixel(ball.x, ball.y, ball.color)
                    if self.swipe[0] is not None:
                        # mapping axes (height, width) of Arbalet on axes (x, z) of Leap Motion
                        x_speed_boost = self.swipe[0].direction[
                            0] * self.swipe[0].speed / 500.
                        y_speed_boost = self.swipe[0].direction[
                            2] * self.swipe[0].speed / 500.
                        ball.x_speed += x_speed_boost
                        ball.y_speed += y_speed_boost
                self.swipe[0] = None

    def run(self):
        while True:
            for ball in self.balls:
                ball.step_forward()
            self.render()
            self.rate.sleep()
Ejemplo n.º 11
0
class Bounces(Application):

    def __init__(self, parser, rate):
        Application.__init__(self, parser)
        self.balls = []
        self.rate = Rate(rate)

        def rand():
            return choice([-1, 1])*uniform(1./rate, 10./rate)

        for ball in range(4):
            self.balls.append(Ball(ball, randint(0, self.height-1), randint(0, self.width-1),
                                   self.height, self.width,
                                   Ball.colors[ball%len(Ball.colors)],
                                   rand(), rand()))

        # Motion control via Leap Motion
        self.swipe = [None]
        self.swipe_lock = RLock()

        if leapmotion:
            self.leap_listener = SampleListener(self.swipe, self.swipe_lock)
            self.controller = Controller()
            self.controller.add_listener(self.leap_listener)

    def close(self, reason='unknown'):
        Application.close(self, reason)
        if leapmotion:
            self.controller.remove_listener(self.leap_listener)

    def render(self):
        with self.model:
            self.model.set_all('black')
            with self.swipe_lock:
                for ball in self.balls:
                    self.model.set_pixel(ball.x, ball.y, ball.color)
                    if self.swipe[0] is not None:
                        # mapping axes (height, width) of Arbalet on axes (x, z) of Leap Motion
                        x_speed_boost = self.swipe[0].direction[0] * self.swipe[0].speed / 500.
                        y_speed_boost = self.swipe[0].direction[2] * self.swipe[0].speed / 500.
                        ball.x_speed += x_speed_boost
                        ball.y_speed += y_speed_boost
                self.swipe[0] = None

    def run(self):
        while True:
            for ball in self.balls:
                ball.step_forward()
            self.render()
            self.rate.sleep()
Ejemplo n.º 12
0
class Life(Application):
    def __init__(self, parser, rate):
        Application.__init__(self, parser)
        self.rate = Rate(rate)
        self.t = Table(self.height, self.width, 3)
        print(self.t.table)

    def close(self, reason='unknown'):
        Application.close(self, reason)

    def render(self):
        with self.model:
            self.model.set_all('black')
            self.model.data_frame
            for y in range(0, self.height):
                for x in range(0, self.width):
                    if (self.t.table[y][x] == 1):
                        self.model.set_pixel(
                            y, x,
                            array((uniform(0, 1), uniform(0, 1), uniform(0,
                                                                         1))))

    def turn(self):
        """Turn"""
        nt = copy.deepcopy(self.t.table)
        with self.model:
            self.model.set_all('black')
            self.model.data_frame
            for y in range(0, self.height):
                for x in range(0, self.width):
                    neighbours = self.t.liveNeighbours(y, x)
                    if self.t.table[y][x] == 0:
                        if neighbours == 3:
                            nt[y][x] = 1
                    else:
                        if (neighbours < 2) or (neighbours > 3):
                            nt[y][x] = 0
            self.t.table = nt

    def run(self):
        while True:
            self.turn()
            self.render()
            for i in range(10):
                self.rate.sleep()
Ejemplo n.º 13
0
class ColorDemo(Application):
    generators = [
        gen_random_flashing,
        gen_sweep_async,
        gen_sweep_rand,
    ]

    def __init__(self, parser, animations):
        Application.__init__(self, parser)
        config = animations[self.args.type]
        self.durations = [
            int(config['dur_min'] * config['rate']),
            int(config['dur_max'] * config['rate'])
        ]
        self.rate = Rate(config['rate'])
        self.colors = config['colors']
        self.generator = self.generators[config['generator_id']]

    def run(self):
        # Construct all pixel generators
        generators = []
        for h in xrange(self.height):
            line = []
            for w in xrange(self.width):
                duration = random.randrange(
                    0, self.durations[1] - self.durations[0])
                line.append(
                    self.generator(self.durations[0],
                                   int(2. / self.rate.sleep_dur), duration,
                                   self.colors))
            generators.append(line)

        # Browse all pixel generators at each time
        while True:
            with self.model:
                for h in xrange(self.height):
                    for w in xrange(self.width):
                        try:
                            color = next(generators[h][w])
                        except StopIteration:
                            pass
                        else:
                            self.model.set_pixel(h, w, color)
            self.rate.sleep()
Ejemplo n.º 14
0
    def run(self):
        pa = pyaudio.PyAudio()
        num_bands = self.width if self.args.vertical else self.height
        num_bins = self.height if self.args.vertical else self.width
        self.renderer = Renderer(self.model, self.height, self.width, num_bins, num_bands, self.args.vertical)

        input_device_info = pa.get_default_input_device_info()
        self.framerate = int(input_device_info['defaultSampleRate'])

        stream = pa.open(format=pyaudio.paFloat32,
                         channels=1,
                         rate=self.framerate,
                         output=False,
                         input=True,
                         stream_callback=self.callback)

        stream.start_stream()

        rate = Rate(5)
        while stream.is_active():
            rate.sleep()

        stream.close()
        pa.terminate()
Ejemplo n.º 15
0
class LightsHero(Application):
    def __init__(self, argparser, num_lanes, path, speed):
        Application.__init__(self, argparser, touch_mode='columns')
        self.arbalet.touch.set_keypad(False)
        self.num_lanes = num_lanes
        self.score = 0
        self.speed = float(speed)
        self.rate = Rate(self.speed)
        self.grid = [['background']*num_lanes for h in range(self.height)] # The coming notes (last line included even if it will overwritten by the bottom bar)
        self.bar = ['idle']*num_lanes # The bottom bar, idle = not pressed, hit = pressed during a note, pressed = pressed outside a note

        # Threads creation and starting
        self.renderer = Renderer(self.model, self.grid, self.bar, self.height, num_lanes, self.width)
        self.reader = SongReader(path, num_lanes, self.args.level, speed)
        self.sound = SoundManager(path)
        self.hits = UserHits(self.num_lanes, self.arbalet, self.sound, self.args.simulate_player)

    def next_line(self):
        # Delete the last line leaving the grid
        # Note : The bottom bar will overwrite the last line but the latter needs to be kept to draw the bottom bar
        for l in range(self.height-1, 0, -1):
            for w in range(self.num_lanes):
                self.grid[l][w] = self.grid[l-1][w]

        # Ask for a new line to the song reader and fill the top of the grid with it
        new_line = self.reader.read()
        for lane in range(self.num_lanes):
            self.grid[0][lane] = new_line[lane]

    def process_user_hits(self):
        """
        Read user inputs, update the bottom bar with key states and warn the UserHits class to update the score
        """
        for lane in range(self.num_lanes):
            must_press = self.grid[self.height-1][lane] == 'active' or self.grid[self.height-1][lane] == 'bump'
            pressed = self.hits.get_pressed_keys()[lane]
            if must_press and pressed:
                status = 'hit'
            elif pressed:
                status = 'pressed'
            else:
                status = 'idle'
            self.bar[lane] = status

            # warn the user hits class whether the note has to be played
            self.hits.set_note(lane, self.grid[self.height-1][lane] in ['bump', 'active'])

    def display_score(self):
        levels = [15, 40, 60, 80, 90, 101]
        sentences = ["did you really play?", "you need to practice...", "I'm pretty sure you can do better...",
                    "that's a fair score!", "awesome, you're a master!", "incredible, did you cheat?"]
        colors = ['darkred', 'orange', 'gold', 'yellowgreen', 'green', 'white']
        score = int((100.*self.hits.score)/self.hits.max_score)

        for i, level in enumerate(levels):
            if score<level:
                sentence = sentences[i]
                color = colors[i]
                break

        print("You scored", score, '% with', self.hits.score, 'hits over', self.hits.max_score)

        if self.hits.score>0:
            self.model.write("You scored {}%, {}".format(score, sentence), color)

    def run(self):
        countdown = self.height # Countdown triggered after Midi's EOF
        start = time()

        # We loop while the end countdown is not timed out
        # it starts decreasing only when EOF is returned by the song reader
        while countdown>0:
            self.next_line()
            self.process_user_hits()
            self.renderer.update_view()

            if self.reader.eof:
                countdown -= 1

            # delayed sound playing while the first notes are reaching the bottom bar
            if not self.sound.started and time()-start > (self.height-2)/self.speed:
                self.sound.start()

            self.rate.sleep()
        self.display_score()
Ejemplo n.º 16
0
class LightsHero(Application):
    def __init__(self, argparser, num_lanes, path, speed):
        Application.__init__(self, argparser, touch_mode='columns')
        self.arbalet.touch.set_keypad(False)
        self.num_lanes = num_lanes
        self.score = 0
        self.speed = float(speed)
        self.rate = Rate(self.speed)
        self.grid = [
            ['background'] * num_lanes for h in range(self.height)
        ]  # The coming notes (last line included even if it will overwritten by the bottom bar)
        self.bar = [
            'idle'
        ] * num_lanes  # The bottom bar, idle = not pressed, hit = pressed during a note, pressed = pressed outside a note

        # Threads creation and starting
        self.renderer = Renderer(self.model, self.grid, self.bar, self.height,
                                 num_lanes, self.width)
        self.reader = SongReader(path, num_lanes, self.args.level, speed)
        self.sound = SoundManager(path)
        self.hits = UserHits(self.num_lanes, self.arbalet, self.sound,
                             self.args.simulate_player)

    def next_line(self):
        # Delete the last line leaving the grid
        # Note : The bottom bar will overwrite the last line but the latter needs to be kept to draw the bottom bar
        for l in range(self.height - 1, 0, -1):
            for w in range(self.num_lanes):
                self.grid[l][w] = self.grid[l - 1][w]

        # Ask for a new line to the song reader and fill the top of the grid with it
        new_line = self.reader.read()
        for lane in range(self.num_lanes):
            self.grid[0][lane] = new_line[lane]

    def process_user_hits(self):
        """
        Read user inputs, update the bottom bar with key states and warn the UserHits class to update the score
        """
        for lane in range(self.num_lanes):
            must_press = self.grid[self.height -
                                   1][lane] == 'active' or self.grid[
                                       self.height - 1][lane] == 'bump'
            pressed = self.hits.get_pressed_keys()[lane]
            if must_press and pressed:
                status = 'hit'
            elif pressed:
                status = 'pressed'
            else:
                status = 'idle'
            self.bar[lane] = status

            # warn the user hits class whether the note has to be played
            self.hits.set_note(
                lane, self.grid[self.height - 1][lane] in ['bump', 'active'])

    def display_score(self):
        levels = [15, 40, 60, 80, 90, 101]
        sentences = [
            "did you really play?", "you need to practice...",
            "I'm pretty sure you can do better...", "that's a fair score!",
            "awesome, you're a master!", "incredible, did you cheat?"
        ]
        colors = ['darkred', 'orange', 'gold', 'yellowgreen', 'green', 'white']
        score = int((100. * self.hits.score) / self.hits.max_score)

        for i, level in enumerate(levels):
            if score < level:
                sentence = sentences[i]
                color = colors[i]
                break

        print("You scored", score, '% with', self.hits.score, 'hits over',
              self.hits.max_score)

        if self.hits.score > 0:
            self.model.write("You scored {}%, {}".format(score, sentence),
                             color)

    def run(self):
        countdown = self.height  # Countdown triggered after Midi's EOF
        start = time()

        # We loop while the end countdown is not timed out
        # it starts decreasing only when EOF is returned by the song reader
        while countdown > 0:
            self.next_line()
            self.process_user_hits()
            self.renderer.update_view()

            if self.reader.eof:
                countdown -= 1

            # delayed sound playing while the first notes are reaching the bottom bar
            if not self.sound.started and time() - start > (self.height -
                                                            2) / self.speed:
                self.sound.start()

            self.rate.sleep()
        self.display_score()