コード例 #1
1
ファイル: main.py プロジェクト: mataeoh/kivy_contest
	def build(self):
		global rootW, rootH
		global unitW, unitH
		global cx, cy
		global clickSnd, wrongSnd
		global fUpdateTime
		global bButtonLock
		
		fUpdateTime = 1.0/60.0
		bButtonLock = False

		clickSnd = SoundLoader.load("click.wav")
		clickSnd.volume = 1.0
		wrongSnd = SoundLoader.load("wrong.wav")
		wrongSnd.volume = 1.0

		rootW = Window.size[0]
		rootH = Window.size[1]
		unitW = rootW / 10.0
		unitH = rootH / 10.0
		cx = rootW / 2
		cy = rootH / 2
		self.bPopup = False
		
		self.root = NumPuzzleRoot()
		self.root.size = (rootW, rootH)
		self.root.start()
		self.bind(on_start = self.post_build_init)
		return self.root
コード例 #2
0
    def setLevelImages(self):
        random.shuffle(self.levelInfos[levelProps[0]])
        random.shuffle(self.levelInfos[levelProps[1]])

        self.ids.tool1.setImage(self.levelInfos[levelProps[0]][0][0])
        self.ids.tool1.isGoal = self.levelInfos[levelProps[0]][0][1]
        
        self.ids.tool2.setImage(self.levelInfos[levelProps[0]][1][0])
        self.ids.tool2.isGoal = self.levelInfos[levelProps[0]][1][1]
        
        self.ids.tool3.setImage(self.levelInfos[levelProps[0]][2][0])
        self.ids.tool3.isGoal = self.levelInfos[levelProps[0]][2][1]
        
        self.ids.person1.setImage(self.levelInfos[levelProps[1]][0][0])
        self.ids.person1.isGoal = self.levelInfos[levelProps[1]][0][1]
        
        self.ids.person2.setImage(self.levelInfos[levelProps[1]][1][0])
        self.ids.person2.isGoal = self.levelInfos[levelProps[1]][1][1]
        
        self.ids.person3.setImage(self.levelInfos[levelProps[1]][2][0])
        self.ids.person3.isGoal = self.levelInfos[levelProps[1]][2][1]
        
        self.ids.sceneImage.source = self.levelInfos[levelProps[2]]
        
        self.winSound = SoundLoader.load(self.levelInfos[levelProps[4]])
        self.failSound = SoundLoader.load('res/sounds/fail.wav')
コード例 #3
0
ファイル: koalas.py プロジェクト: aq1/kivy_contest_game_2014
    def __init__(self, sound=None):
        super(KoalasMainWidget, self).__init__()

        self.size = Window.size
        self.start_menu = None
        self.points = 0
        self.liana_width = self.width / 15

        liana = Image(x=self.width / 2 - self.liana_width / 2,
                      y=self.height,
                      source='img/koalas/Steble_01.png',
                      size=(self.liana_width, self.height),
                      )

        self.add_widget(liana)
        anim = Animation(x=liana.x, y=0, d=2)
        anim.start(liana)

        Clock.schedule_interval(self.__reduce_transparency, 0.05)
        self.add_widget(StartMenu())

        if sound:
            self.sound = sound
        else:
            self.sound = SoundLoader.load('sound/koalas.ogg')

        self.wrong_sound = SoundLoader.load('sound/wrong.ogg')
        self.sound.loop = True
        self.sound.play()
コード例 #4
0
ファイル: main.py プロジェクト: KeyWeeUsr/Fish
 def __init__(self, **kwargs):
     self.app = App.get_running_app()
     self.app.pfish = self
     self.eatsound = SoundLoader.load(self.app.path+'/eat.wav')
     self.diesound = SoundLoader.load(self.app.path+'/die.wav')
     super(PlayerFish, self).__init__(**kwargs)
     Clock.schedule_interval(self.collision, 1/60.0)
コード例 #5
0
ファイル: main.py プロジェクト: mn22nw/IU
    def build(self):
        self.sound = {}
        self.title = 'DB Shooter'      
	    
        from kivy.base import EventLoop
        EventLoop.ensure_window()
        self.window = EventLoop.window

        # start the background music:
        self.music = SoundLoader.load('sound/background.mp3')
        self.music.volume = self.config.getint('General', 'Music') / 100.0
        self.music.bind(on_stop=self.replaySound)
        self.music.play()


        # create the root widget and give it a reference of the view / application instance 
        self.MyViewController = MyViewController(app=self)
        self.root = self.MyViewController.view        

        # load all other sounds:
        self.sound['pop'] = SoundLoader.load('sound/pop.mp3')
        self.sound['popping'] = SoundLoader.load('sound/popping.mp3')
        self.sound['swoosh'] = SoundLoader.load('sound/swoosh.mp3')
        
        
        sound_volume = self.config.getint('General', 'Sound') / 100.0
        for item in self.sound:
            self.sound[item].volume = sound_volume

        # if the user started the game the first time, display quick start guide
        if self.config.get('General', 'FirstStartup') == 'Yes':            
            Clock.schedule_once(self.displayHelpScreen,0)
            self.config.set('General', 'FirstStartup', 'No')
            self.config.write()
コード例 #6
0
	def build(self):

		self.data_path = os.path.realpath(os.path.dirname(sys.argv[0])) + os.sep + "Data" + os.sep

		self.load_ether()
	
		#self.test()
		#self.solution()
		
		self.screenManager = ScreenManager(transition=FadeTransition())

		self.splash = Splash(name="splash")
		self.menu   = Menu(name="menu")
		self.help   = Help(name="help")
		self.game   = Game(name="game")
		
		self.screenManager.add_widget(self.splash)
		self.screenManager.add_widget(self.menu)
		self.screenManager.add_widget(self.help)
		self.screenManager.add_widget(self.game)
		
		sound_intro = SoundLoader.load(filename= self.data_path + '42286__erh__f-eh-angelic-3.ogg')
		self.sound_find  = SoundLoader.load(filename= self.data_path + '30342__junggle__waterdrop25.ogg')
		
		sound_intro.play()
		
		self.showSplash()
		
		return self.screenManager
コード例 #7
0
    def __init__(self, *args, **kwargs):
        super(ChiliTriosGame, self).__init__(*args, **kwargs)

        # Create Menu
        cmenu = Factory.ChiliMenu(chiligame=self)
        cmenu.chiligame = self
        self.menu = Popup(title='CHILI TRIOS', content=cmenu,
                          size_hint=(None, None), size=(400, 400),
                          title_size='18sp', separator_height='4dp',
                          separator_color=[0, 0.5, 1, 0.9],
                          auto_dismiss=False)

        # Load sets and create menu buttons for each one.
        sets = os.listdir('card_sets')
        for n, i in enumerate(sets):
            path = ''.join(['card_sets/', i])
            set_name = i.split('.')[0]
            self.sets_list.append([set_name, path])
            # Add setbutton to menu
            set_menubtn = Factory.SetButton(text=set_name.capitalize())
            set_menubtn.set_id = n
            self.menu.content.set_options.add_widget(set_menubtn)

        self.menu.content.set_options.add_widget(
            Factory.SetButton(text="Random"))  # Random button

        # Iinitialize Helpers.
        Helper.chiligame = self
        self.helpers = {
            'show': self.showcards_helper, 'guess': self.guessobj_helper}

        # Game sound effects
        self.match_sound = SoundLoader.load('sound/match.ogg')
        self.win_sound = SoundLoader.load('sound/win.ogg')
        self.forbidden_sound = SoundLoader.load('sound/forbidden.ogg')
コード例 #8
0
ファイル: main.py プロジェクト: easytech247/LaneCrash
 def __init__(self,*args,**kwargs):
     super(Field,self).__init__(**kwargs)
     self.crash_sound = SoundLoader.load("audio/crash.ogg")
     self.speed_sound = SoundLoader.load("audio/car-run.ogg")
     self.stop_sound = SoundLoader.load("audio/car-brake.ogg")
     self.score_sound = SoundLoader.load("audio/score.ogg")
     self.sounds = [self.crash_sound,self.speed_sound,self.stop_sound,
                    self.score_sound]
コード例 #9
0
ファイル: main.py プロジェクト: brousch/immersioncoffeetimer
 def cancel_timer(self):
     SoundLoader.load('media/cancel.wav').play()
     self.timer_is_running = False
     self.timer_is_paused = False
     Clock.unschedule(self._decrement_timer)
     Clock.unschedule(self._stir_notification)
     self.current_timer = 0
     self.start_pause_resume_button.text = "Start Timer"
コード例 #10
0
ファイル: main.py プロジェクト: ubuntunux/KivyProject
	def loadMySound(self, iconFile):
		key = iconFile.split(".png")[0].split(sep)[1]
		if self.sounds.has_key(key):
			self.mySound = SoundLoader.load(choice(self.sounds[key]))
		else:
			self.mySound = SoundLoader.load(choice(self.sounds['default']))
		if self.mySound:
			self.mySound.volume = 1.0
コード例 #11
0
ファイル: camp.py プロジェクト: SynedraAcus/camp
 def __init__(self, game_manager=None, **kwargs):
     super(GameWidget, self).__init__(**kwargs)
     #  Widget-related stuff
     self.map_widget = None
     self.log_widget = None
     self.status_widget = None
     #  Connecting to manager
     self.game_manager = game_manager
     self.game_manager.game_widget = self
     self.rebuild_widgets()
     #  Sound object
     self.boombox = {'moved': SoundLoader.load('dshoof.wav'),
                     'attacked': SoundLoader.load('dspunch.wav'),
                     'exploded': SoundLoader.load('dsbarexp.wav'),
                     'shot': SoundLoader.load('dspistol.wav')}
     #  Sound in kivy seems to be loaded lazily. Files are not actually read until they are necessary,
     #  which leads to lags for up to half a second when a sound is used for the first time. The following
     #  two lines are forcing them to be loaded right now.
     for sound in self.boombox.keys():
         self.boombox[sound].seek(0)
     #  Keyboard controls
     #  Initializing keyboard bindings and key lists
     self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
     self._keyboard.bind(on_key_down=self._on_key_down)
     #  Keys not in this list are ignored by _on_key_down
     self.allowed_keys = [  # Movement
                          'spacebar', '.',
                          'h', 'j', 'k', 'l',
                          'y', 'u', 'b', 'n',
                          'up', 'down', 'left', 'right',
                          'numpad1', 'numpad2', 'numpad3', 'numpad4', 'numpad5',
                          'numpad6', 'numpad7', 'numpad8', 'numpad9', 'numpad0',
                          #  PC stats viewctory.create_widget(a)
                          'c',
                          #  Used for inventory & spell systems
                          '0', '1', '2', '3', '4', '5',
                          '6', '7', '8', '9',
                          #  Inventory management
                          'g', ',', 'd', 'i',
                          #  Targeted effects
                          'z', 'x', 'f',
                          #  Others
                          'escape', 'enter', 'numpadenter']
     #  Keys in this list are processed by self.map_widget.map
     self.map_keys = ['spacebar', '.',
                      'h', 'j', 'k', 'l',
                      'y', 'u', 'b', 'n',
                      'up', 'down', 'left', 'right',
                      'numpad1', 'numpad2', 'numpad3', 'numpad4', 'numpad5',
                      'numpad6', 'numpad7', 'numpad8', 'numpad9',
                      'g', ',']
     self.key_parser = KeyParser()
     #  Game state
     self.game_state = 'playing'
     #  Stuff for various game states
     self.state_widget = None
     self.target_coordinates = (None, None)
     self.targeted_item_number = None
コード例 #12
0
    def init_sounds(self):
        if self.pre_post_flag == 1:
            self.phrases_A = ['growth_02_buffy',
                              'fixed_03_buffy',
                              'growth_04_buffy',
                              'fixed_05_buffy',
                              'fixed_07_buffy',
                              'growth_08_buffy',
                              'fixed_09_buffy',
                              'growth_10_buffy',
                              'fixed_11_buffy',
                              'growth_12_buffy']
            self.phrases_B = ['fixed_02_fluffy',
                              'growth_03_fluffy',
                              'fixed_04_fluffy',
                              'growth_05_fluffy',
                              'growth_07_fluffy',
                              'fixed_08_fluffy',
                              'growth_09_fluffy',
                              'fixed_10_fluffy',
                              'growth_11_fluffy',
                              'fixed_12_fluffy']
        elif self.pre_post_flag == 2:
            self.phrases_A = ['fixed_01_buffy',
                              'growth_02_buffy',
                              'fixed_03_buffy',
                              'growth_04_buffy',
                              'growth_06_buffy',
                              'fixed_07_buffy',
                              'growth_08_buffy',
                              'fixed_13_buffy',
                              'growth_16_buffy',
                              'fixed_17_buffy']
            self.phrases_B = ['growth_01_fluffy',
                              'fixed_02_fluffy',
                              'growth_03_fluffy',
                              'fixed_04_fluffy',
                              'fixed_06_fluffy',
                              'growth_07_fluffy',
                              'fixed_08_fluffy',
                              'growth_13_fluffy',
                              'fixed_16_fluffy',
                              'growth_17_fluffy']
        self.number_of_questions = len(self.phrases_A)
        self.question = 'which'
        self.sound_question = SoundLoader.load("./sounds/" + self.question + ".wav")

        self.intro1 = 'intro1'
        self.sound_intro1 = SoundLoader.load("./sounds/" + self.intro1 + ".wav")

        self.intro2 = 'intro2'
        self.sound_intro2 = SoundLoader.load("./sounds/" + self.intro2 + ".wav")

        self.sounds_A = []
        self.sounds_B = []
        for n in range(len(self.phrases_A)):
            self.sounds_A.append(SoundLoader.load("./sounds/" + self.phrases_A[n] + ".wav"))
            self.sounds_B.append(SoundLoader.load("./sounds/" + self.phrases_B[n] + ".wav"))
コード例 #13
0
ファイル: main.py プロジェクト: tito/TwoDeeWars
 def __init__(self):
     ret = super(Game, self).__init__()
     self.sounds = dict()
     self.sounds['firing'] = SoundLoader.load("sounds/firing.ogg")
     self.sounds['enemy_death'] = SoundLoader.load("sounds/enemy_death.ogg")
     self.sounds['game_over'] = SoundLoader.load("sounds/game_over.ogg")
     self.top_points = 0
     self.points = 0
     self.reset_state()
     return ret
コード例 #14
0
ファイル: Battleship.py プロジェクト: Xayom/Battleship_Kivy
    def button_pressed(self, button):
        if button.text == 'YES':
            self.manager.current = 'main'
            self.popup.dismiss()
        else:
            global CURRENT_PLAYER, AMOUNT, CURRENT1, SOME_LIST1
            row, column = button.coords
            status_index = row * 10 + column
            already_played = self.status[status_index]
            if not already_played and CURRENT_PLAYER == 1:
                self.status[status_index] = CURRENT_PLAYER

                for ship in SHIPS_OF_COMP:
                    if ship[0] == (row, column):
                        CURRENT1 += 1
                        SOME_LIST1.append((row, column))
                        button.background_color = ship[1]
                        #button.text = str(ship[2])
                        self.sound.stop()
                        self.sound = SoundLoader.load('bomb2.wav')
                        self.sound.play()

                        if CURRENT1 == ship[2]:
                            for ship in SOME_LIST1:
                                x, y = ship
                                s = [1, 0, -1]
                                t = [1, 0, -1]
                                for xx in s:
                                    for yy in t:
                                        for child in self.ids.grid.children:
                                            if child.coords == (x + xx, y + yy) and (x + xx, y + yy) not in SOME_LIST1:
                                                child.text = 'X'
                                                child.background_color = [1, 0, 0, 1]
                            SOME_LIST1 = []
                            CURRENT1 = 0

                        AMOUNT += 1
                        if AMOUNT == 4 + 3 * 2 + 2 * 3 + 4:
                            Winner.play()
                            winner.children[0].text = 'You WIN!!!!!'
                            winner.bind(on_dismiss = self.somefunc)
                            winner.open()
                        break

                if button.background_color == [1, 1, 1, 1]:
                    button.text = 'X'

                    self.sound.stop()
                    self.sound = SoundLoader.load('Not_ship.wav')
                    self.sound.play()

                    button.background_color = [1, 0, 0, 1]
                    Clock.schedule_once(self.callback, 1)
                    CURRENT_PLAYER *= -1
コード例 #15
0
ファイル: one.py プロジェクト: nitinsaroha/Kivame
 def __init__(self, app, *args, **kwargs):
     super(ScreenOne, self).__init__(*args, **kwargs)
     self.app = app
     self.questions = ["44%6", "x*x = 4 so x is", "Largest Democracy in the World?", "When did World War 2 begin?", "Total no of kivy properties", "Planet with rings", "NYC", "Speed of light(km/s)"]
     self.answers = [1, 3, 3, 2, 3, 2, 1, 2]
     self.thunder = SL.load("static/lightning.wav")
     self.rain_music = SL.load("static/rain.wav")
     self.rain_music.loop = True
     assert len(self.questions) == len(self.answers)
     self.create_objects()
     self.update()
コード例 #16
0
ファイル: sequence_manager.py プロジェクト: Mau21710/Mentor
 def _initialize_sound(self):
     """
     initializes and eventually starts the sound for the current step
     :return:
         True if everything is ok
         False if the sound shouldn't / coundn't be started
     """
     #Logger.debug("[{}]".format(self.seq_snds[self.idx_stp]))
     if self.seq_snds[self.idx_stp] == "":
         Logger.debug('_initialize_sound no sound played for step {}'.format(
             self.idx_stp))
         return False
     else:
         if self.seq_snds[self.idx_stp] == "default":
             Logger.debug('_initialize_sound default sound for step {}\
                          ({})'.format(self.idx_stp, self.default_snd))
             self.sound = SoundLoader.load(self.default_snd)
         else:
             Logger.debug('_initialize_sound loading sound for step {}\
                          ({})'.format(self.idx_stp, self.seq_snds[self.idx_stp]))
             if os.path.exists(self.seq_snds[self.idx_stp]):
                 self.sound = self.seq_snds[self.idx_stp]
             else:
                 self.sound = SoundLoader.load(os.path.join(self.base_seq_dir, self.seq_snds[self.idx_stp]))
         if self.sound is None:
             Logger.debug("_initialize_sound: not a valid sound for step {}: {}".format(
                 self.idx_stp, self.seq_snds[self.idx_stp]))
             return False
         elif self.sound.state == 'stop':
             self.sound.play()
             if platform == "android":
                 self.music_folder = "/sdcard/Music/PerAttivita"  # ToDo: not good at all
                 self.time_sound_played = time.time() + int(os.path.basename(self.default_snd).split("_")[0])
                 # ToDo: eliminate this ugly condition
             elif platform == "win":
                 self.music_folder = "C:\Mao\Progetti\Musica\MusicaSuNexus\PerAttivita"  # ToDo: not good at all
                 self.time_sound_played = time.time() + self.sound.length
             else:
                 self.music_folder = "."  # ToDo: not good at all
                 self.time_sound_played = time.time()
             #Logger.info("New sequence: Loading the mucis folder: {}".format(self.music_folder))
             # self.sound_manager.scan_music_folder(self.music_folder)
             # ToDo sound_manager
             Logger.debug('activity_click: Sound {} end playing sound on{}. Sound\
                 length is {}. Now is{}'.format(self.sound.filename, self.time_sound_played,
                 self.sound.length, time.time()))
             return True
         else:
             Logger.debug("activity_click: Sound in not expected state {} for step {}: {}".format(
                 self.sound.state,
                 self.idx_stp,
                 self.seq_snds[self.idx_stp]))
             return False
コード例 #17
0
ファイル: camera.py プロジェクト: NonnEmilia/rmap
	def __init__(self, **kwargs):
		super(CameraPreview, self).__init__(**kwargs)
		self.bind(
			preferred_picture_size=self.resolve_picture_size,
			supported_picture_sizes=self.resolve_picture_size,
			preferred_preview_size=self.resolve_preview_size,
			supported_preview_sizes=self.resolve_preview_size,
			autofocus_supported=self.update_focus_feature,
			focus_areas_supported=self.update_focus_feature)
		self.focus_move_sound = SoundLoader.load('sounds/camera-focusing.mp3')
		self.focus_done_sound = SoundLoader.load('sounds/camera-focus-beep.mp3')
		self.shutter_sound = SoundLoader.load('sounds/camera-shutter-click.mp3')
コード例 #18
0
ファイル: main.py プロジェクト: leonardocsantoss/kivy-abc
    def __init__(self, *args, **kwargs):
        super(GestureBoard, self).__init__()
        self.gdb = GestureDatabase()

        self.error_sound = SoundLoader.load('error.mp3')
        self.success_sound = SoundLoader.load('success.mp3')

        #Gestures
        for key, ges in gestures.items():
            self.gdb.add_gesture(ges)

        self.sort_letter()
コード例 #19
0
ファイル: main.py プロジェクト: gerard/TwoDeeWars
    def __init__(self):
        ret = super(Game, self).__init__()
        Config.adddefaultsection('records')
        Config.setdefault('records', 'top_points', '0')

        self.sounds = dict()
        self.sounds['firing'] = SoundLoader.load("sounds/firing.ogg")
        self.sounds['enemy_death'] = SoundLoader.load("sounds/enemy_death.ogg")
        self.sounds['game_over'] = SoundLoader.load("sounds/game_over.ogg")
        self.top_points = int(Config.get('records', 'top_points'))
        self.points = 0
        self.reset_state()
        return ret
コード例 #20
0
ファイル: main.py プロジェクト: brousch/playground
 def _type_a_letter(self, dt):
     ''' Types the next letter and plays a typewriter sound.
     '''
     # Play the sound
     SoundLoader.load('9098__ddohler__typewriter.wav').play()
     # Append the next letter
     self.the_label.text += self.type_this[self.string_pos]
     # Advance the position
     self.string_pos += 1
     # If there are more letters, schedule the next one at a random time
     # between 0.25 and 0.75 seconds from now.
     if self.string_pos < len(self.type_this):
         Clock.schedule_once(self._type_a_letter,
                             random.uniform(0.25, 0.75))
コード例 #21
0
ファイル: gui.py プロジェクト: ju5td0m7m1nd/DataBason
    def sound_control(self, which):
        if which == 'create':
            self.sound = SoundLoader.load("table_created.mp3")
        elif which == 'insert':
            self.sound = SoundLoader.load("data_inserted.mp3")
        elif which == 'select':
            self.sound = SoundLoader.load("data_selected.mp3")
        else:
            self.sound = SoundLoader.load("runtimeerror.mp3")

        if self.sound.status != 'stop':
            self.sound.stop()
        
        if not self.mute_flag:
            self.sound.play()
コード例 #22
0
ファイル: main.py プロジェクト: et8109/pathfinder
 def get_message(self, msg):
     self.print_message("playing: "+msg)
     sound = SoundLoader.load("audio/"+msg)
     if sound:
         #print("Sound found at %s" % sound.source)
         #print("Sound is %.3f seconds" % sound.length)
         sound.play()
コード例 #23
0
ファイル: cows.py プロジェクト: aq1/kivy_contest_game_2014
    def lose_the_cow(self, cow):
        sound = SoundLoader.load('sound/moo_%s.ogg' % random.randint(0, 2))
        sound.play()
        self.life -= 1

        self.remove_widget(self.life_list[-1])
        del self.life_list[-1]

        self.cows[cow.index] = None
        # self.cows = self.cows[:cow.index-1] + self.cows[cow.index:]
        self.remove_widget(cow)
        x = random.randint(0, Window.width - COW_WIDTH)

        # c_w_e_c = False  # Collides_with_existing_cow

        # while not c_w_e_c:
        #     for cow_ in self.cows:
        #         if cow_ and cow_.collide_point(x):
        #             c_w_e_c = True
        #             x = random.randint(0, Window.width - COW_WIDTH)
        #             break

        #     c_w_e_c = True
        self.add_cow(x, cow.index, True)
        if self.life == 0:
            self.game_over()
            return
コード例 #24
0
ファイル: dancingwindow.py プロジェクト: CRivlaldo/Timmy
 def init_track_data(self, track_name):
     self.current_track_name = track_name
     self.bands = Bands(track_name, track_manager.get_music_folder_path(), self.bands)
     self.track_sound = SoundLoader.load(self.get_current_track_path())
     self.sound_data = SoundData(self.get_current_track_path(), self.bands)
     self.dance = Dance(self.sound_data, self.play_track, self.on_stop_dancing)
     self.settings_group.reload(self.bands)
コード例 #25
0
ファイル: main.py プロジェクト: jjjesus/ArithmeBricks
 def load_sounds(self):
     self.symbol_to_sound = QueryDict()
     sound_ids = list('0123456789') + list(SOUND_ID_TO_SYMBOL)
     for sound_id in sound_ids:
         filename = SOUND_FILENAME_PATTERN.format(sound_id)
         symbol = SOUND_ID_TO_SYMBOL.get(sound_id, sound_id)
         self.symbol_to_sound[symbol] = SoundLoader.load(filename)
コード例 #26
0
ファイル: cows.py プロジェクト: aq1/kivy_contest_game_2014
    def __init__(self, points=0):
        super(CowStartMenu, self).__init__()
        self.size = Window.size

        if points == 0:
            self.text = INVITE_TEXT
            return
        elif points >= 600:
            self.text = 'Cows really love you.'
        elif points >= 500:
            self.text = 'Did you really play this game so long?'
        elif points >= 400:
            self.text = 'Impressing.'
        elif points >= 300:
            self.text = 'Great!'
        elif points >= 200:
            self.text = 'Good!'
        elif points >= 100:
            self.text = 'Nice!'
        elif points < 100:
            self.text = "It's okay."

        self.sound = SoundLoader.load('sound/menu.ogg')
        self.sound.volume = 0.2
        self.sound.play()

        self.text += ' %s points.\nAgain?' % points
コード例 #27
0
 def start_screen(self):
     """Displays the start screen with the title and play button. Also sets the initial difficulty variables."""
     self.clear_widgets()
     #create the logo
     self.logo = Label(text='Expression Collector',font_size=0.1*Window.height)
     self.logo.center_x = Window.width/2
     self.logo.center_y = Window.height/2
     self.add_widget(self.logo)
     #create the playbtn
     self.playbtn = Button(text='play',font_size=0.05*Window.height,background_color=[0,0,0,0])
     self.playbtn.center_x = Window.width/2
     self.playbtn.center_y = Window.height/2 - 0.1*Window.height
     self.playbtn.bind(on_release=self.play)
     self.add_widget(self.playbtn)
     #create the howtoplaybtn 100 px under the playbtn
     self.howtoplaybtn = Button(text='how to play',font_size=0.05*Window.height,background_color=[0,0,0,0])
     self.howtoplaybtn.center_x = Window.width/2
     self.howtoplaybtn.center_y = self.playbtn.center_y - 100
     self.howtoplaybtn.bind(on_release=self.howtoplay)
     self.add_widget(self.howtoplaybtn)
     #make bindings to make start screen fluid
     Window.bind(size=self.adjust_start_widgets)
     #create initial difficulty variables
     self.MINUTE = 0 #it has been 0 minutes so far
     self.MAX_NUMBER = 2 # the biggest number that can be part of an expression
     self.MAX_LENGTH = 2 #the maximum number of numbers in an expression
     self.AVAILABLE_OPERATORS = ['+','-'] #at first just + and - operators are available
     self.sound = SoundLoader.load('startscreen.wav')
     self.sound.loop = True
     self.sound.play()
コード例 #28
0
ファイル: PlaySound.py プロジェクト: thica/ORCA-Remote
def PlaySound(uSoundName, fSoundVolume=-1):
    ''' plays a given sound with a given volume '''
    try:
        oTup = oORCA.oTheScreen.aSounds.get(uSoundName)
        fVolume = fSoundVolume
        if oTup:
            uSoundFile  = oTup[0]
            SoundVolume = oTup[1]
            if uSoundFile:
                oSound = SoundLoader.load(uSoundFile)
                aSounds[uSoundFile]=oSound
                if oSound:
                    if oSound.status != 'stop':
                        oSound.stop()

                    if isinstance(fSoundVolume, string_types):
                        if fSoundVolume!=u'':
                            fVolume=ToFloat(fSoundVolume)

                    if not fVolume==-1 and not fVolume==u'':
                        fVolume=fVolume*SoundVolume
                    else:
                        fVolume=SoundVolume
                    oSound.volume=fVolume

                    #SoundLoader._set_volume(fVolume)
                    if fVolume>0:
                        oSound.play()
            return True
    except Exception as e:
        LogError(u'Playing sound failed:'+uSoundName,e)
        return False
コード例 #29
0
ファイル: main.py プロジェクト: Gagaro/runivy
 def __init__(self, **kwargs):
     super(RunivyGame, self).__init__(**kwargs)
     self.ground = Image('data/ground.png').texture
     self.ground.wrap = "repeat"
     self.music = SoundLoader.load("data/music.mp3")
     self.music.loop = True
     self.music.play()
コード例 #30
0
    def play(self,*args):
        """Goes from the start screen to the game screen. Creates the playerexpr, grid, and random Exprs."""
        #Delete the logo and button
        self.remove_widget(self.logo)
        self.remove_widget(self.playbtn)
        self.remove_widget(self.howtoplaybtn)
        #Delete start screen music, load game music
        self.sound.stop()
        self.sound = SoundLoader.load('game.wav')
        self.sound.loop = True
        self.sound.play()

        #create the grid
        global grid
        grid = Grid()
        grid.adjust_grid() #Adjust/draw the grid to the initial window size
        Window.bind(size=grid.adjust_grid) #bind Window.size -> grid.adjust_grid
        self.add_widget(grid)

        #create the playerexpr
        global playerexpr
        playerexpr = PlayerExpr(value=1,text='1',color=[1,1,1,1],font_size=grid.cell_height)
        self.add_widget(playerexpr)

        Clock.schedule_interval(playerexpr.check_collisions,1/30.0) #Check for collisions with PlayerExpr
        Clock.schedule_interval(self.create_expr,2) #create Expr objects for the game
        Clock.schedule_interval(self.make_harder,60) #make the game harder every 60 seconds

        #play bindings
        Window.bind(size=self.reposition_children) #bind window resizing to repositioning all of its children
コード例 #31
0
ファイル: main.py プロジェクト: TetoBertolla1/Site-1
        self.saveData()


class Tarefa(BoxLayout):
    def __init__(self, text='', **kwargs):
        super(Tarefa, self).__init__(**kwargs)
        self.ids.label.text = text


class Assistente(Screen):
    bot = Chatbot('Pedro')

    def mensagem(self, msg, *args):
        self.ids.box.add_widget(Tarefa(text=msg))
        frase = self.bot.escuta(frase=msg)
        resp = self.bot.pensa(frase)
        self.bot.fala(resp)
        self.ids.box.add_widget(Tarefa(text=resp))
        self.ids.texto.text = ''


class Test(App):
    def build(self):
        return Gerenciador()


popSound = SoundLoader.load('pop.mp3')
poppapSound = SoundLoader.load('poppap.mp3')

Test().run()
コード例 #32
0
    def write(self):

        global combo2
        global k
        global a
        global labeled
        sound = SoundLoader.load('garsas/swipe.wav')
        sound.play()
        if self.ids.carousel.index == 0:
            combo2 += 1
            # row = [self.ids.image1.source, 2]
            # with open('doc.csv', 'a') as f:
            #     f.write('{},{}\n'.format(self.ids.image1.source, 2))

            cursor.execute("INSERT INTO labelstuff VALUES(?, ?)",
                           (str(self.ids.image1.source), "2"))
            conn.commit()

            if self.ids.image1.source[:5] == 'label':
                k += 1
                if int(self.ids.image1.source[5]) == 2:
                    a += 1
                    labeled += 1
                    if labeled == 2:
                        Clock.schedule_once(self.RetrunCombo1, 0.1)
                        labeled = 0
                        combo2 = 0
                else:
                    labeled = 0
                    combo2 = 0
                    sound = SoundLoader.load('garsas/combobreaker.wav')
                    sound.play()

            self.ids.image1.source = self.rand_image(img_label=new_labels)
            self.ids.carousel.index = 1
            # print row
        if self.ids.carousel.index == 2:
            combo2 += 1
            # row = [self.ids.image1.source, 1]
            # with open('doc.csv', 'a') as f:
            #     f.write('{},{}\n'.format(self.ids.image1.source, 1))
            cursor.execute("INSERT INTO labelstuff VALUES(?, ?)",
                           (str(self.ids.image1.source), "1"))
            conn.commit()

            if self.ids.image1.source[:5] == 'label':
                k += 1
                if int(self.ids.image1.source[5]) == 1:
                    a += 1
                    labeled += 1
                    if labeled == 2:
                        Clock.schedule_once(self.RetrunCombo1, 0.1)
                        labeled = 0
                        combo2 = 0
                else:
                    labeled = 0
                    combo2 = 0
                    sound = SoundLoader.load('garsas/combobreaker.wav')
                    sound.play()

            self.ids.image1.source = self.rand_image(img_label=new_labels)
            self.ids.carousel.index = 1
コード例 #33
0
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)

        self.hi_score = [0,0,0,0,0,0,0,0,0,0]

        self.get_save()


        # sets the window size
        """window_height = 960
        window_width = 540
        Window.size = (window_width,window_height)"""


        # creates the base layout of the screen
        layout = BoxLayout(orientation="vertical")


        #creates the main widget that is used to draw stuff on
        self.play_field_widget = Widget()

        # adds the play_field_widget to the layout
        layout.add_widget(self.play_field_widget)

        # add the layout to the window
        self.add_widget(layout)

        # create a boolean to hold the state of the game, pauses or unpaused
        self.paused = False

        # creates the variables that holds the amount of squares of the playfield
        self.board_size_x = 3
        self.board_size_y = 5

        # variable to hold the maximum size of the board
        self.max_board_size_x = 6
        self.max_board_size_y = 8

        # creates the base varuables
        self.setup_base_variables()



        # creates the timer value
        self.timer = 0.0

        self.seconds = 0
        self.minutes = 0
        self.rounded_sec = 0

        self.timer_text = ""

        # creates the variables used for calculating the user input
        self.touch_down_x = 0
        self.touch_down_y = 0
        self.angle = 0

        # main menu object
        self.menu = Main_menu.Main_menu(True)

        # creates the player object
        self.player = Player.Player(1,0, self.sq_w, self.sq_h,
                                    self.board_size_x, self.board_size_y)

        self.player_movable = False
        self.player_moving = 0
        self.player_move_time = 0
        self.player_target_position = 0


        # instansiate the Rocket_Controll class
        self.rocket_control = Rocket_Controll.Rocket_Controll(self.play_field_width, self.play_field_height,
                                                              self.board_size_x, self.board_size_y)

        self.rip = False
        self.update_once = True
        self.grow_field = False

        # background stuff
        self.background = Background.Backgrounds(["img/background/background1.jpg","img/background/background2.jpg",\
                                            "img/background/background3.jpg","img/background/background4v2.jpg",\
                                            "img/background/background5v2.jpg"],\
                                            self.width, self.height)





        # sound
        self.bg_music = SoundLoader.load("audio/mainmenu.mp3")
        if(self.bg_music):
            self.bg_music.loop = True
            self.bg_music.volume = 3.0
            self.bg_music.play()

        self.sound_explosion = SoundLoader.load("audio/sounds/explosiontemp.mp3")
        self.sound_explosion.volume = 0.2
コード例 #34
0
ファイル: main.py プロジェクト: Allamaris0/MyKivyTimer
class CenterBox(Widget):
    con = ObjectProperty(None)
    now = datetime.now()
    start = timedelta(hours=0, minutes=0, seconds=0)
    trigger = 0
    store = None
    sound = SoundLoader.load('bell.mp3')

    numberlist=[t for t in range(0,60)] #Variable to Set Alarm Popop

    def update_clock(self, *args):
        self.now = datetime.now()
        self.label1.text = self.now.strftime('%H:%M:%S')

        if self.store!=None:
            try:
                store_hour=datetime(self.now.year, self.now.month, self.now.day, int(self.store[0]), int(self.store[1]), int(self.store[2]))
                if datetime.timestamp(store_hour) <= datetime.timestamp(self.now):
                    self.sound.play()
                    self.store=None

            except:
                exceptPopup=Popup(title="Alarm Clock", content=Label(text='Invalid value', font_size= '20sp'), size_hint=(0.5, 0.5))
                exceptPopup.open()
                self.store=None

        if self.trigger==1:
            self.start = self.start + timedelta(seconds=1)
            self.label2.text = str(self.start)
            self.btn_start.text = 'Reset'

        elif self.trigger>=1:
            self.label2.text="0:00:00"
            self.start = timedelta(hours=0, minutes=0, seconds=0)
            self.trigger=1

    def openpop(self):
        self.con = PopAlarm()
        self.con.title='Set Alarm Clock'
        self.con.size_hint=(0.7,0.7)
        self.con.content = PopContent()
        self.con.open()

    def add(self,attribute,input_value):
        #The function to Set Alarm Popup
        try:
            input_value=int(input_value)
            if attribute=="hour":
               if input_value>=23:
                   input_value = 0
               else:
                   input_value = self.numberlist[self.numberlist.index(input_value) + 1]
            elif attribute=="min":
               if input_value>=59:
                   input_value = 0
               else:
                   input_value = self.numberlist[self.numberlist.index(input_value) + 1]
            elif attribute=="sec":
               if input_value>=59:
                   input_value = 0
               else:
                   input_value= self.numberlist[self.numberlist.index(input_value) + 1]
            return input_value
        except:
            input_value=0
            return input_value

    def subtract(self,attribute,input_value):
        # The function to Set Alarm Popup
        try:
            input_value=int(input_value)
            if attribute=="hour":
               if input_value<=0:
                   input_value = 23
               else:
                   input_value = self.numberlist[self.numberlist.index(input_value) - 1]
            elif attribute=="min":
               if input_value<=0:
                   input_value = 59
               else:
                   input_value = self.numberlist[self.numberlist.index(input_value) - 1]
            elif attribute=="sec":
               if input_value<=0:
                   input_value = 59
               else:
                   input_value = self.numberlist[self.numberlist.index(input_value) - 1]
            return input_value
        except:
            input_value=0
            return input_value
コード例 #35
0
    def init(self,
             animal_names_dict=None,
             rew_in=None,
             task_in=None,
             test=None,
             hold=None,
             targ_structure=None,
             autoquit=None,
             rew_var=None,
             targ_timeout=None,
             nudge_x=None,
             nudge_y=None):

        self.rew_cnt = 0
        self.small_rew_cnt = 0

        self.use_cap_sensor = False

        if self.use_cap_sensor:
            self.serial_port_cap = serial.Serial(port='COM5')

        self.rhtouch_sensor = 0.

        targ_timeout_opts = [15, 30, 45, 60]
        for i, val in enumerate(targ_timeout['tt']):
            if val:
                self.target_timeout_time = targ_timeout_opts[i]

        small_rew_opts = [0., .1, .3, .5]
        for i, val in enumerate(rew_in['small_rew']):
            if val:
                small_rew = small_rew_opts[i]

        big_rew_opts = [0., .3, .5, .7]
        for i, val in enumerate(rew_in['big_rew']):
            if val:
                big_rew = big_rew_opts[i]

        if rew_in['rew_anytouch']:
            self.reward_for_anytouch = [True, small_rew]
        else:
            self.reward_for_anytouch = [False, 0]

        if np.logical_or(rew_in['rew_targ'], rew_in['rew_center_pls_targ']):
            self.reward_for_targtouch = [True, big_rew]
        else:
            self.reward_for_targtouch = [False, 0]

        if rew_in['rew_center_pls_targ']:
            self.reward_for_center = [True, small_rew]
        else:
            self.reward_for_center = [False, 0]

        if rew_in['snd_only']:
            self.reward_for_targtouch = [True, 0.]
            self.skip_juice = True
        else:
            self.skip_juice = False

        target_rad_opts = [.5, .75, .82, .91, 1.0, 1.5, 2.25, 3.0]
        for i, val in enumerate(task_in['targ_rad']):
            if val:
                self.periph_target_rad = target_rad_opts[i]
                self.center_target_rad = target_rad_opts[i]

        for i, (nm, val) in enumerate(animal_names_dict.items()):
            if val:
                animal_name = nm

        self.use_center = False
        for i, (nm, val) in enumerate(targ_structure.items()):
            if val:
                generatorz = getattr(self, nm)
                self.generatorz_param2 = nm
                if 'co' in nm:
                    self.use_center = True

        holdz = [0.0, 0.1, 0.2, 0.3, 0.4, .5, .6, '.4-.6']

        self.cht_type = None
        self.tht_type = None

        for i, val in enumerate(hold['hold']):
            if val:
                if type(holdz[i]) is str:
                    mx, mn = holdz[i].split('-')
                    self.tht_type = holdz[i]
                    self.tht = (float(mn) + float(mx)) * .5
                else:
                    self.tht = holdz[i]

        for i, val in enumerate(hold['chold']):
            if val:
                if type(holdz[i]) is str:
                    mx, mn = holdz[i].split('-')
                    self.cht_type = holdz[i]
                    self.cht = (float(mn) + float(mx)) * .5
                else:
                    self.cht = holdz[i]

        nudge_x_opts = [-6, -4, -2, 0, 2, 4, 6]
        for i, val in enumerate(nudge_x['nudge_x']):
            if val:
                self.nudge_x = nudge_x_opts[i]

        nudge_y_opts = [-3, -2, -1, 0, 1, 2, 3]
        for i, val in enumerate(nudge_y['nudge_y']):
            if val:
                self.nudge_y = nudge_y_opts[i]

        try:
            pygame.mixer.init()
        except:
            pass

        # reward_delay_opts = [0., .4, .8, 1.2]
        # for i, val in enumerate(rew_del['rew_del']):
        #     if val:
        self.reward_delay_time = 0.0

        reward_var_opt = [1.0, .5, .33]
        for i, val in enumerate(rew_var['rew_var']):
            if val:
                self.percent_of_trials_rewarded = reward_var_opt[i]
                if self.percent_of_trials_rewarded == 0.33:
                    self.percent_of_trials_doubled = 0.1
                else:
                    self.percent_of_trials_doubled = 0.0

        self.reward_generator = self.gen_rewards(
            self.percent_of_trials_rewarded, self.percent_of_trials_doubled,
            self.reward_for_targtouch)

        # white_screen_opts = [True, False]
        # for i, val in enumerate(white_screen['white_screen']):
        #     if val:
        self.use_white_screen = False

        test_vals = [True, False, False]
        in_cage_vals = [False, False, True]
        for i, val in enumerate(test['test']):
            if val:
                self.testing = test_vals[i]
                #self.in_cage = in_cage_vals[i]

        import os
        path = os.getcwd()
        if 'BasalGangulia' in path:
            self.in_cage = True
        else:
            self.in_cage = False

        autoquit_trls = [10, 25, 50, 100, 10**10]
        for i, val in enumerate(autoquit['autoquit']):
            if val:
                self.max_trials = autoquit_trls[i]

        # drag_ok = [True, False]
        # for i, val in enumerate(drag['drag']):
        #     if val:
        #         self.drag_ok = drag_ok[i]
        self.drag_ok = False

        # nudge_9am_dist = [0., .5, 1.]
        # for i, val in enumerate(nudge['nudge']):
        #     if val:
        self.nudge_dist = 0.

        # targ_pos = ['corners', None]
        # for i, val in enumerate(targ_pos['targ_pos']):
        #     if val:
        self.generator_kwarg = 'corners'

        # Preload sounds:
        self.reward1 = SoundLoader.load('reward1.wav')
        self.reward2 = SoundLoader.load('reward2.wav')

        self.state = 'ITI'
        self.state_start = time.time()
        self.ITI = self.ITI_std + self.ITI_mean

        # Initialize targets:
        self.center_target.set_size(2 * self.center_target_rad)

        self.center_target_position = np.array([0., 0.])
        if self.in_cage:
            self.center_target_position[0] = self.center_target_position[0] - 4
        else:
            self.center_target_position[
                0] = self.center_target_position[0] + self.nudge_x
            self.center_target_position[
                1] = self.center_target_position[1] + self.nudge_y
        self.center_target.move(self.center_target_position)
        self.periph_target.set_size(2 * self.periph_target_rad)

        self.exit_target1.set_size(2 * self.exit_rad)
        self.exit_target2.set_size(2 * self.exit_rad)
        self.indicator_targ.set_size(self.exit_rad)
        self.indicator_targ.move(self.indicator_pos)
        self.indicator_targ.color = (0., 0., 0., 1.)

        self.exit_target1.move(self.exit_pos)
        self.exit_pos2 = np.array([self.exit_pos[0], -1 * self.exit_pos[1]])
        self.exit_target2.move(self.exit_pos2)
        self.exit_target1.color = (.15, .15, .15, 1)
        self.exit_target2.color = (.15, .15, .15, 1)

        self.target_list = generatorz(self.target_distance, self.nudge_dist,
                                      self.generator_kwarg)
        self.target_list[:, 0] = self.target_list[:, 0] + self.nudge_x
        self.target_list[:, 1] = self.target_list[:, 1] + self.nudge_y
        self.target_index = 0
        self.repeat = False

        self.periph_target_position = self.target_list[self.target_index, :]

        self.FSM = dict()
        self.FSM['ITI'] = dict(end_ITI='vid_trig', stop=None)
        self.FSM['vid_trig'] = dict(rhtouch='target', stop=None)

        if self.use_center:
            self.FSM['vid_trig'] = dict(end_vid_trig='center', stop=None)
            self.FSM['center'] = dict(touch_center='center_hold',
                                      center_timeout='timeout_error',
                                      non_rhtouch='RH_touch',
                                      stop=None)
            self.FSM['center_hold'] = dict(
                finish_center_hold='target',
                early_leave_center_hold='hold_error',
                non_rhtouch='RH_touch',
                stop=None)

        self.FSM['target'] = dict(
            touch_target='targ_hold',
            target_timeout='timeout_error',
            stop=None,
            anytouch='rew_anytouch',
            non_rhtouch='RH_touch')  #,touch_not_target='touch_error')
        self.FSM['targ_hold'] = dict(finish_targ_hold='reward',
                                     early_leave_target_hold='hold_error',
                                     targ_drag_out='drag_error',
                                     stop=None,
                                     non_rhtouch='RH_touch')
        self.FSM['reward'] = dict(end_reward='ITI',
                                  stop=None,
                                  non_rhtouch='RH_touch')

        if self.use_center:
            return_ = 'center'
        else:
            return_ = 'target'

        self.FSM['touch_error'] = dict(end_touch_error=return_,
                                       stop=None,
                                       non_rhtouch='RH_touch')
        self.FSM['timeout_error'] = dict(end_timeout_error='ITI',
                                         stop=None,
                                         non_rhtouch='RH_touch')
        self.FSM['hold_error'] = dict(end_hold_error=return_,
                                      stop=None,
                                      non_rhtouch='RH_touch')
        self.FSM['drag_error'] = dict(end_drag_error=return_,
                                      stop=None,
                                      non_rhtouch='RH_touch')
        self.FSM['rew_anytouch'] = dict(end_rewanytouch='target',
                                        stop=None,
                                        non_rhtouch='RH_touch')
        self.FSM['idle_exit'] = dict(stop=None)

        try:
            self.reward_port = serial.Serial(port='COM4', baudrate=115200)
            self.reward_port.close()
        except:
            pass

        try:
            self.dio_port = serial.Serial(port='COM5', baudrate=115200)
            time.sleep(4.)
        except:
            pass

        try:
            self.cam_trig_port = serial.Serial(port='COM6', baudrate=9600)
            time.sleep(3.)
            # Say hello:
            self.cam_trig_port.write('a'.encode())

            # Start cams @ 50 Hz
            self.cam_trig_port.write('1'.encode())
        except:
            pass

        # save parameters:
        d = dict(
            animal_name=animal_name,
            center_target_rad=self.center_target_rad,
            periph_target_rad=self.periph_target_rad,
            target_structure=generatorz.__name__,
            target_list=self.target_list,
            ITI_mean=self.ITI_mean,
            ITI_std=self.ITI_std,
            ch_timeout=self.ch_timeout,
            cht=self.cht,
            reward_time_small=self.reward_for_center[1],
            reward_time_big=self.reward_for_targtouch[1],
            reward_for_anytouch=self.reward_for_anytouch[0],
            reward_for_center=self.reward_for_center[0],
            reward_for_targtouch=self.reward_for_targtouch[0],
            touch_error_timeout=self.touch_error_timeout,
            timeout_error_timeout=self.timeout_error_timeout,
            hold_error_timeout=self.hold_error_timeout,
            drag_error_timeout=self.drag_error_timeout,
            ntargets=self.ntargets,
            target_distance=self.target_distance,
            start_time=datetime.datetime.now().strftime('%Y%m%d_%H%M'),
            testing=self.testing,
            rew_delay=self.reward_delay_time,
            use_cap_sensor=self.use_cap_sensor,
            drag_ok=self.drag_ok,
        )

        print(self.reward_for_center)
        print(self.reward_for_targtouch)
        print(self.reward_for_anytouch)

        #try:
        if self.testing:
            pass

        else:
            import os
            path = os.getcwd()
            path = path.split('\\')
            path_data = [
                p for p in path
                if np.logical_and('Touch' not in p, 'Targ' not in p)
            ]
            path_root = ''
            for ip in path_data:
                path_root += ip + '/'
            p = path_root + 'data/'
            print('Auto path : %s' % p)
            # Check if this directory exists:
            if os.path.exists(p):
                pass
            else:
                p = path_root + 'data_tmp_' + datetime.datetime.now().strftime(
                    '%Y%m%d') + '/'
                if os.path.exists(p):
                    pass
                else:
                    os.mkdir(p)
                    print('Making temp directory: ', p)

            print('')
            print('')
            print('Data saving PATH: ', p)
            print('')
            print('')
            self.filename = p + animal_name + '_' + datetime.datetime.now(
            ).strftime('%Y%m%d_%H%M')

            if self.in_cage:
                self.filename = self.filename + '_cage'

            pickle.dump(d, open(self.filename + '_params.pkl', 'wb'))
            self.h5file = tables.open_file(self.filename + '_data.hdf',
                                           mode='w',
                                           title='NHP data')
            self.h5_table = self.h5file.create_table('/', 'task', Data, '')
            self.h5_table_row = self.h5_table.row
            self.h5_table_row_cnt = 0
コード例 #36
0
ファイル: main.py プロジェクト: haje01/kivy-energy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ListProperty, ObjectProperty
from kivy.metrics import dp
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
from kivy.vector import Vector
from kivy.core.image import Image as CoreImage
from kivy.graphics import Rectangle
from kivy.animation import Animation
from kivy.core.audio import SoundLoader

SOUND = True

if SOUND:
    snd_start = SoundLoader.load('sounds/appear.wav')
    snd_bgm = SoundLoader.load('sounds/alien.wav')
    snd_hit = SoundLoader.load('sounds/torpedo.wav')
    snd_explode = SoundLoader.load('sounds/bomb.wav')


UPDATE_TERM = 0.03

__version__ = '0.0.1'


class ScrollingBackground(Widget):
    text_rectangle = ObjectProperty()
    speed = NumericProperty(0.5)
    x_offset = NumericProperty(0)
コード例 #37
0
 def build(self):
     self.sound = SoundLoader.load('11_1_1_1.mp3')
     return sm
コード例 #38
0
from kivy.core.audio import SoundLoader

sound = SoundLoader.load('teste.mp3')
print('-------', sound)
if sound:
    print("Sound found at %s" % sound.source)
    print("Sound is %.3f seconds" % sound.length)
    sound.play()
コード例 #39
0
 def __init__(self, user, **kwargs):
     super(UserInventory, self).__init__(**kwargs)
     self.user = user
     self.item_dictionary_logic = {}
     self.number_of_items = len(self.item_dictionary_logic)
     self.inv_open_sound = SoundLoader.load('sounds/general/takethat.wav')
コード例 #40
0
 def __init__(self, **kwargs):
     super(OpenCityApp, self).__init__(**kwargs)
     self.sound1 = SoundLoader.load(
         os.path.join(original_dir, "button_press.mp3"))
コード例 #41
0
class LocalMultiplayerView(Screen):

    dictIndexToButtonName = {
        1: "btn1",
        2: "btn2",
        3: "btn3",
        4: "btn4",
        5: "btn5",
        6: "btn6",
        7: "btn7",
        8: "btn8",
        9: "btn9"
    }

    soundClick = SoundLoader.load("assets/menu_selection_click.ogg")

    game = TicTacToeGame()
    player1 = Player("Player1", "X")
    player2 = Player("Player2", "O")

    game.add_player([player1, player2])

    player1.start_first()
    game.start()

    def set_all_button_disable(self, isDisable):

        for index in range(1, len(self.dictIndexToButtonName) + 1):
            self.ids[self.dictIndexToButtonName[index]].disabled = isDisable

    def set_all_button_text(self, value):

        for index in range(1, len(self.dictIndexToButtonName) + 1):
            self.ids[self.dictIndexToButtonName[index]].text = value

    def restart_game(self):

        self.game = TicTacToeGame()
        self.player1 = Player("Player1", "X")
        self.player2 = Player("Player2", "O")

        self.game.add_player([self.player1, self.player2])

        self.player1.start_first()
        self.game.start()

        self.reset_button()

    def reset_button(self):
        self.set_all_button_text("")
        self.set_all_button_disable(False)

    def btnRestart_press(self, btn):
        self.restart_game()
        self.reset_button()

    def btnMainMenu_press(self, btn):
        self.restart_game()
        self.manager.current = "mainmenu"

    def btnGame_press(self, btn):

        if (self.soundClick):
            self.soundClick.play()

        if (not self.game.isOver):

            if (self.player1.isTurn):

                selectedNum = 0
                totalButton = len(self.dictIndexToButtonName)

                for index in range(1, totalButton + 1):
                    if (btn == self.ids[self.dictIndexToButtonName[index]]):
                        selectedNum = index
                        break

                self.player1.pick(selectedNum)
                self.game.remove_choice(selectedNum)

                btn.text = self.player1.marking
                btn.disabled = True

                self.game.check_winner()

                if (self.game.isHasWinner
                        or len(self.game.lstAvailableChoice) == 0):
                    self.game.over()

                self.game.next_turn()

            elif (self.player2.isTurn):

                selectedNum = 0
                totalButton = len(self.dictIndexToButtonName)

                for index in range(1, totalButton + 1):
                    if (btn == self.ids[self.dictIndexToButtonName[index]]):
                        selectedNum = index
                        break

                self.player2.pick(selectedNum)
                self.game.remove_choice(selectedNum)

                btn.text = self.player2.marking
                btn.disabled = True

                self.game.check_winner()

                if (self.game.isHasWinner
                        or len(self.game.lstAvailableChoice) == 0):
                    self.game.over()

                self.game.next_turn()

    def btnGame_release(self, btn):

        if (self.game.isOver):

            self.set_all_button_disable(True)

            boxLayout = BoxLayout(orientation="vertical")

            dlgGameOver = Popup(title="GameOver",
                                size_hint=(None, None),
                                size=(400, 400),
                                auto_dismiss=False)

            lblWinner = Label(text="Winner : ")
            lblWinner.font_size = 24

            btnRestart = Button(text="Restart")
            btnRestart.bind(on_press=self.btnRestart_press)
            btnRestart.bind(on_release=dlgGameOver.dismiss)

            btnMainMenu = Button(text="MainMenu")
            btnMainMenu.bind(on_press=self.btnMainMenu_press)
            btnMainMenu.bind(on_release=dlgGameOver.dismiss)

            if (self.player1.isWin):
                lblWinner.text += self.player1.name + " (" + self.player1.marking + ")"

            elif (self.player2.isWin):
                lblWinner.text += self.player2.name + " (" + self.player2.marking + ")"

            else:
                lblWinner.text = "Tie"

            boxLayout.add_widget(lblWinner)
            boxLayout.add_widget(btnRestart)
            boxLayout.add_widget(btnMainMenu)

            dlgGameOver.content = boxLayout
            dlgGameOver.open()
コード例 #42
0
class RLBotPlayerView(Screen):
    dictIndexToButtonName = {
        1: "btn1",
        2: "btn2",
        3: "btn3",
        4: "btn4",
        5: "btn5",
        6: "btn6",
        7: "btn7",
        8: "btn8",
        9: "btn9"
    }

    soundClick = SoundLoader.load("assets/menu_selection_click.ogg")

    state_space = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]

    game = TicTacToeGame()
    player = Player("Player", "X")
    enemy = RLBot("Computer", "O")

    game.add_player([player, enemy])

    enemy.start_first()
    game.start()

    def set_all_button_disable(self, isDisable):

        for index in range(1, len(self.dictIndexToButtonName) + 1):
            self.ids[self.dictIndexToButtonName[index]].disabled = isDisable

    def set_all_button_text(self, value):

        for index in range(1, len(self.dictIndexToButtonName) + 1):
            self.ids[self.dictIndexToButtonName[index]].text = value

    def restart_game(self):

        self.game = TicTacToeGame()
        self.player = Player("Player", "X")
        self.enemy = RLBot("Computer", "O")

        self.game.add_player([self.player, self.enemy])
        self.state_space = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
        self.enemy.start_first()
        self.game.start()

        self.reset_button()

    def reset_button(self):
        self.set_all_button_text("")
        self.set_all_button_disable(False)

    def btnRestart_press(self, btn):
        self.restart_game()
        self.reset_button()
        self.state_space = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]

    def btnMainMenu_press(self, btn):
        self.restart_game()
        self.manager.current = "selection"

    def btnRLGame_press(self, btn):
        print("In here-RLBot")
        if (self.soundClick):
            self.soundClick.play()

        if (not self.game.isOver):
            if (self.player.isTurn):
                selectedNum = 0
                totalButton = len(self.dictIndexToButtonName)

                for index in range(1, totalButton + 1):
                    if (btn == self.ids[self.dictIndexToButtonName[index]]):
                        selectedNum = index
                        break

                self.player.pick(selectedNum)
                self.game.remove_choice(selectedNum)
                self.game.play(self.state_space, "X", selectedNum)
                print("Human placed at :" + str(selectedNum))

                btn.text = self.player.marking
                btn.disabled = True

                self.game.check_winner()

                if (self.game.isHasWinner
                        or len(self.game.lstAvailableChoice) == 0):
                    self.game.over()

                self.game.next_turn()

            if (self.enemy.isTurn):
                selectedNum = self.enemy.get_Predicted_Values(self.state_space)
                self.game.play(self.state_space, "O", selectedNum)
                print("AI placed at :" + str(selectedNum))

                if (selectedNum > 0):

                    self.enemy.pick(selectedNum)
                    self.game.remove_choice(selectedNum)

                    self.ids[self.dictIndexToButtonName[
                        selectedNum]].text = self.enemy.marking
                    self.ids[self.dictIndexToButtonName[
                        selectedNum]].disabled = True

                self.game.check_winner()

                if (self.game.isHasWinner
                        or len(self.game.lstAvailableChoice) == 0):
                    self.game.over()

                self.game.next_turn()

    def btnRLGame_release(self, btn):

        if (self.game.isOver):

            self.set_all_button_disable(True)

            boxLayout = BoxLayout(orientation="vertical")

            dlgGameOver = Popup(title="Game Over",
                                size_hint=(None, None),
                                size=(500, 400),
                                auto_dismiss=False)

            lblWinner = Label(text="")
            lblWinner.font_size = 24

            btnMainMenu = Button(text="MainMenu")
            btnMainMenu.bind(on_press=self.btnMainMenu_press)
            btnMainMenu.bind(on_release=dlgGameOver.dismiss)

            if (self.player.isWin):
                lblWinner.text += "You won!"

            elif (self.enemy.isWin):
                lblWinner.text += "Yay!! I won"
            else:
                lblWinner.text = "Draw! You are tough to crack"

            boxLayout.add_widget(lblWinner)
            boxLayout.add_widget(btnMainMenu)

            dlgGameOver.content = boxLayout
            dlgGameOver.open()
コード例 #43
0
class MathsApp(App):
    sw_started = False
    sw_seconds = 0
    result = ""
    symbol_set = "+-x/"
    count = 1
    correct = 0
    sound_correct = SoundLoader.load('correct.wav')
    sound_wrong = SoundLoader.load('wrong.wav')

    def update_time(self, nap):
        self.root.ids.time.text = strftime('[b]%H[/b]:%M:[size=40]%S[/size]')

    def on_start(self):
        Clock.schedule_interval(self.update_time, 1)
        Clock.schedule_interval(self.update, 0.016)
        self.root.ids.question.text = ""
        self.update_score()

    def update(self, nap):
        if self.sw_started:
            self.sw_seconds += nap
            minutes, seconds = divmod(self.sw_seconds, 60)
            self.root.ids.stopwatch.text = (
                '%02d:%02d.[size=40]%02d[/size]' %
                (int(minutes), int(seconds), int(seconds * 100 % 100)))

    def start_stop(self):
        if self.sw_started:
            self.root.ids.start_stop.text = 'Start'
            self.sw_started = False
            self.root.ids.question.text = ""
            self.count = 1
            self.correct = 0
            self.sw_seconds = 0
            minutes, seconds = divmod(self.sw_seconds, 60)
            self.root.ids.stopwatch.text = (
                '%02d:%02d.[size=40]%02d[/size]' %
                (int(minutes), int(seconds), int(seconds * 100 % 100)))
        else:
            self.root.ids.start_stop.text = ('Start'
                                             if self.sw_started else 'Reset')
            self.sw_started = True
            self.get_question()

    def get_question(self):
        a = randint(-99, 99)
        while a % 10 == 0 or a in (-1, 0, 1):
            a = randint(-99, 99)
        b = randint(-99, 99)
        while b % 10 == 0 or b in (-1, 0, 1):
            b = randint(-99, 99)
        s = choice(self.symbol_set)
        if s == "+":
            self.result = str(a + b)
        elif s == "-":
            self.result = str(a - b)
        elif s == "x":
            self.result = str(a * b)
        else:
            self.result = "{}/{}".format(a // gcd(a, b), b // gcd(a, b))
        self.root.ids.question.text = "{} {} {} =".format(a, s, b)

    def update_score(self):
        self.root.ids.score.text = "Question: {} Correct: {} out of {}".format(
            self.count, self.correct, self.count)

    def next(self):
        if self.root.ids.answer.text == self.result:
            self.correct += 1
            self.sound_correct.play()
        else:
            self.sound_wrong.play()
        self.count += 1
        self.root.ids.answer.text = ""
        self.update_score()
        self.get_question()
コード例 #44
0
 def Sound(self, index):
     sound = SoundLoader.load('wav/%d.wav' % index)
     if sound:
         sound.play()
     return True
コード例 #45
0
 def __init__(self, file, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.sound = SoundLoader.load(file)
コード例 #46
0
# ===============================================================================
#
# This script contains all code pertaining to the sound effects used by the app.
#
# ===============================================================================

from kivy.core.audio import SoundLoader
soundPath = r"C:\Users\tahmi\OneDrive\Documents\Git\Vending-Machine\Sounds\\"
successNoise = SoundLoader.load(soundPath + 'chaching.wav')
failureNoise = SoundLoader.load(soundPath + 'breaking.wav')
コード例 #47
0
class DoubleSlitScreen(BoxLayout):
    beep = SoundLoader.load('ping.wav')

    #Objects binded from .kv file
    p_rectangle = ObjectProperty()

    button_1slit = ObjectProperty()
    button_2slits = ObjectProperty()

    button_large = ObjectProperty()
    button_medium = ObjectProperty()
    button_small = ObjectProperty()

    button_CA = ObjectProperty()
    button_ES = ObjectProperty()
    button_EN = ObjectProperty()

    label_speed = ObjectProperty()

    speed_slider = ObjectProperty()

    widget_plot = ObjectProperty()

    #Objects created here
    frame = NumericProperty(0)  #current frame
    frames = NumericProperty(0)  #total number of frames
    texture = ObjectProperty()  #texture object (initialized at create_texture)
    zoom = NumericProperty(1)  #this value autoadjusts when calling blit_P

    #Drawing parameters
    #size and position of he heatmap
    wh = 0
    hh = 0
    xh = 0
    yh = 0

    #Playback status and settings
    clock = None
    speed = NumericProperty(4)
    playing = True
    normalize_each_frame = True
    loop = True
    lasttime = time()

    #Simulation results
    Pt = None
    times = None
    maxP = 1

    slits = 2
    slit_size = "medium"

    current_filename = "lastsim"

    language = 0
    strings = {
        'slit': ['1 escletxa', '1 ranura', '1 slit'],
        'slits': ['2 escletxes', '2 ranuras', '2 slits'],
        'large': ['Grans', 'Grandes', 'Large'],
        'medium': ['Mitjanes', 'Medianas', 'Medium'],
        'small': ['Petites', 'Pequeñas', 'Small'],
        'speed': ['Velocitat', 'Velocidad', 'Speed']
    }

    measures_popup = ObjectProperty()

    def __init__(self, *args, **kwargs):
        super(DoubleSlitScreen, self).__init__(*args, **kwargs)

        self.canvas_qua = FigureCanvasKivyAgg(fig_qua)

        self.widget_plot.add_widget(self.canvas_qua)

        #Tries to load old simulation, in case there isn't any, it creates an
        #empty experiment with only psi(t=0)
        print("Trying to load last simulation")
        try:
            self.load_experiment()
        except FileNotFoundError:
            print("Could not find last simulation, creating new one...")
            self.experiment = DSexperiment()
            self.experiment.set_gaussian_psi0(p0x=150 / self.experiment.Lx)
            self.maxP = np.max(self.experiment.Pt)

        self.create_textures()
        self.clock = Clock.schedule_interval(self.update, 1.0 / 30.0)

    def set_language(self, lang):
        self.language = lang
        self.button_1slit.text = self.strings['slit'][self.language]
        self.button_2slits.text = self.strings['slits'][self.language]
        self.button_large.text = self.strings['large'][self.language]
        self.button_medium.text = self.strings['medium'][self.language]
        self.button_small.text = self.strings['small'][self.language]
        self.label_speed.text = self.strings['speed'][self.language]

    def load_experiment(self):
        self.experiment = create_experiment_from_files("{}_{}".format(
            self.slits, self.slit_size))
        print("Simulation loaded correctly")
        self.computation_done(save=False)
        self.remove_measurements()
        self.experiment.compute_py(force=True)
        aqu.cla()
        aqu.get_xaxis().set_ticks([])
        aqu.get_yaxis().set_ticks([])
        aqu.plot(np.arange(-self.experiment.Ly, self.experiment.Ly,
                           self.experiment.dx),
                 self.experiment.py,
                 c="g",
                 lw=4)
        aqu.set_xlim(-self.experiment.Ly, self.experiment.Ly)
        aqu.set_ylim(0, np.max(self.experiment.py))
        self.canvas_qua.draw()

    #Drawing functions
    def create_textures(self):
        """
        Creates the textures that will be used (for the wavefunction and for the potential (slits) )
        """
        self.texture_psi = Texture.create(
            size=self.experiment.Pt[0].shape[::-1],
            colorfmt="luminance",
            bufferfmt="float")
        self.texture_V = Texture.create(size=self.experiment.Pt[0].shape[::-1],
                                        colorfmt="rgba",
                                        bufferfmt="float")

    wall_color = (200, 0, 255)

    def blit_P(self, P):
        """
        This function draws the heatmap for P centered at
        P is a 2d numpy array
        """

        #Basically if white should represent the maximum value of P at each frame
        #or should represent the maximum value of all frames
        if self.normalize_each_frame:
            max = np.max(P)
        else:
            max = self.maxP

        #Stores the P matrix in the texture object
        #this texture is created in the method creature_texture and already has the size
        #It's a gray-scale texture so value must go from 0 to 255 (P/self.maxP)*255
        #It must be an array of unsigned 8bit integers. And also it has to be flattened

        self.texture_psi.blit_buffer(
            ((P[:, ::-1] / max)).astype(np.float32).reshape(P.size),
            colorfmt="luminance",
            bufferfmt="float")

        #Draws walls
        with self.p_rectangle.canvas:
            #Determines the size of the box:
            #Full height
            self.zoom = self.p_rectangle.height / P.shape[0]
            #If full height implies cutting by the sides, it uses full width
            if P.shape[1] * self.zoom > self.p_rectangle.width:
                #Full width
                self.zoom = self.p_rectangle.width / P.shape[1]

            self.wh = P.shape[1] * self.zoom
            self.hh = P.shape[0] * self.zoom

            self.xh = self.p_rectangle.pos[
                0] + self.p_rectangle.width / 2 - self.wh / 2
            self.yh = self.p_rectangle.pos[
                1] + self.p_rectangle.height / 2 - self.hh / 2

            Color(self.wall_color[0] / 255, self.wall_color[1] / 255,
                  self.wall_color[2] / 255)  #Red
            #box wall
            Rectangle(pos=(self.xh - 5, self.yh - 5),
                      size=(self.wh + 10, self.hh + 10))

            #Heatmap
            Color(1., 1., 1.)  #White
            Rectangle(texture=self.texture_psi,
                      pos=(self.xh, self.yh),
                      size=(self.wh, self.hh))

    def draw_slits(self):
        """
        Draws the slits (heatmap of the potential energy)
        """
        with self.p_rectangle.canvas:
            V = self.experiment.V[:, ::-1]
            Vo = self.experiment.Vo

            M = np.zeros((V.shape[0], V.shape[1], 4), dtype=np.float32)
            for i in range(3):
                M[:, :, i] = (self.wall_color[i] * V / Vo).astype(np.float32)
            M[:, :, 3] = M[:, :, 0]

            self.texture_V.blit_buffer(M.reshape(M.size),
                                       colorfmt="rgba",
                                       bufferfmt="float")

            Rectangle(texture=self.texture_V,
                      pos=(self.xh, self.yh),
                      size=(self.wh, self.hh))

    def draw_measures(self):
        """
        Draws points representing measures in the main UI
        """

        with self.p_rectangle.canvas:
            scale = self.zoom / self.experiment.dx

            #Measuring screen
            Color(0, 1., 0, 0.25)
            Rectangle(pos=(self.xh + self.wh - self.experiment.mp * self.zoom,
                           self.yh),
                      size=(self.experiment.mw * self.zoom, self.hh))

            Color(0, 1., 0)
            for measure in self.experiment.measurements:
                Ellipse(pos=(self.xh + self.wh -
                             2 * self.experiment.mp * self.zoom +
                             measure[0] * self.zoom,
                             self.yh + measure[1] * self.zoom),
                        size=(self.zoom, self.zoom))

    def computation_update(self, msg, x):
        """
        This is called by the thread computing the simulation
        """
        pass

    def computation_done(self, save=True):
        """
        This is called when the simulation has been completed
        """
        self.frames = self.experiment.Pt.shape[0]
        self.maxP = np.max(self.experiment.Pt)
        self.create_textures()

        if save:
            self.experiment.save_to_files("lastsim")

    def slider_moved(self, a, b):
        Clock.schedule_once(self.reset_speed, 5 * 60)

    def reset_speed(self, a):
        self.speed_slider.value = 5

    #Playback functions
    def playpause(self):
        self.playing = not self.playing
        if self.playing:
            self.clock = Clock.schedule_interval(self.update, 1.0 / 30.0)
            self.playpause_button.text = "Pause experiment"
        else:
            self.clock.cancel()
            self.playpause_button.text = "Start experiment"

    def change_frame(self):
        self.playing = False

    bins = 40
    Nexp = 200

    def measure(self, N=1):
        self.experiment.measure(N)
        dx = 2 * self.experiment.Ly / self.bins
        A = max(self.Nexp, len(self.experiment.measurements)) * dx
        #self.beep.play()
        aqu.cla()
        aqu.get_xaxis().set_ticks([])
        aqu.get_yaxis().set_ticks([])
        aqu.hist([
            -self.experiment.Ly + measure[1] * self.experiment.dx
            for measure in self.experiment.measurements
        ],
                 range=(-self.experiment.Ly, self.experiment.Ly),
                 bins=self.bins,
                 edgecolor='g')
        aqu.set_xlim(-self.experiment.Ly, self.experiment.Ly)
        aqu.set_ylim(0, np.max(self.experiment.py * A))
        aqu.plot(np.arange(-self.experiment.Ly, self.experiment.Ly,
                           self.experiment.dx),
                 self.experiment.py * A,
                 c="g",
                 lw=4)
        self.canvas_qua.draw()

    def remove_measurements(self):
        self.experiment.clear_measurements()

    lang_dict = {'CA': 0, 'ES': 1, 'EN': 2}

    def button_toggled(self, button):
        if button.name in ["1", "2"]:
            self.button_1slit.color = (1.0, 1.0, 1.0, 1.0)
            self.button_2slits.color = (1.0, 1.0, 1.0, 1.0)
            self.last_number = button
            button.color = (0, 0.75, 1, 1)
            self.slits = int(button.name)
            self.load_experiment()
        elif button.name in ["small", "medium", "large"]:
            self.button_small.color = (1.0, 1.0, 1.0, 1.0)
            self.button_medium.color = (1.0, 1.0, 1.0, 1.0)
            self.button_large.color = (1.0, 1.0, 1.0, 1.0)
            self.last_size = button
            button.color = (0, 0.75, 1, 1)
            self.slit_size = button.name
            self.load_experiment()
        elif button.name in ["CA", "ES", "EN"]:
            self.button_CA.color = (1.0, 1.0, 1.0, 1.0)
            self.button_ES.color = (1.0, 1.0, 1.0, 1.0)
            self.button_EN.color = (1.0, 1.0, 1.0, 1.0)
            self.last_lang = button
            button.color = (0, 0.75, 1, 1)
            self.set_language(self.lang_dict[button.name])

        print(self.slits, self.slit_size)

    def update(self, dt):

        self.speed = int(self.speed_slider.value)

        if self.playing:
            self.p_rectangle.canvas.clear()
            self.blit_P(self.experiment.Pt[self.frame])
            self.draw_slits()
            self.draw_measures()
            self.frame = (self.frame + self.speed)

            if self.frame >= self.frames:
                if self.beep:
                    self.beep.play()
                self.measure()
                if self.loop:
                    self.frame = self.frame % self.frames
                else:
                    self.frame = 0

        else:
            self.p_rectangle.canvas.clear()
            self.blit_P(self.experiment.Pt[self.frame])
            self.draw_slits()
            self.draw_measures()
コード例 #48
0
ファイル: view.py プロジェクト: rrrrr4788/poppy
    def capture(self):
        '''
        Function to capture the images and give them the names
        according to their captured time and date.
        '''
        camera = self.ids['camera']
        timestr = time.strftime("%Y%m%d_%H%M%S")
        error_sound = SoundLoader.load('windows_error.mp3')

        # if not path.exists("/sdcard/kivy_temp"):
        #     mkdir("/sdcard/kivy_temp")

        # Clock.schedule_once(partial(camera.export_to_png,
        #                             "/sdcard/kivy_temp/IMG_{}.png".format(timestr)))
        camera.export_to_png("IMG_{}.png".format(timestr))

        with open("IMG_{}.png".format(timestr), "rb") as image_file:
            encoded_string = base64.b64encode(image_file.read())

        # with open("/sdcard/kivy_temp/IMG_{}.png".format(timestr), "rb") as image_file:
        #     encoded_string = base64.b64encode(image_file.read())

        data = {'img_string': encoded_string}
        # r = requests.post(url="http://localhost:5000", data=data)
        r = requests.post(
            url="https://guarded-sea-73072.herokuapp.com/", data=data)

        pastebin_url = r.text
        # print("The pastebin URL is:%s"%pastebin_url)
        if r.status_code != 200:
            print(r.status_code, "bad analysis")
            error_sound.play()
            # vibrator.vibrate(0.5)
        else:
            print(r.status_code, r.reason, r.content.decode('utf-8'))
            if r.content.decode('utf-8') != "Another One":
                content = r.content.decode('utf-8')
                body = ""
                start_of_time = False
                start_of_body = False
                for line in content.splitlines():
                    print(line, start_of_body, start_of_time)
                    
                    if start_of_time:
                        task_ = (body, line[:19])
                        self.db.add_task(task_)
                        # vibrator.vibrate(0.2)
                        # time.sleep(0.1)
                        # vibrator.vibrate(0.2)
                    if line.strip() == "The alarms are set for:":
                        start_of_time = True
                        start_of_body = False
                    if start_of_body:
                        body += line
                    if line.strip() == "This is the event below:":
                        start_of_body = True
            else:
                error_sound.play()
                # vibrator.vibrate(0.5)

        remove("IMG_{}.png".format(timestr))
コード例 #49
0
 def on_enter(self):
     self.bttn_effect = SoundLoader.load('steelsword.wav')
     self.bttn_effect.play()
     new_game.unstoppable = SoundLoader.load('unstoppable.wav')
     new_game.unstoppable.volume = .4
コード例 #50
0
#add: quit button, try/catch pop-ups, dicitonary list, audtodict

import time
from kivy.core.audio import SoundLoader
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.core.clipboard import Clipboard
from kivy.config import Config

Config.set('graphics', 'fullscreen', 'auto')
open_sound = SoundLoader.load('Laugh.mp3')
open_sound.volume = 0.2
encode_sound = SoundLoader.load('Healing.mp3')
encode_sound.volume = 0.2
decode_sound = SoundLoader.load('Pointer.mp3')
decode_sound.volume = 0.2
quit_sound = SoundLoader.load('Run.mp3')
quit_sound.volume = 0.2
error_sound = SoundLoader.load('Li.mp3')
error_sound.volume = 0.2
copy_sound = SoundLoader.load('Save.mp3')
copy_sound.volume = 0.2
paste_sound = SoundLoader.load('SavePoint.mp3')
paste_sound.volume = 0.2

alphadict_q = {
    1: 'q',
    2: 'w',
    3: 'e',
    4: 'r',
コード例 #51
0
 def on_start(self):
     DragonWars.intro = SoundLoader.load('intro.wav')
     Clock.schedule_once(self.play_intro, 3)
コード例 #52
0
 def play_music(self):
     new_game.unstoppable.play()
     self.player_fire_breath = SoundLoader.load('player_dragon_breath.wav')
     self.enemy_fire_breath = SoundLoader.load('enemy_dragon_breath.wav')
コード例 #53
0
 def audio(self, dt):
     sound = SoundLoader.load('audio_file.wav')
     if sound:
         sound.play()
コード例 #54
0
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.core.audio import SoundLoader
# core for window & apps this one is for mobile devices
from kivy.core.window import Window
from kivy.uix.button import Button

#Sounds
buttonsound = SoundLoader.load('sounds/button_click_0.wav')  #button click
errorsound = SoundLoader.load('sounds/error.wav')  #error click
clearsound = SoundLoader.load(
    'sounds/clear_button_0_thanos_snap.wav')  #clearing click
equalsound = SoundLoader.load('sounds/equal.wav')  #equal click


class CalcWindow(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # mobile device screen for iphone or andriods
        Window.size = (300, 500)

        # creating a list for the numbers
        numbers = [
            7, 8, 9, '+', 4, 5, 6, '-', 1, 2, 3, '*', '.', 0, '(', ')', '/'
        ]
        self.numbers = self.ids.numbers

        # Number clearing
        numbers_clear = ['C', 'Ca']  # clear, clear all
        self.numbers = self.ids.numbers
コード例 #55
0
    def __init__(self, **kwargs):
        super(Experiment_Staging, self).__init__(**kwargs)
        self.monitor_x_dim = GetSystemMetrics(0)
        self.monitor_y_dim = GetSystemMetrics(1)
        self.size = (self.monitor_x_dim, self.monitor_y_dim)

        self.curr_dir = os.getcwd()
        self.trial_displayed = False
        self.data_dir = self.curr_dir + "\\Data"
        if not os.path.exists(self.data_dir):
            os.makedirs(self.data_dir)

        self.presentation_delay_start = False
        self.image_on_screen = False
        self.feedback_displayed = False
        self.correction_active = False

        self.delay_length = 10

        self.max_trials = 30  # MAX Number of Trials / Session
        self.max_time = 3600  # Cutoff Time / Session (sec)

        self.time_elapsed = 0  # How long has elapsed during the protocol
        self.start_time = time.time()  # Timer to track ITI/Stim Pres/etc
        self.start_iti_time = 0  # Start time for timer to track

        self.iti_time = 8  # Delay time between trials
        self.presentation_delay_time = 10  # Amount of time between start and presentation (Trial # 1)
        self.feedback_length = 2  # Amount of time Sound/Cue are Present

        self.image_list = ['marble', 'fan']  # Names of Files #
        self.image_pos = [-1, 1]  # Index position for Image Shift from Center

        #SELECT CORRECT IMAGE###########
        self.correct_image_index = 1  ## 0 = LEFT, 1 = RIGHT)

        # Set the incorrect based on correct
        if self.correct_image_index == 0:
            self.incorrect_image_index = 1
        elif self.correct_image_index == 1:
            self.incorrect_image_index = 0

        # Random # Generator to determine which side each stimuli goes to
        self.correct_image_pos = random.randint(0, 1)
        if self.correct_image_pos == 0:
            self.incorrect_image_pos = 1
        elif self.correct_image_pos == 1:
            self.incorrect_image_pos = 0
        ###############################

        self.lat = 0  # Placeholder for Latency Time

        self.current_trial = 1  # Current Trial #
        self.current_correct = 0  # Is current trial a correct one?
        self.current_correction = 0  # Is current trial requiring correction?

        self.total_trials = 0
        self.total_correct = 0
        self.total_corrections = 0
        self.correct_latency_list = []
        self.incorrect_latency_list = []

        self.correct_sound_path = self.curr_dir + "\\Sounds\\Correct.wav"  # Filepath to Correct Sound
        self.incorrect_sound_path = self.curr_dir + "\\Sounds\\Incorrect.wav"  # Filepath to Incorrect Sound
        self.feedback_sound = SoundLoader.load(
            self.correct_sound_path)  # Loads sound to placeholder
        self.feedback_sound.loop = True  # Set Sound-Repeating Function

        self.delay_hold_button = ImageButton(
            source='%s\\Images\\white.png' % (self.curr_dir),
            allow_stretch=True)  # Set Delay Button Filepath
        self.delay_hold_button.size_hint = (
            .5, .5)  # Set Delay Button Size (relative to screen size)
        self.delay_hold_button.pos = (
            (self.center_x - (0.25 * self.monitor_x_dim)),
            (self.center_y - (0.25 * self.monitor_y_dim) -
             (0.1 * self.monitor_y_dim))
        )  # Set Relative Position of Delay Button

        Clock.schedule_interval(
            self.clock_update,
            0.001)  # Run Timer Function Every 1000th of a second (Precision)
        self.id_entry()  #Move to next stage to Enter Filename
コード例 #56
0
ファイル: main.py プロジェクト: chrisseymour/walk-kivy
 def __init__(self, file, n):
     self.num = n
     self.sounds = [SoundLoader.load(file) for _ in range(n)]
     self.index = 0
コード例 #57
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        game_sounds = 'assets/sounds/Game/'
        slug_sounds = 'assets/Sounds/Slugs Winning/'

        # game
        self.background_music = SoundLoader.load(game_sounds +
                                                 'Background Music.mp3')
        self.slugs_running_sound = SoundLoader.load(game_sounds +
                                                    'Slugs Running.mp3')
        self.gameover_sound = SoundLoader.load(game_sounds + 'Game Over.mp3')
        self.go_sound = SoundLoader.load(game_sounds + 'Go.mp3')

        # slugs
        self.speedster.win_sound = SoundLoader.load(slug_sounds +
                                                    'Speedster Win.mp3')
        self.trusty.win_sound = SoundLoader.load(slug_sounds +
                                                 'Trusty Win.mp3')
        self.iffy.win_sound = SoundLoader.load(slug_sounds + 'Iffy Win.mp3')
        self.slowpoke.win_sound = SoundLoader.load(slug_sounds +
                                                   'Slowpoke Win.mp3')

        # default volumes
        self.slugs_running_sound.volume = .2
        self.go_sound.volume = .1
        self.gameover_sound.volume = .1

        # sounds
        self.sounds = [
            self.background_music, self.slugs_running_sound,
            self.gameover_sound, self.go_sound, self.speedster.win_sound,
            self.trusty.win_sound, self.iffy.win_sound, self.slowpoke.win_sound
        ]

        # background music
        self.background_music.volume = .1
        self.background_music.loop = True
        self.background_music.play()

        # accidents
        self.acc_broken_leg = BrokenLegAccident()
        self.acc_overheat = OverheatAccident()
        self.acc_heart_attack = HeartAttackAccident()
        self.acc_grass = GrassAccident()
        self.acc_asleep = AsleepAccident()
        self.acc_blind = BlindAccident()
        self.acc_puddle = PuddleAccident()
        self.acc_electroshock = ElectroshockAccident()
        self.acc_turning_back = TurningBackAccident()
        self.acc_shooting_eyes = ShootingEyesAccident()
        self.acc_rubberized = RubberizedAccident()
        self.acc_devoured = DevouredAccident()

        self.accidents = [
            self.acc_broken_leg, self.acc_overheat, self.acc_heart_attack,
            self.acc_grass, self.acc_asleep, self.acc_blind, self.acc_puddle,
            self.acc_electroshock, self.acc_turning_back,
            self.acc_shooting_eyes, self.acc_rubberized, self.acc_devoured
        ]

        self.accident = None
コード例 #58
0
import random

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.core.audio import SoundLoader

sfx_flap = SoundLoader.load('audio/flap.wav')
sfx_score = SoundLoader.load('audio/score.wav')
sfx_die = SoundLoader.load('audio/die.wav')

from kivy.uix.image import Image


class params(object):
    def init(self):
        w, h = Window.size
        ws = float(w) / 288
        hs = float(h) / 284
        self.scale = min(ws, hs)


params = params()


class Sprite(Image):
    def __init__(self, **kwargs):
        super(Sprite, self).__init__(allow_stretch=True, **kwargs)
        w, h = self.texture_size
コード例 #59
0
ファイル: main.py プロジェクト: KivyAcademy/kivyteach
from kivy.app import App
from kivy.clock import Clock
from kivy.core.image import Image
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty, ListProperty, NumericProperty, StringProperty
from kivy.properties import AliasProperty
from kivy.core.window import Window, Keyboard
from kivy.uix.label import Label
from kivy.uix.image import Image as ImageWidget
from kivy.core.audio import SoundLoader
#legg til her
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import Screen
from kivy.storage.jsonstore import JsonStore

sfx_flap = SoundLoader.load("audio/flap.wav")
sfx_score = SoundLoader.load("audio/score.wav")
sfx_die = SoundLoader.load("audio/die.wav")
sfx_start = SoundLoader.load("audio/start.wav")

import random


class BaseWidget(Widget):
    def load_tileable(self, name):
        t = Image('images/{}.png'.format(name)).texture
        t.wrap = 'repeat'
        setattr(self, 'tx_{}'.format(name), t)


class Background(BaseWidget):
コード例 #60
0
 def load_sounds(self):
     self.sounds = {}
     self.sounds[0] = SoundLoader.load("sounds\TangramOpen_myFriend.m4a")
     self.sounds[1] = SoundLoader.load("sounds\TangramOpen_click.m4a")