Ejemplo n.º 1
0
def test_play():
    # Playlist 1
    url = "http://www.youtube.com/feeds/videos.xml?playlist_id=PLsH19NHPTD44m-5CCyx5jKLKAGir3iL2L"
    m1 = Music(url=url, tarot=0)
    m2 = Music(url=url, tarot=10)
    m3 = Music(url=url, tarot=12)
    m4 = Music(url=url, tarot=20)
    m5 = Music(url=url, tarot=33)
    m6 = Music(url=url, tarot=41)

    assert m1.play() == "https://www.youtube.com/watch?v=i0A3-wc0rpw"
    assert m2.play() == "https://www.youtube.com/watch?v=McIYdE4s-gY"
    assert m3.play() == "https://www.youtube.com/watch?v=AGlKJ8CHAg4"
    assert m4.play() == "https://www.youtube.com/watch?v=rQD9EBCwlQc"
    assert m5.play() == "https://www.youtube.com/watch?v=Vab5GT1pd1k"
    assert m6.play() == "https://www.youtube.com/watch?v=5kJZuhyFFCQ"

    # Playlist 2
    X = Music(
        "https://www.youtube.com/feeds/videos.xml?playlist_id=PLYyWwMzPI75TID--pLfPUJRjGIQJckSsL",
        1,
    )
    Y = Music(
        "https://www.youtube.com/feeds/videos.xml?playlist_id=PLYyWwMzPI75TID--pLfPUJRjGIQJckSsL",
        3,
    )
    Z = Music(
        "https://www.youtube.com/feeds/videos.xml?playlist_id=PLYyWwMzPI75TID--pLfPUJRjGIQJckSsL",
        5,
    )
    assert X.play() == "https://www.youtube.com/watch?v=1zd0Eqg04Kk"
    assert Y.play() == "https://www.youtube.com/watch?v=aTOu1g5-Z2M"
    assert Z.play() == "https://www.youtube.com/watch?v=1hZa60t8wSE"

    output = Music(
        "https://www.youtube.com/feeds/videos.xml?playlist_id=PLYyWwMzPI75TID--pLfPUJRjGIQJckSsL",
        1,
    )
    assert output.get_links() == [
        "https://www.youtube.com/watch?v=VlP5E5yen7I",
        "https://www.youtube.com/watch?v=1zd0Eqg04Kk",
        "https://www.youtube.com/watch?v=VltAuKIJNZE",
        "https://www.youtube.com/watch?v=aTOu1g5-Z2M",
        "https://www.youtube.com/watch?v=0a-yqNc5JYY",
        "https://www.youtube.com/watch?v=1hZa60t8wSE",
        "https://www.youtube.com/watch?v=NozOwySZiYA",
        "https://www.youtube.com/watch?v=FoYyqHqbnxc",
        "https://www.youtube.com/watch?v=eOliwArdKPs",
        "https://www.youtube.com/watch?v=6yTvuFy9_ik",
        "https://www.youtube.com/watch?v=oxGcr-KrlUA",
        "https://www.youtube.com/watch?v=86Rr_rTdzIo",
        "https://www.youtube.com/watch?v=ueSgCa6KefQ",
        "https://www.youtube.com/watch?v=o5G-Qtf_gac",
        "https://www.youtube.com/watch?v=FwsL5qKzodg",
    ]
Ejemplo n.º 2
0
    def __init__(self):
        self.game_start = False
        self.game_end = False
        self.menu_music_playing = False
        self.won = False
        self.game_music = Music(
            "https://raw.githubusercontent.com/CalhamZeKoala/Games/master/music/DungeonMusic.ogg?token=AuVrB4f-o_7jKhvx9o8zywf9tICgCGp_ks5coU0IwA%3D%3D"
        )

        self.menu_music = Music(
            "https://raw.githubusercontent.com/CalhamZeKoala/Games/master/music/LobbyMusic.ogg?token=AuVrB01tDWNIZM_FEJe1dp2X42W41OC7ks5coVI9wA%3D%3D"
        )

        self.IMG = simplegui.load_image(
            'https://raw.githubusercontent.com/CalhamZeKoala/Games/master/images/Simple_grey.png?token=AexQrWRp93DDGdtspxKgQRIo_NppOK6Gks5coMbQwA%3D%3D'
        )
        self.IMG_CENTRE = (self.IMG.get_width() / 2, self.IMG.get_height() / 2)
        self.IMG_DIMS = (self.IMG.get_width(), self.IMG.get_height())
        self.IMG_Size = (CANVAS_DIMS[0], CANVAS_DIMS[1])
        self.IMG_Pos = (CANVAS_DIMS[0] / 2, CANVAS_DIMS[1] / 2
                        )  # where to draw image

        self.BUTT = simplegui.load_image(
            'https://raw.githubusercontent.com/CalhamZeKoala/Games/master/images/Start_button.png?token=AexQrbMnYHDhtdp3TYrgjTkO46pzViXQks5coMtLwA%3D%3D'
        )
        self.BUTT_CENTRE = (self.BUTT.get_width() / 2,
                            self.BUTT.get_height() / 2)
        self.BUTT_DIMS = (self.BUTT.get_width(), self.BUTT.get_height())
        self.BUTT_Size = self.BUTT_DIMS
        self.BUTT_Pos = (CANVAS_DIMS[0] / 2, CANVAS_DIMS[1] / 2
                         )  # where to draw image

        self.END = simplegui.load_image(
            'https://raw.githubusercontent.com/CalhamZeKoala/GameImg/master/gameover.jpg'
        )
        self.END_CENTRE = (self.END.get_width() / 2, self.END.get_height() / 2)
        self.END_DIMS = (self.END.get_width(), self.END.get_height())
        self.END_Size = (globals.CANVAS_DIMS[0] * 0.7,
                         globals.CANVAS_DIMS[0] * 0.7)
        self.END_Pos = (globals.CANVAS_DIMS[0] / 2, globals.CANVAS_DIMS[1] / 2
                        )  # where to draw image

        self.END_BUTT_Pos = (CANVAS_DIMS[0] / 2, (CANVAS_DIMS[1] / 6) * 5)

        self.WIN = simplegui.load_image(
            'https://raw.githubusercontent.com/CalhamZeKoala/GameImg/master/win.jpg'
        )
        self.WIN_CENTRE = (self.WIN.get_width() / 2, self.WIN.get_height() / 2)
        self.WIN_DIMS = (self.WIN.get_width(), self.WIN.get_height())
        self.WIN_Size = (CANVAS_DIMS[0], CANVAS_DIMS[1])
        self.WIN_Pos = (CANVAS_DIMS[0] / 2, CANVAS_DIMS[1] / 2
                        )  # where to draw image
Ejemplo n.º 3
0
def element_click_cb(e, name):
    global main_alive

    print(name)

    if (main_alive):
        if (name == "Environment"):
            envPage = Environment()
            envPage.createPage()
        elif (name == "Hvac"):
            hvac = Hvac()
            hvac.createPage()
        elif (name == "Compass"):
            compassPage = Compass()
            compassPage.createPage()
        elif (name == "Sound"):
            ttfPage = SoundTTF()
            ttfPage.createPage()
        elif (name == "Music"):
            musicPage = Music()
            musicPage.createPage()
        elif (name == "Timer"):
            timePage = Timer()
            timePage.createPage()

        main_alive = False
Ejemplo n.º 4
0
def run_game():
    pygame.init()
    mus = Music()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    pygame.display.set_caption("Alien Invasion")
    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, "Play")
    sb = Scoreboard(ai_settings, screen, stats)
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
            gf.update_music(mus)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Ejemplo n.º 5
0
def main():
    file_path = 'resources\stars_image.jpg'
    data = processImage(file_path)

    musicObj = Music(data)
    musicObj.generateSongTuple()
    musicObj.generateMusic()
def getobj(tempS):
    theuser = cur_user.getuser_name
    a = np.zeros(shape=[500, 500],
                 dtype=np.float32)  # Q matrix initialized to 0
    b = np.zeros(shape=[500, 500],
                 dtype=np.float32)  # R matrix initialized to 0
    cur = mysql.connection.cursor()
    cur.execute(
        'select rowno from matrixinput where username = %s', (theuser, )
    )  # to see if the user exits. if it does then the result is not null ie. if the rows are fetched.
    if cur.fetchone():  # see if the rows are fetched for a particular user
        for i in range(0, 500):
            for j in range(0, 500):
                cur.execute(
                    "select Qmatrix, Rmatrix from matrixinput where username = %s and rowno = %s and colno = %s",
                    (theuser, i, j))
                tuple_ = cur.fetchone()
                a[i][j] = tuple_[0]  # creating the q matrix from the DB
                b[i][j] = tuple_[1]  # creating the r matrix from the DB
    s = [
    ]  # if the user does not exist then R-matrix and Q-matrix initialized to 0 are used for object creation.
    for i in range(0, 10):
        cur.execute(
            "select Song_id from songs where song = %s", (tempS[i], )
        )  # tempS has 10 songs based on user type. if new user, then random songs. if existing user, then songs that were last reommended to him ie. from before logout table.
        # fetch the actual song id of the 10 songs in tempS from the songs table in DB
        t = cur.fetchone()
        s.append(t[0])

    mysql.connection.commit()
    cur.close()
    # creating an object of music class so as to bring the recommendation model to the updated position of the user.
    myobj = Music(s, a, b)  # song id of playlist, q matrix, r matrix
    return myobj
Ejemplo n.º 7
0
    def __init__(self):
        # set in ready state
        logging.basicConfig(filename='/tmp/float.log', level=logging.INFO)
        self.state = 1
        self.camera = PiCamera()
        self.camera.resolution = RESOLUTION
        self.rawCapture = PiRGBArray(self.camera, size=RESOLUTION)

        logging.info("{} PiCamera ready".format(
            datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

        self.r_shower = SSRelay(RELAY_SHOWER)
        self.r_filter = SSRelay(RELAY_FILTER)

        self.r_shower.set_output(0)
        self.r_filter.set_output(0)
        logging.info("{} Relays initial off".format(
            datetime.now().strftime("%Y-%m-%d %H:%M:%S")))

        self.music = Music()

        time.sleep(0.1)

        self.scanner = zbar.ImageScanner()
        self.scanner.parse_config('enable')
Ejemplo n.º 8
0
    def page_parse(self):
        soups = Base.page_parse(self)

        data = []

        for soup in soups:
            for rank, tr in enumerate(soup.select('#frm > div > table > tbody > tr'), start=1):
                tds = tr.select('td')
                if tds[2].select('span.up'):
                    rank_change = {'up': int(tds[2].select('span.up')[0].text)}
                elif tds[2].select('span.down'):
                    rank_change = {'down': int(
                        tds[2].select('span.down')[0].text)}
                else:
                    rank_change = {'none': 0}
                album_id = re.findall("\d+", tds[3].select('a')[0]['href'])[0]
                album_photo = tds[1].select('img')[0]['src']
                song = tds[3].select_one(
                    'div[class="ellipsis rank01"]').text.strip()
                singer = tds[3].select_one(
                    'div[class="ellipsis rank02"]').select('a')[0].text.strip()

                data.append(Music(rank, rank_change,
                                  album_photo, song, singer).to_json())
        return data
Ejemplo n.º 9
0
 def __init__(self):
     self.ascii_banner = pyfiglet.figlet_format("Hello!!")
     self.ascii_banner2 = pyfiglet.figlet_format("1337 Alarm")
     self.AWAKE_TIME = "06:30"
     self.CLASS_TIME = "09:25"
     self.music = Music()
     self.voice = Voice()
Ejemplo n.º 10
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((1200, 800))
    play_button = Button(ai_settings, screen, "Play")
    pygame.display.set_caption("Space Invaders")
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    #bg_color = (230, 230, 230)
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    gf.create_fleet(ai_settings, screen, ship, aliens)
    background_image = pygame.image.load("images/space.png").convert()
    Music()
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        screen.blit(background_image, [0, 0])
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
        for bullet in bullets.copy():
            if bullet.rect.bottom <= 0:
                bullets.remove(bullet)
Ejemplo n.º 11
0
 def __init__(self):
     intents = discord.Intents.default()
     intents.members = True
     self.yelp_bearer = keyring.get_password('Yelp', 'bearer token')
     self.client = discord.Client(intents=intents)
     self.music_handler = Music(self.client)
     self.hold_em = False
Ejemplo n.º 12
0
    def __init__(self):
        """Initialize the game, and create game resources"""
        pygame.init()
        self.music = Music()
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Save the City")
        self.statistics_image = pygame.image.load('resources/stats.png')

        # Reading the score from disk
        # d = shelve.open('resources/high_score')
        # score = d['saved_score']
        # Create an instance to store game statistics-
        # -and create a scoreboard.
        self.stats = GameStats(self, 0)
        self.sb = Scoreboard(self)

        self.materials = Materials(self, self.settings.difficulty_level)
        self.worker = Worker(self)

        # Cooldown for collecting resources
        self.last = pygame.time.get_ticks()
        self.cooldown = 0
        # List for obtained values
        self.obtained_list = [False, False, False, False, False]

        # Make the play button
        self.play_button = Button(self, "Play")

        self.show = None
Ejemplo n.º 13
0
    def __init__(self):
        """Initiate pyxel, set up initial game variables, and run."""

        pyxel.init(WIDTH, HEIGHT, caption="Pong!", scale=8, fps=60)
        self.music = Music()
        self.reset_game()
        pyxel.run(self.update, self.draw)
Ejemplo n.º 14
0
def check_aliens_bottom(ai_settings, stats, sb, screen, ship, aliens, bullets):
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom >= screen_rect.bottom:
            Music('Data_base\\explo.mp3', 0.5, 0.4).effect()
            ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets)
            break
Ejemplo n.º 15
0
def run():
    """Main game function."""

    settings = Settings()

    # create game process and set display size and title
    pygame.init()
    screen = pygame.display.set_mode(settings.screen_size)
    pygame.display.set_caption("Connect 4 Pancake")

    clock = pygame.time.Clock()
    music = Music(settings)
    pygame.mixer.init()

    # update screen size to reflect new settings (if modified at all)
    screen = pygame.display.set_mode(settings.screen_size)

    # main game loop
    while True:
        # create the main menu and run the menu event loop
        # retrieve the picked game_mode
        menu = Menu(settings, screen, clock)
        game_mode = menu.show(music)

        # update screen size to reflect new settings (if modified at all)
        screen = pygame.display.set_mode(settings.screen_size)

        game = Game(settings, screen, music, clock, game_mode)
        game.run()
Ejemplo n.º 16
0
def update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets):
    check_fleet_edges(ai_settings, aliens)
    aliens.update()
    if pygame.sprite.spritecollideany(ship, aliens):
        Music('Data_base\\explo.mp3', 0.5, 0.4).effect()
        ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets)
    check_aliens_bottom(ai_settings, stats, screen, sb, ship, aliens, bullets)
Ejemplo n.º 17
0
def enter():
    global easy,hard,extreme,lite,music
    lite = load_image('lite_2.png')
    easy = load_image('easy.png')
    hard = load_image('hard.png')
    extreme = load_image('extreme.png')
    music = Music()
Ejemplo n.º 18
0
def main():
    user32 = ctypes.windll.user32
    screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
    os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (
        screensize[0] // 2 - WINDOW_SIZE[0] // 2,
        screensize[1] // 2 - WINDOW_SIZE[1] // 2 - 10)

    pygame.init()
    pygame.mixer.init()

    clock = pygame.time.Clock()

    state = game_state.State(True, Music())

    screen = pygame.display.set_mode(WINDOW_SIZE)
    generator = g.Generator()

    while state.running:
        clock.tick(30)

        controller.handle_events(state)

        if state.reset:
            m = state.music
            state = game_state.State(False, m)
            generator = g.Generator()

        generator.update(state)  # Has to be before state.update()

        state.update()

        graphics.update_screen(screen, state)

    pygame.quit()
Ejemplo n.º 19
0
def test6():
    """Checking the launch to play explicitly specified sound file."""
    box = Box(directory='test_music')
    music = Music(box.directory)  # explicit music object
    start = datetime.now() + timedelta(seconds=1)
    box.add_music(start.strftime('%H:%M:%S'), music)
    box.start(test=True)
    assert input('Did you hear the note? (y/n) ') == 'y', 'test6'
Ejemplo n.º 20
0
def main():
    '''Sample usage of Music.'''
    kwargs = {'host': 'localhost'}
    music = Music(**kwargs)
    print "Music version %s" % music.version()

    # Randomize the name so that we don't step on each other.
    keyspace = 'NewVotingApp' + str(current_time_millis() / 100)
    music.create_keyspace(keyspace)
    print "Created keyspace: %s" % keyspace

    # Create the table
    kwargs = {
        'keyspace': keyspace,
        'table': 'votecount',
        'schema': {
            'name': 'text',
            'count': 'varint',
            'PRIMARY KEY': '(name)'
        }
    }
    music.create_table(**kwargs)

    # Candidate data
    data = {'Trump': 5, 'Bush': 7, 'Jeb': 8, 'Clinton': 2, 'Bharath': 0}

    # Create an entry in the voting table for each candidate
    # and with a vote count of 0.
    kwargs = {'keyspace': keyspace, 'table': 'votecount'}
    for name in data.iterkeys():
        kwargs['values'] = {'name': name, 'count': 0}
        music.create_row(**kwargs)

    # Update each candidate's count atomically.
    kwargs = {'keyspace': keyspace, 'table': 'votecount', 'pk_name': 'name'}
    for name, count in data.iteritems():
        kwargs['pk_value'] = name
        kwargs['values'] = {'count': count}
        music.update_row_atomically(**kwargs)

    # Read all rows
    kwargs = {'keyspace': keyspace, 'table': 'votecount'}
    print music.read_all_rows(**kwargs)

    # Delete Clinton, read Trump
    kwargs = {'keyspace': keyspace, 'table': 'votecount', 'pk_name': 'name'}
    kwargs['pk_value'] = 'Clinton'
    music.delete_row_eventually(**kwargs)
    kwargs['pk_value'] = 'Trump'
    print music.read_row(**kwargs)

    # Read all rows again
    kwargs = {'keyspace': keyspace, 'table': 'votecount'}
    print music.read_all_rows(**kwargs)

    # Cleanup.
    music.drop_keyspace(keyspace)
    music.delete_all_locks()
Ejemplo n.º 21
0
 def __init__(self, fromUserName):
     self.fromUserName = None
     self.toUserName = None
     self.interface = Interface()
     self.meizitu = Meizitu()
     self.talentapt = TalentApt()
     self.music = Music()
     self.location = Location(fromUserName)
     self.vip_vedio = VipVideo()
Ejemplo n.º 22
0
    def prepare(self):
        super().prepare()
        
        # Read the songbook and load the first song
        self.songbook = SongBook.load()
        if self.songbook is None:
            self.songbook = SongBook()
        self.songbook.validate()
        self.songbook.sort()

        # Add a new song supplied on the command line
        song_args = {
            "--song-add": "",
            "--song-track": "1",
        }
        if MidiMaster.get_cmd_argument(song_args):
            song_path = os.path.join(".", song_args["--song-add"])
            song_track = int(song_args["--song-track"])
            
            def add_song(path:str, track=None):
                new_song = Song()
                new_song.from_midi_file(path, track)
                self.songbook.add_update_song(new_song)

            if os.path.exists(song_path):
                if os.path.isdir(song_path):
                    for file in os.listdir(song_path):
                        full_path = os.path.join(song_path, file)
                        if os.path.isfile(full_path) and file.find("mid") >= 0:
                            add_song(full_path, song_track)    
                elif os.path.isfile(song_path):
                    add_song(song_path, song_track)                
            else:
                print(f"Cannot find specificed midi file or folder {song_path}! Exiting.")
                exit()

        # Setup all the game systems
        self.staff = Staff()
        self.menu = Menu(self.graphics, self.input, self.gui, self.window_width, self.window_height, self.textures)
        self.font_game = Font(os.path.join("ext", "BlackMetalSans.ttf"), self.graphics, self.window)
        self.staff.prepare(self.menu.get_menu(Menus.GAME), self.textures)
        self.note_render = NoteRender(self.graphics, self.window_width / self.window_height, self.staff)
        self.music = Music(self.graphics, self.note_render, self.staff)
        self.menu.prepare(self.font_game, self.music, self.songbook)
        
        if GameSettings.DEV_MODE:
            default_song = self.songbook.get_default_song()
            if default_song is None:
                print("Invalid or missing song data file, unable to continue!")
            else:
                self.music.load(default_song)
        
        # Connect midi inputs and outputs and player input
        self.devices = MidiDevices()
        self.devices.open_input_default()
        self.devices.open_output_default()
        self.setup_input()
Ejemplo n.º 23
0
 def __init__(self, master=None):
     super().__init__(master)
     self.master = master
     self.grid()
     self.editor = Editor(master)
     self.music = Music()
     self.player = Player()
     self.parser = Parser(self.music)
     self.create_widgets()
Ejemplo n.º 24
0
	def __init__(self, sound="None", soundout="pulse"):
		self.music = Music(sound, soundout)
		sleep(0.25)
		self.screen = curses.initscr()
		self.screen.clear()
		self.screen.refresh()
		self.music.start()
		self.mapstr = "map{}.txt"
		curses.noecho()
		self.game = Game(self, 0)
		self.game.start()
Ejemplo n.º 25
0
def delete_api_handler(music_id):
    music = Music(music_id)
    if music.load() == False: abort(404)

    def callback():
        abort(401)

    usr = auth(callback)
    if music.username == usr.username:
        music.delete()
    return succ(u'删除成功!')
Ejemplo n.º 26
0
def main():
    bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'),)

    async def on_ready():
        logger.info(f'{bot.user} has connected to Discord!')

    bot.add_listener(on_ready)
    bot.add_check(commands.guild_only())
    # bot.add_cog(BGGCog(bot))
    bot.add_cog(Music(bot))
    bot.run(token)
Ejemplo n.º 27
0
def detail_api_handler(music_id):
    music = Music(music_id)
    if music.load() == False: abort(404)

    obj = {i: j for i, j in music.__dict__.items()}
    obj['file_path'] = music.file_path[-5:]
    obj['comments'] = music.getComments()
    obj['content_type'] = music.getContentType()
    obj['score'] = music.getScore()
    obj['genre'] = music.getAuthorGenre()

    return make_response(json.dumps(obj), 200)
Ejemplo n.º 28
0
def createGameandDisplay(themeSong):
    '''
    Purpose: createGameandDisplay
    Parameters: None
    
    Returns: Display and Game instances
    '''

    gameInstance = Game()
    displayInstance = MainDisplay()
    musicInstance = Music(themeSong)
    return gameInstance, displayInstance, musicInstance
Ejemplo n.º 29
0
    def run(self):
        try:
            self._init_menu()
            self.music = Music(self.core, self.config['default_tracks'],
                               self.config['default_preset'])
            self.display = DisplayWithPowerSaving(
                self.config['display_min_brightness'],
                self.config['display_max_brightness'],
                self.config['display_off_time_from'],
                self.config['display_off_time_to'])
            self.gpio = Gpio(
                self.config['buttons_enabled'], self.play_stop_music,
                self._on_menu_click, self._on_menu_click_left,
                self._on_menu_click_right, self.config['light_sensor_enabled'],
                self._on_light_sensor, self.config['relay_enabled'])
            self.ir_sender = IrSender(self.config['ir_remote'],
                                      self.gpio.switch_relay)
            self.ir_receiver = IrReceiver(
                self.config['ir_receiver_enabled'], self.play_stop_music,
                self._on_menu_click, self._on_menu_click_left,
                self._on_menu_click_right, self.music.decrease_volume,
                self.music.increase_volume, self.run_alert,
                self._on_change_preset)
            self.timer_on = TimerOn(self.play_music)
            self.timer_off = TimerOff(self.stop_music)
            self.alert = Alert(self.music, self.ir_sender,
                               self.config['alert_files'])
            self.timer_alert = TimerAlert(self.run_alert)
            self.time = Time()
            self.date = Date([self.timer_on, self.timer_off, self.timer_alert])
            self.menu = Menu(self.display, self.MENU, [
                self.time, self.date, self.timer_on, self.timer_off,
                self.timer_alert
            ])

            while True:
                self.menu.run()

                if (self.stopped()):
                    break
                else:
                    sleep(1)

        except Exception as inst:
            logging.error(inst)
        finally:
            self.ir_sender.stop()
            self.ir_receiver.stop()
            self.display.shutdown()
            self.gpio.cleanup()
Ejemplo n.º 30
0
def run_game():
    #initialize game and create a screen object
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    #make a ship
    ship = Ship(ai_settings, screen)
    #make an alien
    aliens = Group()
    #gf.create_fleet(ai_settings, screen, aliens, ship)
    #make bullet sprites group
    bullets = Group()
    #create alien bullet group
    alien_bullets = Group()
    #make screen background
    background = Background(screen)
    #add music to the game
    music = Music()
    #start play
    music.start_play()
    #create statics
    stats = GameStats(ai_settings)
    stats.reset_stats()
    with open("highest_score.txt", 'r') as hs:
        highestscore = hs.readline()
    stats.highest_score = int(highestscore)
    #create play button
    play_button = Button(screen, "Play")
    #initlize score board
    score_board = ScoreBoard(screen, stats, ai_settings)

    #Start the main loop for the game.
    while True:

        #watch for keyboard and mouse events.
        gf.check_events(ai_settings, screen, ship, bullets, play_button, stats,
                        aliens, score_board, alien_bullets)
        if stats.game_active:
            gf.update_ship(ship)
            gf.update_bullets(bullets, aliens, ai_settings, ship, screen,
                              stats, score_board, alien_bullets)
            gf.update_alien_bullets(alien_bullets, ship, stats, aliens,
                                    bullets, screen, ai_settings, score_board)
            gf.update_aliens(aliens, ai_settings, ship, stats, bullets, screen,
                             score_board, alien_bullets)
        gf.update_screen(ai_settings, screen, ship, bullets, background,
                         aliens, play_button, stats, score_board,
                         alien_bullets)