当前位置: 首页>>代码示例>>Python>>正文


Python GestureDatabase.add_gesture方法代码示例

本文整理汇总了Python中kivy.gesture.GestureDatabase.add_gesture方法的典型用法代码示例。如果您正苦于以下问题:Python GestureDatabase.add_gesture方法的具体用法?Python GestureDatabase.add_gesture怎么用?Python GestureDatabase.add_gesture使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在kivy.gesture.GestureDatabase的用法示例。


在下文中一共展示了GestureDatabase.add_gesture方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TabPannel

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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
开发者ID:tehpug,项目名称:RFAttendance,代码行数:59,代码来源:tab_panel.py

示例2: GestureListener

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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+Ht3IWvt2Mfw3zbQ1jNjuuf3Sz0WE7LgcJlNbsM59NLdymXHOavvYT5U8jKbwu9VpSV9f3pcBzqslSX5X8s+1bvCj1cn6A+wntZAhiWcRHr9n/qJdVL0pQNjZUIkAzC5cf6/1B2qITdnbe7oRBSxEwSIXJCmkb5a4E9olDEVCBnUGAUsmlWclZuwULvDeGRVSr62BfjNAudRU1YXj1KE5Z3j9aE5d3jQ/dfyikrIEgmzMCRTSZh5OUTtIF5+0RtYF4/SRuY90/WBuYCqI0AdgH8TAAmyBaVc8oCZvkTMBfA1AbmAljawFwAWxuYC+DcBCYuQNoIEBcgbQSIC5BnAjjFmCiJMSOxpemvv7gAsTYwFyC5CUxdgEIbmAtQagNzAdpGgLoAbSNAXYA+E6AEEa38eVWTaflNTLHM+zdowvL6jZqwvH2TT7LqmLc5d93xPrSZ1qnNLMyXlqSsXxLnchh6S2H9GOZrGD+GKXpoNArBQ8mjED1kGIXkIego5BpqHu2exEMbMzWsr6+27w67/VAnUbuPlb8P22FfoxSWEPUaDqfX7rw+buoInLJPGDW+Vfy9P5+2b5sKymUfXmA0SGqmkAG0Dh+Lv5QfIpE=')
        self.GSTR_SWIPE_RIGHT = \
        self.gdb.str_to_gesture('eNq1l82O2jAQgO9+Ebhs5Pm3X4C9VuIBKgoRi3YLEWTb7tvXnmzbjVQKquRcDJOZb4Z8KLKXh+fDt7du31/G13MfHt/XIYblboCwXhw3X/tFGLB8LAuFy3pxGc+n5/5SvnJYvgwSln+FrD0tDFpRVuqH0+E41rJUy/KVsk81KwwwTVBHeCslgGEVuxhZWRNH4KQ55eTz/Kj3KaweYkcZDJMiCwmBhsuXzb+7sHeRsL/eYP+LzQaQsmSIlqLqHXT/6WAT/aHi0VKCyDFlhMyW9A8fwWI0Js7MSJZv45PjcyM8ugGEVnh0PLXCu1mU+/CRAIgSppwVE0q6LRddLlq7Bq4Xc7MG5IIJ2jVwxUTtGrhkaieZXDLdI7n8R9nUVCxnFJUot+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()
开发者ID:Smug28,项目名称:Mobile-TetriNET,代码行数:55,代码来源:tetriwidgets.py

示例3: Listener

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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
开发者ID:guyzmo,项目名称:kitt,代码行数:53,代码来源:listener.py

示例4: GestureBoard

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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
开发者ID:florian-chassaing,项目名称:museotouch,代码行数:76,代码来源:gesture_board.py

示例5: GestureDatabase

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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/kqf7PdsQIFbtQuUhlBsmrQidOlQC07q7ztVOkSnAh9ciVulxJuCIZm9ZSvQnv1bEaOmAtwJWR5puGIlWSy4hHptRlimjdj7h26lgPK2nBUqKIlPwi4hyJcpcooLQpOxRnhdbUnTio9dvjEvmIlOlS8hEqd6EWYwSQglbRqX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6Huyt9Cd7s+52LRh9f50+pVuj4Aq6/da8u59TSFPErEJlFccfS7nDrNygAh1nFVGaguYUWfMzU3KTWwavs/1+jEqFNIV+Brq2KbUpPgWvGeJ0SunlpcrB+yn5Y1JVYU1Rk8oXmDOKVnrQj5fWLHxGHgd5D9RmX8DJYLuXaAUGaYPeBul4MIv0aYJoZQRuimhhcjxoZ24jWuUAP9+GNzujzCqCm8LmFALw2c7weXk5I49ZObb5EWBWQjhIcFbCMEhoXhKDhGcleqDIrKQccpmtudiBUuYlh1zmq+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)
开发者ID:DeathscytheH,项目名称:creating_apps_in_kivy,代码行数:33,代码来源:gesture_box.py

示例6: Gesture

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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"

开发者ID:AydinSakar,项目名称:kivybits,代码行数:19,代码来源:from+touch+to+gestures.py

示例7: GestureBoard

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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()
开发者ID:15huangtimothy,项目名称:kivy,代码行数:68,代码来源:gesture_board.py

示例8: GestureBox

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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

#.........这里部分代码省略.........
开发者ID:buchuki,项目名称:Todoy,代码行数:103,代码来源:gesturebox.py

示例9: getCurrentCommands

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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)
开发者ID:Sebelino,项目名称:Team18,代码行数:32,代码来源:ProfileManager.py

示例10: GestureDatabase

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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()
    
开发者ID:easytech247,项目名称:LaneCrash,代码行数:32,代码来源:main.py

示例11: AppView

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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) 
#.........这里部分代码省略.........
开发者ID:triselectif,项目名称:Rongo-Rongo,代码行数:103,代码来源:appview.py

示例12: GestureBoard

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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
开发者ID:leonardocsantoss,项目名称:kivy-abc,代码行数:95,代码来源:main.py

示例13: GameMatrix

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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
#.........这里部分代码省略.........
开发者ID:Smug28,项目名称:Mobile-TetriNET,代码行数:103,代码来源:box.py

示例14: DrawingCanvas

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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)
#.........这里部分代码省略.........
开发者ID:lukicmihailo,项目名称:Master_rad,代码行数:103,代码来源:drawingcanvas.py

示例15: DrawingSpace

# 需要导入模块: from kivy.gesture import GestureDatabase [as 别名]
# 或者: from kivy.gesture.GestureDatabase import add_gesture [as 别名]
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)
开发者ID:Anhmike,项目名称:kivy-book-examples,代码行数:89,代码来源:drawingspace.py


注:本文中的kivy.gesture.GestureDatabase.add_gesture方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。