class GestureBoard(FloatLayout): """ Our application main widget, derived from touchtracer example, use data constructed from touches to match symboles loaded from my_gestures. """ def __init__(self, *args, **kwargs): super(GestureBoard, self).__init__() self.gdb = GestureDatabase() # add pre-recorded gestures to database self.gdb.add_gesture(cross) self.gdb.add_gesture(check) self.gdb.add_gesture(circle) self.gdb.add_gesture(square) def on_touch_down(self, touch): # start collecting points in touch.ud # create a line to display the points userdata = touch.ud with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d)) userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): # store points of the touch movement try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError), e: pass
def load_gestures(): gdb = GestureDatabase() gdb.add_gesture(cun_1) gdb.add_gesture(cun_10) print('Loading gestures...') return gdb
class GestureManager(object): def __init__(self, path='./chronos/assets/gestures/'): with open(path + 'gestures.json', "r+") as f: self.path = path self.str_gestures = json.load(f) self.db = GestureDatabase() for name, gesture_string in self.str_gestures.items(): gesture = self.db.str_to_gesture(gesture_string) gesture.name = name self.db.add_gesture(gesture) def add_gesture(self, name, gesture_path): gesture = Gesture() gesture.add_stroke(gesture_path) gesture.normalize() if name in self.str_gestures: raise ValueError('Cannot overwrite existing gesture in file.') gesture.name = name self.str_gestures[name] = self.db.gesture_to_str(gesture).decode( 'utf-8') self.db.add_gesture(gesture) def save(self, path=None): if not path: path = self.path with open(path + 'gestures.json', "r+") as f: f.seek(0) json.dump(self.str_gestures, f) f.truncate()
class GestureBoard(FloatLayout): """ Our application main widget, derived from touchtracer example, use data constructed from touches to match symboles loaded from my_gestures. """ def __init__(self, *args, **kwargs): super(GestureBoard, self).__init__() self.gdb = GestureDatabase() # add pre-recorded gestures to database self.gdb.add_gesture(cross) self.gdb.add_gesture(check) self.gdb.add_gesture(circle) self.gdb.add_gesture(square) def on_touch_down(self, touch): # start collecting points in touch.ud # create a line to display the points userdata = touch.ud with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d)) userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): # store points of the touch movement try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError), e: pass
class TabPannel(TabbedPanel): def __init__(self, *args, **kwargs): super(TabPannel, self).__init__(*args, **kwargs) self.app = RfAttendance.get_running_app() self.gdb = GestureDatabase() self.left_to_right_gesture = self.gdb.str_to_gesture(left_to_right_gesture) self.right_to_left_gesture = self.gdb.str_to_gesture(right_to_left_gesture) self.gdb.add_gesture(self.left_to_right_gesture) self.gdb.add_gesture(self.right_to_left_gesture) def on_touch_down(self, touch): touch.ud['line'] = Line(points=(touch.x, touch.y)) return super(TabPannel, self).on_touch_down(touch) def on_touch_move(self, touch): try: touch.ud['line'].points += [touch.x, touch.y] return super(TabbedPanel, self).on_touch_move(touch) except KeyError: pass def on_touch_up(self, touch): g = Gesture() g.add_stroke(list(zip( touch.ud['line'].points[::2], touch.ud['line'].points[1::2] ))) g.normalize() g.name = '' g2 = self.gdb.find(g, minscore=0.70) if g2 and g2[1] == self.left_to_right_gesture: self.switch_to_left() elif g2 and g2[1] == self.right_to_left_gesture: self.switch_to_right() return super(TabPannel, self).on_touch_up(touch) def switch_to_right(self): current_tab_index = self.tab_list.index(self.current_tab) if current_tab_index == 0: return try: self.switch_to(self.tab_list[current_tab_index - 1]) except IndexError: pass def switch_to_left(self): current_tab_index = self.tab_list.index(self.current_tab) try: self.switch_to(self.tab_list[current_tab_index + 1]) except IndexError: pass
class GestureListener(Widget): def __init__(self, **kwargs): # inicializace self.app = kwargs['root'] self.register_event_type('on_swipe_right') self.register_event_type('on_swipe_left') super(GestureListener, self).__init__(**kwargs) self.gdb = GestureDatabase() self.GSTR_SWIPE_LEFT = \ self.gdb.str_to_gesture('eNqtls2O2jAURvd+EdgU+f7bL0C3lXiAikIEaKYQQabtvH3tC0ITQZtZeJXkU3ycfEdK7vzwcvj1vth1l+Ht3IWvt2Mfw3z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RtZFbcqjayKW5VGVsWtyn1WBYSIxZBztKh8m+5WxRrR3arkNnR1qwqN6G5VqRHdrWojq+pWtZFVdavayKq5VWtk1dyq3WdVY0IDMpn2t7fhLtXkf+H1mLA99/3x96bftO76zcJyBdrFsCIqy8dLwzhYCpuSkK4n5JqAaX4n8pX0FGu60sTjspQYeA/ALs+uDxk4TZFmZeSdNc6CPI0js6CEzfQMnvrD/mmsRx4NK5yPV95UJeP7YTc+1QQrCZpLfQmOp5f+vDlu68krpfqIoYbfVX0ezqfd69axZWjuQKJC3dYgkGp9D3c/Ab86orc=') self.gdb.add_gesture(self.GSTR_SWIPE_LEFT) self.gdb.add_gesture(self.GSTR_SWIPE_RIGHT) def simplegesture(self, name, point_list): # Pomocná funkce pro rozpoznávání gesta g = Gesture() g.add_stroke(point_list) g.normalize() g.name = name return g def on_touch_down(self, touch): # Při doteku, spustí zaznamenávání if self.collide_point(touch.x, touch.y): touch.ud["line"] = Line(points=(touch.x, touch.y)) touch.grab(self) print "< grabbed >" def on_touch_move(self, touch): # Při pohybu prstu, zaznamenává pohyb if (touch.grab_current is self): touch.ud["line"].points += [touch.x, touch.y] def on_touch_up(self, touch): # Při zvednutí prstu, porovnává s gestem v databázi if (touch.grab_current is self): g = self.simplegesture( '', zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])) g2 = self.gdb.find(g, minscore=0.80) if g2: if g2[1] == self.GSTR_SWIPE_LEFT: self.dispatch('on_swipe_left') if g2[1] == self.GSTR_SWIPE_RIGHT: self.dispatch('on_swipe_right') touch.ungrab(self) def on_swipe_left(self, *args): # Událost přejetí prstu doleva self.app.on_swipe_left() def on_swipe_right(self, *args): # Událost přejetí prstu doprava self.app.on_swipe_right()
class GestureListener(Widget): def __init__(self, **kwargs): # inicializace self.app = kwargs['root'] self.register_event_type('on_swipe_right') self.register_event_type('on_swipe_left') super(GestureListener, self).__init__(**kwargs) self.gdb = GestureDatabase() self.GSTR_SWIPE_LEFT = \ self.gdb.str_to_gesture('e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q6LRddLlq7Bq4Xc7MG5IIJ2jVwxUTtGrhkaieZXDLdI7n8R9nUVCxnFJUot+lumHIbOrtehkZ0d8vUiO5iWRrR3So3sspulRtZFbcqjayKW5VGVsWtyn1WBYSIxZBztKh8m+5WxRrR3arkNnR1qwqN6G5VqRHdrWojq+pWtZFVdavayKq5VWtk1dyq3WdVY0IDMpn2t7fhLtXkf+H1mLA99/3x96bftO76zcJyBdrFsCIqy8dLwzhYCpuSkK4n5JqAaX4n8pX0FGu60sTjspQYeA/ALs+uDxk4TZFmZeSdNc6CPI0js6CEzfQMnvrD/mmsRx4NK5yPV95UJeP7YTc+1QQrCZpLfQmOp5f+vDlu68krpfqIoYbfVX0ezqfd69axZWjuQKJC3dYgkGp9D3c/Ab86orc=') self.gdb.add_gesture(self.GSTR_SWIPE_LEFT) self.gdb.add_gesture(self.GSTR_SWIPE_RIGHT) def simplegesture(self, name, point_list): # Pomocná funkce pro rozpoznávání gesta g = Gesture() g.add_stroke(point_list) g.normalize() g.name = name return g def on_touch_down(self, touch): # Při doteku, spustí zaznamenávání if self.collide_point(touch.x, touch.y): touch.ud["line"] = Line(points=(touch.x, touch.y)) touch.grab(self) print "< grabbed >" def on_touch_move(self, touch): # Při pohybu prstu, zaznamenává pohyb if (touch.grab_current is self): touch.ud["line"].points += [touch.x, touch.y] def on_touch_up(self, touch): # Při zvednutí prstu, porovnává s gestem v databázi if (touch.grab_current is self): g = self.simplegesture('', zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])) g2 = self.gdb.find(g, minscore=0.80) if g2: if g2[1] == self.GSTR_SWIPE_LEFT: self.dispatch('on_swipe_left') if g2[1] == self.GSTR_SWIPE_RIGHT: self.dispatch('on_swipe_right') touch.ungrab(self) def on_swipe_left(self, *args): # Událost přejetí prstu doleva self.app.on_swipe_left() def on_swipe_right(self, *args): # Událost přejetí prstu doprava self.app.on_swipe_right()
class Listener(EventDispatcher): """ listener function that queries kivy for touch events, builds the gesture and dispatch it through the actions singleton. """ def __init__(self, config, gestures, el, *args, **kwarg): """ :param config: string containing the path to the action configuration :param gestures: string containing the path to the gestures configuration """ super(EventDispatcher, self).__init__(*args, **kwarg) self._event_loop = el self._gdb = GestureDatabase() self._actions = Actions(config, gestures) self.update_devices() self._multitouches = [] def update_devices(self): log.debug('update_devices()') context = pyudev.Context() for device in context.list_devices(subsystem='input', ID_INPUT_MOUSE=True): if device.sys_name.startswith('event'): if 'PRODUCT' in device.parent.keys(): self._actions.update_gestures(device.parent['PRODUCT']) for gest_n, gest_r in self._actions.get_gestures().iteritems(): for g in gest_r: g = self._gdb.str_to_gesture(g) g.normalize() g.name = gest_n self._gdb.add_gesture(g) def on_touch_down(self, touch): """ listening function executed at begining of touch event builds the gesture """ self._multitouches.append(touch) touch.ud['line'] = Line(points=(touch.sx, touch.sy)) return True def on_touch_move(self, touch): """ listening function executed during touch event store points of the gesture """ # store points of the touch movement try: touch.ud['line'].points += [touch.sx, touch.sy] return True except (KeyError), e: pass
class Listener(EventDispatcher): """ listener function that queries kivy for touch events, builds the gesture and dispatch it through the actions singleton. """ def __init__(self, config, gestures, el, *args, **kwarg): """ :param config: string containing the path to the action configuration :param gestures: string containing the path to the gestures configuration """ super(EventDispatcher, self).__init__(*args, **kwarg) self._event_loop = el self._gdb = GestureDatabase() self._actions = Actions(config, gestures) self.update_devices() self._multitouches = [] def update_devices(self): log.debug('update_devices()') context = pyudev.Context() for device in context.list_devices(subsystem='input', ID_INPUT_MOUSE=True): if device.sys_name.startswith('event'): if 'PRODUCT' in device.parent.keys(): self._actions.update_gestures(device.parent['PRODUCT']) for gest_n, gest_r in self._actions.get_gestures().iteritems(): for g in gest_r: g = self._gdb.str_to_gesture(g) g.normalize() g.name = gest_n self._gdb.add_gesture(g) def on_touch_down(self, touch): """ listening function executed at begining of touch event builds the gesture """ self._multitouches.append(touch) touch.ud['line'] = Line(points=(touch.sx, touch.sy)) return True def on_touch_move(self, touch): """ listening function executed during touch event store points of the gesture """ # store points of the touch movement try: touch.ud['line'].points += [touch.sx, touch.sy] return True except (KeyError), e: pass
class GestureBox(FloatLayout): def __init__(self, **kwargs): super(Box, self).__init__(**kwargs) self.gdb = GestureDatabase() top_to_button = self.gdb.str_to_gesture(gesture_string) self.gdb.add_gesture(top_to_button) self.register_event_type('on_top_to_button') def on_touch_down(self, touch): super(Box, self).on_touch_down(touch) # print('vbar',self.scroll.vbar) if self.scroll.vbar[0] > 0.79 and self.collide_point(*touch.pos): touch.grab(self) touch.ud['data points'] = [(touch.x, touch.y)] def on_touch_move(self, touch): super(Box, self).on_touch_move(touch) if touch.grab_current is self: touch.ud['data points'] += [(touch.x, touch.y)] def on_touch_up(self, touch): super(Box, self).on_touch_up(touch) if touch.grab_current is self: gesture = Gesture() gesture.add_stroke(touch.ud['data points']) gesture.normalize() match = self.gdb.find(gesture, minscore=0.8) if match: # print(match[0]) self.dispatch('on_top_to_button') touch.ungrab(self) def on_top_to_button(self): print('My event happend') def add_widget(self, widget): if len(self.children) == 0: super(Box, self).add_widget(widget) self.scroll = widget else: print("Can't add more than one widget")
class GestureBoard(Widget): def __init__(self, *args, **kwargs): super(GestureBoard, self).__init__() self.gdb = GestureDatabase() self.gdb.add_gesture(check) def on_touch_down(self, touch): userdata = touch.ud with self.canvas: Color(1, 1, 0) d = 30.0 Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d))userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError) as e: pass def on_touch_up(self, touch): g = simplegesture('',list(zip(touch.ud['line'].points[::2],touch.ud['line'].points[1::2])))
class DrawingSpace(StencilView): def __init__(self, *args, **kwargs): super(DrawingSpace, self).__init__() self.gdb = GestureDatabase() self.line45 = self.gdb.str_to_gesture(line45_str) self.circle = self.gdb.str_to_gesture(circle_str) self.cross = self.gdb.str_to_gesture(cross_str) self.line135 = self.line45.rotate(90) self.line225 = self.line45.rotate(180) self.line315 = self.line45.rotate(270) self.gdb.add_gesture(self.line45) self.gdb.add_gesture(self.line135) self.gdb.add_gesture(self.line225) self.gdb.add_gesture(self.line315) self.gdb.add_gesture(self.circle) self.gdb.add_gesture(self.cross) def activate(self): self.bind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def deactivate(self): self.unbind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def down(self, ds, touch): if self.collide_point(*touch.pos): self.points = [touch.pos] self.ix = self.fx = touch.x self.iy = self.fy = touch.y return True def move(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) return True def up(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) gesture = self.gesturize() recognized = self.gdb.find(gesture, minscore=0.50) if recognized: self.discriminate(recognized) return True def gesturize(self): gesture = Gesture() gesture.add_stroke(self.points) gesture.normalize() return gesture def min_and_max(self, x, y): self.ix = min(self.ix, x) self.iy = min(self.iy, y) self.fx = max(self.fx, x) self.fy = max(self.fy, y) def discriminate(self, recognized): if recognized[1] == self.cross: self.add_stickman() if recognized[1] == self.circle: self.add_circle() if recognized[1] == self.line45: self.add_line(self.ix, self.iy, self.fx, self.fy) if recognized[1] == self.line135: self.add_line(self.ix, self.fy, self.fx, self.iy) if recognized[1] == self.line225: self.add_line(self.fx, self.fy, self.ix, self.iy) if recognized[1] == self.line315: self.add_line(self.fx, self.iy, self.ix, self.fy) def add_circle(self): cx = (self.ix + self.fx) / 2.0 cy = (self.iy + self.fy) / 2.0 self.tool_box.tool_circle.widgetize(self, cx, cy, self.fx, self.fy) def add_line(self, ix, iy, fx, fy): self.tool_box.tool_line.widgetize(self, ix, iy, fx, fy) def add_stickman(self): cx = (self.ix + self.fx) / 2.0 cy = (self.iy + self.fy) / 2.0 self.tool_box.tool_stickman.draw(self, cx, cy) def on_children(self, instance, value): self.status_bar.counter = len(self.children)
class QueueViewManager(ScreenManager): origin = ObjectProperty() manager = ObjectProperty() #screens = ListProperty([]) index = NumericProperty() loop = BooleanProperty(False) def __init__(self, *args, **kwargs): super(QueueViewManager, self).__init__() #Initial values self.index = 0 #Create gesture database self.gdb = GestureDatabase() #Add gestures self.gdb.add_gesture(swipe_left) self.gdb.add_gesture(swipe_right) self.gesture_tolerence = 0.70 # minimum score that a gesture must reach before actions can be triggered def getScreenNameByIndex(self, index): return str(self.screens[index].name) ''' def getNext(self): nextIndex = self.index + 1 if (self.loop == False): # if nextIndex would fall outside the scope of the screens list return None if nextIndex > (len(self.screens)-1): return None # otherwise return the widget associated with nextIndex else: return self.screens[nextIndex] else: # if loop is True return the widget no matter what if nextIndex > (len(self.screens)-1): nextIndex = nextIndex - (len(self.screens)-1) return self.screens[nextIndex] def getPrev(self): prevIndex = self.index - 1 if (self.loop == False) and (prevIndex < 0): return None else: return self.screens[prevIndex] next = AliasProperty(getNext, bind=['index']) prev = AliasProperty(getPrev, bind=['index']) ''' def isGesture(self, question, gesture): if question.get_score(gesture) > self.gesture_tolerence: return True else: return False def on_touch_down(self, touch): # create the 'line' key in the touch object, this data is made available # to all other functions that recive this touch object touch.ud['line'] = Line(points=(touch.x, touch.y)) super(QueueViewManager, self).on_touch_down(touch) def on_touch_move(self, touch): # append the newist coordinate data to the point list of the line try: touch.ud['line'].points += (touch.x, touch.y) return True except KeyError: pass super(QueueViewManager, self).on_touch_move(touch) def on_touch_up(self, touch): try: g = simplegesture( '', list( zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))) Logger.info('Swipe Left: {}'.format(g.get_score(swipe_left))) Logger.info('Swipe Right: {}'.format(g.get_score(swipe_right))) if self.isGesture(g, swipe_left): Logger.info("Gesture: gesture is a left swipe") self.gotoScreenRight() # A left swipe should goto the right hand # screen, because the act of dragging # somthing to the left exposes the right # hand side of the object and vice versa. if self.isGesture(g, swipe_right): Logger.info("Gesture: gesture is a right swipe") self.gotoScreenLeft() except KeyError: pass super(QueueViewManager, self).on_touch_up(touch) def on_index(self, widget, index): Logger.info('QueueViewManager: next: {}'.format(self.next)) Logger.info("QueueViewManager: index: {}".format(index)) Logger.info('QueueViewManager: prev: {}'.format(self.prev)) self.current = self.getScreenNameByIndex(index) def gotoScreenLeft(self): # only attempt to change the index if self.screens is not empty self.transition.direction = 'right' ''' if self.screens != []: self.index -= 1 ''' self.current = self.previous() def gotoScreenRight(self): # only attempt to change the index if self.screens is not empty self.transition.direction = 'left' ''' if self.screens != []: self.index += 1 ''' self.current = self.next() def addPostViewScreen(self, post): newName = str(post['id']) if not newName in self.screen_names: Logger.info( "QueueViewManager: I added post {id} by {artist}".format( id=post['id'], artist=post['artist'])) widget = PostView(origin=self.origin, coordinator=self.manager, name=newName) self.add_widget(widget) widget.metadata = post Logger.info(widget.name) #self.screens.append(widget) #widget.bind(origin=self.origin) else: Logger.info("QueueViewManager: I rejected the duplicate entry")
class CurrentSession(Screen): _app = ObjectProperty() working_layout = ObjectProperty() buttons = DictProperty() grid = StringProperty('small') n_of_cols = NumericProperty(number_of_cols) color_manager = ObjectProperty() def __init__(self, **kwargs): super(CurrentSession, self).__init__(**kwargs) #self.snack = Snackbar(text="Current session updated", duration=2) self.ssm = None self.buttons = {} self.available_grid_sizes = ['small', 'large'] self.bind(grid=self.refresh_menu_text, buttons=self.refresh_screen) self.working_layout.bind( minimum_height=self.working_layout.setter('height')) self.menu_items = [{ 'viewclass': 'MDFlatButton', 'text': 'Show %s grid' % self.grid, 'on_release': lambda: self.change_grid_size() }] self.color_manager = ColorManager(md_colors) self.clear_anim = Animation(x=self.width, duration=.5, transition=animation_type) self.bind(width=self.update_anim, size=self.adjust_height) self.gdb = GestureDatabase() self.gdb.add_gesture(left_to_right) Clock.schedule_once(self.my_init) def my_init(self, dt): self.manager = self.parent self.root = self.parent.parent.parent.parent self.working_layout.parent.bind( minimum_height=self.working_layout.parent.setter('height')) self.init_button = self.ids.add_cells def animate_action_button(self, instance): # print instance.content # anim = Animation(size=(0,0), center_x=instance.center_x, duration=1, transition='in_out_quad') # anim2 = Animation(opacity=0, center_x=instance.center_x, duration=1, transition='in_out_quad') # print instance.center_x, instance.center_y # anim.bind(on_complete= self.teste) # anim.start(instance) # anim2.start(instance.content) self.parent.current = 'workspace' def teste(self, x, y): print x, y def update_anim(self, instance, value): self.clear_anim._animated_properties['x'] = self.width def refresh_screen(self, instance, value): if bool(self.buttons): if self.ids.plus_layout.children: self.ids.plus_layout.remove_widget(self.ids.add_cells) else: self.ids.plus_layout.add_widget(self.init_button) def on_touch_down(self, touch): # create an user defined variable and add the touch coordinates touch.ud['gesture_path'] = [(touch.x, touch.y)] super(CurrentSession, self).on_touch_down(touch) def on_touch_move(self, touch): if 'gesture_path' in touch.ud: touch.ud['gesture_path'].append((touch.x, touch.y)) super(CurrentSession, self).on_touch_move(touch) def on_touch_up(self, touch): if 'gesture_path' in touch.ud: # create a gesture object gesture = Gesture() # add the movement coordinates gesture.add_stroke(touch.ud['gesture_path']) # normalize so thwu willtolerate size variations gesture.normalize() # minscore to be attained for a match to be true, default 0.3 g2 = self.gdb.find(gesture, minscore=0.70) if g2: print 'swipe left' #print("gesture representation:", self.gdb.gesture_to_str(gesture)) def finish(self): print 'finishing' self.clear() def adjust_height(self, instance, value): # TODO Analysis pass # print self.width, self.height # print self.ids.add_cells.pos #print self.height #self.ids.plus_layout.height = self.height - self.ids.add_cells.height - self.root.ids.toolbar.height #print self.ids.plus_layout.height # print [x for x in instance.walk()] # print self.buttons #print type(instance) == GridLayout # if type(instance) == GridLayout: # self.ids.plus_layout.height = self.working_layout.row_default_height # self.ids.add_cells.y = self.buttons[sorted(self.buttons.keys())[-1]].y # def on_touch_down(self, touch): # print touch @mainthread def on_enter(self, *args): if not self.parent.has_screen('workspace'): self.parent.add_widget(self.parent.saved_screens['workspace']()) self.ssm = self.parent.get_screen( 'workspace').secondary_screen_manager self.update_dots_menu() @mainthread def on_leave(self, *args): if len(self.root.ids['toolbar'].dots_menu.items) > 3: del self.root.ids['toolbar'].dots_menu.items[1] def update_dots_menu(self): self.root.ids['toolbar'].dots_menu.items.insert(1, self.menu_items[0]) def refresh_menu_text(self, widget, value): self.menu_items[0]['text'] = 'Show %s grid' % value def change_grid_size(self): if self.grid != self.available_grid_sizes[0]: self.grid = self.available_grid_sizes[0] self.n_of_cols = number_of_cols else: self.grid = self.available_grid_sizes[1] self.n_of_cols = number_of_cols + 1 self.root.ids['toolbar'].dots_menu.items[1] = self.menu_items[0] self.root.ids['toolbar'].dots_menu.custom_dismiss() def populate_current_session(self, _widget): if _widget.active: if not self.buttons.has_key(_widget.pass_text) or dev: print 'Adding ' + _widget.pass_text + ' to current session' new_text = _widget.pass_text.replace(' ', '\n') button = MDColorFlatButton(text=new_text, id=_widget.pass_text, size_hint=(1, 1), on_release=self.add) self.bind(grid=button.setter('grid')) self.buttons[_widget.pass_text] = button button.set_bg_color( get_color_from_hex(self.color_manager.pop())) self.working_layout.add_widget(button) else: if self.buttons.has_key(_widget.pass_text): self.working_layout.remove_widget( self.buttons[_widget.pass_text]) del self.buttons[_widget.pass_text] def add(self, button): button.set_is_empty(False) button.increment_counter() if self.parent.get_screen('settings').ids.vibration.active: print "I'm vibratin'!" if (platform == 'android' or platform == 'ios' ) and self.parent.get_screen('settings').ids.vibration.active: #print platform # try: vibrate(0.1) # except NotImplementedError: # print "Can't access the vibrate function" def clear(self): if self.manager.current_screen.name == self.name: for i, button in enumerate(self.buttons.values()): self.clear_anim.start(button) if i == len(self.buttons) - 1: self.clear_anim.bind(on_complete=self.clear_complete) else: self.ssm.reset = not self.ssm.reset def clear_complete(self, instance, value): # sm = self.parent.get_screen('workspace').ids.secondary_screen_manager # sm.reset = not sm.reset self.ssm.reset = not self.ssm.reset
class LockScreen(Screen): '''Screen for configuration settings''' widget_lock = ObjectProperty(None) # Sets the transparency of the background color for each widget _widget_visible = 0.0 # The padding_x value for the child widgets _x_padding = dp(30) def __init__(self, *args, **kwargs): super(LockScreen, self).__init__() self.gdb = GestureDatabase() self.gdb.add_gesture(check) def on_touch_down(self, touch): if touch.x > self.center_x + dp(300) or touch.x < self.center_x - dp( 300): return super(LockScreen, self).on_touch_down(touch) # Start collecting points in touch.ud # Create a line to display the points if self.collide_point(*touch.pos): touch.grab(self) ud = touch.ud ud['group'] = g = str(touch.uid) with self.canvas: Color(0.5, 0.5, 1) d = 60. Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d), group=g) ud['line'] = Line(points=(touch.x, touch.y), width=10, group=g) ret = True else: ret = super(LockScreen, self).on_touch_down(touch) return ret def on_touch_move(self, touch): # Store points of the touch movement #if touch.grab_current is not self: # return try: touch.ud['line'].points += [touch.x, touch.y] except KeyError: pass def on_touch_up(self, touch): # Touch is over ret = False if touch.grab_current is self: # Add gesture to database try: g = Gesture() g.add_stroke( list( zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))) g.normalize() g.name = 'try' # Delete trace line self.canvas.remove_group(touch.ud['group']) # Compare gesture to my_gestures.py #print("gesture representation:", self.gdb.gesture_to_str(g)) #print("check:", g.get_score(check)) # use database to find the more alike gesture, if any g2 = self.gdb.find(g, minscore=0.90) #print(g2) if g2 and g2[1] == check: self.manager.app.open_settings() ret = True except KeyError: ret = super(LockScreen, self).on_touch_up(touch) touch.ungrab(self) return ret
class GestureBox(BoxLayout): 'GestureBox class. See module documentation for more information.' gesture_timeout = NumericProperty(200) '''Timeout allowed to trigger the :data:`gesture_distance`, in milliseconds. If the user has not moved :data:`gesture_distance` within the timeout, the gesture will be disabled, and the touch event will go to the children. :data:`gesture_timeout` is a :class:`~kivy.properties.NumericProperty`, default to 200 (milliseconds) ''' gesture_distance = NumericProperty('20dp') '''Distance to move before attempting to interpret as a gesture, in pixels. As soon as the distance has been traveled, the :class:`GestureBox` will interpret as a gesture. It is advisable that you base this value on the dpi of your target device's screen. :data:`gesture_distance` is a :class:`~kivy.properties.NumericProperty`, default to 20dp. ''' # INTERNAL USE ONLY # used internally to store a touch and # dispatch it if the touch does not turn into a gesture _touch = ObjectProperty(None, allownone=True) def __init__(self, *args, **kwargs): super(GestureBox, self).__init__(*args, **kwargs) self.gestures = GestureDatabase() self.register_event_type('on_gesture') def add_gesture(self, name, gesture_str): '''Add a recognized gesture to the database. :param name: a short identifier for the gesture. This value is passed to the on_gesture event to identify which gesture occurred. :param gesture_str: A (probably very long) string describing the gesture and suitable as input to the :meth:`GestureDatabase.str_to_gesture` method. The `examples/gestures/gesture_board.py` example is a good way to generate such gestures.''' gesture = self.gestures.str_to_gesture(gesture_str) gesture.name = name self.gestures.add_gesture(gesture) def on_touch_down(self, touch): '''(internal) When the touch down event occurs, we save it until we know for sure that a gesture is not being initiated. If a gesture is initiated we intercept all the touch and motion events. Otherwise, we release it to any child widgets.''' if not self.collide_point(*touch.pos): touch.ud[self._get_uid('cavoid')] = True return if self._touch: return super(GestureBox, self).on_touch_down(touch) self._touch = touch uid = self._get_uid() touch.grab(self) touch.ud[uid] = { 'mode': 'unknown', 'time': touch.time_start} # This will be unscheduled if we determine that a gesture is being # attempted before it is called. Clock.schedule_once(self._change_touch_mode, self.gesture_timeout / 1000.) # Start storing the gesture line in case this turns into a gesture touch.ud['gesture_line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): '''(internal) As with touch down events, motion events are recorded until we know that a gesture is or is not being attempted.''' if self._get_uid('cavoid') in touch.ud: return if self._touch is not touch: super(GestureBox, self).on_touch_move(touch) return self._get_uid() in touch.ud if touch.grab_current is not self: return True ud = touch.ud[self._get_uid()] if ud['mode'] == 'unknown': dx = abs(touch.ox - touch.x) dy = abs(touch.oy - touch.y) distance = sqrt(dx * dx + dy * dy) # If we've moved more than the thershold distance inside the # threshold time, treat as a gesture if distance > self.gesture_distance: Clock.unschedule(self._change_touch_mode) ud['mode'] = 'gesture' # Regardless of whether this is a known gesture or not, collect # the motion point in case it becomes one. try: touch.ud['gesture_line'].points += [touch.x, touch.y] except KeyError: pass return True def on_touch_up(self, touch): '''(internal) When the touch up occurs, we have to decide if a gesture was attempted. If so, we fire the on_gesture event. In all other cases we propogate the change to child widget.''' if self._get_uid('cavoid') in touch.ud: return if self in [x() for x in touch.grab_list]: touch.ungrab(self) self._touch = None ud = touch.ud[self._get_uid()] if ud['mode'] == 'unknown': Clock.unschedule(self._change_touch_mode) super(GestureBox, self).on_touch_down(touch) Clock.schedule_once(partial(self._do_touch_up, touch), .1) else: # A gesture was attempted. Did it match? gesture = Gesture() gesture.add_stroke( zip(touch.ud['gesture_line'].points[::2], touch.ud['gesture_line'].points[1::2])) gesture.normalize() match = self.gestures.find(gesture, minscore=0.70) if match: self.dispatch('on_gesture', match[1].name) else: # The gesture wasn't recognized; invoke a normal reaction super(GestureBox, self).on_touch_down(touch) Clock.schedule_once(partial(self._do_touch_up, touch), .1) return True else: if self._touch is not touch and self.uid not in touch.ud: super(GestureBox, self).on_touch_up(touch) return self._get_uid() in touch.ud def _do_touch_up(self, touch, *largs): '''(internal) Simulate touch up events for anything that has grabbed the touch''' super(GestureBox, self).on_touch_up(touch) # don't forget about grab event! for x in touch.grab_list[:]: touch.grab_list.remove(x) x = x() if not x: continue touch.grab_current = x super(GestureBox, self).on_touch_up(touch) touch.grab_current = None return True def _change_touch_mode(self, *largs): '''(internal) Simulate a touch down if we know the touch did not become a gesture''' if not self._touch: return uid = self._get_uid() touch = self._touch ud = touch.ud[uid] if ud['mode'] == 'unknown': touch.ungrab(self) self._touch = None touch.push() touch.apply_transform_2d(self.to_widget) touch.apply_transform_2d(self.to_parent) super(GestureBox, self).on_touch_down(touch) touch.pop() return def _get_uid(self, prefix='sv'): return '{0}.{1}'.format(prefix, self.uid) def on_gesture(self, gesture_name): '''Called whenever a gesture has occured. This is a Kivy event. It can be overridden in a subclass our bound to using :meth:`Widget.bind`. ''' pass
class GameMatrix(GridLayout): def __init__(self, app, **kwargs): # inicializace pole self.app = app super(GameMatrix, self).__init__(**kwargs) self.coords = [] self.dpos = (0, 0) self.colors = [] self.shape = None self.active_color = [.1372, .1372, .1372, 1] self.inactive_color = [.1372, .1372, .1372, 1] self.fUpdate = 12 * 22 * "0" self.tnetCoords2 = [] for y in range(51, 73): for x in range(51, 63): self.tnetCoords2.append(chr(x) + chr(y)) self.tnetCoords = [] for x in range(51, 63): col = [] for y in range(51, 73): col.append((chr(x), chr(y))) self.tnetCoords.append(col) self.tnetColors = [] for c in range(33, 48): self.tnetColors.append(chr(c)) self.move = False self.orientation = 0 self.colored = set() self.colors = [ deepcopy(self.inactive_color), [0, .6, .8, 1], [1, .7333333, .2, 1], [.6, .8, 0, 1], [.666666667, .4, .8, 1], [1, .266666667, .266666667, 1] ] self.COORDS_SET = set() for y in range(int(self.rows)): line = [] for x in range(int(self.cols)): box = Box() box.coords = (x, y) box.colored = deepcopy(self.inactive_color) self.add_widget(box) line.append(box) self.COORDS_SET.add((x, y)) self.coords.append(line) self.b = 0 self.startgame = False self.seed = randint(0, 0xFFFFFF) self.specials = set() self.buildNext = False self.mLR = False self.gdb = GestureDatabase() self.GSTR_DROP = \ self.gdb.str_to_gesture('eNq1l82O2jAQgO9+Ebg08ng8M/YL0GslHqBKIQK0W4iSbHf37WtPIjZS/6Si4WIYez4P+Yyxt5eny4/35tSN08vQuc9L23u3Pfbg9ptr+73buD6Ut6VBN+434zTcnrqxfIxu+9yT2/4WstdhrueKkpLf3y7Xqaalmpb/kPaljnI9zBXUEt5LCgS3803EKCmwT5yJCXKt5q32Yu31HsETZe85AIAQsBu/tX+fJuo05E7zDEEEBDOg17k8ufH0AF2/O4gRPSk929CDCghgRA9KRyO6Wg13qx7viyaUaRLyY3jVGsQKr15DNsKjikWwwqtZRCu8qkUrtahq0Uotqlpc1H7yDaT1jhbKY3sEH1VtBCu8qo1ohVe1kazwqjaKFV7VRiu1pGrJSi2pWvpQG0Ne/9k+SFezREZ0FUtiRFevlG3orFoZjOhqlY2sslplI6usVtnIKqtV/rC6bPDLCSTBQi89HhIjUvQogcWXn+C/4KJSBWzg6lTQBq5Khf4XXm8Hh6HrrvezvnA97Iu47Q4FG+92UUJppl6Sa38N5nUwogaTXwUxpzkI6yAtwbAOQmnWL64jUEdwriNCWtKia+fqz93ldJ7qHYXcrmyxpbtEXy/H6VyDXIqaQ9PtuRva66FejpLUZQg1vDzWr/1wO74cFJRKJQ2Vs4OUK0sMwEF0gTY/AXq8jUg=') self.gdb.add_gesture(self.GSTR_DROP) self.dropAnimation2 = Animation(colored=self.inactive_color, d=.03) self.dropAnimation = Animation(colored=self.inactive_color, d=.1) self.spectate = False def simplegesture(self, name, point_list): # Pomocná funkce pro rozpoznávání gest g = Gesture() g.add_stroke(point_list) g.normalize() g.name = name return g def generate(self): # Algoritmus pseudonáhodného generování herních bloků a = 0x08088405 c = 1 M = 2**32 self.seed = (a * self.seed + c) % M block = int(self.seed * 100. / M) self.seed = (a * self.seed + c) % M orientation = int(self.seed * 4. / M) return (block, orientation) def build(self, dt): # Pomocná funkce pro automatické volání self._build() def _build(self): # Přidá do pole nový herní blok if self.startgame == False: self.stack = [self.generate() for y in range(5)] st = self.stack.pop(0) piece = int(self.app.serverConf.blockFreq[st[0]]) nextPC = int(self.app.serverConf.blockFreq[self.stack[0][0]]) self.app.nextPiece.showNext(nextPC) orientation = st[1] if piece in (1, 5, 6): if orientation % 2 == 0: self.orientation = 0 else: self.orientation = 1 elif piece == 2: self.orientation = 0 self.shape = deepcopy(PIECES[piece]) self.active_color = deepcopy(COLORS[piece]) self.stack.append(self.generate()) full = False for box in self.shape[self.orientation]: if tuple(box) in self.colored: full = True break if full == False: for box in self.shape[self.orientation]: self.drop(box) for box in self.shape[self.orientation]: self.mark(box) if self.app.tetrifast: self._fall() Clock.schedule_interval(self.fall, (1005 - (self.app.lvl * 10)) / 1000.) self.app.send_message("f " + str(self.app.id) + " " + self.fUpdate) self.startgame = True else: self.startgame = False self.spectate = True self.app.send_message("playerlost {0}".format(self.app.id)) for i in range(22): self.addLine() self.buildNext = False self.blockRotation = False def get(self, x, y): # Vrátí objekt Box - 1 kostku z pole return self.coords[y][x] def getMinMax(self, shape): # Vrací minimální a maximální souřadnice bloku x = [] y = [] for box in shape: x.append(box[0]) y.append(box[1]) return {'x': (min(x), max(x)), 'y': (min(y), max(y))} def drop(self, coords, anim=0): # Přebarví kostku na šedou (barva pole) box = self.get(coords[0], coords[1]) box.colored = deepcopy(self.inactive_color) box.active = False box.texture = False box.sb = False def mark(self, coords, random=False, anim=0): # Přebarví kostku na barevnou box = self.get(coords[0], coords[1]) box.colored = self.active_color if random == False else choice( deepcopy(COLORS)) box.active = True def fall(self, dt): # Pomocná funkce pro automatické volání print self.colored self._fall() def _fall(self, animate=1): # Slouží ke spadení bloku o jedno dolů (každou cca 1 s) if (self.buildNext == False) and self.startgame and (self.app.paused == False): anim = [] unschedule = False next_pos = deepcopy(self.shape[self.orientation]) for box in next_pos: box[1] += 1 if self.shape[self.orientation][-1][1] >= 21: unschedule = True print "< fall unschedule >" elif len(self.colored.intersection(set(tuple(y) for y in next_pos))) != 0: unschedule = True else: for box in self.shape[self.orientation]: self.drop(box, anim=animate) for i in self.shape: for box in i: box[1] += 1 for box in self.shape[self.orientation]: self.mark(box, anim=animate) unschedule = False if unschedule == True: self.blockRotation = True print "Current: " + str(self.shape[self.orientation]) print "Next: " + str(next_pos) Clock.unschedule(self.fall) for i in self.shape[self.orientation]: try: g = self.get(i[0], i[1]) if g.colored != [.1372, .1372, .1372, 1]: anim.append(g) self.colored.add(tuple(i)) except: pass self.orientation = 0 self.tetris(anim) del (anim) self.buildNext = True if self.app.tetrifast == False: Clock.schedule_once(self.build, 1) else: self._build() unschedule = False def on_touch_down(self, touch): # Uživatel se dotkl pole if self.collide_point(touch.x, touch.y) and self.startgame and (self.app.paused == False): touch.grab(self) touch.ud["line"] = Line(points=(touch.x, touch.y)) def on_touch_move(self, touch): # Uživatel pohybuje s prstem po poli if (touch.grab_current is self) and self.startgame and ( self.app.paused == False) and (self.blockRotation == False): touch.ud["line"].points += [touch.x, touch.y] self.box_size = self.get(0, 0).size[0] self.dpos = (touch.dpos[0] + self.dpos[0], touch.dpos[1] + self.dpos[1]) if abs(self.dpos[0]) >= self.box_size: next_pos = deepcopy(self.shape[self.orientation]) for box in next_pos: box[0] += int( round((0.5 * self.dpos[0]) / self.box_size, 0)) minmax = self.getMinMax(next_pos) if minmax['x'][0] < 0 or minmax['x'][1] > 11: pass elif len( self.colored.intersection( set(tuple(y) for y in next_pos))) != 0: pass else: for box in self.shape[self.orientation]: self.drop(box, anim=1) for i in self.shape: for box in i: box[0] += int( round((0.5 * self.dpos[0]) / self.box_size, 0)) for box in self.shape[self.orientation]: self.mark(box, anim=1) self.move = True self.mLR = True self.dpos = (0, self.dpos[1]) if -1 * (self.dpos[1]) >= 1.05 * self.box_size: for i in range( abs(int(round(self.dpos[1] / self.box_size, 0) * 1))): self._fall() self.move = True self.dpos = (self.dpos[0], 0) def on_touch_up(self, touch): # Uživatel zvedl prst z obrazovky if touch.grab_current is self: g = self.simplegesture( '', zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])) g2 = self.gdb.find(g, minscore=0.80) if g2 and (self.mLR == False) and (self.blockRotation == False): if g2[1] == self.GSTR_DROP: print "< GESTURE: Drop >" for i in range(21 - self.shape[self.orientation][-1][1]): self._fall(animate=2) self.mLR = False else: if (self.mLR == False) and (self.move == False) and (self.blockRotation == False): if touch.x <= self.parent.size[0] / 2.: self.rotate(False) #left else: self.rotate(True) #right self.mLR = False if self.move == True: self.move = False touch.ungrab(self) def dropAnim(self, fall): # Animace padání bloku if fall: d = .1 else: d = .2 boxes = [] for box in self.shape[self.orientation]: if ((box[0] >= 0) and (box[0] <= 11)) and ((box[1] >= 0) and (box[1] <= 21)): cur = self.get(box[0], box[1]) a = Box() a.size = cur.size a.pos = cur.pos a.colored = cur.colored a.size_hint = (None, None) boxes.append(a) self.app.sOverlay.add_widget(a) if len(boxes) != 0: anims = [ Animation(y=p.y - p.size[1], opacity=0., t='linear', d=d) for p in boxes ] for i in range(len(boxes)): anims[i].start(boxes[i]) Clock.schedule_once(self.clearAnimation, d) def fellAnim(self, widgets): # Animace po spadení bloku (změna barvy) color1 = widgets[0].colored color2 = [y + .3 for i, y in enumerate(color1) if i < 3] + [ color1[-1], ] anim = Animation(colored=color2, duration=.2) + Animation( colored=color1, duration=.2) for i in widgets: anim.start(i) def clearAnimation(self, dt): # Odstraní widgety vytvořené animací self.app.sOverlay.clear_widgets() print "< widgets cleared >" def rotate(self, direction): # Otáčení s blokem maximum = len(self.shape) now = deepcopy(self.orientation) if direction: #left self.orientation -= 1 if self.orientation < 0: self.orientation = maximum - 1 else: #right self.orientation += 1 if self.orientation > maximum - 1: self.orientation = 0 if now != self.orientation: for box in self.shape[now]: self.drop(box) coords = self.getMinMax(self.shape[self.orientation]) if coords['y'][1] > 21: print "posunout nahoru o {0}".format(coords['y'][1] - 21) if coords['x'][0] < 0: print "posunout doprava o {0}".format(abs(coords['x'][0])) for s in self.shape: for box in s: box[0] += abs(coords['x'][0]) if coords['x'][1] > 11: print "posunout doleva o {0}".format(coords['x'][1] - 11) for s in self.shape: for box in s: box[0] -= coords['x'][1] - 11 if len( self.colored.intersection( set(tuple(y) for y in self.shape[self.orientation]))) != 0: self.orientation = now for box in self.shape[self.orientation]: self.mark(box) print self.orientation def tetris(self, anim): # Rozhoduje o tom, zda byl vyplněn řádek (voláno po spadení bloku) full = [] for i in self.colored: full.append(i[1]) lines = [] for i in range(22): if full.count(i) == 12: lines.append(i) if len(lines) != 0: if self.app.onAndroid(): self.app.vibrate(0.05) self.app.linesCleared += len(lines) if self.app.linesCleared % int(self.app.serverConf.linesLvl) == 0: self.app.lvl += int(self.app.serverConf.lvlInc) print "Lines cleared: " + str(self.app.linesCleared) print "Level: " + str(self.app.lvl) for i in range(len(lines)): for j in range(12): self.colored.remove((j, lines[i])) self.specials.discard((j, lines[i])) box = self.get(j, lines[i]).sb if box != False: self.app.dock.addSpecial(box) self.drop((j, lines[i])) lns = deepcopy(lines) lns.sort() print lns for num, ln in enumerate(lns): colored = list(self.colored) colored.sort(cmp=lambda x, y: cmp(x[1], y[1])) colored.reverse() for coord in colored: if coord[1] < ln: new = (coord[0], coord[1] + 1) box = self.get(coord[0], coord[1]) newColor = box.colored sType = box.sb self.drop(coord) self.colored.discard(coord) if sType != False: self.specials.discard(coord) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) if self.app.serverConf[-2] == '1': if len(lines) >= 2 and len(lines) <= 3: self.app.send_message("sb 0 cs{0} {1}".format( len(lines) - 1, self.app.id)) print "add id:" + str(self.app.id) elif len(lines) == 4: print "Tetris!" if self.app.serverConf[-2] == '1': self.app.send_message("sb 0 cs{0} {1}".format( 4, self.app.id)) print "add id:" + str(self.app.id) else: print "< tetris() >" if self.app.linesCleared % int( self.app.serverConf.linesSpecial) == 0: self.addSpecial() else: self.fellAnim(anim) self.fieldUpdate() def addSpecial(self): # Přidá novou speciální kostku do pole if len(self.colored) - len(self.specials) > 0: special = choice(list(self.colored.difference(self.specials))) self.specials.add(special) self.drop(special) box = self.get(special[0], special[1]) sType = SPECIALS[ int(self.app.serverConf.specialFreq[randint(0, 99)]) - 1] box.special(sType) print sType print special else: for i in range(20): col = randint(0, 11) empty = True for c in self.colored: if c[0] == col: empty = False break if empty == True: self.colored.add((col, 21)) self.specials.add((col, 21)) self.drop((col, 21)) box = self.get(col, 21) sType = SPECIALS[ int(self.app.serverConf.specialFreq[randint(0, 99)]) - 1] box.special(sType) print sType print(col, 21) print "< Add special >" break def addLine(self, update=True): # Přidání náhodného řádku do pole (speciální kostkou) garbage = [randint(0, 7) for i in range(12)] garbage[randint(0, 11)] = 0 move = list(self.colored) move.sort(cmp=lambda x, y: cmp(x[1], y[1])) for coord in move: if coord[1] <= 21 and coord[1] >= 1: new = (coord[0], coord[1] - 1) box = self.get(coord[0], coord[1]) newColor = box.colored sType = box.sb self.drop(coord) self.colored.remove(coord) if sType != False: self.specials.discard(coord) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) for i, cell in enumerate(garbage): box = self.get(i, 21) box.texture = False if cell > 0: box.colored = COLORS[cell] self.colored.add((i, 21)) else: box.colored = self.inactive_color self.colored.discard((i, 21)) if update: self.fieldUpdate() for i, b in enumerate(self.shape): drop = False if i == self.orientation: drop = True for box in self.shape[i]: box = [box[0], box[1] + 1] if drop: for box in self.shape[i]: self.drop(box) for box in self.shape[i]: self.mark(box) def fieldUpdate(self, *args): # Vytvoření řetězce pro aktualizaci pole a odeslání aktualizace fupdate = "" for y in range(22): for x in range(12): s = set() s.add((x, y)) if self.colored.issuperset(s): box = self.get(x, y) if box.sb == False: fupdate += str(self.colors.index(box.colored)) else: fupdate += box.sb else: fupdate += '0' print fupdate d = [] prev = False for i in range(len(self.fUpdate)): if self.fUpdate[i] != fupdate[i]: try: color = int(fupdate[i]) except: color = self.tnetColors.index(chr(39)) + SPECIALS.index( fupdate[i]) if prev == False: d.append(self.tnetColors[color]) prev = fupdate[i] else: if prev != fupdate[i]: d.append(self.tnetColors[color]) prev = fupdate[i] d.append(self.tnetCoords2[i]) self.fUpdate = fupdate dstr = "f " + str(self.app.id) + " " for i in d: dstr += i self.app.send_message(dstr) self.app.print_message(dstr + "\xff") def clearLine(self): # Odstraní řádek od konce (speciální kostkou) for j in range(12): self.colored.discard((j, 21)) self.specials.discard((j, 21)) self.drop((j, 21)) colored = list(self.colored) colored.sort(cmp=lambda x, y: cmp(x[1], y[1])) colored.reverse() print colored for coord in colored: if coord[1] < 21: new = (coord[0], coord[1] + 1) box = self.get(coord[0], coord[1]) newColor = box.colored sType = box.sb self.drop(coord) self.colored.remove(coord) if sType != False: self.specials.discard(coord) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) self.fieldUpdate() def nuke(self): # Vyprázdnění pole (speciální kostkou) for box in self.colored: self.drop(box) self.colored = set() self.specials = set() self.fieldUpdate() def randomClear(self): # Náhodné odstranění několika kostek (speciální kostkou) cells = [] for i in range(10): cells.append((randint(0, 11), randint(0, 21))) for coord in cells: self.colored.discard(coord) self.specials.discard(coord) self.drop(coord) self.fieldUpdate() def clearSpecials(self): # Odstraní všechny speciální kostky (speciální kostkou) coords = list(self.specials) for coord in coords: self.specials.discard(coord) self.drop(coord) self.mark(coord, True) self.fieldUpdate() def quake(self): # Náhodně posune řádky o 3 doleva/doprava (speciální kostkou) colored = list(self.colored) colored.sort(cmp=lambda x, y: cmp(x[1], y[1])) cells = [[y[0], y[1]] for y in colored] prev = None rnd = 0 for cell in cells: if prev != cell[1]: prev = cell[1] rnd = choice(range(-3, 4)) cell[0] += rnd if cell[0] > 11: cell[0] -= 11 elif cell[0] < 0: cell[0] = 12 + cell[0] print cells for i in range(len(colored)): new = (cells[i][0], cells[i][1]) box = self.get(colored[i][0], colored[i][1]) newColor = box.colored sType = box.sb self.drop(colored[i]) self.colored.discard(colored[i]) if sType != False: self.specials.discard(colored[i]) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) self.fieldUpdate() def switchField(self, pid): # Vymění si pole s protivníkem (speciální kostkou) for y in range(22): for x in range(12): sender = self.app.overlay.children[0].children[ pid].matrix.coords[y][x] if type(sender) == type(None): self.drop((x, y)) self.colored.discard((x, y)) self.specials.discard((x, y)) else: newColor = sender.colored newStype = sender.sb box = self.get(x, y) box.colored = newColor self.colored.add((x, y)) if sender.sb != False: box.special(newStype) self.specials.add((x, y)) self.fieldUpdate() def gravity(self): # Spadení kostek, vyplnění mezer (speciální kostkou) colored = list(self.colored) colored.sort(cmp=lambda x, y: cmp(x[1], y[1])) colored.reverse() color = [ colored, ] i = 0 while True: color.append([]) for b in color[i]: if b[1] < 21: if (b[0], b[1] + 1) not in color[i]: color[i + 1].append((b[0], b[1] + 1)) else: color[i + 1].append(b) else: color[i + 1].append(b) if color[i] == color[i - 1]: break i += 1 color = color[-1] for j, b in enumerate(colored): if b != color[j]: old = self.get(b[0], b[1]) new = self.get(color[j][0], color[j][1]) new.colored = old.colored new.sb = old.sb new.texture = old.texture self.drop(b) self.colored.remove(b) self.colored.add(color[j]) if new.sb != False: self.specials.remove(b) self.specials.add(color[j]) self.fieldUpdate() def blockBomb(self): # Odstranění kostek blockbomb a vystřelení okolních do pole # (speciální kostkou) bombs = [] colored_remove = [] s = range(-1, 2) s.reverse() for bomb in self.specials: box = self.get(bomb[0], bomb[1]) if box.sb == 'o': bombs.append(bomb) for bomb in bombs: self.specials.remove(bomb) for i in range(-1, 2): for j in s: b = (bomb[0] + i, bomb[1] + j) if b in self.colored: colored_remove.append(b) new = choice( list( self.COORDS_SET.difference( self.colored.union( set([ tuple(a) for a in self.shape[ self.orientation] ]))))) self.colored.add(new) new = self.get(new[0], new[1]) old = self.get(b[0], b[1]) new.colored = old.colored for bomb in bombs + colored_remove: self.colored.discard(bomb) self.drop(bomb) self.fieldUpdate()
import json from kivy.properties import ObjectProperty from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition from kivy.gesture import GestureDatabase, Gesture from gallery.stage import StageLayout from gallery.overview import OverviewScrollView gesture_db = GestureDatabase() gesture_string = json.load(open('gallery/gesture_string.json', 'rb')) for name, gs in gesture_string.items(): gesture = gesture_db.str_to_gesture(gs) gesture.name = name gesture_db.add_gesture(gesture) class MyScreen(Screen): content = ObjectProperty() def __init__(self, name, content): super(MyScreen, self).__init__(name=name) self.content.add_widget(content) class MyScreenManager(ScreenManager): transition = FadeTransition() def __init__(self): super(MyScreenManager, self).__init__() # self.overview_screen = MyScreen('overview')
class GestureBoard(FloatLayout): """ Our application main widget, derived from touchtracer example, use data constructed from touches to match symboles loaded from my_gestures. """ def __init__(self, *args, **kwargs): super(GestureBoard, self).__init__() self.gdb = GestureDatabase() # add pre-recorded gestures to database self.gdb.add_gesture(cross) self.gdb.add_gesture(check) self.gdb.add_gesture(circle) self.gdb.add_gesture(square) def on_touch_down(self, touch): # start collecting points in touch.ud # create a line to display the points userdata = touch.ud with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d)) userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): # store points of the touch movement try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError) as e: pass def on_touch_up(self, touch): # touch is over, display informations, and check if it matches some # known gesture. g = simplegesture( '', list( zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))) # gestures to my_gestures.py print("gesture representation:", self.gdb.gesture_to_str(g)) # print match scores between all known gestures print("cross:", g.get_score(cross)) print("check:", g.get_score(check)) print("circle:", g.get_score(circle)) print("square:", g.get_score(square)) # use database to find the more alike gesture, if any g2 = self.gdb.find(g, minscore=0.70) print(g2) if g2: if g2[1] == circle: print("circle") if g2[1] == square: print("square") if g2[1] == check: print("check") if g2[1] == cross: print("cross") # erase the lines on the screen, this is a bit quick&dirty, since we # can have another touch event on the way... self.canvas.clear()
class GesturePad(Widget): minimum_x_distance = NumericProperty(0.0) minimum_y_distance = NumericProperty(0.0) def __init__(self, **kwargs): self.register_event_type('on_left') self.register_event_type('on_right') self.gdb = GestureDatabase() self.gdb.add_gesture(left) self.gdb.add_gesture(right) super().__init__(**kwargs) def simple_gesture(self, name, point_list): g = Gesture() g.add_stroke(point_list) g.normalize() g.name = name return g def on_touch_down(self, touch): touch.ud['start'] = (touch.x, touch.y) touch.ud['line'] = Line(points=(touch.x, touch.y)) return super().on_touch_down(touch) def on_touch_move(self, touch): try: touch.ud['line'].points += [touch.x, touch.y] except (KeyError) as e: pass return super().on_touch_move(touch) def on_touch_up(self, touch): if 'start' in touch.ud: if math.fabs(touch.x - touch.ud['start'][0]) <= self.minimum_x_distance: return super().on_touch_up(touch) if math.fabs(touch.y - touch.ud['start'][1]) <= self.minimum_y_distance: return super().on_touch_up(touch) else: return super().on_touch_up(touch) g = self.simple_gesture( '', list( zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))) # print("gesture representation:", self.gdb.gesture_to_str(g)) # print("left:", g.get_score(left)) # print("right:", g.get_score(right)) g2 = self.gdb.find(g, minscore=0.70) if g2: if g2[1] == left: self.dispatch('on_left') if g2[1] == right: self.dispatch('on_right') return super().on_touch_up(touch) def on_left(self, *args): pass def on_right(self, *args): pass
class DrawingCanvas(StencilView): def __init__(self, *args, **kwargs): super(DrawingCanvas, self).__init__() self.gdb = GestureDatabase() self.line45 = self.gdb.str_to_gesture(line45_str) self.circle = self.gdb.str_to_gesture(circle_str) self.cross = self.gdb.str_to_gesture(cross_str) self.line135 = self.line45.rotate(90) self.line225 = self.line45.rotate(180) self.line315 = self.line45.rotate(270) self.gdb.add_gesture(self.line45) self.gdb.add_gesture(self.line135) self.gdb.add_gesture(self.line225) self.gdb.add_gesture(self.line315) self.gdb.add_gesture(self.circle) self.gdb.add_gesture(self.cross) self.links = [] def addLink(self,link): self.links.append(link) def removeLink(self,link): self.remove_widget(link.widgetLink) self.links.remove(link) def getLink(self,element1, element2): for child in self.links: if ( child.element1 == element1 and child.element2 == element2 ) or ( child.element1 == element2 and child.element2 == element1 ): return child return None def getLinksForOneElement(self,element): tempLinks = [] for child in self.links: if ( child.element1 == element or child.element2 == element ): tempLinks.append(child) return tempLinks def activate(self): self.bind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def deactivate(self): self.unbind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def down(self, ds, touch): if self.collide_point(*touch.pos): self.points = [touch.pos] self.ix = self.fx = touch.x self.iy = self.fy = touch.y return True def move(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) return True def up(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) gesture = self.gesturize() recognized = self.gdb.find(gesture, minscore=0.50) if recognized: self.discriminate(recognized) return True def gesturize(self): gesture = Gesture() gesture.add_stroke(self.points) gesture.normalize() return gesture def min_and_max(self, x, y): self.ix = min(self.ix, x) self.iy = min(self.iy, y) self.fx = max(self.fx, x) self.fy = max(self.fy, y) def discriminate(self, recognized): if recognized[1] == self.cross: self.add_stickman() if recognized[1] == self.circle: self.add_circle() if recognized[1] == self.line45: self.add_line(self.ix,self.iy,self.fx,self.fy) if recognized[1] == self.line135: self.add_line(self.ix,self.fy,self.fx,self.iy) if recognized[1] == self.line225: self.add_line(self.fx,self.fy,self.ix,self.iy) if recognized[1] == self.line315: self.add_line(self.fx,self.iy,self.ix,self.fy) def add_circle(self): cx = (self.ix + self.fx)/2.0 cy = (self.iy + self.fy)/2.0 self.tool_box.tool_circle.widgetize(self, cx, cy, self.fx, self.fy) def add_line(self,ix,iy,fx,fy): self.tool_box.tool_line.widgetize(self,ix,iy,fx,fy) def add_stickman(self): cx = (self.ix + self.fx)/2.0 cy = (self.iy + self.fy)/2.0 self.tool_box.tool_stickman.draw(self,cx,cy) def on_children(self, instance, value): self.status_bar.counter = len(self.children) def repaintAllLinks(self,element1,povezaniElementi): for child in povezaniElementi: self.tool_box.tool_line.widgetizeLink(self,element1,child) def paint_links(self,element1,element2): self.tool_box.tool_line.widgetizeLink(self,element1,element2) element1.addLinkElement(element2) element2.addLinkElement(element1) def export_to_png(self, filename, *args): if self.parent is not None: canvas_parent_index = self.parent.canvas.indexof(self.canvas) self.parent.canvas.remove(self.canvas) fbo = Fbo(size=self.size, with_stencilbuffer=True) with fbo: ClearColor(0, 0, 0, 1) ClearBuffers() Scale(1, -1, 1) Translate(-self.x, -self.y - self.height, 0) fbo.add(self.canvas) fbo.draw() fbo.texture.save(filename, flipped=False) fbo.remove(self.canvas) if self.parent is not None: self.parent.canvas.insert(canvas_parent_index, self.canvas) return True
class DrawingSpace(StencilView): def __init__(self, *args, **kwargs): super().__init__() self.gdb = GestureDatabase() self.line45 = self.gdb.str_to_gesture(line45_str) self.cirlce = self.gdb.str_to_gesture(cirlce_str) self.cross = self.gdb.str_to_gesture(cross_str) self.line135 = self.line45.rotate(90) self.line225 = self.line45.rotate(180) self.line315 = self.line45.rotate(270) self.gdb.add_gesture(self.line45) self.gdb.add_gesture(self.line135) self.gdb.add_gesture(self.line225) self.gdb.add_gesture(self.line315) self.gdb.add_gesture(self.cross) self.gdb.add_gesture(self.cirlce) def activate(self): self.tool_box.disabled = True self.bind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def deactivate(self): self.unbind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) self.tool_box.disabled = False def down(self, ds, touch): if self.collide_point(*touch.pos): self.points = [touch.pos] self.ix = self.fx = touch.x self.iy = self.fy = touch.y return True def move(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) return True def up(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) gesture = self.gesturize() recognized = self.gdb.find(gesture, minscore=0.50) if recognized: self.discriminate(recognized) return True def gesturize(self): gesture = Gesture() gesture.add_stroke(self.points) gesture.normalize() return gesture def min_and_max(self, x, y): self.ix = min(self.ix, x) self.iy = min(self.iy, y) self.fx = max(self.fx, x) self.fy = max(self.fy, y) def discriminate(self, recognized): gest = recognized[1] if gest == self.cross: self.add_stickman() if gest == self.cirlce: self.add_circle() if gest == self.line45: self.add_line(self.ix, self.iy, self.fx, self.fy) if gest == self.line135: self.add_line(self.ix, self.fy, self.fx, self.iy) if gest == self.line225: self.add_line(self.fx, self.fy, self.ix, self.iy) if gest == self.line315: self.add_line(self.fx, self.iy, self.ix, self.fy) def add_circle(self): cx = (self.ix + self.fx) / 2.0 cy = (self.iy + self.fy) / 2.0 self.tool_box.tool_circle.widgetsize(self, cx, cy, self.ix, self.iy) def add_stickman(self): cx = (self.ix + self.fx) / 2.0 cy = (self.iy + self.fy) / 2.0 self.tool_box.tool_stickman.draw(self, cx, cy) def add_line(self, ix, iy, fx, fy): self.tool_box.tool_line.widgetsize(self, ix, iy, fx, fy) def on_children(self, instance, value): self.status_bar.counter = len(self.children)
class GestureBoard(FloatLayout): """ Our application main widget, derived from touchtracer example, use data constructed from touches to match symboles loaded from my_gestures. """ def __init__(self, *args, **kwargs): super(GestureBoard, self).__init__() self.gdb = GestureDatabase() # add pre-recorded gestures to database self.gdb.add_gesture(cross) self.gdb.add_gesture(check) self.gdb.add_gesture(circle) self.gdb.add_gesture(square) def on_touch_down(self, touch): # start collecting points in touch.ud # create a line to display the points userdata = touch.ud with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d)) userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): # store points of the touch movement try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError) as e: pass def on_touch_up(self, touch): # touch is over, display informations, and check if it matches some # known gesture. g = simplegesture('', list(zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))) # gestures to my_gestures.py print("gesture representation:", self.gdb.gesture_to_str(g)) # print match scores between all known gestures print("cross:", g.get_score(cross)) print("check:", g.get_score(check)) print("circle:", g.get_score(circle)) print("square:", g.get_score(square)) # use database to find the more alike gesture, if any g2 = self.gdb.find(g, minscore=0.70) print(g2) if g2: if g2[1] == circle: print("circle") if g2[1] == square: print("square") if g2[1] == check: print("check") if g2[1] == cross: print("cross") # erase the lines on the screen, this is a bit quick&dirty, since we # can have another touch event on the way... self.canvas.clear()
def getCurrentCommands(): commands = db.query("SELECT commands.name,commands.description,commands.script\ FROM commands,profiles,activeprofile WHERE profiles.name =\ activeprofile.name AND commands.name = commandname ORDER BY LOWER(commandname)") return commands gdb = GestureDatabase() kivygestures = dict() for [name,description,representation] in getCurrentGestures(): if len(representation) < 20: # Fulhack för att känna igen multitouch. continue kivygestures.update({representation:name}) gest = gdb.str_to_gesture(representation.encode("ascii")) gdb.add_gesture(gest) def getCommand(gesture): if gesture.multitouch: return getMultitouchedCommand(gesture) g = gdb.str_to_gesture(gesture.toString()) identifiedGesture = None current_max = 0.7 # Minimum score for gi in [gdb.str_to_gesture(st) for st in kivygestures.keys()]: if(g.get_score(gi) > current_max): current_max = g.get_score(gi) identifiedGesture = gi nop = Command.Command("No operation","Does nothing","nop") if identifiedGesture != None: strang = gdb.gesture_to_str(identifiedGesture)
class GestureBoard(FloatLayout): ponts = 0 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() def sort_letter(self): self.letter = random.choice(gestures.keys()) letter_button = Button( text=self.letter, size_hint=(.1, .1), pos_hint={'x':0, 'y':.9}, font_size=38, line_height=1 ) self.add_widget(letter_button) ponts_button = Button( text=u"Pontos: %s" % self.ponts, size_hint=(.3, .1), pos_hint={'x':.7, 'y':.9} ) self.add_widget(ponts_button) def on_touch_down(self, touch): # start collecting points in touch.ud # create a line to display the points userdata = touch.ud with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d/2, touch.y - d/2), size=(d, d)) userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): # store points of the touch movement try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError) as e: pass def on_touch_up(self, touch): # touch is over, display informations, and check if it matches some # known gesture. g = self.simplegesture( '', list(zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])) ) print("gesture representation:", self.gdb.gesture_to_str(g)) # use database to find the more alike gesture, if any g2 = self.gdb.find(g, minscore=0.70) if g2: if self._get_key_by_gesture(g2[1]) == self.letter: self.ponts += 10 if self.success_sound.status != 'stop': self.success_sound.stop() self.success_sound.play() else: if self.error_sound.status != 'stop': self.error_sound.stop() self.error_sound.play() # erase the lines on the screen, this is a bit quick&dirty, since we # can have another touch event on the way... self.canvas.clear() self.sort_letter() def _get_key_by_gesture(self, g): for key, ges in gestures.items(): if g == ges: return key def simplegesture(self, name, point_list): """ A simple helper function """ g = Gesture() g.add_stroke(point_list) g.normalize() g.name = name return g
class GameMatrix(GridLayout): def __init__(self, app, **kwargs): # inicializace pole self.app = app super(GameMatrix, self).__init__(**kwargs) self.coords = [] self.dpos = (0,0) self.colors = [] self.shape = None self.active_color = [.1372,.1372,.1372,1] self.inactive_color = [.1372,.1372,.1372,1] self.fUpdate = 12*22*"0" self.tnetCoords2 = [] for y in range(51,73): for x in range(51,63): self.tnetCoords2.append(chr(x)+chr(y)) self.tnetCoords = [] for x in range(51,63): col = [] for y in range(51,73): col.append((chr(x), chr(y))) self.tnetCoords.append(col) self.tnetColors = [] for c in range(33, 48): self.tnetColors.append(chr(c)) self.move = False self.orientation = 0 self.colored = set() self.colors = [deepcopy(self.inactive_color), [0,.6,.8,1], [1,.7333333,.2,1], [.6,.8,0,1], [.666666667,.4,.8,1], [1,.266666667,.266666667,1]] self.COORDS_SET = set() for y in range(int(self.rows)): line = [] for x in range(int(self.cols)): box = Box() box.coords = (x, y) box.colored = deepcopy(self.inactive_color) self.add_widget(box) line.append(box) self.COORDS_SET.add((x, y)) self.coords.append(line) self.b = 0 self.startgame = False self.seed = randint(0,0xFFFFFF) self.specials = set() self.buildNext = False self.mLR = False self.gdb = GestureDatabase() self.GSTR_DROP = \ self.gdb.str_to_gesture('eNq1l82O2jAQgO9+Ebg08ng8M/YL0GslHqBKIQK0W4iSbHf37WtPIjZS/6Si4WIYez4P+Yyxt5eny4/35tSN08vQuc9L23u3Pfbg9ptr+73buD6Ut6VBN+434zTcnrqxfIxu+9yT2/4WstdhrueKkpLf3y7Xqaalmpb/kPaljnI9zBXUEt5LCgS3803EKCmwT5yJCXKt5q32Yu31HsETZe85AIAQsBu/tX+fJuo05E7zDEEEBDOg17k8ufH0AF2/O4gRPSk929CDCghgRA9KRyO6Wg13qx7viyaUaRLyY3jVGsQKr15DNsKjikWwwqtZRCu8qkUrtahq0Uotqlpc1H7yDaT1jhbKY3sEH1VtBCu8qo1ohVe1kazwqjaKFV7VRiu1pGrJSi2pWvpQG0Ne/9k+SFezREZ0FUtiRFevlG3orFoZjOhqlY2sslplI6usVtnIKqtV/rC6bPDLCSTBQi89HhIjUvQogcWXn+C/4KJSBWzg6lTQBq5Khf4XXm8Hh6HrrvezvnA97Iu47Q4FG+92UUJppl6Sa38N5nUwogaTXwUxpzkI6yAtwbAOQmnWL64jUEdwriNCWtKia+fqz93ldJ7qHYXcrmyxpbtEXy/H6VyDXIqaQ9PtuRva66FejpLUZQg1vDzWr/1wO74cFJRKJQ2Vs4OUK0sMwEF0gTY/AXq8jUg=') self.gdb.add_gesture(self.GSTR_DROP) self.dropAnimation2 = Animation(colored=self.inactive_color, d=.03) self.dropAnimation = Animation(colored=self.inactive_color, d=.1) self.spectate = False def simplegesture(self, name, point_list): # Pomocná funkce pro rozpoznávání gest g = Gesture() g.add_stroke(point_list) g.normalize() g.name = name return g def generate(self): # Algoritmus pseudonáhodného generování herních bloků a = 0x08088405 c = 1 M = 2**32 self.seed = (a*self.seed + c) % M block = int(self.seed*100./M) self.seed = (a*self.seed + c) % M orientation = int(self.seed*4./M) return (block,orientation) def build(self, dt): # Pomocná funkce pro automatické volání self._build() def _build(self): # Přidá do pole nový herní blok if self.startgame == False: self.stack = [self.generate() for y in range(5)] st = self.stack.pop(0) piece = int(self.app.serverConf.blockFreq[st[0]]) nextPC = int(self.app.serverConf.blockFreq[self.stack[0][0]]) self.app.nextPiece.showNext(nextPC) orientation = st[1] if piece in (1,5,6): if orientation % 2 == 0: self.orientation = 0 else: self.orientation = 1 elif piece == 2: self.orientation = 0 self.shape = deepcopy(PIECES[piece]) self.active_color = deepcopy(COLORS[piece]) self.stack.append(self.generate()) full = False for box in self.shape[self.orientation]: if tuple(box) in self.colored: full = True break if full == False: for box in self.shape[self.orientation]: self.drop(box) for box in self.shape[self.orientation]: self.mark(box) if self.app.tetrifast: self._fall() Clock.schedule_interval(self.fall, (1005 - (self.app.lvl * 10))/1000.) self.app.send_message("f "+str(self.app.id)+" "+self.fUpdate) self.startgame = True else: self.startgame = False self.spectate = True self.app.send_message("playerlost {0}".format(self.app.id)) for i in range(22): self.addLine() self.buildNext = False self.blockRotation = False def get(self, x, y): # Vrátí objekt Box - 1 kostku z pole return self.coords[y][x] def getMinMax(self, shape): # Vrací minimální a maximální souřadnice bloku x = [] y = [] for box in shape: x.append(box[0]) y.append(box[1]) return {'x':(min(x), max(x)), 'y':(min(y), max(y))} def drop(self, coords, anim=0): # Přebarví kostku na šedou (barva pole) box = self.get(coords[0], coords[1]) box.colored = deepcopy(self.inactive_color) box.active = False box.texture = False box.sb = False def mark(self, coords, random=False, anim=0): # Přebarví kostku na barevnou box = self.get(coords[0], coords[1]) box.colored = self.active_color if random == False else choice(deepcopy(COLORS)) box.active = True def fall(self, dt): # Pomocná funkce pro automatické volání print self.colored self._fall() def _fall(self, animate=1): # Slouží ke spadení bloku o jedno dolů (každou cca 1 s) if (self.buildNext == False) and self.startgame and (self.app.paused == False): anim = [] unschedule = False next_pos = deepcopy(self.shape[self.orientation]) for box in next_pos: box[1] += 1 if self.shape[self.orientation][-1][1] >= 21: unschedule = True print "< fall unschedule >" elif len(self.colored.intersection(set(tuple(y) for y in next_pos))) != 0: unschedule = True else: for box in self.shape[self.orientation]: self.drop(box, anim=animate) for i in self.shape: for box in i: box[1] += 1 for box in self.shape[self.orientation]: self.mark(box, anim=animate) unschedule = False if unschedule == True: self.blockRotation = True print "Current: "+str(self.shape[self.orientation]) print "Next: "+str(next_pos) Clock.unschedule(self.fall) for i in self.shape[self.orientation]: try: g = self.get(i[0], i[1]) if g.colored != [.1372,.1372,.1372,1]: anim.append(g) self.colored.add(tuple(i)) except: pass self.orientation = 0 self.tetris(anim) del(anim) self.buildNext = True if self.app.tetrifast == False: Clock.schedule_once(self.build, 1) else: self._build() unschedule = False def on_touch_down(self, touch): # Uživatel se dotkl pole if self.collide_point(touch.x, touch.y) and self.startgame and (self.app.paused == False): touch.grab(self) touch.ud["line"] = Line(points=(touch.x, touch.y)) def on_touch_move(self, touch): # Uživatel pohybuje s prstem po poli if (touch.grab_current is self) and self.startgame and (self.app.paused == False) and (self.blockRotation == False): touch.ud["line"].points += [touch.x, touch.y] self.box_size = self.get(0,0).size[0] self.dpos = (touch.dpos[0]+self.dpos[0], touch.dpos[1]+self.dpos[1]) if abs(self.dpos[0]) >= self.box_size: next_pos = deepcopy(self.shape[self.orientation]) for box in next_pos: box[0] += int(round((0.5*self.dpos[0])/self.box_size,0)) minmax = self.getMinMax(next_pos) if minmax['x'][0] < 0 or minmax['x'][1] > 11: pass elif len(self.colored.intersection(set(tuple(y) for y in next_pos))) != 0: pass else: for box in self.shape[self.orientation]: self.drop(box, anim=1) for i in self.shape: for box in i: box[0] += int(round((0.5*self.dpos[0])/self.box_size,0)) for box in self.shape[self.orientation]: self.mark(box, anim=1) self.move = True self.mLR = True self.dpos = (0, self.dpos[1]) if -1*(self.dpos[1]) >= 1.05*self.box_size: for i in range(abs(int(round(self.dpos[1]/self.box_size,0)*1))): self._fall() self.move = True self.dpos = (self.dpos[0], 0) def on_touch_up(self, touch): # Uživatel zvedl prst z obrazovky if touch.grab_current is self: g = self.simplegesture('', zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])) g2 = self.gdb.find(g, minscore=0.80) if g2 and (self.mLR == False) and (self.blockRotation == False): if g2[1] == self.GSTR_DROP: print "< GESTURE: Drop >" for i in range(21-self.shape[self.orientation][-1][1]): self._fall(animate=2) self.mLR = False else: if (self.mLR == False) and (self.move == False) and (self.blockRotation == False): if touch.x <= self.parent.size[0]/2.: self.rotate(False) #left else: self.rotate(True) #right self.mLR = False if self.move == True: self.move = False touch.ungrab(self) def dropAnim(self, fall): # Animace padání bloku if fall: d = .1 else: d= .2 boxes = [] for box in self.shape[self.orientation]: if ((box[0] >= 0) and (box[0] <= 11)) and ((box[1] >= 0) and (box[1] <= 21)): cur = self.get(box[0], box[1]) a = Box() a.size = cur.size a.pos = cur.pos a.colored = cur.colored a.size_hint = (None, None) boxes.append(a) self.app.sOverlay.add_widget(a) if len(boxes) != 0: anims = [Animation(y=p.y-p.size[1], opacity=0., t='linear', d=d) for p in boxes] for i in range(len(boxes)): anims[i].start(boxes[i]) Clock.schedule_once(self.clearAnimation, d) def fellAnim(self, widgets): # Animace po spadení bloku (změna barvy) color1 = widgets[0].colored color2 = [y+.3 for i, y in enumerate(color1) if i < 3] + [color1[-1],] anim = Animation(colored=color2, duration=.2) + Animation(colored=color1, duration=.2) for i in widgets: anim.start(i) def clearAnimation(self, dt): # Odstraní widgety vytvořené animací self.app.sOverlay.clear_widgets() print "< widgets cleared >" def rotate(self, direction): # Otáčení s blokem maximum = len(self.shape) now = deepcopy(self.orientation) if direction: #left self.orientation -= 1 if self.orientation < 0: self.orientation = maximum-1 else: #right self.orientation += 1 if self.orientation > maximum-1: self.orientation = 0 if now != self.orientation: for box in self.shape[now]: self.drop(box) coords = self.getMinMax(self.shape[self.orientation]) if coords['y'][1] > 21: print "posunout nahoru o {0}".format(coords['y'][1] - 21) if coords['x'][0] < 0: print "posunout doprava o {0}".format(abs(coords['x'][0])) for s in self.shape: for box in s: box[0] += abs(coords['x'][0]) if coords['x'][1] > 11: print "posunout doleva o {0}".format(coords['x'][1] - 11) for s in self.shape: for box in s: box[0] -= coords['x'][1] - 11 if len(self.colored.intersection(set(tuple(y) for y in self.shape[self.orientation]))) != 0: self.orientation = now for box in self.shape[self.orientation]: self.mark(box) print self.orientation def tetris(self, anim): # Rozhoduje o tom, zda byl vyplněn řádek (voláno po spadení bloku) full = [] for i in self.colored: full.append(i[1]) lines = [] for i in range(22): if full.count(i) == 12: lines.append(i) if len(lines) != 0: if self.app.onAndroid(): self.app.vibrate(0.05) self.app.linesCleared += len(lines) if self.app.linesCleared % int(self.app.serverConf.linesLvl) == 0: self.app.lvl += int(self.app.serverConf.lvlInc) print "Lines cleared: "+str(self.app.linesCleared) print "Level: "+str(self.app.lvl) for i in range(len(lines)): for j in range(12): self.colored.remove((j, lines[i])) self.specials.discard((j, lines[i])) box = self.get(j, lines[i]).sb if box != False: self.app.dock.addSpecial(box) self.drop((j, lines[i])) lns = deepcopy(lines) lns.sort() print lns for num, ln in enumerate(lns): colored = list(self.colored) colored.sort(cmp=lambda x,y: cmp(x[1],y[1])) colored.reverse() for coord in colored: if coord[1] < ln: new = (coord[0], coord[1]+1) box = self.get(coord[0], coord[1]) newColor = box.colored sType = box.sb self.drop(coord) self.colored.discard(coord) if sType != False: self.specials.discard(coord) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) if self.app.serverConf[-2] == '1': if len(lines) >= 2 and len(lines) <= 3: self.app.send_message("sb 0 cs{0} {1}".format(len(lines)-1, self.app.id)) print "add id:"+str(self.app.id) elif len(lines) == 4: print "Tetris!" if self.app.serverConf[-2] == '1': self.app.send_message("sb 0 cs{0} {1}".format(4, self.app.id)) print "add id:"+str(self.app.id) else: print "< tetris() >" if self.app.linesCleared % int(self.app.serverConf.linesSpecial) == 0: self.addSpecial() else: self.fellAnim(anim) self.fieldUpdate() def addSpecial(self): # Přidá novou speciální kostku do pole if len(self.colored) - len(self.specials) > 0: special = choice(list(self.colored.difference(self.specials))) self.specials.add(special) self.drop(special) box = self.get(special[0], special[1]) sType = SPECIALS[int(self.app.serverConf.specialFreq[randint(0,99)])-1] box.special(sType) print sType print special else: for i in range(20): col = randint(0,11) empty = True for c in self.colored: if c[0] == col: empty = False break if empty == True: self.colored.add((col, 21)) self.specials.add((col, 21)) self.drop((col, 21)) box = self.get(col, 21) sType = SPECIALS[int(self.app.serverConf.specialFreq[randint(0,99)])-1] box.special(sType) print sType print (col, 21) print "< Add special >" break def addLine(self, update=True): # Přidání náhodného řádku do pole (speciální kostkou) garbage = [randint(0,7) for i in range(12)] garbage[randint(0,11)] = 0 move = list(self.colored) move.sort(cmp=lambda x,y: cmp(x[1],y[1])) for coord in move: if coord[1] <= 21 and coord[1] >=1: new = (coord[0], coord[1]-1) box = self.get(coord[0], coord[1]) newColor = box.colored sType = box.sb self.drop(coord) self.colored.remove(coord) if sType != False: self.specials.discard(coord) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) for i, cell in enumerate(garbage): box = self.get(i, 21) box.texture = False if cell > 0: box.colored = COLORS[cell] self.colored.add((i, 21)) else: box.colored = self.inactive_color self.colored.discard((i, 21)) if update: self.fieldUpdate() for i, b in enumerate(self.shape): drop = False if i == self.orientation: drop = True for box in self.shape[i]: box = [box[0], box[1]+1] if drop: for box in self.shape[i]: self.drop(box) for box in self.shape[i]: self.mark(box) def fieldUpdate(self, *args): # Vytvoření řetězce pro aktualizaci pole a odeslání aktualizace fupdate = "" for y in range(22): for x in range(12): s = set() s.add((x,y)) if self.colored.issuperset(s): box = self.get(x, y) if box.sb == False: fupdate += str(self.colors.index(box.colored)) else: fupdate += box.sb else: fupdate += '0' print fupdate d = [] prev = False for i in range(len(self.fUpdate)): if self.fUpdate[i] != fupdate[i]: try: color = int(fupdate[i]) except: color = self.tnetColors.index(chr(39)) + SPECIALS.index(fupdate[i]) if prev == False: d.append(self.tnetColors[color]) prev = fupdate[i] else: if prev != fupdate[i]: d.append(self.tnetColors[color]) prev = fupdate[i] d.append(self.tnetCoords2[i]) self.fUpdate = fupdate dstr = "f "+str(self.app.id)+" " for i in d: dstr+=i self.app.send_message(dstr) self.app.print_message(dstr+"\xff") def clearLine(self): # Odstraní řádek od konce (speciální kostkou) for j in range(12): self.colored.discard((j, 21)) self.specials.discard((j, 21)) self.drop((j, 21)) colored = list(self.colored) colored.sort(cmp=lambda x,y: cmp(x[1],y[1])) colored.reverse() print colored for coord in colored: if coord[1] < 21: new = (coord[0], coord[1]+1) box = self.get(coord[0], coord[1]) newColor = box.colored sType = box.sb self.drop(coord) self.colored.remove(coord) if sType != False: self.specials.discard(coord) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) self.fieldUpdate() def nuke(self): # Vyprázdnění pole (speciální kostkou) for box in self.colored: self.drop(box) self.colored = set() self.specials = set() self.fieldUpdate() def randomClear(self): # Náhodné odstranění několika kostek (speciální kostkou) cells = [] for i in range(10): cells.append((randint(0,11), randint(0,21))) for coord in cells: self.colored.discard(coord) self.specials.discard(coord) self.drop(coord) self.fieldUpdate() def clearSpecials(self): # Odstraní všechny speciální kostky (speciální kostkou) coords = list(self.specials) for coord in coords: self.specials.discard(coord) self.drop(coord) self.mark(coord, True) self.fieldUpdate() def quake(self): # Náhodně posune řádky o 3 doleva/doprava (speciální kostkou) colored = list(self.colored) colored.sort(cmp=lambda x,y: cmp(x[1],y[1])) cells = [[y[0], y[1]] for y in colored] prev = None rnd = 0 for cell in cells: if prev != cell[1]: prev = cell[1] rnd = choice(range(-3,4)) cell[0] += rnd if cell[0] > 11: cell[0] -= 11 elif cell[0] < 0: cell[0] = 12+cell[0] print cells for i in range(len(colored)): new = (cells[i][0], cells[i][1]) box = self.get(colored[i][0], colored[i][1]) newColor = box.colored sType = box.sb self.drop(colored[i]) self.colored.discard(colored[i]) if sType != False: self.specials.discard(colored[i]) box = self.get(new[0], new[1]) box.colored = newColor self.colored.add(new) if sType != False: box.special(sType) self.specials.add(new) self.fieldUpdate() def switchField(self, pid): # Vymění si pole s protivníkem (speciální kostkou) for y in range(22): for x in range(12): sender = self.app.overlay.children[0].children[pid].matrix.coords[y][x] if type(sender) == type(None): self.drop((x, y)) self.colored.discard((x, y)) self.specials.discard((x, y)) else: newColor = sender.colored newStype = sender.sb box = self.get(x, y) box.colored = newColor self.colored.add((x, y)) if sender.sb != False: box.special(newStype) self.specials.add((x, y)) self.fieldUpdate() def gravity(self): # Spadení kostek, vyplnění mezer (speciální kostkou) colored = list(self.colored) colored.sort(cmp=lambda x,y: cmp(x[1],y[1])) colored.reverse() color = [colored, ] i = 0 while True: color.append([]) for b in color[i]: if b[1] < 21: if (b[0], b[1]+1) not in color[i]: color[i+1].append((b[0], b[1]+1)) else: color[i+1].append(b) else: color[i+1].append(b) if color[i] == color[i-1]: break i += 1 color = color[-1] for j, b in enumerate(colored): if b != color[j]: old = self.get(b[0], b[1]) new = self.get(color[j][0], color[j][1]) new.colored = old.colored new.sb = old.sb new.texture = old.texture self.drop(b) self.colored.remove(b) self.colored.add(color[j]) if new.sb != False: self.specials.remove(b) self.specials.add(color[j]) self.fieldUpdate() def blockBomb(self): # Odstranění kostek blockbomb a vystřelení okolních do pole # (speciální kostkou) bombs = [] colored_remove = [] s = range(-1,2) s.reverse() for bomb in self.specials: box = self.get(bomb[0], bomb[1]) if box.sb == 'o': bombs.append(bomb) for bomb in bombs: self.specials.remove(bomb) for i in range(-1,2): for j in s: b = (bomb[0]+i, bomb[1]+j) if b in self.colored: colored_remove.append(b) new = choice(list(self.COORDS_SET.difference(self.colored.union(set([tuple(a) for a in self.shape[self.orientation]]))))) self.colored.add(new) new = self.get(new[0], new[1]) old = self.get(b[0], b[1]) new.colored = old.colored for bomb in bombs+colored_remove: self.colored.discard(bomb) self.drop(bomb) self.fieldUpdate()
from kivy.gesture import Gesture, GestureDatabase # Create a gesture g = Gesture() g.add_stroke(point_list=[(1, 1), (3, 4), (2, 1)]) g.normalize() g.name = "triangle" # Add it to database gdb = GestureDatabase() gdb.add_gesture(g) # And for the next gesture, try to find a match! g2 = Gesture() g2.add_stroke(point_list=[(1, 1), (3, 4), (2, 1)]) g2.normalize() print gdb.find(g2).name # will print "triangle"
class AppView(Scatter): app = ObjectProperty(None) texture_sidebar = ObjectProperty(None) texture = ObjectProperty(None) bar_width = NumericProperty(135) bar_translation_min_distance = NumericProperty(250) content = ObjectProperty(None) def __init__(self, **kwargs): super(AppView, self).__init__(**kwargs) #internal variables self.touches2 = {} self.last_touch_id = -1 #self.translation_allowed = False self.gesture_found = False self.position_left = True self.anim = False #currently animated self.set_texture('style/bar/slider-fond.png') #add gestures self.gdb = GestureDatabase() self.create_gesture( [(0,0),(10,0)] ) self.create_gesture( [(0,0),(-10,0)] ) ''' def add_widget(self, child): if self.content: print child return self.content.add_widget(child) return super(AppView, self).add_widget(child) ''' def set_texture(self,path): #from kivy.core.image import Image tex = Image(path).texture tex.wrap = 'repeat' self.texture_sidebar = tex #tex = Image('style/1.png').texture if tex is not None: tex.wrap = 'repeat' self.texture = tex def create_gesture(self,point_list): # Create a gesture g = Gesture() g.add_stroke(point_list) g.normalize() # Add it to database self.gdb.add_gesture(g) def on_touch_down(self,touch): id = touch.id if touch.x < self.x + self.bar_width : self.touches2[id] = touch.pos self.last_touch_id = id #if len(self._touches) <= 1 : # return True l = len(self.touches2) if l > 1 : #if several touches on the bar self.set_texture('style/bar/slider-fond.png') return super(AppView, self).on_touch_down(touch) def on_touch_up(self,touch): id = touch.id if id in self.touches2.keys() and len(self.touches2) == 2: #still one more touch on bar #does the user want to translate the bar to the right or the left ? origin = self.touches2[id]#.pos current = touch.pos dist = Vector(origin).distance( Vector(current) ) #print len(self.touches2), self.touches2[id], touch.pos, dist #if touch.id in self.touches2.keys() : if dist >= self.bar_translation_min_distance : # try to find a gesture g = Gesture() g.add_stroke(point_list=[origin,current]) g.normalize() gest = self.gdb.find(g) try : if gest[0] > 0.95 : #gesture found if len(self.touches2) == 2: #no touch left on bar d = current[0] - origin[0] if d > 0: self.move_bar_to_right() else : self.move_bar_to_left() except : self.move_back() else : self.move_back() if id in self.touches2.keys(): del self.touches2[id] if len(self.touches2) <= 0 : self.set_texture('style/bar/slider-fond.png') return super(AppView, self).on_touch_up(touch) def on_touch_move(self,touch): #move only if several touches if len(self.touches2) <= 1 : return True super(AppView, self).on_touch_move(touch) def transform_with_touch(self, touch): # PB : By default the kivy scatter does not translate if several touches are down # TRICK : So we have to set do_rotation to True and avoid rotation to occur ... # just do a simple one finger drag DOES NOT OCCUR HERE #only the last touch moves it if not self.last_touch_id == touch.id : return # _last_touch_pos has last pos in correct parent space, # just like incoming touch dx = (touch.x - self._last_touch_pos[touch][0]) \ * self.do_translation_x dy = (touch.y - self._last_touch_pos[touch][1]) \ * self.do_translation_y if dx > 50 : return self.apply_transform(Matrix().translate(dx, dy, 0)) return def move_bar_to_right(self): if self.position_left : #print 'bar : r' a = Animation(x = self.width - 1*self.bar_width, duration = 1.5) a.bind(on_complete=self.animation_is_over) a.start(self) self.position_left = False self.anim = True self.app.bar.unopacify() def move_bar_to_left(self): if self.position_left == False: #print 'bar : l' a = Animation(x = 0 , duration = 1.5) a.bind(on_complete=self.animation_is_over) a.start(self) self.position_left = True self.anim = True self.app.bar.opacify() def animation_is_over(self,a,b): self.anim = False if self.position_left == False : self.app.bar.show_leave_app_button() def move_back(self): if self.anim : return #print 'bar : b' if self.position_left : x = 0 else : x = self.width - 1.0*self.bar_width a = Animation(x = x, t='out_circ') a.start(self) def launch_app(self,id, title): print 'launch app ' + title if self.position_left : self.move_bar_to_right() def leave_current_app(self,a): print 'leave app' if not self.position_left : self.move_bar_to_left()
gesture_strings = { 'left_to_right_line': 'eNq1WMtSI0cQvM+PwMVE17vrB9irI/gABwYFELsGBWht79+7p0qPHoE044NExAhyslPVmdU9La5fvr/8/evmafWx+fm+Gr5t39dluH5cw3B39Xr/1+pqWGP7tb3R8HF39bF5f/u++mh/8nD9Yy3D9Zcid0Eb1jpKWRu/fnt53YzD6jjMTwz7fWQNa8gKxhJ+tSGAw+1v5aZocUexWtkNodpYz7/jfYr7Sk6ExZWNXajd/vP+/MdwfIwMT6c/4WknXqComhcSlMILxGPqYEvERUphpdpQR3KeF68h7ovEkYUUrEIxLVpnxTHcR1gizrXuqm7ew7w2hjYdtEWqF6FaiMgFVDpxNHHjgnnVeV8wEkW5lHxkil2mUnauWLNWKx/kqf7PdsQIFbtQuUhlBsmrQidOlQC07q7ztVOkSnAh9ciVulxJuCIZm9ZSvQnv1bEaOmAtwJWR5puGIlWSy4hHptRlimjdj7h26lgPK2nBUqKIlPwi4hyJcpcooLQpOxRnhdbUnTio9dvjEvmIlOlS8hEqd6EWYwSQglbRqXCXKiDkKkqDfD5Wjli5i7VwtTYFz+ukaYqJiEpVtNL6B+b7nSNY9gvJS0Qr22hHdcn9yzQyEO/U0Q+PjsZa4L1EtEJ7+X3dcbVugy+lybaP39aPbeueVY9kRQ7q4yLdb8JsuJUfa4eudHCXefUIVmyvjkX50DtOclBnZyYGii3Bqs6LR6ziB/FDv6u2ZckH8XpwpVT1+f1dI1SFBeIAtXt0KMybrhGp0hJxnmzvNu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b5EWBWQjhIcFbCMEhoXhKDhGcleqDIrKQccpmtudiBUuYlh1zmq+4ySOYr7TZI5qsbQ7o4X90YKJjVbX3sefPy9Lzv/5HQ98J8SUlBDv/z8rh/rqPct5ITlxGll+zfvm3e718fNlUmde/tx4ee+8f2/e3x+0NDaz76K8++nbOA5w4RUU+0q/8AAJ5q8g==' } from kivy.uix.boxlayout import BoxLayout # BEGIN GESTURE_DB from kivy.gesture import GestureDatabase gestures = GestureDatabase() for name, gesture_string in gesture_strings.items(): gesture = gestures.str_to_gesture(gesture_string) gesture.name = name gestures.add_gesture(gesture) # END GESTURE_DB # BEGIN GESTUREBOX class GestureBox(BoxLayout): def on_touch_down(self, touch): touch.ud['gesture_path'] = [(touch.x, touch.y)] super(GestureBox, self).on_touch_down(touch) def on_touch_move(self, touch): touch.ud['gesture_path'].append((touch.x, touch.y)) super(GestureBox, self).on_touch_move(touch) def on_touch_up(self, touch): print(touch.ud['gesture_path']) super(GestureBox, self).on_touch_up(touch)
import math from kivy.uix.behaviors import ButtonBehavior #------------------------------------- hsff = HighScore gdb = GestureDatabase() swipe_up = gdb.str_to_gesture(up_swipe) swipe_up.name = "swipe_up" swipe_down = gdb.str_to_gesture(down_swipe) swipe_down.name = "swipe_down" swipe_left = gdb.str_to_gesture(left_swipe) swipe_left.name = "swipe_left" swipe_right = gdb.str_to_gesture(right_swipe) swipe_right.name = "swipe_right" gdb.add_gesture(swipe_up) gdb.add_gesture(swipe_down) gdb.add_gesture(swipe_down) gdb.add_gesture(swipe_left) gdb.add_gesture(swipe_right) #-------------------------------------------- class Root(ScreenManager): game_screen = ObjectProperty() hs = ObjectProperty() class Cbutton(ButtonBehavior,Widget):#Menu Button src = StringProperty()
class GestureBoard(FloatLayout): """ Our application main widget, derived from touchtracer example, use data constructed from touches to match symboles loaded from my_gestures. """ edge_size = NumericProperty(0) exists=BooleanProperty(False) def __init__(self, *args, **kwargs): super(GestureBoard, self).__init__() self.gdb = GestureDatabase() # add pre-recorded gestures to database for square in squares: self.gdb.add_gesture(square) def on_touch_down(self, touch): super(GestureBoard,self).on_touch_down(touch) if self.collide_point(*touch.pos): if App.get_running_app().config.getboolean('museotouch','validation') == True: # start collecting points in touch.ud # create a line to display the points userdata = touch.ud userdata['line'] = Line(points=(touch.x, touch.y)) return True def on_touch_move(self, touch): if self.collide_point(*touch.pos): super(GestureBoard,self).on_touch_move(touch) # store points of the touch movement try: touch.ud['line'].points += [touch.x, touch.y] return True except (KeyError) as e: pass def on_touch_up(self, touch): super(GestureBoard,self).on_touch_up(touch) # touch is over, display informations, and check if it matches some # known gesture. try : g = simplegesture( '', list(zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])) ) self.edge_size = (self.stroke_length(list(zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2]))))/4 if self.edge_size < 150: self.edge_size=150 # gestures to my_gestures.py except : return # use database to find the more alike gesture, if any g2 = self.gdb.find(g, minscore=0.9) if g2: for index,square in enumerate(squares) : if (g2[1] == square): if index in [0,1]: square_pos=[touch.x,touch.y-self.edge_size] elif index in [2,3]: square_pos=[touch.x-self.edge_size,touch.y-self.edge_size] elif index in [4,5]: square_pos=[touch.x-self.edge_size,touch.y] elif index in [6,7]: square_pos=[touch.x,touch.y] valid = Valid(pos=(0,0),size=[self.edge_size,self.edge_size],rotation=180,scale_min=0.5) self.add_widget(valid) Animation(pos=square_pos,d=.3,rotation=0,transition='out_sine').start(valid) self.exists=True break def stroke_length(self,l): distance = 0 for index, point in enumerate(l) : if index < len(l)-1: distance += Vector(point).distance(l[index+1]) return distance
class DrawingCanvas(StencilView): def __init__(self, *args, **kwargs): super(DrawingCanvas, self).__init__() self.gdb = GestureDatabase() self.line45 = self.gdb.str_to_gesture(line45_str) self.circle = self.gdb.str_to_gesture(circle_str) self.cross = self.gdb.str_to_gesture(cross_str) self.line135 = self.line45.rotate(90) self.line225 = self.line45.rotate(180) self.line315 = self.line45.rotate(270) self.gdb.add_gesture(self.line45) self.gdb.add_gesture(self.line135) self.gdb.add_gesture(self.line225) self.gdb.add_gesture(self.line315) self.gdb.add_gesture(self.circle) self.gdb.add_gesture(self.cross) self.links = [] def addLink(self, link): self.links.append(link) def removeLink(self, link): self.remove_widget(link.widgetLink) self.links.remove(link) def getLink(self, element1, element2): for child in self.links: if (child.element1 == element1 and child.element2 == element2) or ( child.element1 == element2 and child.element2 == element1): return child return None def getLinksForOneElement(self, element): tempLinks = [] for child in self.links: if (child.element1 == element or child.element2 == element): tempLinks.append(child) return tempLinks def activate(self): self.bind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def deactivate(self): self.unbind(on_touch_down=self.down, on_touch_move=self.move, on_touch_up=self.up) def down(self, ds, touch): if self.collide_point(*touch.pos): self.points = [touch.pos] self.ix = self.fx = touch.x self.iy = self.fy = touch.y return True def move(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) return True def up(self, ds, touch): if self.collide_point(*touch.pos): self.points += [touch.pos] self.min_and_max(touch.x, touch.y) gesture = self.gesturize() recognized = self.gdb.find(gesture, minscore=0.50) if recognized: self.discriminate(recognized) return True def gesturize(self): gesture = Gesture() gesture.add_stroke(self.points) gesture.normalize() return gesture def min_and_max(self, x, y): self.ix = min(self.ix, x) self.iy = min(self.iy, y) self.fx = max(self.fx, x) self.fy = max(self.fy, y) def discriminate(self, recognized): if recognized[1] == self.cross: self.add_stickman() if recognized[1] == self.circle: self.add_circle() if recognized[1] == self.line45: self.add_line(self.ix, self.iy, self.fx, self.fy) if recognized[1] == self.line135: self.add_line(self.ix, self.fy, self.fx, self.iy) if recognized[1] == self.line225: self.add_line(self.fx, self.fy, self.ix, self.iy) if recognized[1] == self.line315: self.add_line(self.fx, self.iy, self.ix, self.fy) def add_circle(self): cx = (self.ix + self.fx) / 2.0 cy = (self.iy + self.fy) / 2.0 self.tool_box.tool_circle.widgetize(self, cx, cy, self.fx, self.fy) def add_line(self, ix, iy, fx, fy): self.tool_box.tool_line.widgetize(self, ix, iy, fx, fy) def add_stickman(self): cx = (self.ix + self.fx) / 2.0 cy = (self.iy + self.fy) / 2.0 self.tool_box.tool_stickman.draw(self, cx, cy) def on_children(self, instance, value): self.status_bar.counter = len(self.children) def repaintAllLinks(self, element1, povezaniElementi): for child in povezaniElementi: self.tool_box.tool_line.widgetizeLink(self, element1, child) def paint_links(self, element1, element2): self.tool_box.tool_line.widgetizeLink(self, element1, element2) element1.addLinkElement(element2) element2.addLinkElement(element1) def export_to_png(self, filename, *args): if self.parent is not None: canvas_parent_index = self.parent.canvas.indexof(self.canvas) self.parent.canvas.remove(self.canvas) fbo = Fbo(size=self.size, with_stencilbuffer=True) with fbo: ClearColor(0, 0, 0, 1) ClearBuffers() Scale(1, -1, 1) Translate(-self.x, -self.y - self.height, 0) fbo.add(self.canvas) fbo.draw() fbo.texture.save(filename, flipped=False) fbo.remove(self.canvas) if self.parent is not None: self.parent.canvas.insert(canvas_parent_index, self.canvas) return True