Exemple #1
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
Exemple #2
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
Exemple #3
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)
    def keyPressed(self, code, mod):

        # change music volume
        if code == pygame.K_EQUALS:
            Music.changeVol(0.05)
        elif code == pygame.K_MINUS:
            Music.changeVol(-0.05)

        # start game, view credits
        if Game.MODE == 'Title Screen':
            if code == pygame.K_RETURN:
                Game.MODE = 'Intro'
                self.startMusic = True
            elif code == pygame.K_SPACE:
                Game.MODE = 'Credits'

        elif Game.MODE == 'Credits':
            if code == pygame.K_ESCAPE:
                Game.MODE = 'Title Screen'

        # skip intro
        elif Game.MODE == 'Intro':
            if code == pygame.K_RETURN:
                Game.MODE = 'Wheel'
                self.startMusic = True
Exemple #5
0
	def run(self):
		self._screen().blit(self._background(), (0, 0))
		pygame.display.flip()
		clock = pygame.time.Clock()
		music = Music()
		music.play()
		while 1:
			clock.tick()
			
			self._draw_background()
			self._draw_monsters()
			self._draw_hero()
			self._draw_coins()
			self._draw_hud()
			
			pygame.display.flip()
			
			
			for event in pygame.event.get():
				if event.type == QUIT:
					return
				elif event.type == KEYDOWN and event.key == K_ESCAPE:
					return
				elif event.type == KEYDOWN:
					self.hero().handle_keydown(event.key)
				elif event.type == KEYUP:
					self.hero().handle_keyup(event.key)
Exemple #6
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')
Exemple #7
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()
Exemple #8
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
Exemple #9
0
def main():
    dt = DumplingTown()
    music = Music()
    music.animalCrossingDay()
    #music.pause()
    #music.pause()
    music.play()
Exemple #10
0
def reset():
    """ Reset game state """
    score = 0
    speed = 0.5
    Screen.start_screen()
    Grid.start_grid()
    Music.play_bg_music()
    return score, speed
Exemple #11
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()
Exemple #12
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()
Exemple #13
0
 def pacman_die(self):
     if self.scores.lives >= 1:
         self.scores.lives -= 1
         if self.scores.lives:
             Music.play('go')
             self.units.reset()
             Input.reset()
         else:
             self.game_over()
Exemple #14
0
 def next_level(self):
     # type: () -> None
     """Switch to next level"""
     self.scores.level += 1
     Input.reset()
     self.field = Field(str(self.scores.level) + '_lvl.txt')
     self.units.add_pacman(self.field.get_pacman_spawn())
     self.units.add_ghosts(self.field.get_ghosts_spawn())
     Music.play('bg', .1)
Exemple #15
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()
Exemple #16
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()
Exemple #17
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'删除成功!')
Exemple #18
0
 def do_movement(self):
     x_pos = self.pacman.x * self.width()
     y_pos = self.pacman.y * self.height()
     pacman_direction = self.pacman.current_direction
     self.animation.current_direction = pacman_direction
     self.move(x_pos, y_pos)
     scene = self.parentWidget().scene
     food = scene.itemAt(x_pos, y_pos, QTransform())
     if food is not None and self.pacman.x not in [0, 18]:
         scene.removeItem(food)
         if self.pacman.eaten_food % 2 == 1:
             Music.waka()
Exemple #19
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
Exemple #20
0
    def __start(self):
        music_helper = MusicHelper()

        while self._file_name_list:
            file_path = self._file_name_list.pop()
            music_tag = music_helper.get_music_tag(file_path)
            music_info = Music()
            music_info.file_path = file_path
            if music_tag == {}:
                logger.info("Music tag can't be got: " + music_info.file_path)
            else:
                music_info.music_tag = music_tag
                self._music_tag_queue.put(music_info)
Exemple #21
0
 def move(self):
     # type: () -> None
     cur_cell = self.game.field.get_cell(self.get_position().to_rel())
     if cur_cell.get_type() in self.game.type_scores:  # кушаем
         self.game.add_score(
             self.game.type_scores.get(cur_cell.get_type(), 0))  # добавляем соответствующее количество очков
         cur_cell.set_type('0')
         self.game.field.seed_count -= 1
         if cur_cell.get_type == 'e':  # если съели енерджайзер, то приведения переходят в режим разберания
             self.game.units.fear()
             Music.play('en')
         if cur_cell.get_type == 's':
             Music.play('se')
     super(Pacman, self).move()
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)
Exemple #23
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()
Exemple #24
0
def gen():

    r = Rec()
    m = Music()

    #print (m.get_all_notes())
    #exit(0)

    prev_pos = 0
    for i in range(0, 1000):
        
        cur_pos = r.get_current()
        print (cur_pos)
        m.play(prev_pos, cur_pos)
        _ = r.generate_next()
        prev_pos = cur_pos
Exemple #25
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()
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
Exemple #27
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()
Exemple #28
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)
Exemple #29
0
def makeMusic(**params):
    name = params['name']
    extraData = params['extraData']
    author = params['author']
    public = params['public']
    content = params['content']
    img_url = params['img_url']
    db_num = params['db_num']
    card = Card()
    card.set('name', name)
    card.set('author', author)
    card.set('content', content)
    card.set('img_url', img_url)
    card.set('extraData', json.loads(extraData))
    card.set('db_num', db_num)
    if 'formId' in params:
        formId = params['formId']
        card.set('formId', formId)
    userid = params['userid']
    user = User.create_without_data(userid)
    card.set('user', user)
    card.set('user', user)
    card.set('type', 'music')
    card.set('public', public)
    card.set('publish', False)
    card.set('likes', 0)
    card.set('shares', 0)
    card.save()
    stat = Music.generate(card)
    if stat == 'ok':
        result = {'code': 200, 'data': card.get('objectId')}
        return result
    else:
        result = {'code': 500, 'message': 'failed'}
        return result
Exemple #30
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()
Exemple #31
0
def getlisting_api_handler():
    score = request.args.get('score', None)
    music_cat = request.args.get('music_cat', '')
    author_cat = request.args.get('author_cat', '')
    subclause = u''
    if music_cat:
        subclause = u"type='%s' " % MysqlModel.escape(music_cat)
    if author_cat:
        if subclause: subclause += u'and '
        subclause += u"(select genre from Artist as Y where Y.author=Music.author)='%s' " % MysqlModel.escape(
            author_cat)
    if score:
        score = int(score)
        return make_response(
            json.dumps(Music.getListByScore(score, subclause)), 200)
    return make_response(json.dumps(Music.getList(subclause)), 200)
Exemple #32
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
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)
Exemple #34
0
    def __init__(self):
        self.window_manager = WindowManager()
        self.events = Queue()
        self.panel = Panel()
        self.clock = Clock()
        self.notification_monitor = NotificationMonitor()

        try:
            with open(os.path.expanduser('~/.config/mpd/credentials.conf'), 'r') as f:
                mpd_settings = json.load(f)
        except FileNotFoundError:
            self.music = Music()
        else:
            self.music = Music(**mpd_settings)
        self.music_controller = self.music.clone()

        self.system_info = SystemInfo()
Exemple #35
0
class LokoPizza:
	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()
	
	def nextLevel(self):
		level = self.game.level
		if level:
			level += 1
		self.loadLevel(level)
	
	def loadLevel(self, level):
		self.screen.clear()
		self.music.reset()
		self.game.stop()
		try:
			self.game = Game(self, level)
			self.game.start()
		except IOError:
			self.mapstr = "map{}.txt"
			self.loadLevel(0)
	
	def quit(self):
		self.music.keeprunning = False
		curses.endwin()
		sys.exit(0)
	
	def by(self, string):
		#Noetig, um Python 2.7 und 3 zu unterstuetzen
		try:
			return bytes(string, encoding="utf-8")
		except TypeError: #Python 2.7
			return string
def run_game():
    pygame.init()
    ai_setting = Settings()
    screen = pygame.display.set_mode((ai_setting.screen_width, ai_setting.screen_height))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(ai_setting, screen)
    bullets = Group()
    aliens = Group()
    stats = GameStats(ai_setting)
    sb = Scoreboard(ai_setting, screen, stats)
    gf.create_fleet(ai_setting, screen, ship, aliens)
    play_button = Button(ai_setting, screen, "Play")
    music = Music()

    while True:
        gf.check_events(ai_setting, screen, stats, sb, play_button, ship, aliens, bullets, music)
        if stats.game_active:
            music.play_bgm()
            ship.update()
            gf.update_bullets(ai_setting, screen, stats, sb, ship, aliens, bullets, music)
            gf.update_aliens(ai_setting, screen, stats, sb, ship, aliens, bullets)

        gf.update_screen(ai_setting, screen, stats, sb, ship, aliens, bullets, play_button)
Exemple #37
0
def parse(fname):
	soup = BeautifulSoup(open(fname), 'lxml')
	soup = BeautifulSoup(soup.prettify('shift-jis'), 'lxml')
	music = Music()

	title, artist = getHeader(soup)
	keys = getKeys(soup)
	lyrics = getLyrics(soup)
	chords = getChords(soup)

	music.title = title
	music.artist = artist
	music.keys = keys
	music.lyrics = lyrics
	music.chords = chords

	return music
Exemple #38
0
class EventLoop:
    def __init__(self):
        self.window_manager = WindowManager()
        self.events = Queue()
        self.panel = Panel()
        self.clock = Clock()
        self.notification_monitor = NotificationMonitor()

        try:
            with open(os.path.expanduser('~/.config/mpd/credentials.conf'), 'r') as f:
                mpd_settings = json.load(f)
        except FileNotFoundError:
            self.music = Music()
        else:
            self.music = Music(**mpd_settings)
        self.music_controller = self.music.clone()

        self.system_info = SystemInfo()

    def start_thread(self, loop):
        thread = threading.Thread(
            target=loop,
            kwargs={'events': self.events}
        )
        thread.daemon = True
        thread.start()
        return thread

    def process_event(self, event):
        if isinstance(event, PanelStrip):
            self.panel.update(event)
        elif isinstance(event, UserCommand):
            try:
                command = event.command.split()
                if command[0] == 'music_pause':
                    self.music_controller.pause()
                elif command[0] == 'music_stop':
                    self.music_controller.stop()
                elif command[0] == 'music_home':
                    self.music_controller.seek(0)
                elif command[0] == 'music_next':
                    self.music_controller.next()
                elif command[0] == 'music_previous':
                    self.music_controller.previous()
                elif command[0] == 'music_volume':
                    if command[1].startswith('+') or command[1].startswith('-'):
                        is_relative = True
                    else:
                        is_relative = False
                    self.music_controller.volume(int(command[1]), is_relative)
                elif command[0] == 'notification_next':
                    self.notification_monitor.history_next(self.events)
            except:
                sys.stderr.write(
                    "failed executing command. details: \n" +
                    traceback.format_exc()
                )

    def loop(self):
        self.window_manager_thread = self.start_thread(
            self.window_manager.loop
        )
        self.clock_thread = self.start_thread(
            self.clock.loop
        )
        self.system_info_thread = self.start_thread(
            self.system_info.loop
        )
        self.music_thread = self.start_thread(
            self.music.loop
        )
        self.notification_monitor_thread = self.start_thread(
            self.notification_monitor.loop
        )

        self.panel.start()

        while True:
            self.process_event(self.events.get())
Exemple #39
0
 def music(jsonData):
     Music.playCmd(jsonData)
app.secret_key = settings.secret_key


#Routes	
app.add_url_rule('/',
			view_func=Main.as_view('main')
			methods=["GET"])

app.add_url_rule('/<page>/',
			view_func=Main.as_view('main')
			methods=["GET"])

app.add_url_rule('/Login/', 
			view_func=Login.as_view('login'), 
			methods=['GET', 'POST'])

app.add_url_rule('/remote/', 
			view_func=Music.as_view('remote'), 
			methods=(['GET'])

app.add_url_rule('/music/',
			view_func=Music.as_view('music'),
			methods=['GET'])

@app.errorhandler(404)
def page_not_found(error):
		return flask.render_template('404.html'), 404


app.debug = True
app.run()
Exemple #41
0
import flask
import settings

#Views
from main import Main
from login import Login
from remote import Remote
from music import Music

app = flask.Flask(__name__)
app.secret_key = settings.secret_key

#Routes
app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"])
app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["GET"])
app.add_url_rule('/login/', view_func=Login.as_view('login'), methods=["GET", "POST"])
app.add_url_rule('/remote/', view_func=Remote.as_view('remote'), methods=["GET", "POST"])
app.add_url_rule('/music/', view_func=Music.as_view('music'), methods=["GET"])

@app.errorhandler(404)
def page_not_found(error):
	return flask.render_template('404.html'), 404

app.debug = True
app.run()
 def __init__(self):
     self.music = Music()
Exemple #43
0
from events import Events
from users import Users
from docs import Docs

# configuration
DATABASE = 'test.json'

app = flask.Flask(__name__)
app.secret_key = settings.secret_key

#URL rules:  add as needed for the various dynamic pages
app.add_url_rule('/', view_func=Main.as_view('main'), methods=('get','post'))
app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=('get','post'))
app.add_url_rule('/login/', view_func=Login.as_view('login'), methods=('get','post'))
app.add_url_rule('/remote/', view_func=Remote.as_view('remote'), methods=('get','post'))
app.add_url_rule('/music/', view_func=Music.as_view('music'), methods=('get', 'post'))
app.add_url_rule('/events/', view_func=Events.as_view('events'), methods=('get','post'))
app.add_url_rule('/users/', view_func=Users.as_view('users'), methods=('get','post'))
app.add_url_rule('/docs/', view_func=Docs.as_view('docs'), methods=('get','post'))

#error handling wrapper
@app.errorhandler(404)
def page_not_found(error):
	return flask.render_template('404.html'), 404

#database handling wrappers
@app.before_request
def before_request():
    """Make sure we are connected to the database each request."""
    try:
        db = open(DATABASE).read()
Exemple #44
0
"""

from display import Display
from controller import Controller
from music import Music

import threading
import gobject

if __name__ == '__main__':
    gobject.threads_init()

    display = Display()
    controller = Controller()
    music = Music()
    mainloop = gobject.MainLoop()

    # Connect signals between components.
    controller.connect('change-mode', display.change_mode)
    controller.connect('station-up', music.tune_station, 1)
    controller.connect('station-down', music.tune_station, -1)
    controller.connect('play-pause', music.play_pause)
    controller.connect('next-song', music.skip_song)
    music.connect('station-changed', display.change_station)
    music.connect('song-changed', display.change_song)
    music.connect('state-changed', display.change_state)

    # Start user interface loop.
    display_thread = threading.Thread(target=display.run, args=(mainloop,))
    display_thread.daemon = True
Exemple #45
0
app =flask.Flask(__name__)

app.secret_key = settings.secret_key

#Routes

app.add_url_rule('/',
			view_func=Main.as_view('main'),
			methods=['GET'])

app.add_url_rule('/<page>/',
			view_func=Main.as_view('page'),
			methods=['GET'])

app.add_url_rule('/login',
			view_func=Login.as_view('login'),
			methods=['GET','POST'])
app.add_url_rule('/remote',
			view_func=Remote.as_view('remote'),
			methods=['GET','POST'])
app.add_url_rule('/music',
			view_func=Music.as_view('music'),
			methods=['GET'])

@app.errorhandler(404)
def page_not_found(error):
	return flask.render_template('404.html'),404

app.debug=True

app.run()
class Generator:

    def __init__(self):
        self.music = Music()

    def write_arffs(self):
        for next_file in os.listdir("midi"):
            if os.path.isfile("midi/" + next_file):
                print "adding midi/" + next_file
                self.music.load_song("midi/" + next_file)

        print "generating arff files"
        self.music.write_arff("test")

    def train(self):
        print "loading arff files"
        instrument_data, note_data, velocity_data, duration_data, time_delta_data = self.music.read_arff(
            "test")
        
        self.transform_instrument = preprocessing.OneHotEncoder(categorical_features=[0,1,2,5,6,7,10,11,12,15,16,17,20,21,22])
        self.transform_instrument.fit(instrument_data[:, :-1])

        self.transform_note = preprocessing.OneHotEncoder(categorical_features=[0,1,2,5,6,7,10,11,12,15,16,17,20,21,22])
        self.transform_note.fit(note_data[:, :-1])

        self.transform_duration = preprocessing.OneHotEncoder(categorical_features=[0,1,2,5,6,7,10,11,12,15,16,17,20,21,22])
        self.transform_duration.fit(duration_data[:, :-1])

        self.transform_time_delta = preprocessing.OneHotEncoder(categorical_features=[0,1,2,5,6,7,10,11,12,15,16,17,20,21,22])
        self.transform_time_delta.fit(time_delta_data[:, :-1])

        print "training instruments"
        self.instrument_clf = RandomForestClassifier(n_estimators=10)
        self.instrument_clf = self.instrument_clf.fit(
            self.transform_instrument.transform(instrument_data[:, :-1]), instrument_data[:, -1:])
        print "training notes"
        self.note_clf = RandomForestRegressor(n_estimators=10)
        print note_data[:, :-1]
        self.note_clf = self.note_clf.fit(self.transform_note.transform(note_data[:, :-1]), note_data[:, -1:])
        print "training velocity"
        self.velocity_clf = RandomForestClassifier(n_estimators=10)
        self.velocity_clf = self.velocity_clf.fit(
            velocity_data[:, :-1], velocity_data[:, -1:])
        print "training duration"
        self.duration_clf = RandomForestClassifier(n_estimators=10)
        self.duration_clf = self.duration_clf.fit(
            self.transform_duration.transform(duration_data[:, :-1]), duration_data[:, -1:])
        print "training time_delta"
        self.time_delta_clf = RandomForestClassifier(n_estimators=10)
        self.time_delta_clf = self.time_delta_clf.fit(
            self.transform_time_delta.transform(time_delta_data[:, :-1]), time_delta_data[:, -1:])

    def generate_song(self, filename):
        self.song = Song()

        self.song.add_note(self.get_seed_note())
        self.song.add_note(self.get_seed_note())

        print "generating new song"
        for _ in range(5000):
            notes = self.song.get_last_notes()
            notes = np.array(notes).reshape(1, -1)
            instrument = self.instrument_clf.predict(self.transform_instrument.transform(notes))[0]
            note = self.note_clf.predict(self.transform_note.transform(notes))[0]
            velocity = self.velocity_clf.predict(notes)[0]
            note_duration = self.duration_clf.predict(self.transform_duration.transform(notes))[0] * 2
            time_delta = self.time_delta_clf.predict(self.transform_time_delta.transform(notes))[0] * 0.75

            self.song.add_note(Note(int(instrument), int(note), int(
                velocity), int(time_delta), duration=int(note_duration)))

        print "writing song to " + filename
        self.song.write_file(filename)

    def get_seed_note(self):
        return Note(0, random.randrange(0, 126), 100, 0, duration=random.randrange(1, 10) * 10)