Example #1
0
    def kleene_star(self):
        """ return an FA that is the kleene closure of this FA """
        start_label = frozenset([self.start_state])
        states = {start_label: State()}
        transitions = dict()
        final_states = {states[start_label]}

        boundary = {start_label}
        while boundary:
            label = boundary.pop()
            if any(x in self.final_states for x in label):
                final_states.add(states[label])

            for symbol in self.alphabet:
                # build next label
                next_label = [self.transitions[x, symbol] for x in label]
                if any(x in self.final_states for x in next_label):
                    next_label.append(self.start_state)
                next_label = frozenset(next_label)
                # create state for new labels
                if next_label not in states:
                    states[next_label] = State()
                    boundary.add(next_label)

                transitions[states[label], symbol] = states[next_label]

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[start_label],
            final_states,
        )
Example #2
0
    def __init__(self, game_opts):
        # initialize the state
        State.__init__(self, constants.SCENES['intro'])

        ## the game's command line options
        self.game_opts = game_opts

        ## intro slides
        slide_num = len(constants.FILES['graphics']['intro']['slides'])
        self.slides = [
            graphics.load_image(
                constants.FILES['graphics']['intro']
                ['slides'][i])[0] for i in range(slide_num)
            ]

        ## cut scenes object
        self.cutscenes = IntroCutScene(self.slides)

        # set sound volume to minimum
        pygame.mixer.music.set_volume(0.0)

        # play the background music theme
        sound_mixer.play_music(
            constants.FILES['sounds']['menu']['share']['bg'][0])

        # pause or unpause music according to user preference
        if self.game_opts.music:
            pygame.mixer.music.unpause()
        else:
            pygame.mixer.music.pause()

        # set sound volume to maximum
        pygame.mixer.music.set_volume(MAX_VOLUME)
Example #3
0
    def intersect(self, other):
        """ return an FA that is the intersection of this FA with other """
        start_label = frozenset([self.start_state, other.start_state])
        states = {start_label: State()}  # maps a label to its new state
        transitions = dict()
        final_states = set()

        boundary = {start_label}
        while boundary:
            label = boundary.pop()
            if all(x in self.final_states | other.final_states for x in label):
                final_states.add(states[label])

            for symbol in self.alphabet:
                # build next label
                merged_transitions = {**self.transitions, **other.transitions}
                next_label = [merged_transitions[x, symbol] for x in label]
                next_label = frozenset(next_label)
                # create state for new labels
                if next_label not in states:
                    states[next_label] = State()
                    boundary.add(next_label)

                transitions[states[label], symbol] = states[next_label]

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[start_label],
            final_states,
        )
Example #4
0
    def __init__(self):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        # initialize the state
        State.__init__(self, constants.SCENES['level_one'])
        # the 1st level states
        self.states = FSM()
        # self.game_opts = game_opts
        self.states.active_state = None
Example #5
0
    def __init__(self):
        # part of the borg pattern
        self.__dict__ = self.__shared_state

        # initialize the state
        State.__init__(self, constants.SCENES['level_one'])
        # the 1st level states
        self.states = FSM()
        # self.game_opts = game_opts
        self.states.active_state = None
Example #6
0
    def from_atom(cls, atom, alphabet="ab"):
        """create an FA from an atom"""
        state = start_state = State()
        garbage = State()
        states = {start_state, garbage}
        transitions = {(garbage, symbol): garbage for symbol in alphabet}

        for char in atom:
            new_state = State()
            for symbol in alphabet:
                transitions[state,
                            symbol] = new_state if char == symbol else garbage
            state = new_state
            states.add(state)

        # have all edges from final state point to garbage state
        transitions.update({(state, symbol): garbage for symbol in alphabet})
        return cls(states, alphabet, transitions, start_state, {state})
Example #7
0
    def test_tcp_fsm(self):
        STATES = ['LISTEN', 'SYN RCVD', 'ESTABLISHED', 'SYN SENT', 
          'FIN WAIT 1', 'FIN WAIT 2', 'TIME WAIT', 'CLOSING', 'CLOSE WAIT',
          'LAST ACK']

        tcpip = FiniteStateMachine('TCP IP')
        closed = State('CLOSED', initial=True)
        listen, synrcvd, established, synsent, finwait1, finwait2, timewait, \
        closing, closewait, lastack = [State(s) for s in STATES]
        
        timewait['(wait)'] = closed
        closed.update({r'passive\nopen': listen,
                       'send SYN': synsent})
        
        synsent.update({r'close /\ntimeout': closed,
                        r'recv SYN,\nsend\nSYN+ACK': synrcvd,
                        r'recv SYN+ACK,\nsend ACK': established})
        
        listen.update({r'recv SYN,\nsend\nSYN+ACK': synrcvd,
                       'send SYN': synsent})
        
        synrcvd.update({'recv ACK': established,
                        'send FIN': finwait1,
                        'recv RST': listen})
        
        established.update({'send FIN': finwait1,
                            r'recv FIN,\nsend ACK': closewait})
        
        closewait['send FIN'] = lastack
        
        lastack['recv ACK'] = closed
        
        finwait1.update({'send ACK': closing,
                         'recv ACK': finwait2,
                         r'recv FIN, ACK\n send ACK': timewait})
        
        finwait2[r'recv FIN,\nsend ACK'] = timewait
        
        closing[r'recv\nACK'] = timewait
        
        graph = get_graph(tcpip)
        graph.draw('tcp.png', prog='dot')
    def __init__(self, game_opts):
        State.__init__(self, constants.SCENES['intro'])
        self.game_opts = game_opts
        parser = ConfigParser(constants.MAIN_CFG, constants.CFG_XMLNS)

        # intro slides
        dir_name = parser.first_match('intro').attrib
        slides = [i.text for i in parser.all_matches('slide')]
        slides = [path.join(dir_name['dir'], i) for i in slides]
        slide_num = len(slides)
        self.slides = [ResourceManager().getImage(slides[i]) for i in range(slide_num)]
        self.cutscenes = IntroCutScene(self.slides)

        pygame.mixer.music.set_volume(0.0)
        sound_mixer.play_music(
            constants.FILES['sounds']['menu']['share']['bg'][0])
        if self.game_opts.music:
            pygame.mixer.music.unpause()
        else:
            pygame.mixer.music.pause()
        pygame.mixer.music.set_volume(MAX_VOLUME)
Example #9
0
def initialize_fsm():
    req_data = request.get_json()

    global fsm
    fsm = FiniteStateMachine(State(req_data['start']))

    for transition in req_data['transitions']:
        print_transition_data(transition)
        fsm.add_transition(transition['currentState'], transition['nextState'],
                           transition['actionName'])

    return json.dumps(req_data), 201
Example #10
0
def mk_state(mode, name, next_state, condition):
    return State(
        id=mode.value,
        name=name,
        attributes={"mode": mode.value},
        transitions=[
            Transition(
                id=f"{mode.value}_to_{next_state.value}",
                next=next_state.value,
                conditions=[condition],
            )
        ],
    )
Example #11
0
 def drawStateTransitionGraph():
     #Here we appy the state transitions to create a finite state machine
     ktail = FiniteStateMachine('K-TAIL')
     for nx,kvx in stateMap1.items():
             for c in kvx:
                 State(nx).update({kvx[c]:State(c)})
                 print 'State Transition: ' +str(nx) + '-->'+str(c) + '[label='+kvx[c] +']'
             #Define initial state    
             if nx==0:
                     nx=State(0, initial=True)
     #Create a state machine
     print '------------------------------------------------------------------------------------'
     #Check if there is existing graph data 
     try:
         graph=get_graph(ktail)
         if graph!=None:
             graph.draw('../graph/ktail.png', prog='dot')
             print graph
         else:
             pass
     except GraphvizError:
         tkMessageBox.ERROR
Example #12
0
    def concatenate(self, other):
        """ return an FA that is the concatenation of this FA with other """
        start_label = [self.start_state]
        if self.start_state in self.final_states:
            start_label.append(other.start_state)
        start_label = frozenset(start_label)

        states = {start_label: State()}
        transitions = dict()
        final_states = set()

        boundary = {start_label}
        while boundary:
            label = boundary.pop()
            if any(x in other.final_states for x in label):
                final_states.add(states[label])

            for symbol in self.alphabet:
                # build next label
                merged_transitions = {**self.transitions, **other.transitions}
                next_label = [merged_transitions[x, symbol] for x in label]
                if any(x in self.final_states for x in next_label):
                    next_label.append(other.start_state)
                next_label = frozenset(next_label)
                # create state for new labels
                if next_label not in states:
                    states[next_label] = State()
                    boundary.add(next_label)

                transitions[states[label], symbol] = states[next_label]

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[start_label],
            final_states,
        )
Example #13
0
    def __init__(self, game_opts):
        # initialize the state
        State.__init__(self, 'intro')

        ## the game's command line options
        self.game_opts = game_opts

        ## the intro background slides
        self.slides = [
            graphics.load_image( # slide 0
                constants.FILES['graphics']['intro']['slides'][0])[0],

            graphics.load_image( # slide 1
                constants.FILES['graphics']['intro']['slides'][1])[0],

            graphics.load_image( # slide 2
                constants.FILES['graphics']['intro']['slides'][2])[0]
        ]

        ## a cut scenes object
        self.cs = CutScenes(self.slides)

        # set sound volume to minimum
        pygame.mixer.music.set_volume(0.0)

        # play the background music theme
        sound_mixer.play_music(
            constants.FILES['sounds']['menu']['share']['bg'][0])

        # pause or unpause music according to user preference
        if self.game_opts.music:
            pygame.mixer.music.unpause()
        else:
            pygame.mixer.music.pause()

        # set sound volume to maximum
        pygame.mixer.music.set_volume(1.0)
Example #14
0
    def complement(self):
        """return a DFA that is the complement of this DFA"""
        states = {x: State() for x in self.states}
        transitions = {(states[state], symbol): states[to_state]
                       for (state,
                            symbol), to_state in self.transitions.items()}
        final_states = {
            states[state]
            for state in self.states - self.final_states
        }

        return Dfa(
            set(states.values()),
            self.alphabet,
            transitions,
            states[self.start_state],
            final_states,
        )
Example #15
0
def fxn_lang_load(fsm):
    #the states
    a=State('A'); b=State('B'); c=State('C'); d=State('D'); e=State('E')
    f=State('F'); g=State('G'); h=State('H'); i=State('I'); j=State('J')
    k=State('K'); l=State('L'); m=State('M'); n=State('N'); o=State('O')
    p=State('P'); q=State('Q'); r=State('R'); s=State('S'); t=State('T')
    u=State('U'); v=State('V'); w=State('W', True); x=State('X'); y=State('Y')
    z=State('Z'); a2=State('A2'); b2=State('B2'); 
    c2=State('C2'); d2=State('D2'); e2=State('E2'); f2=State('F2')

    #transition functions
    a.add_fxn('idtok',b)
    b.add_fxn('Lparen',c)
    c.add_fxn('idtok',d)
    c.add_fxn('rparen',f)
    d.add_fxn('commatok',e)
    d.add_fxn('rparen',f)
    e.add_fxn('idtok',d)
    f.add_fxn('lbrace',g)
    g.add_fxn('iftok',h)
    g.add_fxn('rbrace',w)
    h.add_fxn('Lparen',i)
    i.add_fxn('idtok',j)
    i.add_fxn('numtok',j)
    i.add_fxn('strtok',j)
    j.add_fxn('equalsTok',k)
    j.add_fxn('gtTok',k)
    j.add_fxn('ltTok',k)
    j.add_fxn('grTok',k)
    j.add_fxn('leTok',k)
    k.add_fxn('idtok',l)
    k.add_fxn('strtok',l)
    k.add_fxn('numtok',l)
    l.add_fxn('rparen',m)
    m.add_fxn('thentok',n)
    n.add_fxn('lbrace',o)
    o.add_fxn('idtok',p)
    p.add_fxn('assigntok',q)
    q.add_fxn('idtok',r)
    q.add_fxn('numtok',r)
    q.add_fxn('strtok',r)
    r.add_fxn('plustok',s)
    r.add_fxn('minustok',s)
    r.add_fxn('divtok',s)
    r.add_fxn('multtok',s)
    s.add_fxn('idtok',t)
    s.add_fxn('numtok',t)
    s.add_fxn('strtok',t)
    t.add_fxn('semictok',u)
    u.add_fxn('rbrace',v)
    u.add_fxn('idtok',p)
    v.add_fxn('rbrace',u)
    v.add_fxn('elsetok',x)
    x.add_fxn('iftok',h)
    x.add_fxn('lbrace',y)
    y.add_fxn('idtok',z)
    z.add_fxn('assigntok',a2)
    a2.add_fxn('idtok',b2)
    a2.add_fxn('strtok',b2)
    b2.add_fxn('plustok',c2)
    b2.add_fxn('minustok',c2)
    b2.add_fxn('divtok',c2)
    b2.add_fxn('multtok',c2)
    c2.add_fxn('strtok',d2)
    c2.add_fxn('idtok',d2)
    d2.add_fxn('semictok',e2)
    e2.add_fxn('idtok',z)
    e2.add_fxn('rbrace',f2)
    f2.add_fxn('rbrace',w)
    f2.add_fxn('iftok',h)
    
    fsm.set_start_state(a)
Example #16
0
from fsm import MealyMachine, State

adder = MealyMachine('Binary addition')

carry = State('carry')
nocarry = State('no carry', initial=True)

nocarry[(1, 0), 1] = nocarry
nocarry[(0, 1), 1] = nocarry
nocarry[(0, 0), 0] = nocarry
nocarry[(1, 1), 0] = carry

carry[(1, 1), 1] = carry
carry[(0, 1), 0] = carry
carry[(1, 0), 0] = carry
carry[(0, 0), 1] = nocarry

number1 = list(int (i) for i in '0001010')
number2 = list(int (i) for i in '0001111')

inputs = zip(number1, number2)

print list(adder.process(inputs[::-1]))[::-1]
Example #17
0
from fsm import InitState, State, TerminalState, FSM

fsm = FSM({
    'A': InitState({
        'a': 'A',
        'b': 'B',
        'c': 'D'
    }),
    'B': State({
        'a': 'A',
        'b': 'B',
        'c': 'C'
    }),
    'C': State({
        'a': 'A',
        'b': 'F',
        'c': 'D'
    }),
    'D': State({'b': 'E'}),
    'E': TerminalState({}),
    'F': TerminalState({
        'a': 'A',
        'b': 'B',
        'c': 'C'
    })
})
Example #18
0
    def __init__(self, name):
        self.name = name

        # initialize the state
        State.__init__(self, self.name)
Example #19
0
    def test_parkingmeter_fsm(self):
        parking_meter = MooreMachine('Parking Meter')

        ready = State('Ready', initial=True)
        verify = State('Verify')
        await_action = State(r'Await\naction')
        print_tkt = State('Print ticket')
        return_money = State(r'Return\nmoney')
        reject = State('Reject coin')
        ready[r'coin inserted'] = verify
        
        verify.update({'valid': State(r'add value\rto ticket'), 
                       'invalid': reject})
        
        for coin_value in verify:
            verify[coin_value][''] = await_action
        
        await_action.update({'print': print_tkt,
                             'coin': verify,
                             'abort': return_money,
                             'timeout': return_money})
        return_money[''] = print_tkt[''] = ready
        get_graph(parking_meter).draw('parking.png', prog='dot')
Example #20
0
from fsm import FiniteStateMachine, get_graph, State

STATES = ['LISTEN', 'SYN RCVD', 'ESTABLISHED', 'SYN SENT',
          'FIN WAIT 1', 'FIN WAIT 2', 'TIME WAIT', 'CLOSING', 'CLOSE WAIT',
          'LAST ACK']

tcpip = FiniteStateMachine('TCP IP')

closed = State('CLOSED', initial=True)
listen, synrcvd, established, synsent, finwait1, finwait2, timewait, \
closing, closewait, lastack = [State(s) for s in STATES]

timewait['(wait)'] = closed
closed.update({r'passive\nopen': listen,
               'send SYN': synsent})

synsent.update({r'close /\ntimeout': closed,
                r'recv SYN,\nsend\nSYN+ACK': synrcvd,
                r'recv SYN+ACK,\nsend ACK': established})

listen.update({r'recv SYN,\nsend\nSYN+ACK': synrcvd,
               'send SYN': synsent})

synrcvd.update({'recv ACK': established,
                'send FIN': finwait1,
                'recv RST': listen})

established.update({'send FIN': finwait1,
                    r'recv FIN,\nsend ACK': closewait})

closewait['send FIN'] = lastack
Example #21
0
File: loop.py Project: NielXu/fsm

def foo(mapper):
    if mapper["a"] < mapper["k"]:
        return False
    return True


def incre(mapper):
    print("Looping:", mapper["a"])
    mapper["a"] += 1


set_any("*")

start = State("Start")
s0 = State("Loop", exe=incre)
end = State("End")

# Start state go to s0 directly
start.add_transit(get_any(), s0)
# Define bool expr
sin0 = Signal(foo)

# Define two transits, if a >= k go to end
# Otherwise, go back to itself
s0.add_transit(sin0, end)
s0.add_transit(get_any(), s0)

m = Machine(start, [end], mapper)
m.start()
Example #22
0
    def createContentModel(self, node, _stack=list()):
        name = node.prop("name")
        minOccurs = node.prop("minOccurs")
        minOccurs = 1 if minOccurs is None else int(minOccurs)
        maxOccurs = node.prop("maxOccurs")
        maxOccurs = 1 if maxOccurs is None else (
            maxOccurs if maxOccurs == "unbounded" else int(maxOccurs))
        fsm = None
        ea = list()
        la = list()
        self.processActions(node, ea, la)
        if _stack.count(node) > 0:
            if node.name != "element" or ("{%s}%s" %
                                          (self.targetNamespace(node),
                                           name)) not in self.providedElements:
                print "*** recursion detected ***"
                return XMLFsm().empty()

        stack = list(_stack)
        stack.append(node)
        print "%s%s: '{%s}%s' (%s, %s) %s | %s" % (
            len(_stack) * "  ", node.name, self.targetNamespace(node), name,
            minOccurs, maxOccurs, [self.actions[e]
                                   for e in ea], [self.actions[a] for a in la])
        for case in switch(node.name):
            if case("element"):
                # wenn Referenz, dann verwende das Model des referenzierten Elements und wende Aktionen und Particle-Rule an
                if node.prop("ref") is not None:
                    ref = self.Decls[1][self.expandQName(
                        node, node.prop("ref"))]
                    if ref is None:
                        raise BaseException(
                            "Referenced element not known: %s" %
                            node.prop("ref"))
#					print "Verwende referenz %s" % node.prop("ref")
                    fsm = self.createContentModel(
                        ref, stack).onenter(ea).onleave(la).particle(
                            minOccurs, maxOccurs)
                else:
                    # sonst, falls nicht abstract, baue das Modell aus dem angegebenen Typ oder den Kind-Elementen
                    #   und erzeuge das Element
                    # erzeuge für jedes Mitglied der SubstitutionGroup das Inhaltsmodell und ggf. den Aufruf für die Gruppe
                    #   und füge diese mit dem für dieses Element zusammen
                    # Ist das Element provided, wird ein Einsprung dafür definiert
                    substitutions = []
                    name = node.prop("name")
                    if name is None:
                        raise BaseException(
                            "Element declaration requires a name")

                    qname = "{%s}%s" % (self.targetNamespace(node), name)
                    if qname in self.providedElements or \
                       qname in self.elements:
                        #						print "Creating call to %s" % name
                        # Einsprung via Element-Name in Zielmaschine; abstract="true" impliziert --preserve-substitution
                        fsm = XMLFsm()
                        fsm.entry = State()
                        leave = State()
                        fsm.entry.addTransition(
                            self.getElementId(
                                self.targetNamespace(node),
                                "%s%s" % ('!' if node.prop("abstract")
                                          == "true" else "", name)), leave, ea)
                        fsm.accepts.add(leave)
                        fsm = fsm.particle(minOccurs, maxOccurs)
                    else:
                        #						print "%s nicht in %s" % (qname, self.providedElements)
                        if "{%s}%s" % (self.targetNamespace(node),
                                       name) in self.genElements:
                            self.providedElements.add(
                                "{%s}%s" % (self.targetNamespace(node), name))
                        if node.prop("abstract") != "true":
                            #							print "Erzeuge content model fuer %s" % name
                            content = None
                            # compute the direct content model
                            if node.prop("type") is not None:
                                typename = self.expandQName(
                                    node, node.prop("type"),
                                    self.targetNamespace(node))
                                if not self.Decls[2].has_key(typename):
                                    raise BaseException("Unknown type %s" %
                                                        typename)
                                if self.Decls[2][typename] is not None:
                                    content = self.createContentModel(
                                        self.Decls[2][typename], stack)
                                # if None, it is a predefined simpleType
                            else:
                                child = node.children
                                while child is not None:
                                    if child.name in ("simpleType",
                                                      "complexType"):
                                        content = self.createContentModel(
                                            child, stack)
                                        break
                                    child = child.next
                            if content is None:
                                content = XMLFsm().empty()
                            substitutions.append(XMLFsm().element(
                                self.getElementId(self.targetNamespace(node),
                                                  name), content, ea,
                                la).particle(minOccurs, maxOccurs))
#						else:
#							print "Kein content-model fuer %s, da abstract" % name

                        if self.substs.has_key(qname):
                            for child in self.substs[qname]:
                                #								print "Fuege subst %s fuer %s hinzu" % (child.prop("name"), qname)
                                substitutions.append(
                                    self.createContentModel(child, stack))
                        if qname in self.preservedSubsts:
                            f = XMLFsm()
                            f.entry = State()
                            leave = State()
                            f.entry.addTransition(
                                self.getElementId(self.targetNamespace(node),
                                                  "!%s" % name), leave, ea)
                            f.accepts.add(leave)
                            substitutions.append(f)
                        fsm = XMLFsm().empty() if len(
                            substitutions) == 0 else XMLFsm().choice(
                                substitutions).particle(minOccurs, maxOccurs)
                break

            if case("simpleType", "simpleContent"):
                fsm = XMLFsm().empty()
                break

            if case("complexType"):
                if node.prop("name") is None or self.expandQName(
                        node, node.prop("name"),
                        self.targetNamespace(node)) not in self.providedTypes:
                    if "{%s}%s" % (self.targetNamespace(node),
                                   name) in self.genTypes:
                        self.providedTypes.add(
                            "{%s}%s" % (self.targetNamespace(node), name))
                    child = node.children
                    while child is not None:
                        if child.name in ("simpleContent", "complexContent",
                                          "group", "choice", "sequence",
                                          "all"):
                            fsm = self.createContentModel(
                                child, stack).onenter(ea).onleave(la)
                            break
                        child = child.next
                if fsm is None: fsm = XMLFsm().empty()
                break

            if case("sequence", "choice"):
                content = []
                child = node.children
                while child is not None:
                    if child.name in ("element", "group", "choice", "sequence",
                                      "any"):
                        content.append(self.createContentModel(child, stack))
                    child = child.next
                fsm = XMLFsm().empty() if len(content) == 0 else (
                    XMLFsm().sequence(content, ea, la)
                    if node.name == "sequence" else XMLFsm().choice(
                        content, ea, la)).particle(minOccurs, maxOccurs)
                break

            if case("complexContent"):
                content = None
                child = node.children
                while child is not None:
                    if child.name in ("extension", "restriction"):
                        content = self.createContentModel(child, stack)
                        break
                    child = child.next
                fsm = XMLFsm().empty() if content is None else content
                break

            if case("extension", "restriction"):
                if node.name == "extension":
                    qname = self.expandQName(node, node.prop("base"),
                                             self.targetNamespace(node))
                    if qname not in self.Decls[2]:
                        raise BaseException("base type %s not known" % qname)
                    base = self.Decls[2][qname]
                    baseContent = XMLFsm().empty(
                    ) if base is None else self.createContentModel(
                        base, stack)
                else:
                    baseContent = XMLFsm().empty()
                content = None
                child = node.children
                while child is not None:
                    if child.name in ("group", "choice", "sequence"):
                        content = self.createContentModel(child, stack)
                        break
                    child = child.next
                fsm = baseContent if content is None else baseContent.concat(
                    content)
                break

            if case("any"):
                fsm = XMLFsm().element(
                    self.getElementId(self.targetNamespace(node), "*"),
                    XMLFsm().empty(), ea, la).particle(minOccurs, maxOccurs)
                break

            if case("group"):
                if node.prop("ref") is not None:
                    ref = self.Decls[1][self.expandQName(
                        node, node.prop("ref"))]
                    if ref is None:
                        raise BaseException("Referenced group not known: %s" %
                                            node.prop("ref"))
                    fsm = self.createContentModel(
                        ref, stack).onenter(ea).onleave(la).particle(
                            minOccurs, maxOccurs)
                else:
                    content = None
                    child = node.children
                    while child is not None:
                        if child.name in ("all", "choice", "sequence"):
                            content = self.createContentModel(child, stack)
                            break
                        child = child.next
                    fsm = XMLFsm(
                    ).empty if content is None else content.onenter(
                        ea).onleave(la)
                break

            if case():
                raise BaseException("Unknown schema object: %s" % node.name)


#		self.dump(fsm)
#		print "*" * 32
        if len(stack) % 5 == 0: fsm = fsm.determinize(False).minimize(False)
        return fsm
Example #23
0
import json

import flask
from flask import request

from fsm import FiniteStateMachine
from fsm import State

app = flask.Flask(__name__)
app.config["DEBUG"] = True

fsm = FiniteStateMachine(State('uninitialized'))


@app.route('/fsm', methods=['GET'])
@app.route('/fsm/current-state', methods=['GET'])
def get_current_state():
    return json.dumps(
        {"currentState": fsm.get_current_state().current_state_name})


@app.route('/fsm/valid-actions', methods=['GET'])
def get_valid_actions():
    return json.dumps({"validActions": fsm.list_valid_actions()})


@app.route('/fsm', methods=['POST'])
def post_fsm():
    args = request.args

    if "action_name" in args:
Example #24
0
    def generateStateTransition(self, loadEquiState, tmpDictx, dotFile):
        ktailx = loadEquiState

        if len(ktailx) == 0:
            pass

        #Identify unique states from the merged state list
        kTailFSMGraph.getUniqueStates = set()

        for val in ktailx:
            kTailFSMGraph.getUniqueStates.add(val)

        print 'unique states' + str(kTailFSMGraph.getUniqueStates)

        #Dictionary to keep track of the state and its assocated transition labels
        kTailFSMGraph.transDict = {}
        for g in kTailFSMGraph.getUniqueStates:
            for tmpk, tmpv in tmpDictx.items():
                if g == tmpk:
                    kTailFSMGraph.transDict[g] = tmpv

        print 'transDict' + str(kTailFSMGraph.transDict)

        #Create a list of mapping combinations identified from the state merged list
        #Example: [0,1,1,3,4] ==>[0-->1,1-->1,1-->3,3-->4]

        current = None
        nxt = None
        index = 0
        kTailFSMGraph.mapping = []
        while (index + 1) < len(ktailx):
            current = ktailx[index]
            nxt = ktailx[index + 1]
            kTailFSMGraph.mapping.append(str(current) + '-->' + str(nxt))
            index += 1

        print 'mapping' + str(kTailFSMGraph.mapping)

        #This dictionary stores transition of each state
        #A state may have multiple transitions.
        #Example: State 0: may have a or more transitions to itself and another transition to other state

        kTailFSMGraph.stateMap = {}
        kTailFSMGraph.sampleStatemap = {}
        print kTailFSMGraph.transDict
        for td, tv in kTailFSMGraph.transDict.items():
            #Intialize the embedded dictionary with empty string for each state
            if dotFile == 'sample':
                kTailFSMGraph.sampleStatemap[td] = {}
            elif dotFile == 'ktail':
                kTailFSMGraph.stateMap[td] = {
                }  #The embedded dictionary stores the next transition state with the transition label as the key.

        for z in kTailFSMGraph.getUniqueStates:
            for e, f in kTailFSMGraph.transDict.items():
                if z == e:
                    for m in kTailFSMGraph.mapping:
                        st = [int(s) for s in m.split('-->') if s.isdigit()
                              ]  #extract digits in a mapping entry
                        if str(z) == str(st[0]) and str(z) == str(st[1]):
                            if dotFile == 'sample':
                                kTailFSMGraph.sampleStatemap[z][int(st[0])] = f
                            else:
                                kTailFSMGraph.stateMap[z][int(st[0])] = f
                            #Check if the transition from the current node
                            #to the next node is the same as the self-transition on current node
                            #If so then we assign and arbitrary label-as it might cause non-deterministic fsm
                        elif str(z) != str(st[1]) and str(z) == str(st[0]):
                            if dotFile == 'sample':
                                kTailFSMGraph.sampleStatemap[z][int(st[1])] = f
                            else:
                                kTailFSMGraph.stateMap[z][int(st[1])] = f

        print 'Test Input Trace Map' + str(kTailFSMGraph.stateMap)
        print 'Sample Input Trace Map' + str(kTailFSMGraph.sampleStatemap)

        #Look for non-determistic paths in the traces for the sample input.

        if dotFile == 'sample':
            print 'Checking for non-deterministic paths in Sample Trace Automata:'
            kTailFSMGraph.samplendfaloginfor.append(
                'Checking for non-deterministic paths in Sample Trace Automata:'
            )
            for k, v in kTailFSMGraph.transDict.items():
                if self.duplicate_dictionary_check(
                        kTailFSMGraph.sampleStatemap, str(v)) == None:
                    pass
                else:
                    kTailFSMGraph.samplendfaloginfor.append('==>' + str(
                        self.duplicate_dictionary_check(
                            kTailFSMGraph.sampleStatemap, str(v))))
                    print self.duplicate_dictionary_check(
                        kTailFSMGraph.sampleStatemap, str(v))
                    tkMessageBox.showinfo(
                        "Non-deterministic FA",
                        self.duplicate_dictionary_check(
                            kTailFSMGraph.sampleStatemap, str(v)))

        elif dotFile == 'ktail':
            kTailFSMGraph.ndfaloginfor = []  #re
            print 'Checking for non-deterministic paths in Input Trace Automata:'
            kTailFSMGraph.ndfaloginfor.append(
                'Checking for non-deterministic paths in Input Trace Automata:'
            )
            #print 'alpa'+str(alphabet)
            for k, v in kTailFSMGraph.transDict.items():
                #print self.duplicate_dictionary_check(kTailFSMGraph.stateMap,str(v))
                if self.duplicate_dictionary_check(kTailFSMGraph.stateMap,
                                                   str(v)) == None:
                    pass
                else:
                    kTailFSMGraph.ndfaloginfor.append('==>' + str(
                        self.duplicate_dictionary_check(
                            kTailFSMGraph.stateMap, str(v))))
                    print self.duplicate_dictionary_check(
                        kTailFSMGraph.stateMap, str(v))
                    #tkMessageBox.showinfo("Non-deterministic FA", self.duplicate_dictionary_check(kTailFSMGraph.stateMap,str(v)))

        #Here we appy the state transitions to create a finite state machine

        ktailFSM = FiniteStateMachine('K-TAIL')
        kTailFSMGraph.alphabetfromtrace.clear()
        tmpstateMap = {}

        #make a shallow copy of the state map dictionaries
        if dotFile == 'sample':
            tmpstateMap = kTailFSMGraph.sampleStatemap.copy()
        elif dotFile == 'ktail':
            tmpstateMap = kTailFSMGraph.stateMap.copy()

        for nx, kvx in tmpstateMap.items():
            #n=[State(s) for s in list(getUniqueStates)]
            for c in kvx:
                State(nx).update({kvx[c]: State(c)})
                print 'State Transition: ' + str(nx) + '-->' + str(
                    c) + '[label=' + kvx[c] + ']'
                kTailFSMGraph.alphabetfromtrace[(nx, kvx[c])] = c
            #Define initial state
            if nx == 0:
                nx = State(0, initial=True)
            #Define acceptings states for the state machine
            if dotFile == 'sample':
                for a in kTailFSMGraph.accepting_states:
                    if a == nx:
                        nx = State(a, accepting=True)
        #clear the the tmp states map after the operation
        tmpstateMap.clear()
        #Create a state machine

        print '------------------------------------------------------------------------------------'

        try:
            graph = get_graph(ktailFSM)
            if graph != None:  #Check if there is existing graph data
                graph.draw('../graph/' + dotFile + '.png', prog='dot')
            else:
                pass
        except GraphvizError:
            tkMessageBox.ERROR

        print '-------------------------------------------------------------------------------------'
Example #25
0
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 05 19:20:23 2014

@author: dlmu__000
"""

from fsm import State, Transducer, get_graph

microwave = Transducer('Microwave Oven')

closed_i = State(r'CLOSED\nidle', initial=True)
closed_p = State(r'CLOSED\nprocessing')
opened_i = State(r'OPEN\nidle')
paused = State('PAUSED')
settings = State(r'SETUP')

closed_i[r'PSB, TK /\nset program,\nset timer'] = closed_i
closed_i['SSB / start'] = closed_p
closed_i['ODH / open door'] = opened_i
closed_i['ELS / enter setup'] = settings
settings['SSB / save setup'] = settings
settings['ELS / leave setup'] = closed_i
opened_i['DL / shut door'] = closed_i
closed_p['PRB / pause'] = paused
closed_p['ODH / open door'] = opened_i
closed_p['TO / ready'] = closed_i
paused['SSB / stop'] = closed_i
paused['PRB / resume'] = closed_p
paused[r'PSB, TK /\nreset program,\nreset timer'] = paused
paused['ODH / open door'] = opened_i
Example #26
0
    def __init__(self, game_opts):
        # initialize the state
        State.__init__(self, constants.SCENES["menu"])

        ## the game's command line options
        self.game_opts = game_opts

        ## the screen surface
        self.screen = pygame.display.get_surface()

        ## flag to control the settings menu's loop
        self.menu_settings_running = None

        ## flag to control the main menu's loop
        self.menu_main_running = True

        # enable key repeat for the menu
        pygame.key.set_repeat(MENU_KEY_DEL, MENU_KEY_INT)

        ## set the main menu's background
        self.menu_main_bg = graphics.load_image(constants.FILES["graphics"]["menu"]["main"]["bg"][0])[0]

        ## set the settings menu's background
        self.menu_settings_bg = graphics.load_image(constants.FILES["graphics"]["menu"]["share"]["bg"][0])[0]

        ## set the settings menu's background box
        self.menu_box_bg = graphics.load_image(constants.FILES["graphics"]["menu"]["settings"]["box"][0])[0]

        ## set the window frame
        self.window_frame = graphics.load_image(constants.FILES["graphics"]["menu"]["share"]["frame"][0])[0]

        ## set the mouse cursor
        self.mouse_cursor = graphics.load_image(constants.FILES["graphics"]["menu"]["share"]["cursor"][0])[0]

        ## set the sound when a menu option is entered
        self.select_option_snd = sound_mixer.load_sound(constants.FILES["sounds"]["menu"]["share"]["sel"][0])

        ## create the main menu - string, callback function
        self.menu_main = KezMenu(
            self.game_opts,
            ["Play", self._play_option],
            ["Settings", self._settings_option],
            ["Credits", self._credits_option],
            ["Quit", self._quit_option],
        )

        # set the position of the main menu
        self.menu_main.set_position(MENU_MAIN_POS_X, MENU_MAIN_POS_Y)

        # set the main menu's font
        self.menu_main.set_font(graphics.load_font(constants.FILES["fonts"]["menu"]["share"][0], MAIN_FONT_SIZE))

        # set the main menu's highlight color
        self.menu_main.set_highlight_color(MAIN_FOCUS_COLOR)

        ## create the settings menu - string, callback function
        self.menu_settings = KezMenu(
            self.game_opts,
            ["Fullscreen", self._toggle_fullscreen_option],
            ["Sounds", self._toggle_sounds_option],
            ["Music", self._toggle_music_option],
            ["Back", self._back_option],
        )

        # disable the menu graphic for focused options
        self.menu_settings.toggle_image()

        # set the settings menu's font
        self.menu_settings.set_font(graphics.load_font(constants.FILES["fonts"]["menu"]["share"][0], MENU_FONT_SIZE))

        # set the position of the settings menu
        self.menu_settings.center_at(constants.SCREEN_WIDTH / 2.0, constants.SCREEN_HEIGHT / 2.0)

        # set the settings menu's highlight color
        self.menu_settings.set_highlight_color(SETTINGS_FOCUS_COLOR)

        ## the animated sprite group
        self.anim_sprites = pygame.sprite.RenderUpdates()

        # create the animated sprites
        sprite_num = len(constants.FILES["graphics"]["menu"]["share"]["anim"])
        sprite_fact = SpriteFactory()
        for i in range(sprite_num):
            # create the "right" type of animated sprite using the factory
            r_sprite = sprite_fact.create_anim_sprite(
                i, constants.FILES["graphics"]["menu"]["share"]["anim"][i], ANIM_SPRITE_SPEED
            )
            self.anim_sprites.add(r_sprite)

        ## create clock and track time
        self.clock = pygame.time.Clock()
Example #27
0
    def generateStateTransition(self, loadEquivalentState):
        #print k_tail_value,trace
        #kt=kTails('k-tails')
        ktailx = loadEquivalentState  #kt.do_kTailEquivCheck(k_tail_value,trace)

        print 'transition ' + str(ktailx)

        if len(ktailx) == 0:
            pass
        #for mv in ktailx:
        #    if mv==match_Values(ktailx):
        #        print mv

        #Identify unique states from the merged state list
        getUniqueStates = set()
        for val in ktailx:
            getUniqueStates.add(val)

        print getUniqueStates
        #Dictionary to keed track of the state and its assocated transition labels
        transDict = {}
        for g in getUniqueStates:
            for tmpk, tmpv in ktail.tmpDict.items():
                if g == tmpk:
                    transDict[g] = tmpv

        print 'transDict' + str(transDict)

        #Create a list of mapping combinations identified from the state merged list
        #Example: [0,1,1,3,4] ==>[0-->1,1-->1,1-->3,3-->4]
        current = None
        nxt = None
        index = 0
        mapping = []
        while (index + 1) < len(ktailx):
            current = ktailx[index]
            nxt = ktailx[index + 1]
            mapping.append(str(current) + '-->' + str(nxt))
            index += 1

        print 'mapping' + str(mapping)

        #This dictionary stores transition of each state
        #A state may have multiple transitions.
        #Example: State 0: may have a or more transitions to itself and another transition to other state
        stateMap = {}
        print transDict
        for td, tv in transDict.items():
            #for tm in mapping:
            #    stm=[int(s) for s in tm.split('-->') if s.isdigit()]
            #    if str(td)==stm[0]:
            #stateMap[td]={ tv:' '}  #Intialize the embedded dictionary with empty string for each state
            stateMap[td] = {
            }  #The embedded dictionary stores the next transition state with the
            #transition label as the key.
        print 'stateMap' + str(stateMap)
        for z in getUniqueStates:
            for e, f in transDict.items():
                if z == e:
                    for m in mapping:
                        st = [int(s) for s in m.split('-->')
                              if s.isdigit()]  #extract digits a mapping entry
                        if str(z) == str(st[0]) and str(z) == str(st[1]):
                            #if str(z)==m[-1] and str(z)==m[0]:#Check for occurance of transition to itself
                            #if m[0] not in stateMap[z]:
                            stateMap[z][int(st[0])] = f
                            #print 'x'+stateMap[z][m[-1]] + m
                            #Check if the transition from the current node
                            #to the next node is the same as the self-transition on current node
                            #If so then we assign and arbitrary label-as it might cause non-deterministic fsm
                        elif str(z) != str(st[1]) and str(z) == str(st[0]):
                            #print stateMap[z][int(st[1])]
                            stateMap[z][int(st[1])] = f
                        #elif str(z)==str(st[1]) and str(z)!=str(st[0]):
                        #    stateMap[z][int(st[0])]=f
        print 'statemap' + str(stateMap)

        #Here we appy the state transitions to create a finite state machine
        for nx, kvx in stateMap.items():
            #n=[State(s) for s in list(getUniqueStates)]
            for c in kvx:
                State(nx).update({kvx[c]: State(c)})
                print 'State: ' + str(nx) + kvx[c] + ':' + str(c)
            #Define initial state
            if nx == 0:
                nx = State(0, initial=True)

        #Create a state machine
        graph = get_graph(ktail)
        graph.draw('ktail.png', prog='dot')
        print 'End of Print line'
Example #28
0
    def __init__(self, name):
        self.name = name

        # initialize the state
        State.__init__(self, self.name)
Example #29
0
    def __init__(self, game_opts):
        # initialize the state
        State.__init__(self, constants.SCENES['menu'])

        ## the game's command line options
        self.game_opts = game_opts

        ## the screen surface
        self.screen = pygame.display.get_surface()

        ## flag to control the settings menu's loop
        self.menu_settings_running = None

        ## flag to control the main menu's loop
        self.menu_main_running = True

        # enable key repeat for the menu
        pygame.key.set_repeat(MENU_KEY_DEL, MENU_KEY_INT)

        ## set the main menu's background
        self.menu_main_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['main']['bg'][0])[0]

        ## set the settings menu's background
        self.menu_settings_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['bg'][0])[0]

        ## set the settings menu's background box
        self.menu_box_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['settings']['box'][0])[0]

        ## set the window frame
        self.window_frame = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['frame'][0])[0]

        ## set the mouse cursor
        self.mouse_cursor = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['cursor'][0])[0]

        ## set the sound when a menu option is entered
        self.select_option_snd = sound_mixer.load_sound(
            constants.FILES['sounds']['menu']['share']['sel'][0])

        ## create the main menu - string, callback function
        self.menu_main = KezMenu(self.game_opts, ['Play', self._play_option],
                                 ['Settings', self._settings_option],
                                 ['Credits', self._credits_option],
                                 ['Quit', self._quit_option])

        # set the position of the main menu
        self.menu_main.set_position(MENU_MAIN_POS_X, MENU_MAIN_POS_Y)

        # set the main menu's font
        self.menu_main.set_font(
            graphics.load_font(constants.FILES['fonts']['menu']['share'][0],
                               MAIN_FONT_SIZE))

        # set the main menu's highlight color
        self.menu_main.set_highlight_color(MAIN_FOCUS_COLOR)

        ## create the settings menu - string, callback function
        self.menu_settings = KezMenu(
            self.game_opts, ['Fullscreen', self._toggle_fullscreen_option],
            ['Sounds', self._toggle_sounds_option],
            ['Music', self._toggle_music_option], ['Back', self._back_option])

        # disable the menu graphic for focused options
        self.menu_settings.toggle_image()

        # set the settings menu's font
        self.menu_settings.set_font(
            graphics.load_font(constants.FILES['fonts']['menu']['share'][0],
                               MENU_FONT_SIZE))

        # set the position of the settings menu
        self.menu_settings.center_at(constants.SCREEN_WIDTH / 2.0,
                                     constants.SCREEN_HEIGHT / 2.0)

        # set the settings menu's highlight color
        self.menu_settings.set_highlight_color(SETTINGS_FOCUS_COLOR)

        ## the animated sprite group
        self.anim_sprites = pygame.sprite.RenderUpdates()

        # create the animated sprites
        sprite_num = len(constants.FILES['graphics']['menu']['share']['anim'])
        sprite_fact = SpriteFactory()
        for i in range(sprite_num):
            # create the "right" type of animated sprite using the factory
            r_sprite = sprite_fact.create_anim_sprite(
                i, constants.FILES['graphics']['menu']['share']['anim'][i],
                ANIM_SPRITE_SPEED)
            self.anim_sprites.add(r_sprite)

        ## create clock and track time
        self.clock = pygame.time.Clock()
    def __init__(self, game_opts):
        State.__init__(self, constants.SCENES['menu'])

        self.game_opts = game_opts
        self.screen = pygame.display.get_surface() 

        self.menu_settings_running = None
        self.menu_main_running = True

        pygame.key.set_repeat(MENU_KEY_DEL, MENU_KEY_INT)

        self.menu_main_bg = ResourceManager().getImage(
            constants.FILES['graphics']['menu']['main']['bg'][0])
        self.menu_settings_bg = ResourceManager().getImage(
            constants.FILES['graphics']['menu']['share']['bg'][0])
        self.menu_box_bg = ResourceManager().getImage(
            constants.FILES['graphics']['menu']['settings']['box'][0])
        self.window_frame = ResourceManager().getImage(
            constants.FILES['graphics']['menu']['share']['frame'][0])
        self.mouse_cursor = ResourceManager().getImage(
            constants.FILES['graphics']['menu']['share']['cursor'][0])

        self.select_option_snd = sound_mixer.load_sound(
            constants.FILES['sounds']['menu']['share']['sel'][0])

        # create the main menu - string, callback function
        self.menu_main = KezMenu(self.game_opts,
                         ['Play'     , self._play_option],
                         ['Settings' , self._settings_option],
                         ['Credits'  , self._credits_option],
                         ['Quit'     , self._quit_option])

        self.menu_main.set_position(MENU_MAIN_POS_X, MENU_MAIN_POS_Y)
        self.menu_main.set_font(graphics.load_font(
            constants.FILES['fonts']['menu']['share'][0], MAIN_FONT_SIZE))
        self.menu_main.set_highlight_color(MAIN_FOCUS_COLOR)

        # create the settings menu - string, callback function
        self.menu_settings = KezMenu(self.game_opts,
                             ['Fullscreen' , self._toggle_fullscreen_option],
                             ['Sounds'     , self._toggle_sounds_option],
                             ['Music'      , self._toggle_music_option],
                             ['Back'       , self._back_option])

        # disable the menu graphic for focused options
        self.menu_settings.toggle_image()

        self.menu_settings.set_font(graphics.load_font(
            constants.FILES['fonts']['menu']['share'][0], MENU_FONT_SIZE))
        self.menu_settings.center_at(constants.SCREEN_WIDTH / 2.0,
                                     constants.SCREEN_HEIGHT / 2.0)
        self.menu_settings.set_highlight_color(SETTINGS_FOCUS_COLOR)

        self.sprites = pygame.sprite.LayeredUpdates()

        sprites_number = len(constants.FILES['graphics']['menu']['share']['anim'])
        sprite_area = self.screen.get_rect()
        sprite_limiter = LimiterFactory().getInstance('Default')
        for i in range(sprites_number):
            sprite = MenuSprite(constants.FILES['graphics']['menu']['share']['anim'][i],
                                (sprite_area.center), i, MAX_ALPHA, False, SPRITE_SPEED,
                                sprite_area, 'Random')
            sprite.limiter = sprite_limiter
            self.sprites.add(sprite)

        self.clock = pygame.time.Clock()
Example #31
0
File: menu.py Project: delmoras/tct
    def __init__(self, game_opts):
        # initialize the state
        State.__init__(self, 'menu')

        ## the game's command line options
        self.game_opts = game_opts

        ## the screen surface
        self.screen = pygame.display.get_surface() 

        ## flag to control the settings menu's loop
        self.menu_settings_running = None

        ## flag to control the main menu's loop
        self.menu_main_running = True

        # enable key repeat for the menu
        pygame.key.set_repeat(MENU_KEY_DEL, MENU_KEY_INT)

        ## set the main menu's background
        self.menu_main_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['main']['bg'][0])[0]

        ## set the settings menu's background
        self.menu_settings_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['bg'][0])[0]

        ## set the settings menu's background box
        self.menu_box_bg = graphics.load_image(
            constants.FILES['graphics']['menu']['settings']['box'][0])[0]

        ## set the window frame
        self.window_frame = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['frame'][0])[0]

        ## set the mouse cursor
        self.mouse_cursor = graphics.load_image(
            constants.FILES['graphics']['menu']['share']['cursor'][0])[0]

        ## set the sound when a menu option is entered
        self.select_option_snd = sound_mixer.load_sound(
            constants.FILES['sounds']['menu']['share']['sel'][0])

        ## create the main menu - string, callback function
        self.menu_main = KezMenu(self.game_opts,
                         ['Play'     , self._play_option],
                         ['Settings' , self._settings_option],
                         ['Credits'  , self._credits_option],
                         ['Quit'     , self._quit_option])

        # set the position of the main menu
        self.menu_main.set_position(MENU_MAIN_POS_X, MENU_MAIN_POS_Y)

        # set the main menu's font
        self.menu_main.set_font(graphics.load_font(
            constants.FILES['fonts']['menu']['share'][0], 30))

        # set the main menu's highlight color
        self.menu_main.set_highlight_color(pygame.Color('brown'))

        ## create the settings menu - string, callback function
        self.menu_settings = KezMenu(self.game_opts,
                             ['Fullscreen' , self._toggle_fullscreen_option],
                             ['Sounds'     , self._toggle_sounds_option],
                             ['Music'      , self._toggle_music_option],
                             ['Back'       , self._back_option])

        # disable the menu graphic for focused options
        self.menu_settings.toggle_image()

        # set the settings menu's font
        self.menu_settings.set_font(graphics.load_font(
            constants.FILES['fonts']['menu']['share'][0], 25))

        # set the position of the settings menu
        self.menu_settings.center_at(constants.SCREEN_WIDTH / 2.0,
                                     constants.SCREEN_HEIGHT / 2.0)
    
        # set the settings menu's highlight color
        self.menu_settings.set_highlight_color(pygame.Color('orange'))

        ## the animated sprite group
        self.anim_sprites = pygame.sprite.RenderUpdates()

        # vertical sprite sample
        self.anim_sprites.add(VertAnimSprite(
                constants.FILES['graphics']['menu']['share']['anim'][0],
                [0, 0], ANIM_SPRITE_SPEED))

        # horizontal sprite sample
        self.anim_sprites.add(HorAnimSprite(
                constants.FILES['graphics']['menu']['share']['anim'][1],
                [0, 0], ANIM_SPRITE_SPEED))

        ## create clock and track time
        self.clock = pygame.time.Clock()
Example #32
0
import unittest

from fsm import State, FSM

CONNECTION_STATES = [
    State('LISTENING', {
        'connect': 'CONNECTED',
        'error': 'LISTENING'
    }),
    State('CONNECTED', {
        'accept': 'ACCEPTED',
        'close': 'CLOSED'
    }),
    State('ACCEPTED', {
        'close': 'CLOSED',
        'read': 'READING',
        'write': 'WRITING'
    }),
    State('READING', {
        'read': 'READING',
        'close': 'CLOSED',
        'write': 'WRITING'
    }),
    State('WRITING', {
        'read': 'READING',
        'close': 'CLOSED',
        'write': 'WRITING'
    }),
    State('CLOSED', {}, default_event='LISTENING'),
    State('ERROR', {}, default_event='ERROR')
]
Example #33
0
from fsm import FiniteStateMachine, State
import itertools

STATES = [
    "A", "AC", "ACE", "ACEM", "ACEMU", "ACEMK", "ACK", "ACKM", "ACKME",
    "ACKMU", "ACKS", "ACKSU", "ACKSQ", "ACKI", "ACKIQ", "AI", "AIQ", "AIQS",
    "AIQSK", "AIQSU", "AIK", "AIKC", "AIKCE", "AIKM", "AIKME", "AIKMU", "AIKS",
    "AIKSQ", "AIKSU", "REWARD", "PUNISHMENT"
]

bad_states = [s for s in STATES if (s != "ACKMU") and (len(s) == 5)]

maze = FiniteStateMachine("maze")

states = {}
states['A'] = State('A', initial=True)
for state in STATES[1:]:
    states[state] = State(state)
    states[state].DOT_ATTRS['shape'] = 'rectangle'
    states[state].DOT_ATTRS['height'] = 0.3

states['REWARD'].DOT_ATTRS['fillcolor'] = 'green'
states['PUNISHMENT'].DOT_ATTRS['fillcolor'] = 'red'

states['A'].update({'right': states['AC'], 'down': states['AI']})

states['AC'].update({'right': states['ACE'], 'down': states['ACK']})

states['ACE'].update({'down': states['ACEM']})

states['ACEM'].update({'left': states['ACEMK'], 'down': states['ACEMU']})
Example #34
0
 def __init__(self, nfa_states):
   State.__init__(self, 
       name=namegen.next(),
       description=','.join([nfa_state.name for nfa_state in nfa_states]),
       match=any([state.match for state in nfa_states]))
from fsm import StateMachine, State
import time
traffic_light = StateMachine("LIGHT_GREEN")

light_green = State()
light_yellow = State()
light_red = State()

traffic_light["LIGHT_GREEN"] = light_green
traffic_light["LIGHT_YELLOW"] = light_yellow
traffic_light["LIGHT_RED"] = light_red


@light_green.transition
def switch():
    return "LIGHT_YELLOW"


@light_yellow.transition
def switch():
    return "LIGHT_RED"


@light_red.transition
def switch():
    return "LIGHT_GREEN"


if __name__ == "__main__":
    while True:
        print("Current State: " + traffic_light.state)