Пример #1
0
 def __init__(self):
     self.sp = SoundPlayer(
         sound_dir='/home/thanh/catkinws/src/mira_sound/data')
     rospy.init_node('mira_sound', anonymous=True)
     rospy.Subscriber("/mira_sound/input", Int8, self.callback)
     rospy.Subscriber('/mira_sound/exit', Int8, self.exit_callback)
     # rospy.loginfo("Sound handler ready!")
     rospy.spin()
Пример #2
0
    def __init__(self,
                 fullscreen=False,
                 resolution=None,
                 display_fps=False,
                 sound=True):
        """Initialize Game"""
        gloss.GlossGame.__init__(self, 'Satellife')
        pygame.init()
        pygame.display.set_caption('Game')
        if fullscreen:
            self._set_fullscreen()
        else:
            self._change_resolution(resolution)
        self._screen_center = self.resolution / 2
        self._display_fps = display_fps
        self.speed = 1
        self.zoom = 1
        self._zoom_level = 3.9
        self.changed_scale = True
        self.gcamera = GVector(0, 0)

        # load sounds
        if sound:
            self.soundplayer = SoundPlayer()
        else:
            self.soundplayer = MutePlayer()

        # event handlers
        self.on_mouse_down = self._mouse_click
        self.on_mouse_motion = lambda x: x
        self.on_key_down = self._keypress

        self._menu = Menu(self)
        self.vdebugger = VectorDisplay()
Пример #3
0
async def sound(ctx: Context, *search_terms: str):
    if len(search_terms) == 0:
        await ctx.send("Nothing is not a sound, sorry!")
        return

    sound_player = SoundPlayer.get_or_create(ctx.guild)
    if 'skip' == search_terms[0].lower():
        await sound_player.skip()
    elif 'stop' == search_terms[0].lower():
        await sound_player.stop()
    else:
        await queue_sound(ctx, *search_terms)
Пример #4
0
class MiraSoundHandler():
    def __init__(self):
        self.sp = SoundPlayer(
            sound_dir='/home/thanh/catkinws/src/mira_sound/data')
        rospy.init_node('mira_sound', anonymous=True)
        rospy.Subscriber("/mira_sound/input", Int8, self.callback)
        rospy.Subscriber('/mira_sound/exit', Int8, self.exit_callback)
        # rospy.loginfo("Sound handler ready!")
        rospy.spin()

    def exit_callback(self, data):
        if (data.data == EXIT_SIGNAL):
            rospy.loginfo('Exit signal [%d] received!' % data.data)
            rospy.signal_shutdown('Exit signal received')

    def callback(self, data):
        if (data.data != -1):
            # rospy.loginfo("Received emotion id: %s", (data.data))
            self.sp.change_to_emotion(data.data)
        else:
            rospy.loginfo("Stop playing sound")
Пример #5
0
 def _validate_inputs(dialog_graph: DialogGraph, images: Dict[str, Surface],
                      sound_player: SoundPlayer):
     for node in dialog_graph.nodes():
         if node.graphics.image_ids:
             for image_id in node.graphics.image_ids:
                 if image_id not in images:
                     raise ValueError(
                         f"Invalid config! Graph node '{node.node_id}' refers to missing image: '{image_id}'"
                     )
         if node.sound_id:
             if not sound_player.has_sound(node.sound_id):
                 raise ValueError(
                     f"Invalid config! Graph node '{node.node_id}' refers to missing sound: '{node.sound_id}"
                 )
     background_id = dialog_graph.background_image_id
     if background_id and background_id not in images:
         raise ValueError(
             f"Invalid config! Graph refers to missing background image: '{background_id}'"
         )
Пример #6
0
def start(dialog_filepath: Optional[str] = None,
          image_dir: Optional[str] = None,
          sound_dir: Optional[str] = None):

    pygame.init()
    dialog_font = Font(f"{FONT_DIR}/Monaco.dfont", 17)
    choice_font = Font(f"{FONT_DIR}/Monaco.dfont", 15)

    dialog_graph = load_dialog_from_file(dialog_filepath)

    image_ids = []
    animation_ids = []
    if dialog_graph.background_image_id:
        image_ids.append(dialog_graph.background_image_id)
    for node in dialog_graph.nodes():
        graphics = node.graphics
        if graphics.image_ids:
            image_ids += graphics.image_ids
        if graphics.animation_id:
            animation_ids.append(graphics.animation_id)
    images, animations = load_images(image_dir, image_ids, animation_ids)

    text_blip_sound_id = "text_blip.ogg"
    select_blip_sound_id = "select_blip.ogg"
    sound_ids = [
        n.sound_id for n in dialog_graph.nodes() if n.sound_id is not None
    ]
    sounds = load_sounds(sound_dir, sound_ids)
    sounds[text_blip_sound_id] = load_sound_file(
        str(Path(SOUND_DIR).joinpath(text_blip_sound_id)))
    sounds[select_blip_sound_id] = load_sound_file(
        str(Path(SOUND_DIR).joinpath(select_blip_sound_id)))

    sound_player = SoundPlayer(sounds, sounds[text_blip_sound_id])

    screen = pygame.display.set_mode(SCREEN_SIZE)
    pygame.display.set_caption(dialog_graph.title or dialog_filepath)
    app = App(screen, dialog_font, choice_font, images, animations,
              sound_player, dialog_graph, select_blip_sound_id)
    app.run()
Пример #7
0
 def __init__(self, screen):
     self.screen = screen
     self.save = SaveGame()
     self.sound = SoundPlayer()
     self.menu_font = pygame.font.Font('fonts/GROTESKIA.ttf', 50)
     self.small_font = pygame.font.Font('fonts/C&C Red Alert [INET].ttf', 13)
     self.intro_graphic = pygame.image.load('graphics/background_intro.png').convert()
     self.background = pygame.image.load('graphics/background.png').convert()
     self.background_menu = pygame.image.load('graphics/background_menu.png').convert()
     #self.overlay_won = pygame.image.load('graphics/overlay_background.png').convert()
     self.overlay_won = pygame.Surface(screen.get_size())
     self.overlay_won.fill((0, 0, 0))
     self.overlay_won.set_alpha(128)
     self.won_animation = Animation('graphics/victory.json')
     self.quitting = False
     self.clock = pygame.time.Clock()
     self.menu_options = (Label('Play'),
                          Label('Select Level'),
                          Label('Help'),
                          Label('Credits'),
                          Label('Quit'))
     self.menu_widths = [self.menu_font.size(opt.name)[0] for opt in self.menu_options]
     self.mode = MODE_INTRO
     self.intro_frame = 0
Пример #8
0
class Launcher(object):
    def __init__(self, screen):
        self.screen = screen
        self.save = SaveGame()
        self.sound = SoundPlayer()
        self.menu_font = pygame.font.Font('fonts/GROTESKIA.ttf', 50)
        self.small_font = pygame.font.Font('fonts/C&C Red Alert [INET].ttf', 13)
        self.intro_graphic = pygame.image.load('graphics/background_intro.png').convert()
        self.background = pygame.image.load('graphics/background.png').convert()
        self.background_menu = pygame.image.load('graphics/background_menu.png').convert()
        #self.overlay_won = pygame.image.load('graphics/overlay_background.png').convert()
        self.overlay_won = pygame.Surface(screen.get_size())
        self.overlay_won.fill((0, 0, 0))
        self.overlay_won.set_alpha(128)
        self.won_animation = Animation('graphics/victory.json')
        self.quitting = False
        self.clock = pygame.time.Clock()
        self.menu_options = (Label('Play'),
                             Label('Select Level'),
                             Label('Help'),
                             Label('Credits'),
                             Label('Quit'))
        self.menu_widths = [self.menu_font.size(opt.name)[0] for opt in self.menu_options]
        self.mode = MODE_INTRO
        self.intro_frame = 0

    @property
    def mode(self):
        return self._mode

    @mode.setter
    def mode(self, value):
        self._mode = value
        pygame.key.set_repeat()
        if value == MODE_SELECT_LEVEL:
            world = self.select_list[self.current_menu_item]
            self.select_list = world.levels
            self.current_menu_item = 0
        elif value == MODE_SELECT_WORLD:
            self.current_menu_item = 0
            self.read_level_info()
            self.select_list = sorted(self.worlds.values())
        elif value == MODE_MAIN_MENU:
            self.current_menu_item = 0
            self.select_list = self.menu_options
        elif value == MODE_PLAYING:
            self.screen.fill((0, 0, 0))
            pygame.key.set_repeat(1, 150)

    def select_menu(self):
        option = self.select_list[self.current_menu_item]
        if self.mode == MODE_MAIN_MENU:
            name = option.name
            if name == 'Play':
                self.read_level_info()
                self.current_world, self.level_id = self.save.current()
                self.play()
            elif name == 'Select Level':
                self.mode = MODE_SELECT_WORLD
            elif name == 'Help':
                return False
            elif name == 'Quit':
                self.quitting = True
        elif self.mode == MODE_SELECT_WORLD:
            self.current_world = option.name
            self.mode = MODE_SELECT_LEVEL
        elif self.mode == MODE_SELECT_LEVEL:
            if self.save.available(self.current_world, self.current_menu_item):
                self.level_id = self.current_menu_item
                self.play()
            else:
                return False

        return True

    def read_level_info(self):
        filenames = glob(os.path.join('levels', '*.txt'))
        self.worlds = {}
        for filename in filenames:
            try:
                world = LevelSet(filename)
            except IOError:
                continue
            self.worlds[world.name] = world

    def play(self):
        self.save.set_current(self.current_world, self.level_id)
        self.mode = MODE_PLAYING
        if self.current_world == 'Tutorials':
            if self.level_id == 0:
                self.game = TutorialOne()
            elif self.level_id == 1:
                self.game = TutorialTwo()
            else:
                self.game = game.Game()
        else:
            self.game = game.Game()
        self.renderer = Renderer()
        self.game.loc_from_screen_coords = self.renderer.loc_from_screen_coords
        self.game.load_level(self.worlds[self.current_world].levels[self.level_id].value)
        self.game.start()

    def back(self):
        if self.mode == MODE_MAIN_MENU:
            self.quitting = True
        elif self.mode == MODE_SELECT_WORLD:
            self.mode = MODE_MAIN_MENU
        elif self.mode == MODE_SELECT_LEVEL:
            self.mode = MODE_SELECT_WORLD

    def start(self):
        self.draw()
        while not self.quitting:
            self.clock.tick(game.FRAME_RATE)
            if self.mode == MODE_PLAYING:
                self.game.main_loop()

                if self.game.stopping:
                    if self.game.won:
                        self.mode = MODE_WON
                        self.won_animation.start()
                        continue

                    self.mode = MODE_MAIN_MENU
                    self.draw()
                elif self.game.quitting:
                    self.quitting = True

            elif not self.process_events():
                continue

            self.draw()

    def draw(self):
        if self.mode == MODE_INTRO:
            self.screen.blit(self.intro_graphic, (0, 0))
            alpha = int(max(0, (self.intro_frame - INTRO_DELAY) * 255.0 / (INTRO_FRAMES - INTRO_DELAY)))
            self.background_menu.set_alpha(alpha)
            self.screen.blit(self.background_menu, (0, 0))
            self.intro_frame += 1
            if self.intro_frame > INTRO_FRAMES:
                self.mode = MODE_MAIN_MENU
                self.draw()
        elif self.mode == MODE_MAIN_MENU:
            #self.screen.blit(self.background, (0, 0))
            self.draw_main_menu()
        elif self.mode == MODE_SELECT_WORLD:
            self.screen.blit(self.background, (0, 0))
            self.draw_select_list()
        elif self.mode == MODE_SELECT_LEVEL:
            self.screen.fill((0, 0, 0))
            self.draw_level_list()
        elif self.mode == MODE_PLAYING:
            self.renderer.render(self.game, self.screen)
        elif self.mode == MODE_WON:
            self.renderer.render(self.game, self.screen)
            self.draw_won_overlay()
        pygame.display.flip()

    def draw_won_overlay(self):
        self.screen.blit(self.overlay_won, (0, 0))
        frame = self.won_animation.get_frame()
        if not frame:
            frame = self.won_animation.images[-1]

        w, h = frame.get_rect().size
        x = WINDOW_W / 2 - w / 2
        y = WINDOW_H / 2 - h / 2
        self.screen.blit(frame, (x, y))

        margin = 12
        text = self.menu_font.render('Level complete! Yay!', True, (255, 255, 255))
        text_pos = text.get_rect()
        text_pos.x = WINDOW_W / 2 - text_pos.width / 2
        text_pos.y = y - text_pos.height - margin
        self.screen.blit(text, text_pos)


    def draw_main_menu(self):
        self.screen.blit(self.background_menu, (0, 0))
        height = self.current_menu_item * MENU_ITEM_H + MENU_ITEM_TOP
        width = self.menu_widths[self.current_menu_item]
        self.draw_option_selector(height, width)

    def draw_level_list(self):
        margin = 8
        w = (WINDOW_W - margin) / GRID_COLS - margin
        h = (WINDOW_H - margin) / GRID_COLS - margin
        y = -h
        for i, item in enumerate(self.select_list):
            if i % GRID_COLS == 0:
                x = -w
                y += margin + h
            x += margin + w
            thickness = 4 if i == self.current_menu_item else 1

            completed = self.save.completed(self.current_world, i)
            available = self.save.available(self.current_world, i)
            stats = self.save.stats(self.current_world, i)

            colour = (172, 172, 172) if available else (64, 64, 64)
            if i == self.current_menu_item:
                border = (255, 255, 255) if available else (96, 96, 96)
            else:
                border = colour

            self.screen.fill(border,
                             (x, y, w, h))
            self.screen.fill(colour,
                             (x + thickness, y + thickness, w - 2*thickness, h - 2*thickness))
            id_text = self.menu_font.render(str(i+1), True, (0, 0, 0))
            id_pos = id_text.get_rect()
            id_pos.y = y + margin/2
            id_pos.centerx = x + w/2
            name_text = self.small_font.render(item.name, False, (0, 0, 0))
            name_pos = name_text.get_rect()
            name_pos.bottom = y + h - margin/2
            name_pos.centerx = x + w/2
            if stats:
                turns_text = self.small_font.render('Turns: %d' % stats['turns'], False, (64, 64, 64))
                turns_pos = turns_text.get_rect()
                turns_pos.bottom = id_pos.bottom + margin/2
                turns_pos.centerx = x + w/2
                doors_text = self.small_font.render('Door uses: %d' % stats.get('uses', 0), False, (64, 64, 64))
                doors_pos = doors_text.get_rect()
                doors_pos.top = turns_pos.bottom
                doors_pos.centerx = x + w/2
                self.screen.blit(turns_text, turns_pos)
                self.screen.blit(doors_text, doors_pos)

            self.screen.blit(id_text, id_pos)
            self.screen.blit(name_text, name_pos)

    def draw_select_list(self):
        rendered_items = []
        menu_height = 0
        max_height = 0
        for item in self.select_list:
            rendered_items.append(self.menu_font.render(item.name, True, (255, 255, 255)))
            height = rendered_items[-1].get_height()
            menu_height += height
            max_height = max(height, max_height)

        margin = 3
        menu_top = WINDOW_H / 2 - menu_height / 2 + MENU_OFFSET
        for i, item in enumerate(rendered_items):
            x = WINDOW_W / 2 - item.get_width() / 2
            self.screen.blit(item, (x, menu_top))
            if i == self.current_menu_item:
                #x -= 8 + triangle_x
                self.draw_option_selector(menu_top, item.get_width())

            menu_top += max_height + margin

    def draw_option_selector(self, y, width):
        x = WINDOW_W / 2 - width / 2 - 8 - SELECTOR_W
        pygame.draw.polygon(self.screen,
                            (196, 196, 196),
                            ((x-12, y+SELECTOR_H-12),
                             (x-12, y+SELECTOR_H+12),
                             (x, y+SELECTOR_H)))
        pygame.draw.aalines(self.screen,
                            (255, 255, 255),
                            True,
                            ((x-12, y+SELECTOR_H-12),
                             (x-12, y+SELECTOR_H+12),
                             (x, y+SELECTOR_H)))

        x = WINDOW_W - x - SELECTOR_W
        pygame.draw.polygon(self.screen,
                            (196, 196, 196),
                            ((x+12, y+SELECTOR_H-12),
                             (x+12, y+SELECTOR_H+12),
                             (x, y+SELECTOR_H)))
        pygame.draw.aalines(self.screen,
                            (255, 255, 255),
                            True,
                            ((x+12, y+SELECTOR_H-12),
                             (x+12, y+SELECTOR_H+12),
                             (x, y+SELECTOR_H)))

    def process_events(self):
        if self.mode == MODE_PLAYING:
            return True

        if self.mode == MODE_INTRO:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    self.intro_frame = INTRO_FRAMES

            return True

        if self.mode == MODE_WON:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    self.mode = MODE_SELECT_WORLD
                    self.save.set_completed(self.current_world, self.level_id)
                    self.save.set_stats(self.current_world, self.level_id, self.game.turn, self.game.used_doors())
                    next_level = self.level_id + 1
                    if next_level < len(self.worlds[self.current_world].levels):
                        self.level_id = next_level
                        self.play()
                    elif self.worlds[self.current_world].next:
                        self.current_world = self.worlds[self.current_world].next
                        self.level_id = 0
                        self.play()
                    break

            return True

        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                self.quitting = True
                return False
            if e.type == pygame.KEYDOWN:
                if e.key in game.UP_KEYS:
                    if self.mode == MODE_SELECT_LEVEL:
                        if self.current_menu_item - GRID_COLS >= 0:
                            self.current_menu_item -= GRID_COLS
                        elif self.current_menu_item < len(self.select_list) % GRID_COLS:
                            self.current_menu_item -= len(self.select_list) % GRID_COLS
                        else:
                            self.current_menu_item -= len(self.select_list) % GRID_COLS + GRID_COLS
                    else:
                        self.current_menu_item -= 1
                    self.current_menu_item %= len(self.select_list)
                    self.sound.step()
                    return True
                if e.key in game.DOWN_KEYS:
                    if self.mode == MODE_SELECT_LEVEL:
                        if self.current_menu_item + GRID_COLS < len(self.select_list):
                            self.current_menu_item += GRID_COLS
                        else:
                            self.current_menu_item %= GRID_COLS
                    else:
                        self.current_menu_item += 1
                    self.current_menu_item %= len(self.select_list)
                    self.sound.step()
                    return True
                if e.key in game.LEFT_KEYS and self.mode == MODE_SELECT_LEVEL:
                    self.current_menu_item -= 1
                    self.current_menu_item %= len(self.select_list)
                    self.sound.step()
                    return True
                if e.key in game.RIGHT_KEYS and self.mode == MODE_SELECT_LEVEL:
                    self.current_menu_item += 1
                    self.current_menu_item %= len(self.select_list)
                    self.sound.step()
                    return True
                if e.key in game.ACTION_KEYS:
                    if self.select_menu():
                        self.sound.throw()
                    else:
                        self.sound.land()
                    return True
                if e.key in game.QUIT_KEYS:
                    self.back()
                    self.sound.undo()
                    return True
                if e.key in game.CHEAT_KEYS and self.mode == MODE_SELECT_LEVEL:
                    for id in range(len(self.worlds[self.current_world].levels)):
                        self.save.set_completed(self.current_world, id)
                    return True
Пример #9
0
state = 0x1F
last_state = 0x1F

# Function to init SPI.
def initSPI():
	spi = spidev.SpiDev()
	spi.open(0,0)

	return spi

# Start spi and init Sensors.
spi = initSPI()
sensors = [LaserSensor(port, spi, level) for port in range(5)]

# Init sound
player = SoundPlayer()

try:
	print 'Ready to play...'
	while True:
		state = 0x00		
		for sensor in sensors:
			if (sensor.getState()):
				# Laser on.
				state = state | (1 << sensor.getPort())

		# If any bits have been trun off (laser beam breaked).
		if ((0x1F ^ state) & last_state):
		     	# New sound should be played with the new state (if non change to off expression is false).
		     	#'{0:08b}'.format((int('00011111',2) ^ int('00011010', 2)) & int('00000111',2)) = '00000101'
	     		#	   						31					state               prev
Пример #10
0
    else:
        #print("bad event key!!")
        pass
    return action


# Starting the game components
pygame.init()
pygame.display.set_caption(F.game_name)
board_0 = Board()
board_1 = RightBoard()
status_bar = StatusBar()
gen_ui = GenUI()
DISPLAYSUR = pygame.display.set_mode((F.window_w, F.window_h))
controller = Controller(DISPLAYSUR)
sound_player = SoundPlayer(pygame)
clock = pygame.time.Clock()

# setup a font for displaying block numbers
GFONT = pygame.font.Font('freesansbold.ttf', F.block_font_size)
GFONT_GG = pygame.font.Font('freesansbold.ttf', 66)
GFONTS = [
    pygame.font.Font('freesansbold.ttf',
                     int(F.block_font_size * F.block_font_size_perc[0])),
    pygame.font.Font('freesansbold.ttf',
                     int(F.block_font_size * F.block_font_size_perc[1])),
    pygame.font.Font('freesansbold.ttf',
                     int(F.block_font_size * F.block_font_size_perc[2])),
    pygame.font.Font('freesansbold.ttf',
                     int(F.block_font_size * F.block_font_size_perc[3])),
    pygame.font.Font('freesansbold.ttf',
Пример #11
0
def main():
    pygame.init()
    directory = Path(__file__).parent
    font = Font(str(directory.joinpath("demo_font.dfont")), 13)

    screen_size = (500, 500)
    dialog_margin = 30
    dialog_padding = 5
    outer_dialog_size = (screen_size[0] - dialog_margin * 2, 330)
    dialog_size = (outer_dialog_size[0] - dialog_padding * 2,
                   outer_dialog_size[1] - dialog_padding * 2)
    picture_component_size = (dialog_size[0], 200)

    screen = pygame.display.set_mode(screen_size)
    dialog_surface = Surface(dialog_size)
    dialog_pos = (dialog_margin + dialog_padding,
                  dialog_margin + dialog_padding)
    dialog_rect = Rect(dialog_pos, dialog_size)

    images = {
        "demo1_background": filled_surface(picture_component_size, (0, 50, 35))
    }
    animations = {"demo1_animation": create_animation(picture_component_size)}
    text_blip_sound = load_sound("blip.ogg")
    select_blip_sound = load_sound("blip_2.ogg")
    select_blip_sound_id = "blip"
    sound_player = SoundPlayer(
        sounds={select_blip_sound_id: select_blip_sound},
        text_blip_sound=text_blip_sound)

    dialog_closed_node_id = "DIALOG_CLOSED"
    dialog_graph = DialogGraph(
        root_node_id="ROOT",
        nodes=[
            DialogNode(
                node_id="ROOT",
                text=
                "This is a minimal demo app. Let this text slowly appear or click any key to skip it. "
                "Use the UP/DOWN keys to switch between your dialog choices, and click RETURN to go "
                "for that choice. Or you could just use the mouse!",
                choices=[
                    DialogChoice("See this dialog again", "ROOT"),
                    DialogChoice("Close dialog", dialog_closed_node_id)
                ],
                graphics=NodeGraphics(animation_id="demo1_animation")),
            DialogNode(node_id=dialog_closed_node_id,
                       text="",
                       choices=[],
                       graphics=NodeGraphics(animation_id="demo1_animation")),
        ],
        title="DEMO 1",
        background_image_id="demo1_background")

    pygame.display.set_caption(dialog_graph.title)

    dialog_component = DialogComponent(
        surface=dialog_surface,
        dialog_font=font,
        choice_font=font,
        images=images,
        animations=animations,
        sound_player=sound_player,
        dialog_graph=dialog_graph,
        picture_size=picture_component_size,
        select_blip_sound_id=select_blip_sound_id)

    clock = Clock()

    is_dialog_shown = True

    while True:

        elapsed_time = Millis(clock.tick())

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                _exit_game()
            elif event.type == pygame.KEYDOWN:
                if is_dialog_shown:
                    dialog_component.skip_text()
                    if event.key == pygame.K_RETURN:
                        dialog_component.commit_selected_choice()
                        if dialog_component.current_node_id(
                        ) == dialog_closed_node_id:
                            is_dialog_shown = False
                    elif event.key == pygame.K_DOWN:
                        dialog_component.move_choice_selection(1)
                    elif event.key == pygame.K_UP:
                        dialog_component.move_choice_selection(-1)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                ui_coordinates = translate_screen_to_ui_coordinates(
                    dialog_rect, pygame.mouse.get_pos())
                if ui_coordinates:
                    dialog_component.commit_choice_at_position(ui_coordinates)
                    if dialog_component.current_node_id(
                    ) == dialog_closed_node_id:
                        is_dialog_shown = False
            elif event.type == pygame.MOUSEMOTION:
                ui_coordinates = translate_screen_to_ui_coordinates(
                    dialog_rect, pygame.mouse.get_pos())
                if ui_coordinates:
                    dialog_component.select_choice_at_position(ui_coordinates)

        if is_dialog_shown:
            dialog_component.update(elapsed_time)
            dialog_component.redraw()

        screen.fill(BLACK)
        if is_dialog_shown:
            screen.blit(dialog_component.surface, dialog_pos)
        pygame.draw.rect(screen, (255, 100, 100),
                         Rect((dialog_margin, dialog_margin),
                              outer_dialog_size),
                         width=1)

        fps_string = str(int(clock.get_fps())).rjust(3, ' ')
        rendered_fps = font.render(f"FPS: {fps_string}", True, WHITE,
                                   (0, 0, 0))
        screen.blit(rendered_fps, (5, 5))

        screen.blit(
            font.render(
                "The dialog library is confined to the red rectangle above.",
                True, WHITE), (15, 400))
        screen.blit(
            font.render("This text is handled separately from the dialog.",
                        True, WHITE), (15, 430))
        if not is_dialog_shown:
            screen.blit(
                font.render(
                    "Oops, you closed the dialog. Restart app to see it again.",
                    True, (255, 150, 150)), (15, 460))

        pygame.display.update()
Пример #12
0
import time
from soundfile import SoundFile
from sound import SoundPlayer

blocksize = 1024

player = SoundPlayer(44100, 1)
for block in SoundFile("Mann_short.wav").blocks(blocksize):
    player.play(block)
while player.isplaying:
    time.sleep(0.1)
Пример #13
0
def main():
    try:
        # LED settings
        stand = BallStand()
        stand.run()
        print "stand run"

        led = FullColorLED(stand)
        led.run()
        print "led run"

        # soud settings
        mixer.init(frequency = 22050, size = -16, channels = 2, buffer = 512)
        se = SoundPlayer()
        game = Game()
        print "soud init ok"
        
        # ble connect
        sm = medal.SensorMedal(ROHM_RAW)
        sm.getData()
        print "sensor medal run"

        # motion detect
        m = MotionDetecter(sm)
        m.run()
        print "motion run"

        # start LED color change 
        led.standby = False
        
        # start OK voice
        se.playMotion("kidou")

        cnt = 0
        while True:
            # volume setting
            if se.volume != stand.volume:
                se.volume = stand.volume
            if game.volume != stand.volume:
                game.volume = stand.volume
            
            if stand.mode == 0:
                # ? mode
                if sm.ang_x > 100 or sm.ang_y > 100 or sm.ang_z > 100:
                    se.playSE("byun_w")
                    sleep(1)
                if sm.ang_x < -100 or sm.ang_y < -100 or sm.ang_z < -100:
                    se.playSE("byun_s")
                    sleep(1)
                sleep(SLEEP_SEC)

            if stand.mode == 1:
                # music mode
                if medal.ang_x > 100:
                    se.playSE("do")
                if medal.ang_y > 100:
                    se.playSE("re")
                if medal.ang_z > 100:
                    se.playSE("mi")
                if medal.ang_x < -100:
                    se.playSE("fa")
                if medal.ang_y < -100:
                    se.playSE("so")
                if medal.ang_z < -100:
                    se.playSE("ra")
                sleep(SLEEP_SEC)

            elif stand.mode == 2:
                motion mode
                if m.motion == 1:
                    se.playSE("roll")
                elif m.motion == 2:
                    se.playMotion("hyaa", 1.2)
                elif m.motion == 3:
                    se.playMotion("kyaa", 1.5)
                elif m.motion == 4:
                    se.playMotion("gyaa", 2.0)
                sleep(0.15)

            elif stand.mode == 3:
                # game mode
                while stand.mode == 3:
                    if not game.gaming:
                        if sm.ang_x < 100.0:
                            game.gameStart()
                    else:
                        if game.isLimit():
                            break
                    if game.volume != stand.volume:
                        game.changeVolume(stand.volume)
                    sleep(0.2)
                if game.gaming:
                    game.gameStop()
    
    except KeyboardInterrupt:
        print "Ctl - c"

    except:
        traceback.print_exc()

    finally:
        if game.gaming:
            game.gameStop()
        mixer.quit()
        
        if not m is None:
            m.stop()

        if not led is None:
            led.stop()
            print "led is stopped"
        
        if not stand is None:
            stand.stop()
            print "stand is stopped"

        if not sm is None:
            sm.stop()
            print "getData thread is stop"
            sm.disconnect()
Пример #14
0
 def __init__(self):
     self.sound = SoundPlayer()
Пример #15
0
class Game:
    def __init__(self):
        self.sound = SoundPlayer()

        #self.font = pygame.font.SysFont('Sans', 18)

    def load_level(self, filename):
        self.level_file = filename
        self.level = load_level(self, filename)
        if not self.level:
            self.stopping = True

        self.player = self.level.player

    def can_move_to(self, obj, location):
        tile = self.level[location]
        if not tile:
            return False

        if obj.flag('player') and self.cheating:
            return True

        if obj.special:
            for thing in tile:
                if thing.blocks(obj):
                    return False
            return True

        if tile[0].solid:
            # If the terrain is solid and there is a special object on the tile, use its state.
            for thing in tile[:0:-1]:
                if thing.special:
                    if obj.flag('player'):
                        # Don't allow the player to walk through if they're carrying something
                        # that the special object blocks
                        for c in obj.contained:
                            if thing.blocks(c): return False
                    return not thing.solid
            return False
        else:
            for thing in tile[1:]:
                if thing.solid:
                    return False
        return True

    def get_objects_at(self, location, test=None):
        #First item at a location is always terrain
        if test is None:
            return self.level[location][1:]
        else:
            return [obj for obj in self.level[location][1:] if test(obj)]

    @staticmethod
    def coords_in_dir(loc, dir, dist):
        if loc is None:
            return None

        loc = list(loc)
        if dir == LEFT:
            loc[0] -= dist
        elif dir == RIGHT:
            loc[0] += dist
        elif dir == UP:
            loc[1] -= dist
        elif dir == DOWN:
            loc[1] += dist
        return tuple(loc)

    def used_doors(self):
        return sum([obj.used for obj in self.level.objects if obj.flag('door')])

    def failed_move(self, location):
        pass

    def action(self, direction):
        if self.player.contained:
            if not self.throw(direction):
                self.sound.cancel()
        elif self.pickup(direction):
            pass
        elif self.close(direction):
            pass
        else:
            # Took no action
            return False
        return True

    def pickup(self, direction):
        pickup_loc = self.coords_in_dir(self.player.location, direction, 1)
        self.player.direction = direction

        success = False
        for obj in self.get_objects_at(pickup_loc)[::-1]:
            if obj.flag('door'):
                if self.level[pickup_loc][0].solid and not self.level[self.player.location][0].pickup:
                    continue
                if self.player.add(obj):
                    success = True

        if success:
            self.sound.pickup()

        return success

    def close(self, direction):
        self.player.direction = direction
        close_loc = self.coords_in_dir(self.player.location, direction, 1)
        for obj in self.get_objects_at(close_loc):
            if obj.flag('door') and not obj.solid:
                obj.close()
                return True

    def throw(self, direction):
        self.player.direction = direction
        success = False
        for obj in self.player.contained:
            nextloc = self.coords_in_dir(self.player.location, direction, 1)
            if not self.can_move_to(obj, nextloc):
                continue
            self.player.remove(obj)
            obj.impulse(3, direction)
            self.schedule_update()
            self.player_turn = False
            success = True
        if success:
            self.sound.throw()
        return success

    def win(self):
        #self.quitting = True
        self.player.animate('descending', self.end)
        self.block()
        self.won = True

    def end(self):
        self.stopping = True

    def display_message(self, source, message):
        if message != self.message:
            if message:
                self.msg_anim_frame = 0
            else:
                self.msg_anim_frame = -20

            self.message = message
            self.message_src = source

    def msg_anim_pos(self):
        if self.msg_anim_frame < 24:
            self.msg_anim_frame += 1
        return self.msg_anim_frame / 24.0

    def start(self):
        self.turn = 0
        self.messages = []
        self.msg_anim_frame = 0
        self.state = STATE_NORMAL
        self.cheating = False
        self.player_turn = True
        self.next_turn = 0
        self.next_update = 0
        self.won = False
        self.message = None

        self.stopping = False
        self.quitting = False

        for obj in self.level.objects:
            obj.location = obj.location
            obj.record_state(self.turn)
        if not self.quitting:
            self.update()
        #while not self.quitting:
        #    self.main_loop()

    def main_loop(self):
        self.player_turn = pygame.time.get_ticks() > self.next_turn
        took_turn = self.process_events()
        if took_turn:
            self.next_turn = pygame.time.get_ticks() + TURN_DELAY

        if took_turn or (not self.player_turn and pygame.time.get_ticks() > self.next_update):
            self.update()

    def process_events(self):
        took_turn = False
        if pygame.event.get(pygame.QUIT):
            self.quitting = True
            return False

        if not self.player_turn:
            return False

        held_keys = [key for key in HOLDABLE_KEYS if pygame.key.get_pressed()[key]]
        held_buttons = [button for button in HOLDABLE_BUTTONS if pygame.mouse.get_pressed()[button]]
        if held_keys:
            took_turn = self.keyheld(held_keys)
        elif held_buttons:
            took_turn = self.mouseheld(held_buttons)
        if not took_turn:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    took_turn = self.keypressed(e)
                elif e.type == pygame.MOUSEBUTTONUP:
                    took_turn = self.clicked(e)

        if took_turn:
            self.turn += 1
            for obj in self.level.dynamics:
                obj.record_state(self.turn)

        return took_turn

    def keyheld(self, keys):
        took_turn = False
        if self.state == STATE_NORMAL:
            dirs = [DIR_MAP[key] for key in keys if key in DIR_MAP]
            if len(set(dirs)) == 1:
                dir = dirs[0]
                newloc = self.coords_in_dir(self.player.location, dir, 1)
                self.player.direction = dir
                if newloc != self.player.location:
                    if self.can_move_to(self.player, newloc):
                        self.player.location = newloc
                        self.sound.step()
                        took_turn = True
                    else:
                        self.failed_move(newloc)
                        for thing in self.level[newloc]:
                            if thing.bumped(self.player):
                                took_turn = True
                                break
                return took_turn

        if self.state == STATE_NORMAL or self.state == STATE_LOCKED:
            if filter(keys.__contains__, UNDO_KEYS):
                self.undo()
                self.sound.undo()
                self.state = STATE_NORMAL
                self.next_turn = pygame.time.get_ticks() + TURN_DELAY

        return took_turn

    def mouseheld(self, buttons):
        if len(buttons) == 1 and MOVE_BUTTON in buttons:
            # To move with the mouse, just pretend a key is being held
            dir = self.get_mouse_direction()
            if dir is not None:
                key = I_DIR_MAP[dir]
                return self.keyheld((key,))

        return False

    def keypressed(self, e):
        took_turn = False
        if self.state == STATE_PICK:
            try:
                took_turn = self.pick_direction_done(DIR_MAP[e.key])
            except KeyError:
                self.sound.cancel()
                self.state = STATE_NORMAL
        elif self.state == STATE_NORMAL:
            if e.key in ACTION_KEYS:
                self.pick_direction(self.action)
            elif e.key in CHEAT_KEYS:
                self.cheating = not self.cheating
        elif self.state == STATE_READING:
            if e.key in ACTION_KEYS:
                self.display_message(None, None)

        if self.state != STATE_PICK:
            if e.key in UNDO_KEYS:
                pass
            elif e.key in QUIT_KEYS:
                if self.message:
                    self.display_message(None, None)
                else:
                    self.stopping = True
            elif e.key in RESTART_KEYS:
                self.restart()

        return took_turn

    def clicked(self, e):
        button = e.button - 1
        if self.state == STATE_PICK:
            # Pick state can be entered only with the keyboard; use movement key to pick direction
            dir = self.get_mouse_direction()
            if button == MOVE_BUTTON and dir:
                return self.pick_direction_done(dir)
            else:
                self.sound.cancel()
                self.state = STATE_NORMAL
        elif self.state == STATE_NORMAL:
            if button == ACTION_BUTTON:
                return self.action(self.get_mouse_direction())
        return False

    def pick_direction(self, handler):
        """Enter targeting mode"""
        self.state = STATE_PICK
        self.pick_handler = handler
        self.sound.action()

    def pick_direction_done(self, direction):
        self.state = STATE_NORMAL
        return self.pick_handler(direction)

    def get_mouse_direction(self):
        if not self.player.location:
            return None

        mouse_x, mouse_y = self.loc_from_screen_coords(*(pygame.mouse.get_pos()))
        x, y = self.player.location
        dx, dy = mouse_x - x, mouse_y - y
        if abs(dx) <= 0.5 and abs(dy) <= 0.5:
            return None
        elif dy < 0 and -dy > abs(dx):
            return UP
        elif dy > 0 and dy > abs(dx):
            return DOWN
        elif dx < 0 and -dx >= abs(dy):
            return LEFT
        elif dx > 0 and dx >= abs(dy):
            return RIGHT

    def block(self):
        self.state = STATE_LOCKED

    def unblock(self):
        self.state = STATE_NORMAL

    def schedule_update(self, time=UPDATE_DELAY):
        self.next_update = pygame.time.get_ticks() + time
        self.next_turn = self.next_update + TURN_DELAY

    def update(self):
        # level.objects is a set, so the order of evaluation is undefined
        #self.player_turn = True

        for obj in self.level.dynamics:
            if obj.resolve_movement():
                obj.record_state(self.turn)
                self.schedule_update()

    def restart(self):
        self.load_level(self.level_file)
        self.start()
        #self.turn = 0

        #for obj in self.level.objects:
        #    obj.restore_state(self.turn)

    def undo(self):
        if self.turn == 0:
            return False

        self.turn -= 1

        for obj in self.level.dynamics:
            obj.restore_state(self.turn)