Ejemplo n.º 1
0
    def test_transition(self):
        sm = StateMachine()
        sm.add(State('online', is_starting_state=True))
        sm.add(State('offline'))

        sm.add(Transition('online', ['offline']))
        sm.transition_to('offline')
Ejemplo n.º 2
0
    def __init__(self, _id=None, level=None, room=None,
                 speed=50, chance_to_hit=0.5, weapon_damage=5, healing=0, max_health=100,
                 health=100, ammo=0, morale=100):
        self._id = _id if _id else str(uuid.uuid4())
        self.level = level
        self.room = room

        self.speed = speed
        self.chance_to_hit = chance_to_hit
        self.weapon_damage = weapon_damage  # Note: should depend on equipment
        self.fight_cooldown = 1.0
        self.healing = healing

        self.health = health
        self.ammo = ammo
        self.morale = morale

        self._path = deque()  # the current path the entity is on
        self._vision = set()  # the rooms currently visible to the entity

        self._timeout = 0

        self._fight_timeout = 0

        def log_state_change(a, b):
            self.log("%s -> %s" % (a, b))
        StateMachine.__init__(self, ["IDLE", "MOVING", "FIGHTING", "DEAD"],
                              on_state_change=log_state_change)
Ejemplo n.º 3
0
    def __init__(self):

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("NEW", self._new_file)
        self.stateMachine.add_state("SAM", self._sam)
        self.stateMachine.add_state("BLOCK", self._block)
        self.stateMachine.add_state("CODEBLOCK-START", self._codeblock_start)
        self.stateMachine.add_state("CODEBLOCK", self._codeblock)
        self.stateMachine.add_state("PARAGRAPH-START", self._paragraph_start)
        self.stateMachine.add_state("PARAGRAPH", self._paragraph)
        self.stateMachine.add_state("RECORD-START", self._record_start)
        self.stateMachine.add_state("RECORD", self._record)
        self.stateMachine.add_state("LIST-ITEM", self._list_item)
        self.stateMachine.add_state("NUM-LIST-ITEM", self._num_list_item)
        self.stateMachine.add_state("BLOCK-INSERT", self._block_insert)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.set_start("NEW")
        self.current_paragraph = None
        self.doc = DocStructure()
        self.source = None
        self.patterns = {
            'comment': re.compile(r'\s*#.*'),
            'block-start':
            re.compile(r'(\s*)([a-zA-Z0-9-_]+):(?:\((.*?)\))?(.*)'),
            'codeblock-start': re.compile(r'(\s*)```(.*)'),
            'codeblock-end': re.compile(r'(\s*)```\s*$'),
            'paragraph-start': re.compile(r'\w*'),
            'blank-line': re.compile(r'^\s*$'),
            'record-start': re.compile(r'\s*[a-zA-Z0-9-_]+::(.*)'),
            'list-item': re.compile(r'(\s*)(\*\s+)(.*)'),
            'num-list-item': re.compile(r'(\s*)([0-9]+\.\s+)(.*)'),
            'block-insert': re.compile(r'(\s*)>>\(.*?\)\w*')
        }
Ejemplo n.º 4
0
    def test_stateMachine_initialState(self):
        """Test State Machine Initial set up."""
        machine                                     = StateMachine(State1)

        self.assertTrue(machine.inState(State1))
        self.assertFalse(State1 in machine.state.movesTo)
        self.assertTrue(State2 in machine.state.movesTo)
Ejemplo n.º 5
0
    def handle_events(self):
        events = pygame.event.get()
        for event in events:
            if event.type == pygame.QUIT:
                self.done = True

        StateMachine.instance().handle_events(events)
Ejemplo n.º 6
0
 def __init__(self, robot_num, sim=False):
     super(Core, self).__init__(robot_num, sim)
     StateMachine.__init__(self)
     self.CC = Chase()
     self.AC = Attack()
     self.BC = Behavior()
     self.sim = sim
Ejemplo n.º 7
0
 def __init__(self, parent=None, tempControllerAddress=None,
              interfaceLock=None, **options):
     tk.Frame.__init__(self, parent)
     self.tempControllerAddress = tempControllerAddress
     self.sm = StateMachine(self, tempControllerAddress, interfaceLock)
     self.pack(**options)
     self.makeWidgets()
 def __init__(self):
     self.m = StateMachine()
     #Declaration of all the states
     self.m.add_state("StateA", self.StateA_transitions)
     self.m.add_state("StateB", self.StateB_transitions)
     self.m.add_state("StateC", self.StateC_transitions)
     self.m.set_start("StateA")
Ejemplo n.º 9
0
def main():
    #This makes it so if you hit CTRL+C curses doesn't eat the terminal alive!
    signal.signal(signal.SIGINT, signal_handler)
    
    #Setup curses
    stdscr = curses.initscr()
    curses.noecho()
    curses.cbreak()
    curses.curs_set(0)
    
    #Create the State Machine instance
    s = StateMachine()
    
    win = curses.newwin(20, 40, 2, 2)
    win.addstr(1, 7, "CODE:\n")
    win.addstr(18, 7, "Press q or CTRL-c to quit.")
    win.border()
    win.refresh()
    
    #This while loop keeps checking the input you type on the keyboard
    while True:
        #Get a single keypress and turn it into a string
        win.border()
        c = chr(win.getch())
        win.addstr(13, 7, "Correct PIN: "+" ".join(s.correct_code))
    
        #if you press q, terminate the program
        if c == 'q':
            break
    
        if c.isalnum():
            win.addstr(10, 7, "Prev PIN: "+" ".join(s.cur_code))
    
            old_state = s.state
            s.do_event(StateMachine.E_KEYPRESS, c)
            new_state = s.state
    
            #Write out some debug data
            win.addstr(15, 7, "OLD STATE: %s        "%s.STATE_NAMES[old_state])
            win.addstr(16, 7, "NEW STATE: %s        "%s.STATE_NAMES[new_state])
            win.addstr(18, 7, "Press q or CTRL-c to quit.")
    
            if s.state == StateMachine.IDLE:
                win.erase()
                win.addstr(1, 7, "CODE:  ")

            win.addstr(2, 7, '* '*len(s.cur_code))
    
            if s.state == StateMachine.CODEOK:
                win.addstr(1, 7, "SUCCESS")
    
            elif s.state == StateMachine.CODEBAD:
                win.addstr(1, 7, "NO!    ")
    
            win.addstr(11, 7, "Curr PIN: "+" ".join(s.cur_code))
    
            #Curses only draws changes to the screen when you ask nicely.
            win.refresh()
    
    cleanup_curses()
Ejemplo n.º 10
0
    def __init__(self):
        self.screen = pygame.display.get_surface()
        self.gamestate = StateMachine()
        self.data = None
        self.video = Video()
        self.audio = Audio(self)

        self.running = False
        self.all_maps_loaded = False
        self.force_bg_music = False

        self.clock = pygame.time.Clock()
        self.playtime = 0.0
        self.dt = 0.0
        self.key_timer = 0.0
        self.state_timer = 0.0

        self.debugfont = pygame.font.SysFont(DEBUGFONT, DEBUGFONTSIZE)
        self.key_input = None
        self.mouse_input = None

        self.show_debug = False
        self.debug_mode = False
        self.fps = FPS

        threading.Thread(target=self.load_all_maps).start()
Ejemplo n.º 11
0
 def __init__(self, sim = False):
   super(Core, self).__init__(sim)
   StateMachine.__init__(self)
   self.CC  = Chase()
   self.BC  = Behavior()
   self.block = 0
   dsrv = DynamicReconfigureServer(PassingConfig, self.Callback)
Ejemplo n.º 12
0
    def test_hooks_order(self):
        result = []

        def hook(s):
            def h():
                result.append(s)

            return h

        sm = StateMachine()
        sm.add(
            State('online',
                  is_starting_state=True,
                  will_exit=hook('onwex'),
                  exited=hook('onex')))
        sm.add(State('offline', will_enter=hook('ofwen'),
                     entered=hook('ofen')))

        sm.add(
            Transition('online', ['offline'],
                       before=hook('tb'),
                       after=hook('ta')))
        sm.transition_to('offline')

        assert result == ['tb', 'onwex', 'ofwen', 'onex', 'ofen', 'ta']
Ejemplo n.º 13
0
class Miner(BaseGameEntity):

    def __init__(self, name):
        self.name = name
        self.location = None
        self.gold = 0
        self.fatigue = 0
        self.thirsty = 0
        self.fsm = StateMachine(self)
        self.fsm.set_current_state(states.GoHomeAndSleepTilRested())

        self.pocket_limit = 10
        self.thirsty_limit = 10
        self.fatigue_limit = 10

    def __repr__(self):
        return '<Miner {0}>'.format(self.name)

    def change_location(self, location):
        self.location = location

    def is_pocket_full(self):
        return self.gold >= self.pocket_limit

    def add_gold_carried(self, n):
        self.gold += n

    def increase_fatigue(self):
        self.fatigue += 1
        self.thirsty += 1

    def is_thirsty(self):
        return self.thirsty >= self.thirsty_limit
Ejemplo n.º 14
0
class Game:
    def __init__(self, context):
        self.ctx = context
        self.m = StateMachine()
        self.m.add_state("init", self.sm_init)
        #       m.add_state("idle", sm_idle)
        self.m.add_state("start", self.sm_start)
        self.m.add_state("end", self.sm_end, end_state=1)
        self.m.set_start("init")
        self.m.run(self.ctx)

    def sm_init(self, ctx):
        # initialize
        newState = "start"
        return newState, ctx

    def sm_start(self, ctx):
        # pick two players, start game
        p1, p2 = self.get_random_players()
        p1.init(10)
        p2.init(10)

        p1.print_status()
        p2.print_status()

        res = None
        player = [p1, p2]
        next_move = 0
        while p1.has_ships() and p2.has_ships():
            x, y = player[next_move].get_move(res)
            res = player[next_move ^ 1].set_move(x, y)
            if res not in ["inj", "sink"]:
                next_move ^= 1

        if p1.has_ships():
            print "Player1 won"
        else:
            print "Player2 won"

        # TODO: should be move to "end" state
        p1.finalize()
        p2.finalize()

        newState = "end"

        return newState, ctx

    def sm_end(self, ctx):
        pass

    def get_random_players(self):
        # ugly:
        players = self.ctx.get_players()
        player1 = players.get_player()
        player2 = players.get_player(not_this_one=player1)
        return player1, player2

    def start_game(self):
        pass
Ejemplo n.º 15
0
    def render(self):
        # Fill render screen
        self.render_screen.fill((0, 0, 0))

        StateMachine.instance().render(self.render_screen)

        pygame.display.flip()
        self.dt = self.clock.tick(Settings.instance().settings['fps']) / 1000
Ejemplo n.º 16
0
 def test_stateMachine_transitions_byAssignment(self):
     """Test State Transations from State 1 to State2."""
     machine                                     = StateMachine(State1)
     self.assertRaises(StateError,               machine.goto, State1)
     self.assertTrue(machine.inState(State1))
     machine.state = State2
     self.assertEqual(machine.message,           'Entered State 2')
     self.assertTrue(machine.inState(State2))
Ejemplo n.º 17
0
 def __init__(self, sim=False):
     super(Core, self).__init__(sim)
     StateMachine.__init__(self)
     self.BC = Behavior()
     self.BK = Block()
     self.left_ang = 0
     self.cp_value = 0
     dsrv = DynamicReconfigureServer(RobotConfig, self.Callback)
Ejemplo n.º 18
0
 def __init__(self, sim=False):
     super(MyStateMachine, self).__init__(sim)
     StateMachine.__init__(self)
     dsrv = DynamicReconfigureServer(RobotConfig, self.callback)
     self.dclient = DynamicReconfigureClient("core",
                                             timeout=30,
                                             config_callback=None)
     self.mir = MIR(HOST)
Ejemplo n.º 19
0
    def __init__(self, fromContainer, toContainer, maxRate=float('inf')):

        self.fromContainer = fromContainer
        self.toContainer = toContainer
        self.maxRate = maxRate

        StateMachine.__init__(self, self.states, self.initial,
                              self.transitions)
Ejemplo n.º 20
0
 def __init__(self, context):
     self.ctx = context
     self.m = StateMachine()
     self.m.add_state("init", self.sm_init)
     #       m.add_state("idle", sm_idle)
     self.m.add_state("start", self.sm_start)
     self.m.add_state("end", self.sm_end, end_state=1)
     self.m.set_start("init")
     self.m.run(self.ctx)
Ejemplo n.º 21
0
    def reset(self):
        """ UpdateStateMachin override.

        """
        StateMachine.reset(self)
        if len(self.ctx.orphaned) > 0:
            print "BUG?: Abandoning orphaned requests."
            self.ctx.orphaned.clear()
        self.ctx = ArchiveUpdateContext(self, self.ctx.ui_)
Ejemplo n.º 22
0
 def __init__(self, sim=False):
     super(Core, self).__init__(sim)
     StateMachine.__init__(self)
     self.CC = Chase()
     self.AC = Attack()
     self.BC = Behavior()
     self.left_ang = 0
     self.dest_angle = 0
     dsrv = DynamicReconfigureServer(RobotConfig, self.Callback)
Ejemplo n.º 23
0
 def __init__(self):
     self.m = StateMachine()
     #Declaration of all the states
     self.m.add_state("Still_state", self.still_state_transitions)
     self.m.add_state("Moving_state", self.moving_state_transitions)
     self.m.add_state("Bumping_state", self.bumping_state_transitions)
     self.m.add_state("Holding_state", self.holding_state_transitions)
     self.m.add_state("Crash_state", self.crash_state_transitions)
     self.m.set_start("Still_state")
Ejemplo n.º 24
0
 def __init__(self, camera, button, led, recording_folder):
     StateMachine.__init__(self)
     self._folder = recording_folder
     self._camera = camera
     self._button = button
     self._led = led
     self._tape = Tape()
     self._events = queue.Queue()
     self._conversion_queue = queue.Queue()
     self._button.add_pressed_cb(self._add_toggle_event)
Ejemplo n.º 25
0
 def __init__(self, robot_num, sim = False):
   super(Core, self).__init__(robot_num, sim)
   StateMachine.__init__(self)
   self.CC  = Chase()
   self.AC  = Attack()
   self.BC  = Behavior()
   self.goal_dis = 0
   self.tStart = time.time()
   self.block = 0
   dsrv = DynamicReconfigureServer(RobotConfig, self.Callback)
Ejemplo n.º 26
0
class AutofabricantesExm:
	
	## Initialization
	def __init__(self):		
		
		logging.basicConfig(level=logging.INFO, format='%(relativeCreated)6d %(threadName)s %(message)s')
				
		## counter
		self.counter  = 0
		
		## default mode
		self.mode = TEST_MODE
		self.setMode()
				
		logging.info("\n---> Setup")

		## inputOutputUtils
		self.inputOutputUtils = InputOutputOutils(self.mode)
		
		## stateMachine
		self.stateMachine = StateMachine(self.inputOutputUtils)
		self.stateMachine.start()
			
		
	## Main execution loop  
	def loop(self):
					
		while(True):
			logging.info("\n---> Loop (%i)", self.counter)
			self.counter = self.counter + 1
			self.stateMachine.executeTransition()
			
	## Reset
	def reset(self): 

		logging.debug("\n---> Reset (%i)", self.counter)		
		self.__init__()
		
 
	## setMode
	def setMode(self):
				
# 		input = GPIO.input(GPIO_INPUT_SWITCH_2)
# 		logging.info("\n---> GPIO_INPUT_SWITCH_0 [%i]", input)
# 		  
# 		if(input == 0):	
# 			## Operation mode					
# 			self.operationMode = OPERATION_MODE
# 		else:
# 			self.operationMode = TEST_MODE
		
		#self.mode = TEST_MODE
		self.mode = OPERATION_MODE
		
		logging.debug("IOUTILS::mode: %d", self.mode)
Ejemplo n.º 27
0
 def __init__(self, startCoordinates, name=''):
     GameEntity.__init__(self, startCoordinates, name)
     self.frameNumber = 1
     self.imageFrame = 0
     self.frameTime = 0.
     self.animationSpeed = 0.5 + randint(-3, 3) / 10.0
     self.frameWidth = 0
     self.speed = 0
     self.width = self.height = 0
     self.brain = StateMachine()
     self.actionQueue = []
Ejemplo n.º 28
0
    def run(self):
        while not self.done:
            self.handle_events()
            self.update()
            self.render()
            StateMachine.instance().change()

            if StateMachine.instance().should_exit:
                self.done = True

        self.quit()
Ejemplo n.º 29
0
    def test_transitions_arent_two_way(self):
        sm = StateMachine()
        sm.add(State('online', is_starting_state=True))
        sm.add(State('offline'))

        sm.add(Transition('offline', ['online']))

        assert not sm.can_transition_to('offline')
Ejemplo n.º 30
0
    def __init__(self, name):
        self.name = name
        self.location = None
        self.gold = 0
        self.fatigue = 0
        self.thirsty = 0
        self.fsm = StateMachine(self)
        self.fsm.set_current_state(states.GoHomeAndSleepTilRested())

        self.pocket_limit = 10
        self.thirsty_limit = 10
        self.fatigue_limit = 10
Ejemplo n.º 31
0
def test_weak_wildcard():
    machine = StateMachine({
        'initial'    : 'a',
        'transitions': [
            # A can only go to b on a 1
            { 'from': 'a', 'on': [1], 'to': 'b'},
            # Always stay on b without erroring
            { 'from': 'a', 'on': [ ] }
        ]
    })
    machine.step(1)
    assert(machine._current == 'b')
Ejemplo n.º 32
0
class Brew(tk.Frame):
    def __init__(self, parent=None, tempControllerAddress=None,
                 interfaceLock=None, **options):
        tk.Frame.__init__(self, parent)
        self.tempControllerAddress = tempControllerAddress
        self.sm = StateMachine(self, tempControllerAddress, interfaceLock)
        self.pack(**options)
        self.makeWidgets()

    def destroy(self):
        self.sm.quit()
        tk.Frame.destroy(self)

    def makeWidgets(self):
        self.brewLabel = BrewLabel(self, brewLabelText=self.tempControllerAddress,
                                   side=tk.TOP,
                                   padx=10, pady=0,
                                   ipadx=5, ipady=5,
                                   anchor='w')
        self.recipeFrame = RecipeScrolledList(self, side=tk.LEFT,
                                              padx=10, pady=5,
                                              ipadx=5, ipady=5)
        self.buttonFrame = ButtonFrame(self, side=tk.LEFT,
                                       padx=10, pady=5,
                                       ipadx=5, ipady=5)
        self.timeFrame = TimeFrame(self, side=tk.LEFT,
                                   padx=10, pady=5,
                                   ipadx=5, ipady=5)
        self.tempFrame = TempFrame(self, side=tk.LEFT,
                                   padx=10, pady=5,
                                   ipadx=5, ipady=5)

    def updateViews(self):
        self.sm.updateViews()
        self.after(500, self.updateViews)

    def getRecipe(self):
        return self.recipeFrame.getCurrentRecipe()

    def getStateMachine(self):
        return self.sm

    def setProcessValue(self, pv):
        self.tempFrame.setProcessValue(pv)

    def setSetValue(self, sv):
        self.tempFrame.setSetValue(sv)

    def setStepTimeLeft(self, stl):
        self.timeFrame.setStepTimeLeft(stl)

    def setTotalTimeLeft(self, ttl):
        self.timeFrame.setTotalTimeLeft(ttl)
Ejemplo n.º 33
0
    def reset(self):
        """ StateMachine override. """
        StateMachine.reset(self)

        ctx = UpdateContext(self)
        ctx.repo = self.ctx.repo
        ctx.ui_ = self.ctx.ui_
        ctx.bundle_cache = self.ctx.bundle_cache
        if len(self.ctx.orphaned) > 0:
            print "BUG?: Abandoning orphaned requests."
            self.ctx.orphaned.clear()

        self.ctx = ctx
Ejemplo n.º 34
0
    def reset(self):
        """ StateMachine override. """
        StateMachine.reset(self)

        ctx = UpdateContext(self)
        ctx.repo = self.ctx.repo
        ctx.ui_ = self.ctx.ui_
        ctx.bundle_cache = self.ctx.bundle_cache
        if len(self.ctx.orphaned) > 0:
            print "BUG?: Abandoning orphaned requests."
            self.ctx.orphaned.clear()

        self.ctx = ctx
Ejemplo n.º 35
0
class AnimatedGameEntity(GameEntity):
    def __init__(self, startCoordinates, name=''):
        GameEntity.__init__(self, startCoordinates, name)
        self.frameNumber = 1
        self.imageFrame = 0
        self.frameTime = 0.
        self.animationSpeed = 0.5 + randint(-3, 3) / 10.0
        self.frameWidth = 0
        self.speed = 0
        self.width = self.height = 0
        self.brain = StateMachine()
        self.actionQueue = []
        
    def set_image(self, image, frameNumber=1):
        self.image = image
        self.frameNumber = frameNumber
        self.frameWidth = self.image.get_width() / self.frameNumber
        self.width, self.height = self.image.get_size()
        
    def render(self, surface, offset):
        surface.blit(self.image, 
                     (self.location.x - offset[0], self.location.y - offset[1]), 
                     (self.frameWidth * self.imageFrame, 0, self.frameWidth, self.height))
    
    def adjustPosition(self, dimension):
        self.location.x = min(self.location.x, dimension[0] - 20)
        self.location.x = max(self.location.x, 10)
        self.location.y = min(self.location.y, dimension[1] - 20)
        self.location.y = max(self.location.y, 10)
    
    def handleAction(self, action):
        raise NotImplementedError, 'Entity %s cannot handle Action %s' % (self.name, action)
    
    def process(self, time_passed):
        self.frameTime += time_passed
        if self.frameTime > self.animationSpeed:
            self.frameTime = 0.
            self.imageFrame = (self.imageFrame + 1) % self.frameNumber

        if self.speed > 0. and self.location != self.destination:
            vec_to_destination = self.destination - self.location
            distance_to_destination = vec_to_destination.get_magnitude()
            heading = vec_to_destination.get_normalized()
            travel_distance = min(distance_to_destination, time_passed * self.speed)
            self.location += heading * travel_distance
        
        if self.actionQueue:
            action = self.actionQueue.pop()
            self.handleAction(action)
        else:
            self.brain.think()
Ejemplo n.º 36
0
    def __init__(self, eventController, capacity=float('inf'), qty=0):

        self.capacity = capacity
        self.qty = qty
        self.inputs = set()
        self.outputs = set()
        self.lastupdate = 0

        StateMachine.__init__(self,
                              self.states,
                              self.initial,
                              self.transitions,
                              prepare_event='prepare')
        EventMember.__init__(self, eventController)
Ejemplo n.º 37
0
    def __init__(self):

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("NEW", self._new_file)
        self.stateMachine.add_state("SAM", self._sam)
        self.stateMachine.add_state("BLOCK", self._block)
        self.stateMachine.add_state("CODEBLOCK-START", self._codeblock_start)
        self.stateMachine.add_state("CODEBLOCK", self._codeblock)
        self.stateMachine.add_state("PARAGRAPH-START", self._paragraph_start)
        self.stateMachine.add_state("PARAGRAPH", self._paragraph)
        self.stateMachine.add_state("RECORD-START", self._record_start)
        self.stateMachine.add_state("RECORD", self._record)
        self.stateMachine.add_state("LIST-ITEM", self._list_item)
        self.stateMachine.add_state("NUM-LIST-ITEM", self._num_list_item)
        self.stateMachine.add_state("BLOCK-INSERT", self._block_insert)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.set_start("NEW")
        self.current_paragraph = None
        self.doc = DocStructure()
        self.source = None
        self.patterns = {
            'comment': re.compile(r'\s*#.*'),
            'block-start': re.compile(r'(\s*)([a-zA-Z0-9-_]+):(?:\((.*?)\))?(.*)'),
            'codeblock-start': re.compile(r'(\s*)```(.*)'),
            'codeblock-end': re.compile(r'(\s*)```\s*$'),
            'paragraph-start': re.compile(r'\w*'),
            'blank-line': re.compile(r'^\s*$'),
            'record-start': re.compile(r'\s*[a-zA-Z0-9-_]+::(.*)'),
            'list-item': re.compile(r'(\s*)(\*\s+)(.*)'),
            'num-list-item': re.compile(r'(\s*)([0-9]+\.\s+)(.*)'),
            'block-insert': re.compile(r'(\s*)>>\(.*?\)\w*')
        }
Ejemplo n.º 38
0
    def __init__(self):
        # These attributes are set by the parse method
        self.doc = None
        self.para = None
        self.current_string = None
        self.flow = None

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("PARA", self._para)
        self.stateMachine.add_state("ESCAPE", self._escape)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.add_state("ANNOTATION-START", self._annotation_start)
        self.stateMachine.add_state("CITATION-START", self._citation_start)
        self.stateMachine.add_state("BOLD-START", self._bold_start)
        self.stateMachine.add_state("ITALIC-START", self._italic_start)
        self.stateMachine.add_state("CODE-START", self._code_start)
        self.stateMachine.add_state("QUOTES-START", self._quotes_start)
        self.stateMachine.add_state("INLINE-INSERT", self._inline_insert)
        self.stateMachine.add_state("CHARACTER-ENTITY", self._character_entity)
        self.stateMachine.set_start("PARA")
        self.patterns = {
            'escape': re.compile(r'\\', re.U),
            'escaped-chars': re.compile(r'[\\\(\{\}\[\]_\*,\.\*`"&]', re.U),
            'annotation': re.compile(
                r'(?<!\\)\{(?P<text>.*?)(?<!\\)\}(\(\s*(?P<type>\S*?\s*[^\\"\']?)(["\'](?P<specifically>.*?)["\'])??\s*(\((?P<namespace>\w+)\))?\s*(~(?P<language>[\w-]+))?\))?', re.U),
            'bold': re.compile(r'\*(?P<text>((?<=\\)\*|[^\*])*)(?<!\\)\*', re.U),
            'italic': re.compile(r'_(?P<text>((?<=\\)_|[^_])*)(?<!\\)_', re.U),
            'code': re.compile(r'`(?P<text>(``|[^`])*)`', re.U),
            'quotes': re.compile(r'"(?P<text>((?<=\\)"|[^"])*)(?<!\\)"', re.U),
            'inline-insert': re.compile(r'>\((?P<attributes>.*?)\)', re.U),
            'character-entity': re.compile(r'&(\#[0-9]+|#[xX][0-9a-fA-F]+|[\w]+);'),
            'citation': re.compile(r'(\[\s*\*(?P<id>\S+)(\s+(?P<id_extra>.+?))?\])|(\[\s*\#(?P<name_name>\S+)(\s+(?P<extra>.+?))?\])|(\[\s*(?P<citation>.*?)\])', re.U)
        }
Ejemplo n.º 39
0
    def __init__(self):
        # These attributes are set by the parse method
        self.doc = None
        self.para = None
        self.current_string = None
        self.flow = None

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("PARA", self._para)
        self.stateMachine.add_state("ESCAPE", self._escape)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.add_state("ANNOTATION-START", self._annotation_start)
        self.stateMachine.add_state("CITATION-START", self._citation_start)
        self.stateMachine.add_state("BOLD-START", self._bold_start)
        self.stateMachine.add_state("ITALIC-START", self._italic_start)
        self.stateMachine.add_state("MONO-START", self._mono_start)
        self.stateMachine.add_state("QUOTES-START", self._quotes_start)
        self.stateMachine.add_state("INLINE-INSERT", self._inline_insert)
        self.stateMachine.set_start("PARA")
        self.patterns = {
            "escape": re.compile(r"\\"),
            "escaped-chars": re.compile(r"[\\\(\{\}\[\]_\*,`]"),
            "annotation": re.compile(
                r'(?<!\\)\{(?P<text>.*?)(?<!\\)\}(\(\s*(?P<type>\S*?\s*[^\\"\']?)(["\'](?P<specifically>.*?)["\'])??\s*(\((?P<namespace>\w+)\))?\))?'
            ),
            "bold": re.compile(r"\*(?P<text>\S.+?\S)\*"),
            "italic": re.compile(r"_(?P<text>\S.*?\S)_"),
            "mono": re.compile(r"`(?P<text>\S.*?\S)`"),
            "quotes": re.compile(r'"(?P<text>\S.*?\S)"'),
            "inline-insert": re.compile(r">>\((?P<attributes>.*?)\)"),
            "citation": re.compile(
                r"(\[\s*\*(?P<id>\S+)(\s+(?P<id_extra>.+?))?\])|(\[\s*\#(?P<name_name>\S+)(\s+(?P<extra>.+?))?\])|(\[\s*(?P<citation>.*?)\])"
            ),
        }
Ejemplo n.º 40
0
    def __init__(self):
        self.screen = pygame.display.get_surface()
        self.gamestate = StateMachine()
        self.data = None
        self.video = Video()
        self.audio = Audio(self)

        self.running = False
        self.all_maps_loaded = False
        self.force_bg_music = False

        self.clock = pygame.time.Clock()
        self.playtime = 0.0
        self.dt = 0.0
        self.key_timer = 0.0
        self.state_timer = 0.0

        self.debugfont = pygame.font.SysFont(DEBUGFONT, DEBUGFONTSIZE)
        self.key_input = None
        self.mouse_input = None

        self.show_debug = False
        self.debug_mode = True
        self.fps = FPS

        threading.Thread(target=self.load_all_maps).start()
Ejemplo n.º 41
0
	def __init__(self,argv):
		#self.argv=argv
		self.params={'-h':'localhost','-d':'','-s':'','-u':'SYSDBA','-p':'masterkey'}
		self.ch='UTF8'
		self.ch=self.detect_codecs()
		self.mydb=None
		self.cmd=None
		self.sm = StateMachine()
		self.create_state(self.sm)
		self.parse_cmd(argv)
Ejemplo n.º 42
0
    def __init__(self):
        #Create the State Machine instance
        self._sm = StateMachine()

        #The following two lines simply create the attributes for the instance
        #and assign them blank values so you can read them later and not get
        #an error even if you havn't set a real value to them. This is good 
        #practice for understanding how your class is structured, and avoiding
        #errors when returning None means more. None is a special value for 
        #variables that marks a variable as empty.
        self.stdscr = None
        self.win = None
Ejemplo n.º 43
0
class Wife(BaseGameEntity):
    def __init__(self, name):
        self.name = name
        self.fsm = StateMachine(self)
        self.fsm.set_current_state(states.DoHouseWork())
        self.fsm.set_global_state(states.WifeGlobalState())

    def update(self):
        self.fsm.update()

    def handle_msg(self, sender, msg):
        return self.fsm.handle_message(sender, self, msg)
Ejemplo n.º 44
0
	def __init__(self,db,file_name,log_file_name=None):
		self.sm = StateMachine()
		self.db=db
		self.cur = self.db.cursor()
		file=codecs.open(file_name,'r','utf8')
		if log_file_name: self.log=codecs.open(log_file_name,'w','utf8')
		self.line=self.get_script_line(file)
		self.SQL=u''
		self.r=re.compile('SET[\\s]+TERM')
		self.ex_term=';'
		self.create_state(self.sm)
		self.State=''
		self.log=None
		print "Parse script class"
Ejemplo n.º 45
0
    def __init__(self):

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("NEW", self._new_file)
        self.stateMachine.add_state("SAM", self._sam)
        self.stateMachine.add_state("BLOCK", self._block)
        self.stateMachine.add_state("CODEBLOCK-START", self._codeblock_start)
        self.stateMachine.add_state("CODEBLOCK", self._codeblock)
        self.stateMachine.add_state("BLOCKQUOTE-START", self._blockquote_start)
        self.stateMachine.add_state("FRAGMENT-START", self._fragment_start)
        self.stateMachine.add_state("PARAGRAPH-START", self._paragraph_start)
        self.stateMachine.add_state("PARAGRAPH", self._paragraph)
        self.stateMachine.add_state("RECORD-START", self._record_start)
        self.stateMachine.add_state("RECORD", self._record)
        self.stateMachine.add_state("LIST-ITEM", self._list_item)
        self.stateMachine.add_state("NUM-LIST-ITEM", self._num_list_item)
        self.stateMachine.add_state("LABELED-LIST-ITEM", self._labeled_list_item)
        self.stateMachine.add_state("BLOCK-INSERT", self._block_insert)
        self.stateMachine.add_state("STRING-DEF", self._string_def)
        self.stateMachine.add_state("LINE-START", self._line_start)
        self.stateMachine.add_state("EMBEDDED-XML", self._embedded_xml)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.set_start("NEW")
        self.current_paragraph = None
        self.doc = DocStructure()
        self.source = None
        self.patterns = {
            "sam-declaration": re.compile(r"sam:\s*(?:(?:\{(?P<namespace>\S+?)\})|(?P<schema>\S+))?"),
            "comment": re.compile(r"\s*#.*"),
            "block-start": re.compile(
                r"(?P<indent>\s*)(?P<element>[\w_\.-]+?):(\((?P<attributes>.*?(?<!\\))\))?(?P<content>.+)?"
            ),
            "codeblock-start": re.compile(
                r'(?P<indent>\s*)(?P<flag>```[^\s\(]*)(\((?P<language>\w*)\s*(["\'](?P<source>.+?)["\'])?\s*(\((?P<namespace>\S+?)\))?(?P<other>.+?)?\))?'
            ),
            "blockquote-start": re.compile(
                r'(?P<indent>\s*)("""|\'\'\'|blockquote:)(\((?P<attributes>.*?(?<!\\))\))?((\[\s*\*(?P<id>\S+)(?P<id_extra>.+?)\])|(\[\s*\#(?P<name>\S+)(?P<name_extra>.+?)\])|(\[\s*(?P<citation>.*?)\]))?'
            ),
            "fragment-start": re.compile(r"(?P<indent>\s*)~~~(\((?P<attributes>.*?)\))?"),
            "paragraph-start": re.compile(r"\w*"),
            "line-start": re.compile(r"(?P<indent>\s*)\|(\((?P<attributes>.*?)\))?\s(?P<text>.*)"),
            "blank-line": re.compile(r"^\s*$"),
            "record-start": re.compile(r"(?P<indent>\s*)(?P<record_name>[a-zA-Z0-9-_]+)::(?P<field_names>.*)"),
            "list-item": re.compile(r"(?P<indent>\s*)(?P<marker>\*\s+)(?P<content>.*)"),
            "num-list-item": re.compile(r"(?P<indent>\s*)(?P<marker>[0-9]+\.\s+)(?P<content>.*)"),
            "labeled-list-item": re.compile(r"(?P<indent>\s*)\|(?P<label>\S.*?)(?<!\\)\|\s+(?P<content>.*)"),
            "block-insert": re.compile(r"(?P<indent>\s*)>>\((?P<attributes>.*?)\)\w*"),
            "string-def": re.compile(r"(?P<indent>\s*)\$(?P<name>\w*?)=(?P<value>.+)"),
            "embedded-xml": re.compile(r"(?P<indent>\s*)(?P<xmltag>\<\?xml.+)"),
        }
Ejemplo n.º 46
0
 def test_stateMachine_finalState(self):
     """Test Final State."""
     machine                                     = StateMachine(State1)
     self.assertTrue(machine.inState(State1))
     machine.goto(State2)
     self.assertTrue(machine.inState(State2))
     self.assertFalse(State1 in machine.state.movesTo)
     self.assertFalse(State2 in machine.state.movesTo)
     self.assertRaises(StateError,               machine.goto, State1)
     self.assertRaises(StateError,               machine.goto, State2)
     self.assertTrue(machine.inState(State2))
Ejemplo n.º 47
0
    def __init__(self):

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("NEW", self._new_file)
        self.stateMachine.add_state("SAM", self._sam)
        self.stateMachine.add_state("BLOCK", self._block)
        self.stateMachine.add_state("CODEBLOCK-START", self._codeblock_start)
        self.stateMachine.add_state("CODEBLOCK", self._codeblock)
        self.stateMachine.add_state("BLOCKQUOTE-START", self._blockquote_start)
        self.stateMachine.add_state("FRAGMENT-START", self._fragment_start)
        self.stateMachine.add_state("PARAGRAPH-START", self._paragraph_start)
        self.stateMachine.add_state("PARAGRAPH", self._paragraph)
        self.stateMachine.add_state("RECORD-START", self._record_start)
        self.stateMachine.add_state("RECORD", self._record)
        self.stateMachine.add_state("LIST-ITEM", self._list_item)
        self.stateMachine.add_state("NUM-LIST-ITEM", self._num_list_item)
        self.stateMachine.add_state("LABELED-LIST-ITEM", self._labeled_list_item)
        self.stateMachine.add_state("BLOCK-INSERT", self._block_insert)
        self.stateMachine.add_state("STRING-DEF", self._string_def)
        self.stateMachine.add_state("LINE-START", self._line_start)
        self.stateMachine.add_state("EMBEDDED-XML", self._embedded_xml)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.set_start("NEW")
        self.current_text_block = None
        self.doc = DocStructure()
        self.source = None
        self.patterns = {
            'sam-declaration': re.compile(r'sam:\s*(?:(?:\{(?P<namespace>\S+?)\})|(?P<schema>\S+))?', re.U),
            'comment': re.compile(re_indent + re_comment, re.U),
            'block-start': re.compile(re_indent + re_name + r':' + re_attributes + re_content + r'?', re.U),
            'codeblock-start': re.compile(re_indent + r'(?P<flag>```[^\s\(]*)(\((?P<language>\S*)\s*(["\'](?P<source>.+?)["\'])?\s*(\((?P<namespace>\S+?)\))?(?P<other>.+?)?\))?', re.U),
            'blockquote-start': re.compile(re_indent + r'("""|\'\'\'|blockquote:)' + re_attributes + r'((\[\s*\*(?P<id>\S+)(?P<id_extra>.+?)\])|(\[\s*\#(?P<name>\S+)(?P<name_extra>.+?)\])|(\[\s*(?P<citation>.*?)\]))?', re.U),
            'fragment-start': re.compile(re_indent + r'~~~' + re_attributes, re.U),
            'paragraph-start': re.compile(r'\w*', re.U),
            'line-start': re.compile(re_indent + r'\|' + re_attributes + re_one_space + re_content, re.U),
            'blank-line': re.compile(r'^\s*$'),
            'record-start': re.compile(re_indent + re_name + r'::(?P<field_names>.*)', re.U),
            'list-item': re.compile(re_indent + re_ul_marker + re_attributes + re_spaces + re_content, re.U),
            'num-list-item': re.compile(re_indent + re_ol_marker + re_attributes + re_spaces + re_content, re.U),
            'labeled-list-item': re.compile(re_indent + re_ll_marker + re_attributes + re_spaces + re_content, re.U),
            'block-insert': re.compile(re_indent + r'>>>' + re_attributes, re.U),
            'string-def': re.compile(re_indent + r'\$' + re_name + '=' + re_content, re.U),
            'embedded-xml': re.compile(re_indent + r'(?P<xmltag>\<\?xml.+)', re.U)
        }
Ejemplo n.º 48
0
class Game:
    def __init__(self, ip="127.0.0.1", resources=None, songs=None, states=None):
        self.rgb = RGB(ip)
        self.rgb.invertedX = False
        self.rgb.invertedY = True

        self.framerate = 20

        self.previousControllerState = []
        self.controllers = []
        self.controllerOrientations = []

        if not resources:
            resources = []
        if not songs:
            songs = []
        if not states:
            states = []

        self.stateMachine = StateMachine(states)

        self.music = MusicManager(songs)

        pygame.init()
        pygame.joystick.init()
        pygame.mixer.init()

        self.resources = {}
        for r in resources:
            r.load()
            if self.resources.has_key(r.name):
                print "double resource key: '", r.name,"'"

            self.resources[r.name] = r

        pygame.display.set_mode([200,100])
        self.playerCount = pygame.joystick.get_count()
        print str(self.playerCount) + " Joysticks connected."

        for i in range(self.playerCount):
            joystick = pygame.joystick.Joystick(i)
            self.controllers.append(joystick)
            joystick.init()
            self.previousControllerState.append({
                'xAxis': 0,
                'yAxis': 0,
                'aButton': False,
                'bButton': False,
                'cButton': False,
                'dButton': False
            })
            self.controllerOrientations.append(Orientation.South)

        self.keyboardJoystick = False
        if self.playerCount == 0:
            self.playerCount = 2
            self.keyboardJoystick = True
            self.previousControllerState.append({
                'xAxis': 0,
                'yAxis': 0,
                'aButton': False,
                'bButton': False,
                'cButton': False,
                'dButton': False
            })
            self.controllers.append(KeyboardController(id=0))
            self.controllerOrientations.append(Orientation.South)

            self.previousControllerState.append({
                'xAxis': 0,
                'yAxis': 0,
                'aButton': False,
                'bButton': False,
                'cButton': False,
                'dButton': False
            })
            self.controllers.append(KeyboardController(id=1))
            self.controllerOrientations.append(Orientation.South)

        self.lastFrame = time.time()

    def poll(self, dt):
        pygame.event.pump()


        if self.keyboardJoystick:
            events = pygame.event.get()

        for player in range(len(self.controllers)):
            controller = self.controllers[player]

            if self.keyboardJoystick:
                controller.set_events(events)

            previousControllerState = self.previousControllerState[player]

            xAxis = -controller.get_axis(0)
            yAxis = -controller.get_axis(1)

            previousXAxis = previousControllerState['xAxis']
            previousYAxis = previousControllerState['yAxis']
            xChanged = previousXAxis != xAxis
            yChanged = previousYAxis != yAxis

            if xChanged or yChanged:
                xAxis, yAxis = self._mapAxisToOrientation(player, xAxis, yAxis)
                self.onAxisChanged(player, xAxis, yAxis, previousXAxis, previousYAxis)

                previousControllerState['xAxis'] = xAxis
                previousControllerState['yAxis'] = yAxis

            aButton = controller.get_button(0)
            bButton = controller.get_button(1)
            cButton = controller.get_button(2)
            dButton = controller.get_button(3)
            previousAButton = previousControllerState['aButton']
            previousBButton = previousControllerState['bButton']
            previousCButton = previousControllerState['cButton']
            previousDButton = previousControllerState['dButton']
            aChanged = previousAButton != aButton
            bChanged = previousBButton != bButton
            cChanged = previousCButton != cButton
            dChanged = previousDButton != dButton

            if aChanged or bChanged:
                self.onButtonChanged(player, aButton, bButton, previousAButton, previousBButton)

                previousControllerState['aButton'] = aButton
                previousControllerState['bButton'] = bButton

            if cChanged:
                if not cButton:
                    self._onChangeOrientation(player)

                previousControllerState['cButton'] = cButton

            if dChanged:
                if not dButton:
                    self.onStartMenuTriggered(player)

                previousControllerState['dButton'] = dButton

    def run(self):
        clock = pygame.time.Clock()
        while True:
            dt = clock.tick(self.framerate) / 1000.0
            #dt = time.time() - self.lastFrame

            self.update(dt)

            self.draw(self.rgb)

            self.rgb.send()

            self.lastFrame = time.time()

    def update(self, dt):
        self.poll(dt)

        self.stateMachine.update(dt)

    def draw(self, rgb):
        rgb.clear(BLACK)

        self.stateMachine.draw(rgb)

    def onAxisChanged(self, player, xAxis, yAxis, previousXAxis, previousYAxis):
        #todo rotation

        if (self._notIsZero(xAxis) and self._isZero(previousXAxis)) or \
           (self._notIsZero(yAxis) and self._isZero(previousYAxis)):

            x = 1 if xAxis > 0.1 else 0
            x = -1 if xAxis < -0.1 else x
            y = 1 if yAxis > 0.1 else 0
            y = -1 if yAxis < -0.1 else y

            if x != 0 or y != 0:
                self.onClampedAxisChanged(player, x, y)

        self.stateMachine.onAxisChanged(player, xAxis, yAxis, previousXAxis, previousYAxis)

    def onButtonChanged(self, player, aButton, bButton, previousAButton, previousBButton):
        self.stateMachine.onButtonChanged(player, aButton, bButton, previousAButton, previousBButton)

    def onClampedAxisChanged(self, player, x, y):
        self.stateMachine.onClampedAxisChanged(player, x, y)

    def playSound(self, name):
        res = self.resources[name]
        if isinstance(res, Sound):
            self.resources[name].play()
        else:
            print "tried to play non-sound resource"

    def stopSound(self, name):
        res = self.resources[name]
        if isinstance(res, Sound):
            self.resources[name].stop()
        else:
            print "tried to stop non-sound resource"

    def fadeoutSound(self, name, time):
        res = self.resources[name]
        if isinstance(res, Sound):
            self.resources[name].fadeout(time)
        else:
            print "tried to fadeout non-sound resource"

    def setState(self, name):
        self.stateMachine.setState(name)

    def onStartMenuTriggered(self, player):
        sys.exit(0)

    def _isZero(self, d):
        return abs(d) < 0.1

    def _notIsZero(self, d):
        return abs(d) > 0.1

    def _mapAxisToOrientation(self, player, xAxis, yAxis):
        orientation = self.controllerOrientations[player]

        if orientation == Orientation.North:
            xAxis = -xAxis
            yAxis = -yAxis
        elif orientation == Orientation.West:
            xTmp = xAxis
            xAxis = -yAxis
            yAxis = xTmp
        elif orientation == Orientation.East:
            xTmp = xAxis
            xAxis = yAxis
            yAxis = -xTmp

        return xAxis, yAxis

    def _onChangeOrientation(self, player):
        self.controllerOrientations[player] = (self.controllerOrientations[player] + 1) % Orientation.Count
Ejemplo n.º 49
0
def startthegoddamnedgame():
    m = StateMachine()
    m.add_state("GameStarts", game_started)
    m.add_state("p1TurnStart", p1_turn_start)
    m.add_state("p2TurnStart", p2_turn_start)
    m.add_state("p1TurnEnd", p1_turn_end)
    m.add_state("p2TurnEnd", p2_turn_end)
    m.add_state("p1Win", p1_win)
    m.add_state("p2Win", p2_win)
    m.add_state("Game_Over", None, end_state=1)
    m.set_start("GameStarts")
    m.run(allTiles)
Ejemplo n.º 50
0
class SamParaParser:
    def __init__(self):
        # These attributes are set by the parse method
        self.doc = None
        self.para = None
        self.current_string = None
        self.flow = None

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("PARA", self._para)
        self.stateMachine.add_state("ESCAPE", self._escape)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.add_state("ANNOTATION-START", self._annotation_start)
        self.stateMachine.add_state("CITATION-START", self._citation_start)
        self.stateMachine.add_state("BOLD-START", self._bold_start)
        self.stateMachine.add_state("ITALIC-START", self._italic_start)
        self.stateMachine.add_state("MONO-START", self._mono_start)
        self.stateMachine.add_state("QUOTES-START", self._quotes_start)
        self.stateMachine.add_state("INLINE-INSERT", self._inline_insert)
        self.stateMachine.set_start("PARA")
        self.patterns = {
            "escape": re.compile(r"\\"),
            "escaped-chars": re.compile(r"[\\\(\{\}\[\]_\*,`]"),
            "annotation": re.compile(
                r'(?<!\\)\{(?P<text>.*?)(?<!\\)\}(\(\s*(?P<type>\S*?\s*[^\\"\']?)(["\'](?P<specifically>.*?)["\'])??\s*(\((?P<namespace>\w+)\))?\))?'
            ),
            "bold": re.compile(r"\*(?P<text>\S.+?\S)\*"),
            "italic": re.compile(r"_(?P<text>\S.*?\S)_"),
            "mono": re.compile(r"`(?P<text>\S.*?\S)`"),
            "quotes": re.compile(r'"(?P<text>\S.*?\S)"'),
            "inline-insert": re.compile(r">>\((?P<attributes>.*?)\)"),
            "citation": re.compile(
                r"(\[\s*\*(?P<id>\S+)(\s+(?P<id_extra>.+?))?\])|(\[\s*\#(?P<name_name>\S+)(\s+(?P<extra>.+?))?\])|(\[\s*(?P<citation>.*?)\])"
            ),
        }

    def parse(self, para, doc, strip=True):
        if para is None:
            return None
        self.doc = doc
        self.para = Para(para, strip)
        self.current_string = ""
        self.flow = Flow()
        self.stateMachine.run(self.para)
        return self.flow

    def _para(self, para):
        try:
            char = para.next_char
        except IndexError:
            self.flow.append(self.current_string)
            self.current_string = ""
            return "END", para
        if char == "\\":
            return "ESCAPE", para
        elif char == "{":
            return "ANNOTATION-START", para
        elif char == "[":
            return "CITATION-START", para
        elif char == "*":
            return "BOLD-START", para
        elif char == "_":
            return "ITALIC-START", para
        elif char == "`":
            return "MONO-START", para
        elif char == '"':
            return "QUOTES-START", para
        elif char == ">":
            return "INLINE-INSERT", para
        else:
            self.current_string += char
            return "PARA", para

    def _annotation_start(self, para):
        match = self.patterns["annotation"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            annotation_type = match.group("type")
            text = match.group("text")

            # If there is an annotated phrase with no annotation, look back
            # to see if it has been annotated already, and if so, copy the
            # closest preceding annotation.
            if annotation_type is None:
                # First look back in the current flow
                # (which is not part of the doc structure yet).
                previous = self.flow.find_last_annotation(text)
                if previous is not None:
                    self.flow.append(previous)
                else:
                    # Then look back in the document.
                    previous = self.doc.find_last_annotation(text)
                    if previous is not None:
                        self.flow.append(previous)

                    # Else raise an exception.
                    else:
                        raise SAMParserError(
                            "Blank annotation found: {"
                            + text
                            + "} "
                            + "If you are trying to insert curly braces "
                            + "into the document, use \{"
                            + text
                            + "]. Otherwise, make sure annotated text matches "
                            "previous annotation exactly."
                        )
            elif annotation_type.strip() == "":
                raise SAMParserError("Annotation type cannot be blank: " + match.group(0))
            else:
                # Check for link shortcut
                if urlparse(annotation_type, None).scheme is not None:
                    specifically = annotation_type
                    annotation_type = "link"
                else:
                    specifically = match.group("specifically") if match.group("specifically") is not None else None
                namespace = match.group("namespace").strip() if match.group("namespace") is not None else None
                self.flow.append(Annotation(annotation_type.strip(), text, specifically, namespace))
            para.advance(len(match.group(0)) - 1)
            return "PARA", para
        else:
            self.current_string += "{"
            return "PARA", para

    def _citation_start(self, para):
        match = self.patterns["citation"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""

            try:
                idref = match.group("id")
            except IndexError:
                idref = None
            try:
                nameref = match.group("name")
            except IndexError:
                nameref = None
            try:
                citation = match.group("citation")
            except IndexError:
                citation = None

            if idref:
                citation_type = "idref"
                citation_value = idref.strip()
                extra = match.group("id_extra")
            elif nameref:
                citation_type = "nameref"
                citation_value = nameref.strip()
                extra = match.group("name_extra")
            else:
                citation_type = "citation"
                citation_value = citation.strip()
                extra = None

            self.flow.append(Citation(citation_type, citation_value, extra))
            para.advance(len(match.group(0)) - 1)
            return "PARA", para
        else:
            self.current_string += "["
            return "PARA", para

    def _bold_start(self, para):
        match = self.patterns["bold"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            self.flow.append(Decoration("bold", match.group("text")))
            para.advance(len(match.group(0)) - 1)
        else:
            self.current_string += "*"
        return "PARA", para

    def _italic_start(self, para):
        match = self.patterns["italic"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            self.flow.append(Decoration("italic", match.group("text")))
            para.advance(len(match.group(0)) - 1)
        else:
            self.current_string += "_"
        return "PARA", para

    def _mono_start(self, para):
        match = self.patterns["mono"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            self.flow.append(Decoration("mono", match.group("text")))
            para.advance(len(match.group(0)) - 1)
        else:
            self.current_string += "`"
        return "PARA", para

    def _quotes_start(self, para):
        match = self.patterns["quotes"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            self.flow.append(Decoration("quotes", match.group("text")))
            para.advance(len(match.group(0)) - 1)
        else:
            self.current_string += '"'
        return "PARA", para

    def _inline_insert(self, para):
        match = self.patterns["inline-insert"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            self.flow.append(InlineInsert(parse_insert(match.group("attributes"))))
            para.advance(len(match.group(0)) - 1)
        else:
            self.current_string += ">"
        return "PARA", para

    def _inline_insert_id(self, para):
        match = self.patterns["inline-insert_id"].match(para.rest_of_para)
        if match:
            self.flow.append(self.current_string)
            self.current_string = ""
            self.flow.append(InlineInsert("reference", match.group("id")))
            para.advance(len(match.group(0)) - 1)
        else:
            self.current_string += ">"
        return "PARA", para

    def _escape(self, para):
        char = para.next_char
        if self.patterns["escaped-chars"].match(char):
            self.current_string += char
        else:
            self.current_string += "\\" + char
        return "PARA", para
Ejemplo n.º 51
0
class SamParser:
    def __init__(self):

        self.stateMachine = StateMachine()
        self.stateMachine.add_state("NEW", self._new_file)
        self.stateMachine.add_state("SAM", self._sam)
        self.stateMachine.add_state("BLOCK", self._block)
        self.stateMachine.add_state("CODEBLOCK-START", self._codeblock_start)
        self.stateMachine.add_state("CODEBLOCK", self._codeblock)
        self.stateMachine.add_state("BLOCKQUOTE-START", self._blockquote_start)
        self.stateMachine.add_state("FRAGMENT-START", self._fragment_start)
        self.stateMachine.add_state("PARAGRAPH-START", self._paragraph_start)
        self.stateMachine.add_state("PARAGRAPH", self._paragraph)
        self.stateMachine.add_state("RECORD-START", self._record_start)
        self.stateMachine.add_state("RECORD", self._record)
        self.stateMachine.add_state("LIST-ITEM", self._list_item)
        self.stateMachine.add_state("NUM-LIST-ITEM", self._num_list_item)
        self.stateMachine.add_state("LABELED-LIST-ITEM", self._labeled_list_item)
        self.stateMachine.add_state("BLOCK-INSERT", self._block_insert)
        self.stateMachine.add_state("STRING-DEF", self._string_def)
        self.stateMachine.add_state("LINE-START", self._line_start)
        self.stateMachine.add_state("EMBEDDED-XML", self._embedded_xml)
        self.stateMachine.add_state("END", None, end_state=1)
        self.stateMachine.set_start("NEW")
        self.current_paragraph = None
        self.doc = DocStructure()
        self.source = None
        self.patterns = {
            "sam-declaration": re.compile(r"sam:\s*(?:(?:\{(?P<namespace>\S+?)\})|(?P<schema>\S+))?"),
            "comment": re.compile(r"\s*#.*"),
            "block-start": re.compile(
                r"(?P<indent>\s*)(?P<element>[\w_\.-]+?):(\((?P<attributes>.*?(?<!\\))\))?(?P<content>.+)?"
            ),
            "codeblock-start": re.compile(
                r'(?P<indent>\s*)(?P<flag>```[^\s\(]*)(\((?P<language>\w*)\s*(["\'](?P<source>.+?)["\'])?\s*(\((?P<namespace>\S+?)\))?(?P<other>.+?)?\))?'
            ),
            "blockquote-start": re.compile(
                r'(?P<indent>\s*)("""|\'\'\'|blockquote:)(\((?P<attributes>.*?(?<!\\))\))?((\[\s*\*(?P<id>\S+)(?P<id_extra>.+?)\])|(\[\s*\#(?P<name>\S+)(?P<name_extra>.+?)\])|(\[\s*(?P<citation>.*?)\]))?'
            ),
            "fragment-start": re.compile(r"(?P<indent>\s*)~~~(\((?P<attributes>.*?)\))?"),
            "paragraph-start": re.compile(r"\w*"),
            "line-start": re.compile(r"(?P<indent>\s*)\|(\((?P<attributes>.*?)\))?\s(?P<text>.*)"),
            "blank-line": re.compile(r"^\s*$"),
            "record-start": re.compile(r"(?P<indent>\s*)(?P<record_name>[a-zA-Z0-9-_]+)::(?P<field_names>.*)"),
            "list-item": re.compile(r"(?P<indent>\s*)(?P<marker>\*\s+)(?P<content>.*)"),
            "num-list-item": re.compile(r"(?P<indent>\s*)(?P<marker>[0-9]+\.\s+)(?P<content>.*)"),
            "labeled-list-item": re.compile(r"(?P<indent>\s*)\|(?P<label>\S.*?)(?<!\\)\|\s+(?P<content>.*)"),
            "block-insert": re.compile(r"(?P<indent>\s*)>>\((?P<attributes>.*?)\)\w*"),
            "string-def": re.compile(r"(?P<indent>\s*)\$(?P<name>\w*?)=(?P<value>.+)"),
            "embedded-xml": re.compile(r"(?P<indent>\s*)(?P<xmltag>\<\?xml.+)"),
        }

    def parse(self, source):
        self.source = StringSource(source)
        try:
            self.stateMachine.run(self.source)
        except EOFError:
            raise SAMParserError("Document ended before structure was complete. At:\n\n" + self.current_paragraph)

    def paragraph_start(self, line):
        self.current_paragraph = line.strip()

    def paragraph_append(self, line):
        self.current_paragraph += " " + line.strip()

    def pre_start(self, line):
        self.current_paragraph = line

    def pre_append(self, line):
        self.current_paragraph += line

    def _new_file(self, source):
        line = source.next_line
        match = self.patterns["sam-declaration"].match(line)
        if match:
            self.doc.new_root(match)
            return "SAM", (source, None)
        else:
            raise SAMParserError("Not a SAM file!")

    def _block(self, context):
        source, match = context
        indent = len(match.group("indent"))
        element = match.group("element").strip()
        attributes = self.parse_block_attributes(match.group("attributes"))
        content = match.group("content")
        self.doc.new_block(element, attributes, para_parser.parse(content, self.doc), indent)
        return "SAM", context

    def _codeblock_start(self, context):
        source, match = context
        indent = len(match.group("indent"))
        codeblock_flag = match.group("flag")
        self.patterns["codeblock-end"] = re.compile(r"(\s*)" + codeblock_flag + "\s*$")

        attributes = {}

        language = match.group("language")
        if language is not None:
            attributes["language"] = language

        source = match.group("source")
        if source is not None:
            attributes["source"] = source

        namespace = match.group("namespace")
        if namespace is not None:
            attributes["namespace"] = namespace

        other = match.group("other")
        if other is not None:
            attributes.update(self.parse_block_attributes(other))

        self.doc.new_block("codeblock", attributes, None, indent)
        self.pre_start("")
        return "CODEBLOCK", context

    def _codeblock(self, context):
        source, match = context
        line = source.next_line
        if self.patterns["codeblock-end"].match(line):
            self.doc.new_flow(Pre(self.current_paragraph))
            return "SAM", context
        else:
            self.pre_append(line)
            return "CODEBLOCK", context

    def _blockquote_start(self, context):
        source, match = context
        indent = len(match.group("indent"))

        # TODO: Refactor this with the paraparser version

        extra = source.current_line.rstrip()[len(match.group(0)) :]
        if extra:
            raise SAMParserError("Extra text found after blockquote start: " + extra)

        attributes = self.parse_block_attributes(match.group("attributes"))

        b = self.doc.new_block("blockquote", attributes, None, indent)

        # see if there is a citation
        try:
            idref = match.group("id")
        except IndexError:
            idref = None
        try:
            nameref = match.group("name")
        except IndexError:
            nameref = None
        try:
            citation = match.group("citation")
        except IndexError:
            citation = None

        if idref:
            citation_type = "idref"
            citation_value = idref.strip()
            extra = match.group("id_extra")
        elif nameref:
            citation_type = "nameref"
            citation_value = nameref.strip()
            extra = match.group("name_extra")
        elif citation:
            citation_type = "citation"
            citation_value = citation.strip()
        else:
            citation_type = None

        if citation_type:
            cit = Citation(citation_type, citation_value, extra)
            b.add_child(cit)

        return "SAM", context

    def _fragment_start(self, context):
        source, match = context
        indent = len(match.group("indent"))

        attributes = {}

        attributes_string = match.group("attributes")
        if attributes_string is not None:
            attributes.update(self.parse_block_attributes(attributes_string))

        self.doc.new_block("fragment", attributes, None, indent)
        return "SAM", context

    def _paragraph_start(self, context):
        source, match = context
        line = source.current_line
        local_indent = len(line) - len(line.lstrip())
        self.doc.new_paragraph(None, "", local_indent)
        self.paragraph_start(line)
        return "PARAGRAPH", context

    def _paragraph(self, context):
        source, match = context
        try:
            line = source.next_line
        except EOFError:
            f = para_parser.parse(self.current_paragraph, self.doc)
            self.doc.new_flow(f)
            return "END", context

        if self.patterns["blank-line"].match(line):
            f = para_parser.parse(self.current_paragraph, self.doc)
            self.doc.new_flow(f)
            return "SAM", context

        if self.doc.in_context(["p", "li"]):
            f = para_parser.parse(self.current_paragraph, self.doc)
            self.doc.new_flow(f)
            source.return_line()
            return "SAM", context

        self.paragraph_append(line)
        return "PARAGRAPH", context

    def _list_item(self, context):
        source, match = context
        indent = len(match.group("indent"))
        content_indent = indent + len(match.group("marker"))
        self.doc.new_unordered_list_item(indent, content_indent)
        self.paragraph_start(str(match.group("content")).strip())
        return "PARAGRAPH", context

    def _num_list_item(self, context):
        source, match = context
        indent = len(match.group("indent"))
        content_indent = indent + len(match.group("marker"))
        self.doc.new_ordered_list_item(indent, content_indent)
        self.paragraph_start(str(match.group("content")).strip())
        return "PARAGRAPH", context

    def _labeled_list_item(self, context):
        source, match = context
        indent = len(match.group("indent"))
        label = match.group("label")
        self.doc.new_labeled_list_item(indent, label)
        self.paragraph_start(str(match.group("content")).strip())
        return "PARAGRAPH", context

    def _block_insert(self, context):
        source, match = context
        indent = len(match.group("indent"))
        self.doc.new_block("insert", attributes=parse_insert(match.group("attributes")), text=None, indent=indent)
        return "SAM", context

    def _string_def(self, context):
        source, match = context
        indent = len(match.group("indent"))
        self.doc.new_string_def(match.group("name"), para_parser.parse(match.group("value"), self.doc), indent=indent)
        return "SAM", context

    def _line_start(self, context):
        source, match = context
        indent = len(match.group("indent"))
        self.doc.new_block(
            "line",
            self.parse_block_attributes(match.group("attributes")),
            para_parser.parse(match.group("text"), self.doc, strip=False),
            indent=indent,
        )
        return "SAM", context

    def _record_start(self, context):
        source, match = context
        indent = len(match.group("indent"))
        record_name = match.group("record_name").strip()
        field_names = [x.strip() for x in match.group("field_names").split(",")]
        self.doc.new_record_set(record_name, field_names, indent)
        return "RECORD", context

    def _record(self, context):
        source, match = context
        try:
            line = source.next_line
        except EOFError:
            return "END", context
        indent = len(line) - len(line.lstrip())
        if self.patterns["blank-line"].match(line):
            return "SAM", context
        elif indent < self.doc.current_block.indent:
            source.return_line()
            return "SAM", context
        else:
            field_values = [x.strip() for x in re.split(r"(?<!\\),", line)]
            if len(field_values) != len(self.doc.fields):
                raise SAMParserError("Record length does not match record set header. At:\n\n " + line)
            record = list(zip(self.doc.fields, field_values))
            self.doc.new_record(record)
            return "RECORD", context

    def _embedded_xml(self, context):
        source, match = context
        indent = len(match.group("indent"))
        embedded_xml_parser = xml.parsers.expat.ParserCreate()
        embedded_xml_parser.XmlDeclHandler = self._embedded_xml_declaration_check
        embedded_xml_parser.Parse(source.current_line.strip())
        xml_lines = []
        try:
            while True:
                line = source.next_line
                xml_lines.append(line)
                embedded_xml_parser.Parse(line)
        except xml.parsers.expat.ExpatError as err:
            if err.code == 9:  # junk after document element
                source.return_line()
                xml_text = "".join(xml_lines[:-1])
                self.doc.new_embedded_xml(xml_text, indent)
                return "SAM", context
            else:
                raise

    def _embedded_xml_declaration_check(self, version, encoding, standalone):
        if version != "1.0":
            raise SAMParserError("The version of an embedded XML fragment must be 1.0.")
        if encoding.upper() != "UTF-8":
            raise SAMParserError("The encoding of an embedded XML fragment must be UTF-8.")

    def _sam(self, context):
        source, match = context
        try:
            line = source.next_line
        except EOFError:
            return "END", context

        match = self.patterns["comment"].match(line)
        if match is not None:
            self.doc.new_comment(Comment(line.strip()[1:]))
            return "SAM", (source, match)

        match = self.patterns["record-start"].match(line)
        if match is not None:
            return "RECORD-START", (source, match)

        match = self.patterns["blank-line"].match(line)
        if match is not None:
            return "SAM", (source, match)

        match = self.patterns["codeblock-start"].match(line)
        if match is not None:
            return "CODEBLOCK-START", (source, match)

        match = self.patterns["blockquote-start"].match(line)
        if match is not None:
            return "BLOCKQUOTE-START", (source, match)

        match = self.patterns["fragment-start"].match(line)
        if match is not None:
            return "FRAGMENT-START", (source, match)

        match = self.patterns["list-item"].match(line)
        if match is not None:
            return "LIST-ITEM", (source, match)

        match = self.patterns["num-list-item"].match(line)
        if match is not None:
            return "NUM-LIST-ITEM", (source, match)

        match = self.patterns["labeled-list-item"].match(line)
        if match is not None:
            return "LABELED-LIST-ITEM", (source, match)

        match = self.patterns["block-insert"].match(line)
        if match is not None:
            return "BLOCK-INSERT", (source, match)

        match = self.patterns["string-def"].match(line)
        if match is not None:
            return "STRING-DEF", (source, match)

        match = self.patterns["line-start"].match(line)
        if match is not None:
            return "LINE-START", (source, match)

        match = self.patterns["embedded-xml"].match(line)
        if match is not None:
            return "EMBEDDED-XML", (source, match)

        match = self.patterns["block-start"].match(line)
        if match is not None:
            return "BLOCK", (source, match)

        match = self.patterns["paragraph-start"].match(line)
        if match is not None:
            return "PARAGRAPH-START", (source, match)

        raise SAMParserError("I'm confused")

    def serialize(self, serialize_format):
        return self.doc.serialize(serialize_format)

    def parse_block_attributes(self, attributes_string):
        result = {}
        try:
            attributes_list = attributes_string.split()
        except AttributeError:
            return None
        unexpected_attributes = [x for x in attributes_list if not (x[0] in "?#*")]
        if unexpected_attributes:
            raise SAMParserError("Unexpected attribute(s): {0}".format(", ".join(unexpected_attributes)))
        ids = [x[1:] for x in attributes_list if x[0] == "*"]
        if len(ids) > 1:
            raise SAMParserError("More than one ID specified: " + ", ".join(ids))
        names = [x[1:] for x in attributes_list if x[0] == "#"]
        if len(names) > 1:
            raise SAMParserError("More than one name specified: " + ", ".join(names))
        conditions = [x[1:] for x in attributes_list if x[0] == "?"]
        if ids:
            if ids[0] in self.doc.ids:
                raise SAMParserError("Duplicate ID found: " + ids[0])
            self.doc.ids.extend(ids)
            result["id"] = "".join(ids)
        if names:
            result["name"] = "".join(names)
        if conditions:
            result["conditions"] = " ".join(conditions)
        return result
Ejemplo n.º 52
0
            val = math_func(val)
        print " >>"
    return (newState, val)

def twenties_counter(val):
    print "TWENTIES State:",
    while 1:
        if val <= 0  or  val >= 30:
            newState =  "Out_of_Range"; break
        elif 1 <= val < 10:
            newState =  "ONES"; break
        elif 10 <= val < 20:
            newState =  "TENS"; break
        else:
            print " *%2.1f+" % val,
            val = math_func(val)
        print " >>"
    return (newState, val)

def math_func(n):
     from math import sin
     return abs(sin(n))*31

if __name__== "__main__":
       m = StateMachine()
       m.add_state("ONES", ones_counter)
       m.add_state("TENS", tens_counter)
       m.add_state("TWENTIES", twenties_counter)
       m.add_state("OUT_OF_RANGE", None, end_state=1)
       m.set_start("ONES")
       m.run(1)
Ejemplo n.º 53
0
    elif angle < 246:
        return 3
    elif angle < 275:
        return 2
    elif angle < 304:
        return 1
    else:
        return None

# PyGame help from:
#http://www.sacredchao.net/~piman/writing/sprite-tutorial.shtml

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(SOCKET_ADDR)

sm = StateMachine()
state = sm.state


pygame.init()
pygame.display.set_caption("lpDialer")
screen = pygame.display.set_mode([531, 800])
bg = pygame.image.load('phone_sprite.png')

spinner = Spinner()

needle = pygame.image.load('needle_sprite.png')
needle.set_colorkey(needle.get_at((0,0)))

last_time = time.time()
Ejemplo n.º 54
0
    def __init__(self, ip="127.0.0.1", resources=None, songs=None, states=None):
        self.rgb = RGB(ip)
        self.rgb.invertedX = False
        self.rgb.invertedY = True

        self.framerate = 20

        self.previousControllerState = []
        self.controllers = []
        self.controllerOrientations = []

        if not resources:
            resources = []
        if not songs:
            songs = []
        if not states:
            states = []

        self.stateMachine = StateMachine(states)

        self.music = MusicManager(songs)

        pygame.init()
        pygame.joystick.init()
        pygame.mixer.init()

        self.resources = {}
        for r in resources:
            r.load()
            if self.resources.has_key(r.name):
                print "double resource key: '", r.name,"'"

            self.resources[r.name] = r

        pygame.display.set_mode([200,100])
        self.playerCount = pygame.joystick.get_count()
        print str(self.playerCount) + " Joysticks connected."

        for i in range(self.playerCount):
            joystick = pygame.joystick.Joystick(i)
            self.controllers.append(joystick)
            joystick.init()
            self.previousControllerState.append({
                'xAxis': 0,
                'yAxis': 0,
                'aButton': False,
                'bButton': False,
                'cButton': False,
                'dButton': False
            })
            self.controllerOrientations.append(Orientation.South)

        self.keyboardJoystick = False
        if self.playerCount == 0:
            self.playerCount = 2
            self.keyboardJoystick = True
            self.previousControllerState.append({
                'xAxis': 0,
                'yAxis': 0,
                'aButton': False,
                'bButton': False,
                'cButton': False,
                'dButton': False
            })
            self.controllers.append(KeyboardController(id=0))
            self.controllerOrientations.append(Orientation.South)

            self.previousControllerState.append({
                'xAxis': 0,
                'yAxis': 0,
                'aButton': False,
                'bButton': False,
                'cButton': False,
                'dButton': False
            })
            self.controllers.append(KeyboardController(id=1))
            self.controllerOrientations.append(Orientation.South)

        self.lastFrame = time.time()
Ejemplo n.º 55
0
'''
Created on Aug 5, 2013

@author: nik
'''

from dbmanager import DbManager
import FingerScanner as scanner
from statemachine import StateMachine


if __name__ == '__main__':
    
    dbManager = DbManager()
    statemachine = StateMachine(dbManager)
    statemachine.start()
    
    
    
#     scanner.start(2)