def add_explosion(self, line): line += self.currently_exploding self.currently_exploding += 1 explosion = InstructionGroup() color = Color(1, 1, .5, .8) explosion.add(color) explosion.add(Rectangle( pos=self.coord_to_pos(0, line), size=( self.tile_size()[0] * self.cols, self.tile_size()[1] ) )) self.canvas.add(explosion) def remove(self): self.canvas.remove(explosion) self.currently_exploding -= 1 anim = Animation( a=0, duration=.125 ) anim.bind(on_complete=lambda *args: remove(self)) anim.start(color)
class CompassApp(App): needle_angle = NumericProperty(0) def build(self): self._anim = None Hardware.magneticFieldSensorEnable(True) Clock.schedule_interval(self.update_compass, 1 / 10.) def update_compass(self, *args): # read the magnetic sensor from the Hardware class (x, y, z) = Hardware.magneticFieldSensorReading() # calculate the angle needle_angle = Vector(x, y).angle((0, 1)) + 90. # animate the needle if self._anim: self._anim.stop(self) self._anim = Animation(needle_angle=needle_angle, d=.2, t='out_quad') self._anim.start(self) def on_pause(self): # when you are going on pause, don't forget to stop the sensor Hardware.magneticFieldSensorEnable(False) return True def on_resume(self): # reactivate the sensor when you are back to the app Hardware.magneticFieldSensorEnable(True)
def show_error(self, e): self.info_label.text = str(e) duration = len(self.info_label.text)/50 anim = Animation(top=190.0, opacity=1, d=0.5) +\ Animation(top=190.0, d=duration) +\ Animation(top=0, opacity=0, d=2) anim.start(self.info_label)
def reset_cutter(self): self.cutter_event.cancel() ph = {'right': 1.0} anim = Animation(pos_hint=ph, duration=config.cutter_downtime) anim.bind(on_complete=lambda i, j: self.start_clock()) anim.start(self.cutter)
def fade_out(self, duration): if duration == 0: self._a = 0. return anim = Animation(_a=0., duration=duration, t='out_quad') anim.bind(on_complete=lambda *x: self.dispatch('on_invisible')) anim.start(self)
def sinking(self, instance, value): anim = Animation(y=33, d=9) anim &= Animation(x=self.x + 10, t="in_out_back", d=2.25) + \ Animation(x=self.x - 10, t="in_out_back", d=2.25) + \ Animation(x=self.x + 10, t="in_out_back", d=2.25) + \ Animation(x=self.x, t="in_out_back", d=2.25) anim.start(self)
def on_enter(self): anim = Animation( opacity=1.0, duration=2.0) # anim &= Animation(size=[self.menu_text.size[0]+4, self.menu_text[1]+4], duration=.2) anim.start(self.story_text1) Clock.schedule_once(self.show_text2, 2.0)
def show(self, *args): global movies self.bottom_header.source = 'images/header-suggestions.png' self.buy_btn.x = 1920 self.bottom_layer.pos = (1080,0) self.ad_image.x = 1080 self.video.x = 1080 anim = Animation(x=0, t='out_quad', d=1.5) anim.start(self.bottom_layer) anim2 = Animation(x=0, t='out_quad', d=1.5) anim2.start(self.ad_image) self.movie_title.x=1080 self.movie_meta.x=1080 self.movie_text.x=1080 for c in self.trailer_layer.children[:]: self.trailer_layer.remove_widget(c) self.trailer1 = MovieThumbnail(text="trailer 1") self.trailer1.movie = movies[self.app.suggestions[0]] self.trailer_layer.add_widget(self.trailer1) self.trailer2 = MovieThumbnail(text="trailer 2") self.trailer2.movie = movies[self.app.suggestions[1]] self.trailer_layer.add_widget(self.trailer2) self.trailer3 = MovieThumbnail(text="trailer 3") self.trailer3.movie = movies[self.app.suggestions[2]] self.trailer_layer.add_widget(self.trailer3)
def next(self,*largs): Clock.unschedule(self.next) if(self.screenManager.current == 'page1'): next = 'page2' page = self.page2 else: next = 'page1' page = self.page1 self.index += 1 if self.index == len(self.photos): self.index = 0 page.source = self.photos[self.index] page.background.scale = 1.0 self.screenManager.transition = self.transitions[random.randint(0, len(self.transitions) -1)] self.screenManager.current = next anim = Animation( scale=page.background.scale*1.3, duration=15.0 ) Clock.schedule_once(self.next, 10) anim.start(page.background)
def toggle(self): Animation.stop_all(self, 'x') Animation.stop_all(self.shadow, 'color') if self._open: if self.side == 'left': target_x = -1 * self.width else: target_x = Window.width sh_anim = Animation(duration=self.anim_length_open, t=self.animation_t_open, color=[0, 0, 0, 0]) sh_anim.start(self.shadow) self._get_main_animation(duration=self.anim_length_close, t=self.animation_t_close, x=target_x).start(self) self._open = False else: if self.side == 'left': target_x = 0 else: target_x = Window.width - self.width Animation(duration=self.anim_length_open, t=self.animation_t_open, color=[0, 0, 0, 0.5]).start(self.shadow) self._get_main_animation(duration=self.anim_length_open, t=self.animation_t_open, x=target_x).start(self) self._open = True
def on_touch_down(self, touch): """Either make a new tower, or display menu for an existing one """ tower_coord = (touch.x // self.cell_width // TOWER_SIZE * TOWER_SIZE, touch.y // self.cell_height // TOWER_SIZE * TOWER_SIZE) matrix_coord = tower_coord[0] + 1, tower_coord[1] + 1 if self.matrix[matrix_coord] < 0: # On tower? for tower in self.towers: # Yes, relay the touch to it if tower.coord == tower_coord: tower.on_touch_down(touch) break else: # Not on tower pass else: # On free space – make tower side = int(touch.x > self.window_width / 2) if self.funds[side] >= 0: size = (self.cell_width * TOWER_SIZE, self.cell_height * TOWER_SIZE) tower = Tower( pos=( touch.x // size[0] * size[0], touch.y // size[1] * size[1]), size=size, side=side ) tower.coord = tower_coord if self.add_tower(tower): tower.on_touch_down(touch) else: # Tower would block; display message to that effect label = Label( text='Blocking!', pos=(-50, -50), size=(100, 100), font_size=self.cell_width * 2, color=(1, 1, 1, 1), ) self.add_widget(label) with label.canvas.before: PushMatrix() Translate(touch.pos[0], touch.pos[1], 0) Rotate(90 if side else 270, 0, 0, 1) with label.canvas.after: PopMatrix() # Animate and fade out the message anim = Animation(font_size=TOWER_PIXEL_SIZE * 2, color=(1, 1, 1, 0), duration=1, t='in_quad') anim.start(label) def tick_blocking_anim(dt): label.canvas.ask_update() Clock.schedule_once(tick_blocking_anim) tick_blocking_anim(0) def end_blocking_anim(dt): self.remove_widget(label) Clock.unschedule(tick_blocking_anim) Clock.schedule_once(end_blocking_anim, 1)
def login(self): animation = Animation(x=self.login_area.x - self.login_area.width, duration=0.8) animation.start(self.login_area) self.pan_screen= Image(source= "mylogo1.jpg", keep_ratio= False, allow_stretch= True, color= (1, 1, 1, 0.1)) self.add_widget(self.pan_screen) animation.bind(on_complete=self.check_login)
def __init__(self, **kwargs): super(GoGame, self).__init__(**kwargs) self.stone = GoStone(size=(40,40)) self.stone.center = (100,100) anim = Animation(x=500, y=500, duration=3) anim.start(self.stone) self.add_widget( self.stone )
def on_touch_down(self, touch): if self in touch.ud: self.anim_complete(self, self) self.ripple_pos = ripple_pos = (touch.x, touch.y) Animation.cancel_all(self, 'ripple_rad', 'ripple_color') rc = self.ripple_color ripple_rad = self.ripple_rad self.ripple_color = [rc[0], rc[1], rc[2], 1.] anim = Animation( ripple_rad=max(self.width, self.height) * self.ripple_scale, t=self.ripple_func_in, ripple_color=[rc[0], rc[1], rc[2], self.fade_to_alpha], duration=self.ripple_duration_in) anim.start(self) with self.canvas.after: x,y = self.to_window(*self.pos) width, height = self.size #In python 3 the int cast will be unnecessary ScissorPush(x=int(round(x)), y=int(round(y)), width=int(round(width)), height=int(round(height))) self.col_instruction = Color(rgba=self.ripple_color) self.ellipse = Ellipse(size=(ripple_rad, ripple_rad), pos=(ripple_pos[0] - ripple_rad/2., ripple_pos[1] - ripple_rad/2.)) ScissorPop() self.bind(ripple_color=self.set_color, ripple_pos=self.set_ellipse, ripple_rad=self.set_ellipse) return super(TouchRippleBehavior, self).on_touch_down(touch)
class MDCheckbox(ThemableBehavior, CircularRippleBehavior, ToggleButtonBehavior, Label): active = BooleanProperty(False) _checkbox_icon = StringProperty( u"{}".format(md_icons['md-check-box-outline-blank'])) _radio_icon = StringProperty(u"{}".format(md_icons['md-radio-button-off'])) _icon_active = StringProperty(u"{}".format(md_icons['md-check-box'])) def __init__(self, **kwargs): super(MDCheckbox, self).__init__(**kwargs) self.register_event_type('on_active') self.check_anim_out = Animation(font_size=0, duration=.1, t='out_quad') self.check_anim_in = Animation(font_size=sp(24), duration=.1, t='out_quad') self.check_anim_out.bind( on_complete=lambda *x: self.check_anim_in.start(self)) def on_state(self, *args): if self.state == 'down': self.check_anim_in.cancel(self) self.check_anim_out.start(self) self._radio_icon = u"{}".format(md_icons['md-radio-button-on']) self._checkbox_icon = u"{}".format(md_icons['md-check-box']) self.active = True else: self.check_anim_in.cancel(self) self.check_anim_out.start(self) self._radio_icon = u"{}".format(md_icons['md-radio-button-off']) self._checkbox_icon = u"{}".format( md_icons['md-check-box-outline-blank']) self.active = False def on_active(self, instance, value): self.state = 'down' if value else 'normal'
def prepare_next(self,dt): self.generateGameQuestion(self.level) self.y=self.parent.height/2-self.height/1.5 self.x=-self.width-10 anim=Animation(x=10,d=self.levelSpeed/4,t="in_out_back") anim.bind(on_complete=self.prepareQuestionPanel) anim.start(self)
def move_to_repeat_battle(self, widget=None, event=None): self.graphics_widget.remove_widget(self.scatter_hero) anim = Animation(x = 8 * X_BLOCK, duration = 12) self.image_baddy.walk(30, 8 * X_BLOCK) anim.start(self.image_baddy) self.schedule(self.repeat_battle, 3)
def countdown(self, num): """The countdown for the solving player For positive `num`, shows the number near the maze entrance, animates it, and schedules a call to countdown(num-1) for one second. For num == 0, display 'Go!', animate it, and grow the ball source. """ label = Label( text=str(num) if num else 'Go!', font_size=24, color=(0, 0, 1, 1), ) with label.canvas.before: PushMatrix() Translate( self.window_width - self.cell_size * 1, self.window_height - self.cell_size * 5, 0, ) Rotate(90, 0, 0, 1) with label.canvas.after: PopMatrix() animation = Animation(font_size=256, color=(0, 0, 1, 0), t='in_cubic', duration=1.5) animation.start(label) self.add_widget(label) if num > 0: Clock.schedule_once(lambda dt: self.countdown(num - 1), 1) else: self.ball_source.grow(self.cell_size * 3) if self.parent: self.parent.set_message(True, u'Take a ball from the blue corner.')
def open(self, *largs, **kwargs): '''Show the view window from the :attr:`attach_to` widget. If set, it will attach to the nearest window. If the widget is not attached to any window, the view will attach to the global :class:`~kivy.core.window.Window`. When the view is opened, it will be faded in with an animation. If you don't want the animation, use:: view.open(animation=False) ''' if self._window is not None: Logger.warning('ModalView: you can only open once.') return # search window self._window = self._search_window() if not self._window: Logger.warning('ModalView: cannot open view, no window found.') return self._window.add_widget(self) self._window.bind( on_resize=self._align_center, on_keyboard=self._handle_keyboard) self.center = self._window.center self.fbind('center', self._align_center) self.fbind('size', self._align_center) if kwargs.get('animation', True): a = Animation(_anim_alpha=1., d=self._anim_duration) a.bind(on_complete=lambda *x: self.dispatch('on_open')) a.start(self) else: self._anim_alpha = 1. self.dispatch('on_open')
def __init__(self, cows, difficulty, e_sound, s_sound): super(UFO, self).__init__() self.size = [UFO_WIDTH, UFO_HEIGHT] self.pos = [Window.center[0], Window.height] # self.engine_sound = SoundLoader.load('sound/ufo_engine.ogg') # self.shot_sound = SoundLoader.load('sound/ufo_shot.ogg') self.engine_sound = e_sound self.shot_sound = s_sound self.engine_sound.volume = 0.5 self.engine_sound.loop = True self.source = 'img/cows/ufo_03.png' self.cows = cows # self.victim = None self.difficulty = difficulty self.think_time = 3.5 - difficulty self.__all_engines_start() # self.__move_to_start_position() self.__chose_victim() anim = Animation(x=self.x, y=TOP_BORDER, d=0.5) _f = Clock.schedule_interval anim.bind(on_complete=lambda *args: _f(self.__move, FPS)) anim.start(self)
def grow(self, size): """Animate the widget to `size` over the time of 1 second """ animation = Animation(size=(size, size), t='in_cubic', duration=1) animation.start(self) tick = schedule_tick(self.tick) Clock.schedule_once(lambda dt: Clock.unschedule(tick), 2)
def _start_animation(self, *args): Animation.cancel_all(self) # compute target offset for ease back, next or prev new_offset = 0 is_horizontal = self.direction in ['right', 'left'] extent = self.width if is_horizontal else self.height if self._offset < self.min_move * -extent: new_offset = -extent elif self._offset > self.min_move * extent: new_offset = extent # if new_offset is 0, it wasnt enough to go next/prev dur = self.anim_move_duration if new_offset == 0: dur = self.anim_cancel_duration if not self.loop: # detect edge cases if not looping is_first = (self.index == 0) is_last = (self.index == len(self.slides) - 1) if self.direction in ['right', 'top']: towards_prev = (new_offset > 0) towards_next = (new_offset < 0) if self.direction in ['left', 'bottom']: towards_prev = (new_offset < 0) towards_next = (new_offset > 0) if (is_first and towards_prev) or (is_last and towards_next): new_offset = 0 anim = Animation(_offset=new_offset, d=dur, t='out_quad') anim.start(self)
def _anim_back(self, *args): _angle_back_anim = Animation(_angle_start=self._angle_end - 8, duration=.6, t='in_out_cubic') _angle_back_anim.bind(on_complete=self._start_loop) _angle_back_anim.start(self)
def fader(self): self.img=Image(source="fader.jpg",allow_stretch=True) self.add_widget(self.img) self.img.opacity=0 anim=Animation(opacity=1,d=.5,t="out_sine") anim.bind(on_complete=self.fade_level) anim.start(self.img)
def openGearMenu(self): gearMenu = GearMenu() gearMenu.setScreen(self) gearMenu.opacity = 0 anim = Animation(opacity = 1,duration=0.2) self.ids.layer.add_widget(gearMenu) anim.start(gearMenu)
def push_back_into_place(self,square) : id = str(square.geometry_id) if self.activate_animations : animation = Animation(pos = self.geometry_squares[id].pos, duration = 0.9,t='in_out_back') animation.start(square) else : square.pos = self.geometry_squares[id].pos
def place(self, hex_pos, center_pos): if self.selected: self.hex_pos = hex_pos # self.center = center_pos self.selected = False a = Animation(center_x = center_pos[0], center_y = center_pos[1], duration = 0.1) a.start(self)
def on__rotation_angle(self, *args): if self._rotation_angle == 0: self._rotation_angle = 360 if not self.determinate: _rot_anim = Animation(_rotation_angle=0, duration=2) _rot_anim.start(self)
class CalendarApp(App): # rightnow dateobject for alarms and such rightnow = ObjectProperty(dt.datetime.now()) memos = ObjectProperty(JsonStore('memos.json')) def __init__(self, **kwargs): Logger.info('Building App') super(CalendarApp, self).__init__(**kwargs) # Clock.schedule_interval(self.update_time, 1) self.popup = AlertPopup() self.anim_dismiss_popup = Animation(opacity=0, duration=1.5) self.anim_dismiss_popup.bind(on_complete=self.popup.dismiss) # update self.rightnow to a new datetime object every 1sec def update_time(self, *args): self.rightnow = dt.datetime.now() def build(self): main = Main() return main def alert(self, text): self.popup.label.text = text self.popup.open() self.popup.opacity = 1 self.anim_dismiss_popup.start(self.popup) def on_pause(self, *args): return True
def inflate(self): self.size = BALLOON_WIDTH, BALLOON_HEIGHT self.center[0] = self.parent.center[0] self.y = self.parent.top + COW_WIDTH // 2 # Is there a better way? parent.parent huh? exp = generator.get_expression( True, EASY) # I'm ok with this: exp, self.answer = exp.split('=') while int(self.answer) < 0: exp = generator.get_expression( True, EASY) exp, self.answer = exp.split('=') l, r = re.search(r'[+-/*]', exp).span() # print expression[:operator[0]] exp = [exp[:l]] + [exp[l].replace('/', '%')] + [exp[r:]] # print exp # print expr # print [symbol for symbol in exp] self.expression = '\n'.join(exp) # print y = self.y + Window.height - BOTTOM_BORDER anim = Animation(x=self.x, y=y, d=FLYING_TIME, t='in_quad') anim.start(self)
def __init__(self, **kwargs): super(Number, self).__init__(**kwargs) anim = Animation(scale=1., d=.15, t='out_quad') anim.bind(on_complete=self.clean_canvas) anim.start(self)
def anim_sinyal(self, button_name): if button_name == 's': if self.ids.s_button.sinyal == True: self.ids.s_button.sinyal = False button_picture = ("picture_lib/s_kirmizi.png") else: self.ids.s_button.sinyal = True button_picture = ("picture_lib/s_yesil.png") animation = Animation(size_hint=(0, 0), duration=0.2, t='out_sine') animation.bind(on_progress=partial(self.change_color, button_name, button_picture)) animation.start(self.ids.s_button) if button_name == 'q': if self.ids.q_button.sinyal == True: self.ids.q_button.sinyal = False button_picture = ("picture_lib/q_kirmizi.png") else: self.ids.q_button.sinyal = True button_picture = ("picture_lib/q_yesil.png") animation = Animation(size_hint=(0, 0), duration=0.2, t='out_sine') animation.bind(on_progress=partial(self.change_color, button_name, button_picture)) animation.start(self.ids.q_button) if button_name == 'd': if self.ids.d_button.sinyal == True: self.ids.d_button.sinyal = False button_picture = ("picture_lib/d_kirmizi.png") else: self.ids.d_button.sinyal = True button_picture = ("picture_lib/d_yesil.png") animation = Animation(size_hint=(0, 0), duration=0.2, t='out_sine') animation.bind(on_progress=partial(self.change_color, button_name, button_picture)) animation.start(self.ids.d_button) if button_name == 'c': if self.ids.c_button.sinyal == True: self.ids.c_button.sinyal = False button_picture = ("picture_lib/c_kirmizi.png") else: self.ids.c_button.sinyal = True button_picture = ("picture_lib/c_yesil.png") animation = Animation(size_hint=(0, 0), duration=0.2, t='out_sine') animation.bind(on_progress=partial(self.change_color, button_name, button_picture)) animation.start(self.ids.c_button) if button_name == 'e': if self.ids.e_button.sinyal == True: self.ids.e_button.sinyal = False button_picture = ("picture_lib/e_kirmizi.png") else: self.ids.e_button.sinyal = True button_picture = ("picture_lib/e_yesil.png") animation = Animation(size_hint=(0, 0), duration=0.2, t='out_sine') animation.bind(on_progress=partial(self.change_color, button_name, button_picture)) animation.start(self.ids.e_button)
def hide_anim_spinner(self): spinner = self.ids.body_spinner anim = Animation(y=Window.height, d=0.8, t="out_elastic") anim.bind(on_complete=self.set_spinner) anim.start(spinner)
def test_animation_duration_0(self): a = Animation(x=100, d=0) a.start(self.w) self.sleep(.5)
class AnimationTestCase(unittest.TestCase): def sleep(self, t): start = time() while time() < start + t: sleep(.01) Clock.tick() def setUp(self): self.assertEqual(len(Animation._instances), 0) self.a = Animation(x=100, d=1, t='out_bounce') self.w = Widget() def tearDown(self): self.assertEqual(len(Animation._instances), 0) def test_start_animation(self): self.a.start(self.w) self.sleep(1.5) self.assertAlmostEqual(self.w.x, 100) def test_animation_duration_0(self): a = Animation(x=100, d=0) a.start(self.w) self.sleep(.5) def test_stop_animation(self): self.a.start(self.w) self.sleep(.5) self.a.stop(self.w) self.assertNotAlmostEqual(self.w.x, 100) self.assertNotAlmostEqual(self.w.x, 0) def test_stop_all(self): self.a.start(self.w) self.sleep(.5) Animation.stop_all(self.w) def test_stop_all_2(self): self.a.start(self.w) self.sleep(.5) Animation.stop_all(self.w, 'x') def test_duration(self): self.assertEqual(self.a.duration, 1) def test_transition(self): self.assertEqual(self.a.transition, AnimationTransition.out_bounce) def test_animated_properties(self): self.assertEqual(self.a.animated_properties['x'], 100) def test_animated_instruction(self): instruction = Scale(3) self.a.start(instruction) self.assertEqual(self.a.animated_properties['x'], 100) self.assertAlmostEqual(instruction.x, 3) self.sleep(1.5) self.assertAlmostEqual(instruction.x, 100) def test_weakref(self): widget = Widget() anim = Animation(x=100) anim.start(widget.proxy_ref) del widget gc.collect() try: self.sleep(1.) except ReferenceError: pass
class irc1App(App): def build(self): if platform == 'android': from android import AndroidService service = AndroidService('irc1\'s service', 'running') service.start('service started') self.service = service osc.init() oscid = osc.listen(ipAddr='127.0.0.1', port=activityport) osc.bind(oscid, self.main_api_callback, '/api/main') Clock.schedule_interval(lambda *x: osc.readQueue(oscid), 0.1) self.icon = 'data/icon.png' self.servers = DictStore('servers.db') self.msg_animation = Animation(opacity=1, transition='out_cubic') self.screenmain = ScreenMain() self.running = {} self.boxes = {} for name in sorted(dict(self.servers.find()).keys()): data = self.servers.get(name) box = ServerBox(name=name) self.boxes[name] = box self.screenmain.ids.servers.add_widget(box) manager = ScreenManager(transition=SlideTransition(duration=0.2)) manager.add_widget(self.screenmain) return manager def go_back(self): name = self.root.current if name == 'ScreenMain': pause_app() else: self.root.transition.direction = 'right' self.root.current = 'ScreenMain' def init_connection(self, name): if name not in self.servers: return if name not in self.running: Animation(background_color=(0.1, 1, 0.1, 1)).start( self.boxes[name].ids.servername) screen = ScreenConversation(name=name) data = self.servers.get(name) self.running[name] = screen self.root.add_widget(screen) screen.ids.nick.text = data['nick'] osc.sendMsg( '/api/main', [ 'connect', name, data['host'], data['port'], data['nick'], data['password'], data['auth_nickserv'], data['scripts'] ] + data['autojoin'], port=serviceport) self.root.transition.direction = 'left' self.root.current = name def close_connection(self, name): osc.sendMsg('/api/main', ['disconnect', name], port=serviceport) if name not in self.running: return Animation(background_color=(1, 1, 1, 1)).start(self.boxes[name].ids.servername) self.root.transition.direction = 'right' self.root.current = 'ScreenMain' self.root.remove_widget(self.running[name]) del self.running[name] def disconnect_all(self): for name, data in self.servers.find(): self.close_connection(name) def update_or_add_server(self, popup, name=''): host = str(popup.ids.host.text).strip() port = int(str(popup.ids.port.text).strip()) nick = str(popup.ids.nick.text).strip() password = str(popup.ids.password.text) auth_nickserv = popup.ids.auth_nickserv.active scripts = str(popup.ids.scripts.text).strip() autojoin = str(popup.ids.autojoin.text).strip() autojoin = autojoin.replace(',', ' ').split() data = { 'host': host, 'port': port, 'nick': nick, 'password': password, 'auth_nickserv': auth_nickserv, 'scripts': scripts, 'autojoin': autojoin } if name: self.servers.put(name, **data) return name = '%s:%d' % (host, port) if self.servers.exists(name): return if not host or not port > 0 or not nick: return self.servers.put(name, **data) box = ServerBox(name=name) self.boxes[name] = box self.screenmain.ids.servers.add_widget(box) self.screenmain.ids.serverscroll.scroll_to(box) def del_server(self, serverbox): name = serverbox.name if self.servers.exists(name): self.servers.delete(name) del_animation = Animation(opacity=0, duration=0.2) del_animation.bind( on_complete=lambda *x: serverbox.parent.remove_widget(serverbox)) del_animation.start(serverbox) del self.boxes[name] def log_msg(self, name, message): label = ChatLabel(text=message) self.running[name].ids.chatlog.add_widget(label) self.running[name].ids.chatscroll.scroll_to(label) if self.root.current == name: self.msg_animation.start(label) else: label.opacity = 1 def input_focus(self, name, dt): self.running[name].ids.message.focus = True def send_msg(self, name, message): Clock.schedule_once(partial(self.input_focus, name), 0) osc.sendMsg('/api/main', ['send', name, message], port=serviceport) def change_channel(self, name, channel): osc.sendMsg('/api/main', ['channel', name, channel], port=serviceport) def main_api_callback(self, message, *args): # print message[2:] if len(message) > 3: name = message[3] if name not in self.running: return if message[2] == 'nick': nick = message[4] self.running[name].ids.nick.text = nick elif message[2] == 'channel': channel, channels = message[4], message[5:] self.running[name].ids.channel.text = channel or 'No channel' self.running[name].ids.channel.values = [ x or 'No channel' for x in channels ] elif message[2] == 'check': osc.sendMsg('/api/main', ['unread', name], port=serviceport) elif message[2] == 'unread': self.log_msg(name, message[4]) def on_start(self): Window.softinput_mode = 'below_target' hook_keyboard() def on_pause(self): return True def on_resume(self): pass def on_stop(self): if platform == 'android': self.service.stop()
def start_tiles(self): self.add_widget(self.back_btn) self.tile_list = [] self.btn_y = 0 self.btn_width = Window.width / 4 self.btn_x = [ self.btn_width * 0, self.btn_width * 1, self.btn_width * 2, self.btn_width * 3 ] global box_slide box_slide = BoxLayout(orientation='vertical', pos=(-Window.width, 0)) with box_slide.canvas: Color(.2, .5, 1, .7) box_slide.rect1 = Rectangle(pos=(box_slide.pos), size=(Window.size)) self.restart_btn = Button(text='Restart', size_hint=(None, None), pos_hint={ 'center_x': .5, 'center_y': .4 }) self.restart_btn.bind(on_press=self.game_over1) box_slide.add_widget( Label(text='Game Over', font_size=40, pos_hint={ 'center_x': .5, 'center_y': .7 })) box_slide.add_widget(self.restart_btn) global slide_anim slide_anim = Animation(pos=(0, 0), d=1) for i in range(50): self.btn = btn(size_hint=(None, None), size=(self.btn_width, Window.height / 4), pos=(random.choice(self.btn_x), Window.height + self.btn_y)) self.btn_y += self.btn.height ## self.btn.bind(on_press=self.play_sound) self.add_widget(self.btn) self.btn.bind(on_press=self._state) self.add_widget(box_slide) self.add_widget(self.score) for child in self.children: if child != box_slide and child != self.back_btn and child != self.score: self.time = (child.y + Window.height / 4) / 200 global anim anim = Animation(y=-(Window.height / 4), d=self.time) self.tile_list.append(child) anim.start(child) anim.fbind('on_complete', self.delete_btn) else: pass
def start_display(self, touch): touch.grab(self) a = Animation(circle_progress=1, d=self.creation_timeout) a.bind(on_complete=self.open_menu) touch.ud['animation'] = a a.start(self)
def animate(widget, color): #ref for tutorial: https://youtu.be/qMKPNqbuR5Y anim = Animation(background_color=(255, 255, 255, 1), duration=1) anim += Animation(background_color=color, duration=1) anim += Animation(background_color=widget.color, duration=0.3) anim.start(widget)
def dismiss(self): a = Animation(opacity=0) a.bind(on_complete=self._remove) a.start(self)
def remove(self): animation = Animation(x=300) animation = Animation(x=0, t='in_out_back', duration=self.anim_duration) animation.start(self)
class TransitionBase(EventDispatcher): '''Transition class is used to animate 2 screens within the :class:`ScreenManager`. This class act as a base for others implementation, like :class:`SlideTransition`, :class:`SwapTransition`. :Events: `on_progress`: Transition object, progression float Fired during the animation of the transition `on_complete`: Transition object Fired when the transition is fininshed. ''' screen_out = ObjectProperty() '''Property that contain the screen to hide. Automatically set by the :class:`ScreenManager`. :class:`screen_out` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' screen_in = ObjectProperty() '''Property that contain the screen to show. Automatically set by the :class:`ScreenManager`. :class:`screen_in` is a :class:`~kivy.properties.ObjectProperty`, default to None. ''' duration = NumericProperty(.7) '''Duration in seconds of the transition. :class:`duration` is a :class:`~kivy.properties.NumericProperty`, default to .7 (= 700ms) ''' manager = ObjectProperty() '''Screen manager object, set when the screen is added within a manager. :data:`manager` is a :class:`~kivy.properties.ObjectProperty`, default to None, read-only. ''' is_active = BooleanProperty(False) '''Indicate if the transition is currently active :data:`is_active` is a :class:`~kivy.properties.BooleanProperty`, default to False, read-only. ''' # privates _anim = ObjectProperty(allownone=True) def __init__(self, **kw): self.register_event_type('on_progress') self.register_event_type('on_complete') super(TransitionBase, self).__init__(**kw) def start(self, manager): '''(internal) Start the transition. This is automatically called by the :class:`ScreenManager`. ''' if self.is_active: raise ScreenManagerException('start() is called twice!') self.manager = manager self._anim = Animation(d=self.duration, s=0) self._anim.bind(on_progress=self._on_progress, on_complete=self._on_complete) self.add_screen(self.screen_in) self.screen_in.transition_progress = 0. self.screen_in.transition_state = 'in' self.screen_out.transition_progress = 0. self.screen_out.transition_state = 'out' self.screen_in.dispatch('on_pre_enter') self.screen_out.dispatch('on_pre_leave') self.is_active = True self._anim.start(self) self.dispatch('on_progress', 0) def stop(self): '''(internal) Stop the transition. This is automatically called by the :class:`ScreenManager`. ''' if self._anim: self._anim.cancel(self) self.dispatch('on_complete') self._anim = None self.is_active = False def add_screen(self, screen): '''(internal) Used to add a screen into the :class:`ScreenManager` ''' self.manager.real_add_widget(screen) def remove_screen(self, screen): '''(internal) Used to remove a screen into the :class:`ScreenManager` ''' self.manager.real_remove_widget(screen) def on_complete(self): self.remove_screen(self.screen_out) def on_progress(self, progression): pass def _on_progress(self, *l): progress = l[-1] self.screen_in.transition_progress = progress self.screen_out.transition_progress = 1. - progress self.dispatch('on_progress', progress) def _on_complete(self, *l): self.is_active = False self.dispatch('on_complete') self.screen_in.dispatch('on_enter') self.screen_out.dispatch('on_leave') self._anim = None
def _fade_in_buttons(button, *args): button_anim = Animation(transition='out_expo', duration=FADEIN_DUR, opacity=1) button_anim.start(button)
class TransitionBase(EventDispatcher): '''TransitionBase is used to animate 2 screens within the :class:`ScreenManager`. This class acts as a base for other implementations like the :class:`SlideTransition` and :class:`SwapTransition`. :Events: `on_progress`: Transition object, progression float Fired during the animation of the transition. `on_complete`: Transition object Fired when the transition is finished. ''' screen_out = ObjectProperty() '''Property that contains the screen to hide. Automatically set by the :class:`ScreenManager`. :class:`screen_out` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' screen_in = ObjectProperty() '''Property that contains the screen to show. Automatically set by the :class:`ScreenManager`. :class:`screen_in` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' duration = NumericProperty(.4) '''Duration in seconds of the transition. :class:`duration` is a :class:`~kivy.properties.NumericProperty` and defaults to .4 (= 400ms). .. versionchanged:: 1.8.0 Default duration has been changed from 700ms to 400ms. ''' manager = ObjectProperty() ''':class:`ScreenManager` object, set when the screen is added to a manager. :attr:`manager` is an :class:`~kivy.properties.ObjectProperty` and defaults to None, read-only. ''' is_active = BooleanProperty(False) '''Indicate whether the transition is currently active or not. :attr:`is_active` is a :class:`~kivy.properties.BooleanProperty` and defaults to False, read-only. ''' # privates _anim = ObjectProperty(allownone=True) __events__ = ('on_progress', 'on_complete') def start(self, manager): '''(internal) Starts the transition. This is automatically called by the :class:`ScreenManager`. ''' if self.is_active: raise ScreenManagerException('start() is called twice!') self.manager = manager self._anim = Animation(d=self.duration, s=0) self._anim.bind(on_progress=self._on_progress, on_complete=self._on_complete) self.add_screen(self.screen_in) self.screen_in.transition_progress = 0. self.screen_in.transition_state = 'in' self.screen_out.transition_progress = 0. self.screen_out.transition_state = 'out' self.screen_in.dispatch('on_pre_enter') self.screen_out.dispatch('on_pre_leave') self.is_active = True self._anim.start(self) self.dispatch('on_progress', 0) def stop(self): '''(internal) Stops the transition. This is automatically called by the :class:`ScreenManager`. ''' if self._anim: self._anim.cancel(self) self.dispatch('on_complete') self._anim = None self.is_active = False def add_screen(self, screen): '''(internal) Used to add a screen to the :class:`ScreenManager`. ''' self.manager.real_add_widget(screen) def remove_screen(self, screen): '''(internal) Used to remove a screen from the :class:`ScreenManager`. ''' self.manager.real_remove_widget(screen) def on_complete(self): self.remove_screen(self.screen_out) def on_progress(self, progression): pass def _on_progress(self, *l): progress = l[-1] self.screen_in.transition_progress = progress self.screen_out.transition_progress = 1. - progress self.dispatch('on_progress', progress) def _on_complete(self, *l): self.is_active = False self.dispatch('on_complete') self.screen_in.dispatch('on_enter') self.screen_out.dispatch('on_leave') self._anim = None
def _fly_in_buttons(button, *args): button_anim = Animation(transition='out_expo', duration=1, opacity=1) button_anim &= Animation(transition='out_circ', duration=1, x=button.final_pos[0], y=button.final_pos[1]) button_anim.start(button)
class Catalog(BoxLayout): '''Catalog of widgets. This is the root widget of the app. It contains a tabbed pain of widgets that can be displayed and a textbox where .kv language files for widgets being demoed can be edited. The entire interface for the Catalog is defined in kivycatalog.kv, although individual containers are defined in the container_kvs directory. To add a container to the catalog, first create the .kv file in container_kvs The name of the file (sans .kv) will be the name of the widget available inside the kivycatalog.kv Finally modify kivycatalog.kv to add an AccordionItem to hold the new widget. Follow the examples in kivycatalog.kv to ensure the item has an appropriate id and the class has been referenced. You do not need to edit any python code, just .kv language files! ''' language_box = ObjectProperty() screen_manager = ObjectProperty() _change_kv_ev = None def __init__(self, **kwargs): self._previously_parsed_text = '' super(Catalog, self).__init__(**kwargs) self.show_kv(None, 'Welcome') self.carousel = None def show_kv(self, instance, value): '''Called when an a item is selected, we need to show the .kv language file associated with the newly revealed container.''' self.screen_manager.current = value child = self.screen_manager.current_screen.children[0] with open(child.kv_file, 'rb') as file: self.language_box.text = file.read().decode('utf8') if self._change_kv_ev is not None: self._change_kv_ev.cancel() self.change_kv() # reset undo/redo history self.language_box.reset_undo() def schedule_reload(self): if self.auto_reload: txt = self.language_box.text child = self.screen_manager.current_screen.children[0] if txt == child.previous_text: return child.previous_text = txt if self._change_kv_ev is not None: self._change_kv_ev.cancel() if self._change_kv_ev is None: self._change_kv_ev = Clock.create_trigger(self.change_kv, 2) self._change_kv_ev() def change_kv(self, *largs): '''Called when the update button is clicked. Needs to update the interface for the currently active kv widget, if there is one based on the kv file the user entered. If there is an error in their kv syntax, show a nice popup.''' txt = self.language_box.text kv_container = self.screen_manager.current_screen.children[0] try: parser = Parser(content=txt) kv_container.clear_widgets() widget = Factory.get(parser.root.name)() Builder._apply_rule(widget, parser.root, parser.root) kv_container.add_widget(widget) except (SyntaxError, ParserException) as e: self.show_error(e) except Exception as e: self.show_error(e) def show_error(self, e): self.info_label.text = str(e).encode('utf-8') self.anim = Animation(top=190.0, opacity=1, d=2, t='in_back') +\ Animation(top=190.0, d=3) +\ Animation(top=0, opacity=0, d=2) self.anim.start(self.info_label)
def on_drag_finish(self, mouse_motion_event): global DEBUG_DRAG_FINISH # Don't worry, opacity will be properly set in set_drag_finish_state() # after the animation debug.print( "on_drag_finish: ================================================================", level=DEBUG_DRAG_FINISH) debug.print("on_drag_finish, beginning, parent:", self.parent, "copy?", self.copy, level=DEBUG_DRAG_FINISH) debug.print("self:", self, "is_double_tap?", self.is_double_tap, level=DEBUG_DRAG_FINISH) debug.print( "on_drag_finish: ================================================================", level=DEBUG_DRAG_FINISH) self.opacity = 1.0 drag_destination_list = [] self.found_drop_recipients_ok_dict = {} # del self.drop_recipients[:] if self._dragged and self._draggable: # ------------------------------------------------------------------------- # --- assemble list of possible drag destinations # These destinations are based on either drop groups, or simply because # they've been added to droppable_zone_objects # debug.print "on_drag_finish: DRAGGABLES_DICT:", draggables_dict for drop_group in draggables_dict: if draggables_dict[drop_group].get(self): if drop_group in drag_destinations_dict: for drop_recipient in drag_destinations_dict[ drop_group]: if not drop_recipient in drag_destination_list: drag_destination_list.append(drop_recipient) for drop_group in drag_destinations_dict: if draggables_dict[drop_group].get(self): for drop_recipient in drag_destinations_dict[drop_group]: if not drop_recipient in drag_destination_list: drag_destination_list.append(drop_recipient) for obj in self.droppable_zone_objects: if not obj in drag_destination_list: drag_destination_list.append(obj) #for obj in drag_destination_list: # debug.print ("Possible drop destination:", obj.text) # --- end of assemble list # ------------------------------------------------------------------------- # --- check which object(s) did receive this drop. for obj in drag_destination_list: (touch_window_x, touch_window_y) = self.to_window(self.touch_x, self.touch_y) debug.print("Touch position:", self.touch_x, self.touch_y, "Window position:", touch_window_x, touch_window_y, level=DEBUG_DRAG_FINISH) debug.print("Check if drop ok: touch:", touch_window_x, touch_window_y, "Object's pos in Window:", obj.to_window(obj.x, obj.y), obj.width, obj.height, end=" ", level=DEBUG_DRAG_FINISH) # TODO: IF object does not subclass DropDestination, it won't have this # TODO: method defined! if self.widget_absolute_collide_point(obj, touch_window_x, touch_window_y): debug.print("COLLIDE: True", end=" ", level=DEBUG_DRAG_FINISH) if obj is self._old_parent and not self.can_drop_into_parent: self.found_drop_recipients_ok_dict[obj] = False debug.print("OK: False", level=DEBUG_DRAG_FINISH) else: self.found_drop_recipients_ok_dict[obj] = True debug.print("OK: True", level=DEBUG_DRAG_FINISH) else: debug.print("COLLIDE: False", level=DEBUG_DRAG_FINISH) pass # --- end of check # ------------------------------------------------------------------------- # - (Possibly) perform animations # - if a drop recipient is found (could include the parent), and it's ok # to drop there (parent may not be, so this could be false), then set # - not_drop_ok_do_animation = False # - got_one_successful_drop = True # - drop_ok_do_animation = False (if dropped onto old parent) # - Run self.drop_func or self.failed_drop_func drop_ok_do_animation = self.drop_ok_do_animation not_drop_ok_do_animation = self.not_drop_ok_do_animation got_one_successful_drop = False got_one_drop_not_parent = False # ------------------------------------------------------------------------- for found_drop_recipient, dropped_ok in self.found_drop_recipients_ok_dict.items( ): debug.print("Drop Recipient:", found_drop_recipient, dropped_ok, level=DEBUG_DRAG_FINISH) if dropped_ok: not_drop_ok_do_animation = False got_one_successful_drop = True if found_drop_recipient != self._old_parent: # TODO: Animation runs when the widget is not added to the # TODO: drop recipient. This is a problem, because the widget # TODO: exists but is invisible! # TODO: for app_relative_layout: If a copied widget is dragged, # TODO: its original parent may be the Window (not a widget). # TODO: Therefore, animation is running when we don't want it. got_one_drop_not_parent = True if not got_one_drop_not_parent: drop_ok_do_animation = False # ------------------------------------------------------------------------- # Perform after-drop functions if got_one_successful_drop: debug.print("I will call on_successful_drop", level=DEBUG_DRAG_FINISH) if drop_ok_do_animation: anim = Animation(opacity=0, duration=self.drop_ok_animation_time, t="in_quad") anim.bind(on_complete=self.post_successful_animation) anim.start(self) self.on_successful_drop() else: self.on_successful_drop() self.post_successful_animation() return else: # TODO: Do we want to run the animation? MIKE check this... is it right # TODO: to be here??? debug.print("I will call on_unsuccessful_drop", level=DEBUG_DRAG_FINISH) if not_drop_ok_do_animation: anim = Animation(pos=self._old_drag_pos, duration=self.not_drop_ok_animation_time, t="in_quad") anim.bind(on_complete=self.post_unsuccessful_animation) anim.start(self) self.on_unsuccessful_drop() else: self.on_unsuccessful_drop() self.post_unsuccessful_animation( False ) # Simply resets some flags; opacity will be set after the animation # On a successful drop, the widget will end up with no parent whatsoever. debug.print("THE END. Drag finished, me:", self, "parent:", self.parent, level=DEBUG_DRAG_FINISH)
def adjust_sliders(self, device): """Adjusts the parameter slider values based on the device selected.""" for (param, val) in device.parameters.items(): anim = Animation(transition='out_sine', duration=SLIDER_DUR, value=val) anim.start(getattr(self, param).param_slider)
def animate_up(self, instance): self.parent.clear_selected_button() animate = Animation(pos=(0, 0), size_hint=(1.0, 1.0)) animate.start(self.button) self.selected = True
def die(self): anim = Animation(top=0, duration=.3, t='out_quad') anim.bind(on_complete=lambda *args: _play_next(self)) anim.bind(on_complete=lambda *args: Window.remove_widget(self)) anim.start(self)
def show(self): self.bussy = True ani = Animation(x=0, duration=.1) ani.start(self)
def animate_down(self): animate = Animation(pos=(40, 30), size_hint=(0.8, 0.8)) animate.start(self.button) self.selected = False
class WordsScreen(Screen): chapter = 0 lesson = 0 end_lesson = 0 dropdown = ListProperty([]) ws = ObjectProperty(None) cur_list = ListProperty([]) cur_lesson = [] completed_tup = ('chp1', 'chp2', 'chp3', 'chp4', 'chp5', 'chp6') plyr_banner = StringProperty(player) homescreen = HomeScreen() reading = False def __init__(self, **kwargs): super(WordsScreen, self).__init__(**kwargs) self.chap_drop = ChapterDropDown() self.less_drop = LessonDropDown() #These next 6 lines of code are for the SpeechRecognition app and can be found inthe source code for the Module. self.rec = sr.Recognizer() self.rec.pause_threshold = 0.5 #seconds of non-speaking audio before a phrase is considered complete self.rec.phrase_threshold = 0.3 # minimum seconds of speaking audio before we consider the speaking audio a phrase - values below this are ignored (for filtering out clicks and pops) self.rec.non_speaking_duration = 0.5 # seconds of non-speaking audio to keep on both sides of the recording self.mic = sr.Microphone() self.mic.CHUNK = 768 # The microphone audio is recorded in chunks of ``chunk_size`` samples, at a rate of ``sample_rate`` samples per second (Hertz). If not specified, the value of ``sample_rate`` is determined automatically from the system's microphone settings. try: self.engine = pyttsx3.init() self.voices = self.engine.getProperty('voices') self.engine.setProperty('voice', self.voices[1].id) #changing index, changes voices. 1 for female 0 for male self.volume = self.engine.getProperty('volume') self.engine.setProperty('volume',1.0) # setting up volume level between 0 and 1 self.rate = self.engine.getProperty('rate') self.engine.setProperty('rate', 100) # setting up new voice rate except: pass self.chap_drop.bind(on_select = lambda instance, x: setattr(self.ids.chapters, 'text', x)) self.less_drop.bind(on_select = lambda instance, x: setattr(self.ids.lessons, 'text', x)) self.completed_tup = ('chp1', 'chp2', 'chp3', 'chp4', 'chp5', 'chp6') self.drop_chap = "" self.cur_lesson = [] def exitpop(self): exit_app = ExitPop(title = 'Exit Sight Words', size_hint = (0.6, 0.6), title_align = 'center', auto_dismiss = False) exit_app.open() def preview(self, dt=0): """ Creates a current list of 5 words from the sighlist mod based on the chapter and lesson the user chose. """ if self.ids.chapters.text == 'Chapters' and self.ids.lessons.text == 'Lessons': return self.every_word = sl.master self.chapter = int(self.ids.chapters.text[-1])-1 self.lesson = (int(self.ids.lessons.text[-2::])-1)*5 self.end_lesson = self.lesson+5 if self.lesson == 45: self.end_lesson = len(self.every_word[self.chapter]) self.cur_list = self.every_word[self.chapter][self.lesson:self.end_lesson] self.ids.preview.values = self.cur_list if self.reading == True: Clock.schedule_once(self.word_label) def call_read_list(self): if self.ids.chapters.text == 'Chapters' and self.ids.lessons.text == 'Lessons': return Clock.schedule_interval(self.read_list, 2.3) self.call_index = 0 def read_list(self, dt): self.preview() if self.call_index == 5: self.ids.words.text = 'Get Ready!!!' return False self.ids.words.text = self.cur_list[self.call_index] Clock.schedule_once(self.read_word, 0.3) def read_word(self, dt): try: self.engine.say(self.ids.words.text) self.engine.runAndWait() except: pass self.call_index += 1 def word_label(self, dt=0): if self.ids.chapters.text != 'Chapters' and self.ids.lessons.text != 'Lessons': if len(self.cur_lesson) == 0: self.cur_lesson = self.cur_list self.ids.words.text = random.choice(self.cur_lesson) Clock.schedule_once(self.chooser) def listen(self, recognizer, microphone): """ Implementation of the SpeechRecognition Module. Send voice to Google and return Text. """ if not isinstance(recognizer, sr.Recognizer): raise TypeError("`recognizer` must be `Recognizer` instance") if not isinstance(microphone, sr.Microphone): raise TypeError("`microphone` must be `Microphone` instance") with self.mic as source: self.rec.adjust_for_ambient_noise(source, duration=0.3) audio = self.rec.listen(source, phrase_time_limit=4.0) if self.rec.phrase_threshold >= 4: ### Popup ### Clock.schedule_once(self.preview) return '' self.spoken = {"success": True, "error": None, "transcription": None} try: self.spoken["transcription"] = str(recognizer.recognize_google(audio, show_all=True)) except sr.RequestError: # API was unreachable or unresponsive self.spoken["success"] = False self.spoken["error"] = "API unavailable" except sr.UnknownValueError: # speech was unintelligible self.spoken["error"] = "Urecognizeable speech" finally: self.spoken["error"] = '' return self.spoken["transcription"] def chooser(self, dt=0): """ Simple method to create a copy of the cur_list to pop(correct word) from the list. """ if self.ids.chapters.text != 'Chapters' and self.ids.lessons.text != 'Lessons': if len(self.cur_lesson) == 0: self.cur_lesson = self.cur_list if self.ids.words.text == 'Get Ready!!!': return Clock.schedule_once(self.checker) def checker(self, dt=0): """ Takes the text result from speach to text and checks if it matches the current sight word. If there is a match the word will pop out of the current working list of words for the given lesson. Once the list is empty the completed lesson method is called. """ if re.search(self.ids.words.text, self.listen(self.rec, self.mic), re.IGNORECASE): correct_word = self.ids.words.text.lower() try: self.cur_lesson.pop(self.cur_lesson.index(correct_word)) except: self.cur_lesson.pop(self.cur_lesson.index(correct_word.capitalize())) self.ids.words.text = '' if len(self.cur_lesson) == 0: self.ids.words.text = 'Great Job!!!\n Try Another Lesson' Clock.schedule_once(self.completed_lesson) return else: Clock.schedule_once(self.between_word) Clock.schedule_once(self.preview) return else: Clock.schedule_once(self.between_word) return def between_word(self, dt=0): self.ids.words.text = '' Clock.schedule_once(self.preview, 0.7) def completed_lesson(self, dt=0): """ This method checks to see if the current lesson is already in the json file and if not adds it so it can be called from the resource screen on the copleted lesson dropdowns. """ add_to_chap = int(self.ids.chapters.text[-1])-1 lessson_num = self.ids.lessons.text[-2::] add_lbl = 'Lesson '+lessson_num player = self.ids.plyr_banner.text[6::] if self.ids.chapters.text != 'Chapters' and self.ids.lessons.text != 'Lessons': if add_lbl in comp_list[add_to_chap]: Clock.schedule_once(self.happy_face) return else: comp_list[add_to_chap].append(add_lbl) new_list = sorted(comp_list[add_to_chap]) self.drop_chap = player+self.completed_tup[add_to_chap] if SightWordsApp.word_data.exists(self.drop_chap): if new_list[-1] in SightWordsApp.word_data.get(self.drop_chap)['add_less']: Clock.schedule_once(self.happy_face) return else: new_list.extend(SightWordsApp.word_data.get(self.drop_chap)['add_less']) inter_set = set(new_list) final_list = list(inter_set) SightWordsApp.word_data.put(self.drop_chap, add_less = sorted(final_list)) Clock.schedule_once(self.happy_face, 0) def happy_face(self, dt=0): """ This is a simple animation to show completion of a selected lesson. """ self.hp = Image(source = 'smile.png', allow_stretch = True) self.hp.pos = self.ids.login.pos self.anim_happy = Animation(pos = self.ids.words.pos, size = self.ids.words.size, duration = 1) self.anim_happy.start(self.hp) self.ids.words.add_widget(self.hp) Clock.schedule_once(self.rem_happy, 3) def rem_happy(self, dt): while len(self.ids.words.children) > 0: self.ids.words.remove_widget(self.ids.words.children[0]) def change_label(self): player = self.ids.plyr_banner.text[6::] self.parent.children[0].ids.plyr_banner2.text = 'Hello '+player
def hide(self): self.bussy = False ani = Animation(x=self.width + 10, duration=.1) ani.start(self)
def _dismiss_animation(self): anim = Animation(opacity=0, duration=self.dismiss_duration, t="out_quad") anim.start(self)
class BaseRaisedButton(CommonElevationBehavior, BaseButton): """ Abstract base class for raised buttons which elevate from material. Raised buttons are to be used sparingly to emphasise primary/important actions. Implements elevation behavior as well as the recommended down/disabled colors for raised buttons. """ def __init__(self, **kwargs): if self.elevation_raised == 0 and self.elevation_normal + 6 <= 12: self.elevation_raised = self.elevation_normal + 6 elif self.elevation_raised == 0: self.elevation_raised = 12 super().__init__(**kwargs) self.elevation_press_anim = Animation(elevation=self.elevation_raised, duration=.2, t='out_quad') self.elevation_release_anim = Animation( elevation=self.elevation_normal, duration=.2, t='out_quad') _elev_norm = NumericProperty(2) def _get_elev_norm(self): return self._elev_norm def _set_elev_norm(self, value): self._elev_norm = value if value <= 12 else 12 self._elev_raised = (value + 6) if value + 6 <= 12 else 12 self.elevation = self._elev_norm self.elevation_release_anim = Animation(elevation=value, duration=.2, t='out_quad') elevation_normal = AliasProperty( _get_elev_norm, _set_elev_norm, bind=('_elev_norm',)) _elev_raised = NumericProperty(8) def _get_elev_raised(self): return self._elev_raised def _set_elev_raised(self, value): self._elev_raised = value if value + self._elev_norm <= 12 else 12 self.elevation_press_anim = Animation(elevation=value, duration=.2, t='out_quad') elevation_raised = AliasProperty( _get_elev_raised, _set_elev_raised, bind=('_elev_raised',)) def on_disabled(self, instance, value): if self.disabled: self.elevation = 0 else: self.elevation = self.elevation_normal super().on_disabled(instance, value) def on_touch_down(self, touch): if not self.disabled: if touch.is_mouse_scrolling: return False if not self.collide_point(touch.x, touch.y): return False if self in touch.ud: return False self.elevation_press_anim.stop(self) self.elevation_press_anim.start(self) return super().on_touch_down(touch) def on_touch_up(self, touch): if not self.disabled: if touch.grab_current is not self: return super().on_touch_up(touch) self.elevation_release_anim.stop(self) self.elevation_release_anim.start(self) return super().on_touch_up(touch) def _get_md_bg_color_down(self): t = self.theme_cls c = self.md_bg_color # Default to no change on touch # Material design specifies using darker hue when on Dark theme if t.theme_style == 'Dark': if self.md_bg_color == t.primary_color: c = t.primary_dark elif self.md_bg_color == t.accent_color: c = t.accent_dark return c def _get_md_bg_color_disabled(self): if self.theme_cls.theme_style == 'Dark': c = (1., 1., 1., .12) else: c = (.0, .0, .0, .12) return c
def _start_coin_animation(self, _, coin_widg): animation = Animation(size_hint_x=.05, duration=CoinImage.ANIMATION_DURATION, t='in_out_quad') animation &= Animation(pos_hint=self.rewards_shortcut.pos_hint, duration=CoinImage.ANIMATION_DURATION, t='in_out_quad') animation.start(coin_widg)
class MDSpinner(ThemableBehavior, Widget): """:class:`MDSpinner` is an implementation of the circular progress indicator in `Google's Material Design`. It can be used either as an indeterminate indicator that loops while the user waits for something to happen, or as a determinate indicator. Set :attr:`determinate` to **True** to activate determinate mode, and :attr:`determinate_time` to set the duration of the animation. """ determinate = BooleanProperty(False) """ Determinate value. :attr:`determinate` is a :class:`~kivy.properties.BooleanProperty` and defaults to `False`. """ determinate_time = NumericProperty(2) """ Determinate time value. :attr:`determinate_time` is a :class:`~kivy.properties.NumericProperty` and defaults to `2`. """ active = BooleanProperty(True) """Use :attr:`active` to start or stop the spinner. :attr:`active` is a :class:`~kivy.properties.BooleanProperty` and defaults to `True`. """ color = ListProperty([0, 0, 0, 0]) """ Spinner color. :attr:`color` is a :class:`~kivy.properties.ListProperty` and defaults to ``self.theme_cls.primary_color``. """ palette = ListProperty() """ A set of colors. Changes with each completed spinner cycle. :attr:`palette` is a :class:`~kivy.properties.ListProperty` and defaults to `[]`. """ _alpha = NumericProperty(0) _rotation_angle = NumericProperty(360) _angle_start = NumericProperty(0) _angle_end = NumericProperty(0) _palette = [] def __init__(self, **kwargs): super().__init__(**kwargs) self.color = self.theme_cls.primary_color self._alpha_anim_in = Animation(_alpha=1, duration=0.8, t="out_quad") self._alpha_anim_out = Animation(_alpha=0, duration=0.3, t="out_quad") self._alpha_anim_out.bind(on_complete=self._reset) self.theme_cls.bind(primary_color=self._update_color) if self.determinate: self._start_determinate() else: self._start_loop() def _update_color(self, *args): self.color = self.theme_cls.primary_color def _start_determinate(self, *args): self._alpha_anim_in.start(self) _rot_anim = Animation( _rotation_angle=0, duration=self.determinate_time * 0.7, t="out_quad", ) _rot_anim.start(self) _angle_start_anim = Animation( _angle_end=360, duration=self.determinate_time, t="in_out_quad" ) _angle_start_anim.bind(on_complete=lambda *x: self._alpha_anim_out.start(self)) _angle_start_anim.start(self) def _start_loop(self, *args): if self._alpha == 0: _rot_anim = Animation(_rotation_angle=0, duration=2, t="linear") _rot_anim.start(self) self._alpha = 1 self._alpha_anim_in.start(self) _angle_start_anim = Animation( _angle_end=self._angle_end + 270, duration=0.6, t="in_out_cubic" ) _angle_start_anim.bind(on_complete=self._anim_back) _angle_start_anim.start(self) def _anim_back(self, *args): _angle_back_anim = Animation( _angle_start=self._angle_end - 8, duration=0.6, t="in_out_cubic" ) _angle_back_anim.bind(on_complete=self._start_loop) _angle_back_anim.start(self) def on__rotation_angle(self, *args): if self._rotation_angle == 0: self._rotation_angle = 360 if not self.determinate: _rot_anim = Animation(_rotation_angle=0, duration=2) _rot_anim.start(self) elif self._rotation_angle == 360: if self._palette: try: Animation(color=next(self._palette), duration=2).start(self) except StopIteration: self._palette = iter(self.palette) Animation(color=next(self._palette), duration=2).start(self) def _reset(self, *args): Animation.cancel_all( self, "_angle_start", "_rotation_angle", "_angle_end", "_alpha", "color", ) self._angle_start = 0 self._angle_end = 0 self._rotation_angle = 360 self._alpha = 0 self.active = False def on_palette(self, instance, value): self._palette = iter(value) def on_active(self, *args): if not self.active: self._reset() else: if self.determinate: self._start_determinate() else: self._start_loop()
def move_down(self, use_star): if self.level == 0: return self.level -= 1 anim = Animation(y=self.pos[1] - 34, t='in_out_elastic', duration=.7) anim.start(self) if self.player: actor_anim = Animation(y=self.player.pos[1] - 34, t='in_out_elastic', duration=.7) actor_anim.start(self.player) if self.mod_layer: actor_anim = Animation(y=self.mod_layer.pos[1] - 34, t='in_out_elastic', duration=.7) actor_anim.start(self.mod_layer) if self.star: actor_anim = Animation(y=self.star.pos[1] - 34, t='in_out_elastic', duration=.7) actor_anim.start(self.star) if self.key: actor_anim = Animation(y=self.key.pos[1] - 34, t='in_out_elastic', duration=.7) actor_anim.start(self.key) if self.exit: actor_anim = Animation(y=self.exit.pos[1] - 34, t='in_out_elastic', duration=.7) actor_anim.start(self.exit) if self.portal: portal_anim = Animation(y=self.portal.pos[1] - 34, t='in_out_elastic', duration=.7) portal_anim.start(self.portal) if use_star: self.game_map.tile_with_player.player.use_star()
def _opening_animation(self): self.opacity = 0 anim = Animation(opacity=1, duration=self.opening_duration, t="out_quad") anim.start(self)