class State(StateClass): def __init__(self, parent=None): self.timer = Timer() if parent: self.__dict__.update(parent.__dict__) def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): self.logger = logger self.logger.log_session(session_params, 'Passive') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params self.logger.log_conditions(conditions, self.stim.get_cond_tables()) exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) # Initialize states global states states = { 'PreTrial' : PreTrial(self), 'Trial' : Trial(self), 'InterTrial' : InterTrial(self), 'Exit' : exitState} def run(self): self.StateMachine.run() def updateStatus(self): # updates stateMachine from Database entry - override for timing critical transitions self.logger.update_setup_info({'state': self.__class__.__name__})
def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): self.logger = logger self.logger.log_session(session_params, 'VR') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params self.logger.log_conditions( conditions, self.stim.get_cond_tables() + self.beh.get_cond_tables()) exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) # Initialize states global states states = { 'PreTrial': PreTrial(self), 'Trial': Trial(self), 'Abort': Abort(self), 'Reward': Reward(self), 'Punish': Punish(self), 'InterTrial': InterTrial(self), 'Exit': exitState }
def __init__(self, world, name, image, show_hp=True): pygame.sprite.Sprite.__init__(self) # --- Basic attributes --- self.world = world self.name = name self.image = image if image is not None: self.rect = self.image.get_rect() self.mask = pygame.mask.from_surface(self.image) self.show_hp = show_hp # --- Kinematic attributes --- self.position = Vector2(0, 0) self.orientation = 0 self.velocity = Vector2(0, 0) ## self.rotation = 0. # rotational speed self.maxSpeed = 100. self.brain = StateMachine() self.id = 0 self.team_id = 0 self.max_hp = 100. self.current_hp = self.max_hp
def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): self.logger = logger self.logger.log_session(session_params, 'Match2Sample') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params self.logger.log_conditions( conditions, self.stim.get_cond_tables() + self.beh.get_cond_tables()) # Initialize states exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) global states states = { 'PreTrial': PreTrial(self), 'Cue': Cue(self), 'Delay': Delay(self), 'Response': Response(self), 'Abort': Abort(self), 'Reward': Reward(self), 'Punish': Punish(self), 'InterTrial': InterTrial(self), 'Hydrate': Hydrate(self), 'Offtime': Offtime(self), 'Exit': exitState }
class Explorer(MovingEntity): id = None FSM = None circle = None pos = None searchRectangel = None speed = None path = [] def __init__(self, worker): self.id = worker.id self.pos = worker.pos self.circle = worker.circle self.circle.setFill(JsonLoader.Data["explorer"]["color"]) center = self.circle.getCenter() self.searchRectangel = Rectangle( Point(center.getX() - 100, center.getY() + 100), Point(center.getX() + 100, center.getY() - 100)) #self.searchRectangel.draw(self.window.window) self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Explorer()) self.FSM.SetGlobalState(ExplorerGlobalState()) self.speed = JsonLoader.Data["explorer"]["speed"] def Update(self): self.FSM.Update() def ExploreNeighbours(self): neighbours = self.map.ExploreNeighbours(self.pos) for node in neighbours: self.window.window.items[node].setFill(self.map.grid[node].color)
class FineWorker(MovingEntity): # identifier. id = 0 # number of worker FSM = None pos = None # number of the tile worker is on. circle = None speed = None # speedmodifier # used to time durations of things. startTime = 0 freezeTime = 0 path = [] def __init__(self, worker): self.id = worker.id self.pos = worker.pos EntityManager.RemoveEntity(self) EntityManager.RegisterEntity(self) self.circle = worker.circle self.circle.setFill(self.data["fineworker"]["color"]) self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Fine_Worker()) self.FSM.SetGlobalState(FineWorkerGlobalState()) self.speed = self.data["fineworker"]["speed"] def Update(self): self.FSM.Update()
def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): self.logger = logger self.logger.log_session(session_params, '2AFC') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params self.logger.log_conditions(conditions, self.stim.get_condition_tables()) logger.update_setup_info('start_time', session_params['start_time']) logger.update_setup_info('stop_time', session_params['stop_time']) exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) # Initialize states global states states = { 'PreTrial' : PreTrial(self), 'Trial' : Trial(self), 'PostTrial' : PostTrial(self), 'InterTrial' : InterTrial(self), 'Reward' : Reward(self), 'Punish' : Punish(self), 'Sleep' : Sleep(self), 'OffTime' : OffTime(self), 'Exit' : exitState}
class Worker(MovingEntity): # identifier. id = None FSM = None pos = None circle = None speed = None Path = [] # internal stats. def __init__(self): self.id = BaseGameEntityClass.SetID(self) self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Worker()) self.FSM.SetGlobalState(WorkerGlobalState()) for node in self.map.grid: if node.isSpawn: self.pos = node.id self.circle = node.center self.speed = JsonLoader.Data["worker"]["speed"] self.circle = Circle(self.circle, 3) self.circle.setFill(JsonLoader.Data["worker"]["color"]) def Update(self): self.FSM.Update() def GetFSM(self): return self.FSM
class State(StateClass): def __init__(self, parent=None): self.timer = Timer() if parent: self.__dict__.update(parent.__dict__) def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): self.logger = logger self.logger.log_session(session_params, '2AFC') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params self.logger.log_conditions(conditions, self.stim.get_condition_tables()) logger.update_setup_info('start_time', session_params['start_time']) logger.update_setup_info('stop_time', session_params['stop_time']) exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) # Initialize states global states states = { 'PreTrial': PreTrial(self), 'Trial': Trial(self), 'PostTrial': PostTrial(self), 'InterTrial': InterTrial(self), 'Reward': Reward(self), 'Punish': Punish(self), 'Sleep': Sleep(self), 'OffTime': OffTime(self), 'Exit': exitState } def entry( self ): # updates stateMachine from Database entry - override for timing critical transitions self.StateMachine.status = self.logger.get_setup_info('status') self.logger.update_state(self.__class__.__name__) def run(self): self.StateMachine.run() def is_sleep_time(self): now = datetime.now() start = now.replace( hour=0, minute=0, second=0) + self.logger.get_setup_info('start_time') stop = now.replace(hour=0, minute=0, second=0) + self.logger.get_setup_info('stop_time') if stop < start: stop = stop + timedelta(days=1) time_restriction = now < start or now > stop return time_restriction
def __init__(self): StateMachine.__init__(State.makesChange, { # Current state, input (State.makesChange, HasChange.no) : # test, transition, next state: (null, null, State.noChange), (State.noChange, HasChange.yes) : (null, null, State.noChange) })
def __init__(self, image, position, size, color, speed, angularSpeed): """ Initialize the dog """ super().__init__(image, position, size, color, speed, angularSpeed) self.searchType = SearchType.A_STAR self.gateNumber = 0 self.isFollowingPath = False self.path = [] self.stateMachine = StateMachine(FindTarget()) self.targetSheep = None
def __init__(self, worker): self.id = worker.id self.pos = worker.pos EntityManager.RemoveEntity(self) EntityManager.RegisterEntity(self) self.circle = worker.circle self.circle.setFill(self.data["fineworker"]["color"]) self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Fine_Worker()) self.FSM.SetGlobalState(FineWorkerGlobalState()) self.speed = self.data["fineworker"]["speed"]
def __init__(self): self.id = BaseGameEntityClass.SetID(self) self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Worker()) self.FSM.SetGlobalState(WorkerGlobalState()) for node in self.map.grid: if node.isSpawn: self.pos = node.id self.circle = node.center self.speed = JsonLoader.Data["worker"]["speed"] self.circle = Circle(self.circle, 3) self.circle.setFill(JsonLoader.Data["worker"]["color"])
def __init__(self, worker): self.id = worker.id self.pos = worker.pos EntityManager.RemoveEntity(self) EntityManager.RegisterEntity(self) self.circle = worker.circle self.circle.setFill(self.data["explorer"]["color"]) self.pathBack = [] self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Explorer()) self.FSM.SetGlobalState(ExplorerGlobalState()) self.speed = self.data["explorer"]["speed"] self.maxDist = self.data["explorer"]["maxdist"]
class Explorer(MovingEntity): id = None FSM = None circle = None pos = None searchRectangel = None speed = None path = None pathBack = [] failedPathFindingAttempts = 0 maxDist = None def __init__(self, worker): self.id = worker.id self.pos = worker.pos EntityManager.RemoveEntity(self) EntityManager.RegisterEntity(self) self.circle = worker.circle self.circle.setFill(self.data["explorer"]["color"]) self.pathBack = [] self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Explorer()) self.FSM.SetGlobalState(ExplorerGlobalState()) self.speed = self.data["explorer"]["speed"] self.maxDist = self.data["explorer"]["maxdist"] def Update(self): self.FSM.Update() def ExploreNeighbours(self): neighbours = self.map.ExploreNeighbours(self.pos) for nodeindex in neighbours: self.window.window.items[nodeindex].setFill( self.map.grid[nodeindex].color) for tree in range(0, self.map.grid[nodeindex].numTrees): self.map.grid[nodeindex].trees.append(Tree(tree, nodeindex)) self.map.grid[nodeindex].trees[-1].circle.draw( self.window.window) if self.map.grid[nodeindex].trees: Manager.ResourceManager.treenodes.append( self.map.grid[nodeindex]) self.map.grid[nodeindex].dist = ( (abs(self.map.grid[nodeindex].x - self.map.grid[self.townHall.pos].x))) + ( (abs(self.map.grid[nodeindex].y - self.map.grid[self.townHall.pos].y))) def Del(self): self.circle.undraw() EntityManager.Del(self.id)
class State(StateClass): def __init__(self, parent=None): self.timer = Timer() if parent: self.__dict__.update(parent.__dict__) def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): print('setting up experiment') self.logger = logger self.logger.log_session(session_params, 'VR') print('initializing Behavior & Stimulus') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params print('logging conditions') self.logger.log_conditions( conditions, self.stim.get_cond_tables() + self.beh.get_cond_tables()) print('Done!') exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) print('Initializing states') # Initialize states global states states = { 'PreTrial': PreTrial(self), 'Trial': Trial(self), 'Abort': Abort(self), 'Reward': Reward(self), 'Punish': Punish(self), 'InterTrial': InterTrial(self), 'Exit': exitState } def entry( self ): # updates stateMachine from Database entry - override for timing critical transitions # print(type(self).__name__) self.logger.curr_state = type(self).__name__ self.period_start = self.logger.log('StateOnset', {'state': type(self).__name__}) self.timer.start() def run(self): print('Running state') self.StateMachine.run()
def handle_sensor_data(data): """Handle_sensor_data is called every time the robot gets a new sensorPacket.""" #print dir( data ) D.data = data #Check for a bump if data.bumpRight or data.bumpLeft: print "Bumped!" #Check if play button was pressed if data.play: print "Play button pressed!" StateMachine.state_stop() rospy.signal_shutdown("play button pressed")
class State(StateClass): def __init__(self, parent=None): self.timer = Timer() if parent: self.__dict__.update(parent.__dict__) def setup(self, logger, BehaviorClass, StimulusClass, session_params, conditions): self.logger = logger self.logger.log_session(session_params, 'Match2Sample') # Initialize params & Behavior/Stimulus objects self.beh = BehaviorClass(self.logger, session_params) self.stim = StimulusClass(self.logger, session_params, conditions, self.beh) self.params = session_params self.logger.log_conditions( conditions, self.stim.get_cond_tables() + self.beh.get_cond_tables()) # Initialize states exitState = Exit(self) self.StateMachine = StateMachine(Prepare(self), exitState) global states states = { 'PreTrial': PreTrial(self), 'Cue': Cue(self), 'Delay': Delay(self), 'Response': Response(self), 'Abort': Abort(self), 'Reward': Reward(self), 'Punish': Punish(self), 'InterTrial': InterTrial(self), 'Hydrate': Hydrate(self), 'Offtime': Offtime(self), 'Exit': exitState } def entry( self ): # updates stateMachine from Database entry - override for timing critical transitions self.logger.curr_state = type(self).__name__ self.period_start = self.logger.log('StateOnset', {'state': type(self).__name__}) self.timer.start() def run(self): self.StateMachine.run()
def __init__(self): self.SetID() self.path = None self.pathBack = [] self.carrying = {} self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Worker()) self.FSM.SetGlobalState(WorkerGlobalState()) EntityManager.RegisterEntity(self) for node in self.map.grid: if node.isSpawn: self.pos = node.id self.circle = node.center self.speed = self.data["worker"]["speed"] self.circle = Circle(self.circle, 3) self.circle.setFill(self.data["worker"]["color"])
def __init__(self): super().__init__() self.image = None self.movingObject = None # (index, pos, source) # index: index in hand/characDict # pos: original pos on screen # source is the same as _cursorFocus # 1 player1, 2 player2, 3 board self.movingObjectInfo = None # logic status handler to init UI self.status = None self.cursorImage = None self.cursor = GameObject.GameObject() self.player1Hand = PlayerUI.PlayerUI() self.player2Hand = PlayerUI.PlayerUI() self.boardUI = BoardUI.BoardUI() self._cursorFocus = 0 # 0 lost focus, 1 player1, 2 player2, 3 board self.stateMachine = StateMachine.StateMachine() self.dpos = None
def __init__(self, num_switches=4, num_hosts=8, output="/home/jeffrey/minitest/output", flows=[], ss=True): # attach handlers to listeners core.openflow.addListenerByName("FlowStatsReceived", self.handle_flowstats_received) # JRF: Not dealing with ports right now #core.openflow.addListenerByName("PortStatsReceived", self.handle_portstats_received) self.web_bytes = 0 self.web_flows = 0 self.num_switches = num_switches self.num_hosts = num_hosts self.num_flows = num_hosts * (num_hosts - 1) self.TM = np.array([row, row, row, row, row, row, row, row]) self.f = open(output, 'w') self.filter = st.StateMachine(num_switches=num_switches, num_hosts=num_hosts) self.measurement_counter = 0 self.filter.DefineRoutingMatrix(self.InitRoutingMatrix()) self.flows = flows self.ss = ss if self.ss: print("Performing Switch Selection") else: print("Not performing switch selection") #print("The flows output is " + str(flows)) print("The number of hosts is " + str(self.num_hosts) + " and number of switches is " + str(self.num_switches))
def accepted(): resetTransiotions() re = str(entry.get()) test = StateMachine.StateMachine(states, 'A', transitions) tof = test.transitionRE(re) if not test.accepted: tof = False if tof: test.currState = 'A' statesPassed = [] statesPassed.append((test.getstate(), test.getstate(), ' ')) for letter in re: test.transition(letter) statesPassed.append( (test.prevState, test.getstate(), test.currTrigg)) showTransitions('red', statesPassed) if tof: status = 'accepted.' else: status = 'denied.' acceptedTxt.configure( text=(str(tof) + '. Your regular expression has been ' + status))
def __init__(self, worker): self.id = worker.id self.pos = worker.pos self.circle = worker.circle self.circle.setFill(JsonLoader.Data["explorer"]["color"]) center = self.circle.getCenter() self.searchRectangel = Rectangle( Point(center.getX() - 100, center.getY() + 100), Point(center.getX() + 100, center.getY() - 100)) #self.searchRectangel.draw(self.window.window) self.FSM = StateMachine(self) self.FSM.SetCurrentState(Begin_Life_Explorer()) self.FSM.SetGlobalState(ExplorerGlobalState()) self.speed = JsonLoader.Data["explorer"]["speed"]
def listen_print_loop(responses,micstream): state_machine = sm.StateMachine() # Outputs initial state synthesize_text(state_machine.state.text,micstream) for response in responses: if not response.results: continue result = response.results[0] if not result.alternatives: continue # Display the transcription of the top alternative. transcript = result.alternatives[0].transcript if result.is_final: print('Final: ' + transcript) state_machine.status_callback('Speech:' + transcript) # Outputs text of current state synthesize_text(state_machine.state.text,micstream) if type(state_machine.state) == sm.Greeting: break
def main(): room = [[0.6, 0.3, 0.0, 0.0, 0.1, 0.0, 0.5], [0.3, 0.0, 0.1, 0.0, 0.0, 0.0, 0.3], [0.0, 0.1, 0.0, 0.0, 0.0, 0.1, 0.0]] # actionList = [((3,0),(3,0),(3,0),0), # ((5,0),(4,0),(4,0),1), # ((6,0),(6,0),(6,0),0), # ((6,0),(6,0),(6,0),0)] top_score = SMALL_VALUE for iteration in xrange(0, 50): sm = StateMachine.StateMachine(room) actionList = [] for i in xrange(0, 30): actionList.append(sm.next()) ef = EvalFunction.EvalFunction(room, actionList) if ef.score > top_score: top_score = ef.score top_actionList = actionList root = Tk() ex = RoomDisplay(root, top_actionList, room) root.geometry("450x400+300+300") root.mainloop()
def __init__(self, world, pos): """Base variables""" self.world = world self.pos = pos self.player = self.world.player self.acceleration = 5 self.max_range = 300 self.attacking_range = 150 self.scared_range = 100 self.bullet_list = self.world.bullet_list self.invulnerable = False self.reload_max = 5 self.reload = self.reload_max self.velocity = vec2() self.target = self.player self.mask = None self.look_ahead = 50 self.health = 50 self.health_max = self.health """AI variables""" self.brain = StateMachine() self.radius = 25 self.hit_this_frame = False self.visible = True
def __init__(self): pygame.init() pygame.display.set_caption("Mashing Tester v0.0.3") pygame.joystick.init() self.screen = pygame.display.set_mode((800, 600)) self.state_machine = SM.StateMachine()
def __init__(self, threadName): super(LogMatch, self).__init__(name = threadName) self.log_que = queue.Queue() self.name = threadName self.tvs_handle = (0, 0) self.tid = 0 self.state_machine = StateMachine() self.stop_flag = True
def __init__(self, id): #ctor self._SetID(id) self.stateMachine = StateMachine.StateMachine(self) self.money = 0 self.energi = 0 self.hunger = 0 self.thirst = 0 self.place = None
def __init__(self): super(mainwindow, self).__init__() self.runSM = threading.Event() self.handshakedone = threading.Event() self.SM = StateMachine.stateMachine(self.runSM, self.handshakedone) self.SM.daemon = True self.initUI()
class GameEntity(object): def __init__(self, world, name, image): self.world = world self.name = name self.image = image try: self.image.set_colorkey((255,0,255)) except AttributeError: pass self.location = Vector2(0, 0) self.world_location = Vector2(0, 0) self.destination = Vector2(0, 0) self.speed = 0. self.brain = StateMachine() self.id = 0 self.tp = 1.0 def render(self, surface): x, y = self.world_location w, h = self.image.get_size() pos = (x-w/2, y-h/2) surface.blit(self.image, pos) def process(self, time_passed): self.brain.think() self.tp = time_passed self.world_location=self.location+self.world.background_pos if self.speed > 0. and self.location != self.destination: vec_to_destination = self.destination - self.location distance_to_destination = vec_to_destination.get_length() heading = vec_to_destination.get_normalized() travel_distance = min(distance_to_destination, time_passed * self.speed) self.location += travel_distance * heading *time_passed * self.speed
class GameEntity(object): def __init__(self, world, name, image): self.world = world self.name = name self.image = image try: self.image.set_colorkey((255, 0, 255)) except AttributeError: pass self.location = Vector2(0, 0) self.world_location = Vector2(0, 0) self.destination = Vector2(0, 0) self.speed = 0. self.brain = StateMachine() self.id = 0 self.tp = 1.0 def render(self, surface): x, y = self.world_location w, h = self.image.get_size() pos = (x - w / 2, y - h / 2) surface.blit(self.image, pos) def process(self, time_passed): self.brain.think() self.tp = time_passed self.world_location = self.location + self.world.background_pos if self.speed > 0. and self.location != self.destination: vec_to_destination = self.destination - self.location distance_to_destination = vec_to_destination.get_length() heading = vec_to_destination.get_normalized() travel_distance = min(distance_to_destination, time_passed * self.speed) self.location += travel_distance * heading * time_passed * self.speed
def main(): room = [[0.6, 0.3, 0.0, 0.0, 0.1, 0.0, 0.5], [0.3, 0.0, 0.1, 0.0, 0.0, 0.0, 0.3], [0.0, 0.1, 0.0, 0.0, 0.0, 0.1, 0.0]] sm = StateMachine.StateMachine(room) actionList = [] for i in xrange(0, 30): actionList.append(sm.next()) ef = EvalFunction(room, actionList)
def __init__(self, world, name, image): self.world = world self.name = name self.image = image try: self.image.set_colorkey((255, 0, 255)) except AttributeError: pass self.location = Vector2(0, 0) self.world_location = Vector2(0, 0) self.destination = Vector2(0, 0) self.speed = 0. self.brain = StateMachine() self.id = 0 self.tp = 1.0
def handle_hive_commands(data): """Handles incoming commands from the hive master.""" print data incomingCommand = str(data) command = incomingCommand[6:] #Check for a start command if command == "start": R.state = "active" R.hiveCommand = command StateMachine.state_start() #Check for a stop command elif command == "stop": R.state = "dormant" R.hiveCommand = command StateMachine.state_stop() #Check for a pause command elif command == "pause": R.hiveCommand = command StateMachine.state_wait_for_start() #Check for formation commands elif command == "line": R.hiveCommand = command elif command == "square": R.hiveCommand = command #Check for incorrect commands else: print "Invalid command."
class LogMatch(threading.Thread): def __init__(self, threadName): super(LogMatch, self).__init__(name = threadName) self.log_que = queue.Queue() self.name = threadName self.tvs_handle = (0, 0) self.tid = 0 self.state_machine = StateMachine() self.stop_flag = True def start(self): self.stop_flag = False self.state_machine.add_state("LOG_INVALID", st_invalid) self.state_machine.add_state("LOG_SUCCESS", st_success) self.state_machine.add_state("LOG_FAILED", st_failed) self.state_machine.add_state("LOG_OVER", None, end_state=1) super(LogMatch, self).start() def run(self): self.state_machine.set_start("LOG_INVALID") self.state_machine.run() def stop(self): self.stop_flag = True def st_invalid(self, cargo): item = self.que.get() return (newState, item) def st_success(self, cargo): print "Success" return ("LOG_OVER", cargo) def st_failed(self, cargo): print "Failed" return ("LOG_OVER", cargo)
def generateJFLAPFile(deterministic, typeOfMachine, nodeL, edgeL, initial, accepting): """Using the list of nodes, edges, and the starting/final nodes Generates a state machine and outputs it to a .jjf file""" newNodeL = [StateMachine.Node(node, [], node == initial, node in accepting) for node in nodeL] if DEBUG: print(newNodeL) newEdgeL = [StateMachine.Edge( StateMachine.findNode(edge[0], newNodeL), StateMachine.findNode(edge[1], newNodeL), edge[2]) for edge in edgeL] if DEBUG: print(newEdgeL) for node in newNodeL: node.addEdge(newEdgeL) if DEBUG: print(newNodeL) initNode = StateMachine.findNode( initial, newNodeL ) if DEBUG: print(initNode) finalNodeL = [StateMachine.findNode( name, newNodeL) for name in accepting] if DEBUG: print(finalNodeL) stateMech = StateMachine.StateMachine( newNodeL, newEdgeL, initNode, finalNodeL, typeOfMachine, deterministic) filename = input("What do you want the output to be named?\n") filename+='.txt' JFFWriterv2.writeJFFFile(stateMech, filename)
def do_sockets(): while(True): data = g.conn.recv_data() print "Recieved some Data" temp = BitArray(uint=data[1], length=26) g.clock,plaintext = temp, Bits(bytes=data[3]) rev = BitArray(g.clock) rev.reverse() print "clock: ", g.clock keystream,cipheredTxt =StateMachine.encipher(g.masterID, g.kcPrime, rev, plaintext) g.send_log('true', g.ID == g.masterID, keystream, plaintext, cipheredTxt)
def handle_sensor_data(data): """Handle_sensor_data is called every time the robot gets a new sensorPacket.""" #Store incoming data in the Data object D.data = data #Check for a bump if data.bumpRight or data.bumpLeft: print "Bumped!" #Check if play button was pressed if data.play: print "Stopping..." StateMachine.state_stop() rospy.signal_shutdown("play button pressed") #Check key presses key_press = cv.WaitKey(5) & 255 if key_press != 255: check_key_press(D, key_press) #Display robot updates in Monitor window draw_on_image(D)
def POST(self): print 'recieved message request' g.clock = Bits(uint=g.clock.uint+1, length=26) data = web.input() plaintext = Bits(bytes=data.plaintext.encode('utf-8')) rev = BitArray(g.clock) rev.reverse() keystream,ciphertext =StateMachine.encipher(g.masterID, g.kcPrime, rev, plaintext) print "Sending forward Data" g.conn.send_data(g.clock.uint, ciphertext.bytes) g.send_log('false', g.ID == g.masterID, keystream, ciphertext, plaintext) return 1
def process_seg(fname, fpout): fp = open(fname,'r') sm = StateMachine() for line in fp: ret = sm.move(line) if FLUSH == ret: for strng in sm.get_seg_str(): fpout.write(strng + '\n') sm.move(line) for strng in sm.get_seg_str(): fpout.write(strng + '\n') fp.close()
def __init__(self, parent=None): self.runSM = threading.Event() self.handshakedone=threading.Event() self.SM = StateMachine.stateMachine(self.runSM,self.handshakedone) QtGui.QWidget.__init__(self) self._capture = cv.CreateCameraCapture(0) if not self._capture: print "Error opening capture device" sys.exit(1) # # create storage self.storage = cv.CreateMemStorage(128) self.cascade = cv.Load('haarcascade_frontalface_default.xml') frame = cv.QueryFrame(self._capture) self.setMinimumSize(frame.width,frame.height) self.setMaximumSize(self.minimumSize()) self.image_size = cv.GetSize(frame) # create grayscale version self.grayscale = cv.CreateImage(self.image_size, 8, 1) self.smallgray = cv.CreateImage((100,75),8,1) self.xscale = frame.width/self.smallgray.width self.yscale = frame.height/self.smallgray.height self.bestface = None self._frame = None self.detect(frame) self._image = self._build_image(frame) # Paint every 50 ms self._timer = QtCore.QTimer(self) self._timer.timeout.connect(self.queryFrame) self.runSM.set() self.SM.start() self.handshakedone.wait() self._timer.start(100)
def __init__(self, world, name, image): self.world = world self.name = name self.image = image try: self.image.set_colorkey((255,0,255)) except AttributeError: pass self.location = Vector2(0, 0) self.world_location = Vector2(0, 0) self.destination = Vector2(0, 0) self.speed = 0. self.brain = StateMachine() self.id = 0 self.tp = 1.0
def setUp(self): self._sm = StateMachine(3) self._sm.setNOP(self.nullAction) self._sm.setEntryAction(RTC.ACTIVE_STATE, self.on_activated) self._sm.setEntryAction(RTC.ERROR_STATE,self.on_aborting) self._sm.setPreDoAction(RTC.ACTIVE_STATE, self.on_reset) self._sm.setDoAction(RTC.ACTIVE_STATE, self.on_execute) self._sm.setPostDoAction(RTC.ACTIVE_STATE, self.on_state_update) self._sm.setExitAction(RTC.ACTIVE_STATE, self.on_deactivated) self._sm.setExitAction(RTC.ERROR_STATE, self.on_reset) self._sm.setTransitionAction(self.transition) self._sm.setListener(self) st = StateHolder() st.prev = RTC.INACTIVE_STATE st.curr = RTC.INACTIVE_STATE st.next = RTC.INACTIVE_STATE self._sm.setStartState(st) self._sm.goTo(RTC.INACTIVE_STATE)
class BaseEnemy(object): def __init__(self, world, pos): """Base variables""" self.world = world self.pos = pos self.player = self.world.player self.acceleration = 5 self.max_range = 300 self.attacking_range = 150 self.scared_range = 100 self.bullet_list = self.world.bullet_list self.invulnerable = False self.reload_max = 5 self.reload = self.reload_max self.velocity = vec2() self.target = self.player self.mask = None self.look_ahead = 50 self.health = 50 self.health_max = self.health """AI variables""" self.brain = StateMachine() self.radius = 25 self.hit_this_frame = False self.visible = True def update(self, tick): """ called every frame, the tick is the time passed since the last frame. Multiplying movement by it causes movement to be the same speed regardless of how fast a computer is (not good when frame rate is low)""" self.brain.think(tick) self.velocity *= 0.99 capped_vel = vec2() if self.velocity.x < -10: capped_vel.x = -10 elif self.velocity.x > 10: capped_vel.x = 10 else: capped_vel.x = self.velocity.x if self.velocity.y < -10: capped_vel.y = -10 elif self.velocity.y > 10: capped_vel.y = 10 else: capped_vel.y = self.velocity.y #capped_vel = self.cap(self.velocity, -10, 10) self.pos += capped_vel self.rect.center = self.pos self.mask = pygame.mask.from_surface(self.img) """ if self.world.main_map.test_collisions_point(self.pos): self.velocity*=-.5 """ def update_collisions(self, enemy_list): if self.__class__.__name__ == "Boss": return for i, current_enemy in enumerate(enemy_list): if current_enemy is self or current_enemy.__class__.__name__ == "Boss": continue current_vec = vec2().from_points(self.pos, current_enemy.pos) if current_vec.get_magnitude() < self.radius + current_enemy.radius: self.pos -= 0.1 * current_vec current_enemy.pos += 0.1 * current_vec self.rect.center = self.pos current_enemy.rect.center = current_enemy.pos def get_angle_to_target(self): dy = self.target.pos[1]-self.rect.center[1] dx = self.target.pos[0]-self.rect.center[0] angle = atan2(dy, dx) return angle def change_target(self): angle = random.uniform(0, 2*pi) self.target = RoamPoint(self.pos + vec2(cos(angle), sin(angle)) * random.randint(50, 250)) def health_bar(self, screen): if self.visible == True: width = int((self.img.get_width()/2)*(self.health/float(self.health_max))) pos = (self.rect.center[0]-(self.img.get_width()/2),self.rect.center[1]+(self.img.get_height()/2)+5) w,h = (self.img.get_width(),5) pygame.draw.rect(screen,(255,0,0),((pos),(w,h)),0) pygame.draw.rect(screen,(0,255,0),((pos),(w*(self.health/float(self.health_max)),h)),0) def rot_center(self): angle = self.get_angle_to_target() angle = 180-degrees(angle) orig_rect = self.image.get_rect() rot_image = pygame.transform.rotate(self.image, angle) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() self.img = rot_image self.rect = self.img.get_rect() self.mask = pygame.mask.from_surface(self.img) def get_vector_to_target(self): """returns the normalized vector between the enemy and target""" if self.target is None: return vec2() return vec2(self.target.pos - self.pos).normalise() def cap(self, vec, lower, upper): """caps a vector to a certain threshold""" new_vec = vec2() new_vec.x = max(lower, min(vec.x, upper)) new_vec.y = max(lower, min(vec.y, upper)) return new_vec def get_dist_to(self, other_vec): return vec2(other_vec - self.pos).get_magnitude() def can_see(self, player): """tests to see if the enemy can see the player""" if self.get_dist_to(player.pos) > self.max_range: return False return True def vec_to_int(self, vec): return int(vec.x), int(vec.y) def render(self, surface, camera): """renders the enemy to the given surface""" self.rect.center = self.pos + camera.offset surface.blit(self.img, self.rect) self.health_bar(surface)
def __init__(self): StateMachine.__init__(self, State.quiescent) for(int i = 0 i < items.length i++) for(int j = 0 j < items[i].length j++) items[i][j] = ItemSlot((j+1)*25, 5)
def check_key_press(D, key_press): """Handles incoming key presses.""" D.last_key_pressed = key_press if key_press == ord('q') or key_press == 27: #If a 'q' or ESC was pressed R.move(0,0) print "quitting" rospy.signal_shutdown( "Quit requested from keyboard" ) elif key_press == ord('h'): print " Keyboard Command Menu" print " ==============================" print " ESC/q: quit" print " h : help menu" print " s : save thresholds to file" print " l : load thresholds from file" print " c : mousedrags will no longer set thresholds, kept values will be cleared" print " a : mousedrag will assign thresholds to area within drag, \n" + \ " resets on new click or drag" print " r : mousedrags will remove the area under consideration, \n" + \ " must have set an area in 'a' mode first" print " m : mousedrags will add the area under consideration, \n" + \ " must have set an area in 'a' mode first" print " t : show total threshold image in threshold window" print " A : activate robot for moving, press A again to deactivate " print " 1 : begin state machine as leader" print " 2 : begin state machine as follower" #Save thresholds to file elif key_press == ord('s'): fileName = raw_input('Please enter the name of a color: ') fileName += "_thresholds.txt" writeFile = open(fileName, "w") #open file for writing print >> writeFile, D.thresholds writeFile.close() #Load thresholds from file elif key_press == ord('l'): whichFile = raw_input('Please enter the name of a color: ') whichFile += "_thresholds.txt" readFile = open(whichFile, "r") #open file for reading data = readFile.read() D.thresholds = eval(data) readFile.close() D.loaded_thresholds = True #Reset threshold sliders #for thresh in ['red', 'blue', 'green', 'hue', 'sat', 'val']: # cv.SetTrackbarPos('low_' + thresh, 'Sliders', D.thresholds['low_'+thresh]) # cv.SetTrackbarPos('high_' + thresh, 'Sliders', D.thresholds['high_'+thresh]) #Start picking up thresholded images elif key_press == ord('a'): D.mode = "start" #Clear all loaded sections elif key_press == ord('c'): D.mode = "clear" D.sections = [] #Remove areas from thresholding elif key_press == ord('r'): if len(D.sections) > 0: D.mode = "subtract" else: print "Cannot switch modes, need a starting area first. Press 'i' " + \ "to select a starting area." # Add areas for thresholding elif key_press == ord('m'): if len(D.sections) > 0: D.mode = "add" else: print "Cannot switch modes, need a starting area first. Press 'i' " + \ "to select a starting area." #Display thresholded image elif key_press == ord('t'): D.current_threshold = D.threshed_image # Activate the robot for moving elif key_press == ord('A'): StateMachine.activate() # Activate robot as leader, following a white line elif key_press == ord('1'): print "Setting mode to \"leader\"." R.curState = "state_lead" StateMachine.state_start("leader") # Activate robot as follower, following the defined target elif key_press == ord('2'): print "Setting mode to \"follower\"." R.curState = "state_follow" StateMachine.state_start("follower") #Robot keyboard driving controls elif key_press == 82: #Up arrow: go forward R.move(80, 80) elif key_press == 84: #Down arrow: go backwards R.move(-50, -50) elif key_press == 81: #Left arrow: turn left R.move(-80, 80) elif key_press == 83: #Right arrow: turn right R.move(80,-80) elif key_press == 32: #Spacebar: stop R.move(0,0)
class TestStateMachine(unittest.TestCase): # state = [0,1,2] state = [RTC.INACTIVE_STATE, RTC.ACTIVE_STATE, RTC.ERROR_STATE] def setUp(self): self._sm = StateMachine(3) self._sm.setNOP(self.nullAction) self._sm.setEntryAction(RTC.ACTIVE_STATE, self.on_activated) self._sm.setEntryAction(RTC.ERROR_STATE,self.on_aborting) self._sm.setPreDoAction(RTC.ACTIVE_STATE, self.on_reset) self._sm.setDoAction(RTC.ACTIVE_STATE, self.on_execute) self._sm.setPostDoAction(RTC.ACTIVE_STATE, self.on_state_update) self._sm.setExitAction(RTC.ACTIVE_STATE, self.on_deactivated) self._sm.setExitAction(RTC.ERROR_STATE, self.on_reset) self._sm.setTransitionAction(self.transition) self._sm.setListener(self) st = StateHolder() st.prev = RTC.INACTIVE_STATE st.curr = RTC.INACTIVE_STATE st.next = RTC.INACTIVE_STATE self._sm.setStartState(st) self._sm.goTo(RTC.INACTIVE_STATE) def nullAction(self, st): print "nullAction." return True def on_activated(self, st): print "on_activated." return True def on_deactivated(self, st): print "on_deactivated." return True def on_aborting(self, st): print "on_aborting." return True def on_error(self, st): print "on_error." return True def on_reset(self, st): print "on_reset." return True def on_execute(self, st): print "on_execute." return True def on_state_update(self, st): print "on_state_update." return True def transition(self, st): print "transition." return True def test_setNOP(self): self._sm.setNOP(self.nullAction) def test_getStates(self): self.assertEqual(self._sm.getStates().curr, RTC.INACTIVE_STATE) self.assertEqual(self._sm.getStates().prev, RTC.INACTIVE_STATE) self.assertEqual(self._sm.getStates().next, RTC.INACTIVE_STATE) st = StateHolder() st.prev = RTC.ERROR_STATE st.curr = RTC.ERROR_STATE st.next = RTC.ERROR_STATE self._sm.setStartState(st) self.assertEqual(self._sm.getStates().curr, RTC.ERROR_STATE) self.assertEqual(self._sm.getStates().prev, RTC.ERROR_STATE) self.assertEqual(self._sm.getStates().next, RTC.ERROR_STATE) def test_getState(self): self.assertEqual(self._sm.getState(), RTC.INACTIVE_STATE) def test_isIn(self): self.assertEqual(self._sm.isIn(RTC.INACTIVE_STATE), True) def test_goTo(self): self._sm.goTo(RTC.INACTIVE_STATE)
def check_key_press(D, key_press): """Handles incoming key presses.""" D.last_key_pressed = key_press if key_press == ord('q') or key_press == 27: # if a 'q' or ESC was pressed R.move(0,0) print "quitting" rospy.signal_shutdown( "Quit requested from keyboard" ) elif key_press == ord('h'): print " Keyboard Command Menu" print " ==============================" print " ESC/q: quit" print " h : help menu" print " s : save thresholds to file" print " l : load thresholds from file" print " c : mousedrags will no longer set thresholds, kept values will be cleared" print " a : mousedrag will assign thresholds to area within drag, \n" + \ " resets on new click or drag" print " r : mousedrags will remove the area under consideration, \n" + \ " must have set an area in 'a' mode first" print " m : mousedrags will add the area under consideration, \n" + \ " must have set an area in 'a' mode first" print " t : show total threshold image in threshold window" print " A : activate robot for moving, press A again to deactivate " print " 1 : begin state machine as leader" print " 2 : begin state machine as follower" #Save thresholds to file elif key_press == ord('s'): fileName = raw_input('Please enter the name of a color: ') fileName += "_thresholds.txt" writeFile = open(fileName, "w") #open file for writing print >> writeFile, D.thresholds writeFile.close() #Load thresholds from file elif key_press == ord('l'): whichFile = raw_input('Please enter the name of a color: ') whichFile += "_thresholds.txt" readFile = open(whichFile, "r") #open file for reading data = readFile.read() D.thresholds = eval(data) readFile.close() D.loaded_thresholds = True #Reset threshold sliders #for thresh in ['red', 'blue', 'green', 'hue', 'sat', 'val']: # cv.SetTrackbarPos('low_' + thresh, 'Sliders', D.thresholds['low_'+thresh]) # cv.SetTrackbarPos('high_' + thresh, 'Sliders', D.thresholds['high_'+thresh]) # Start picking up thresholded images elif key_press == ord('a'): D.mode = "start" # Clear all loaded sections elif key_press == ord('c'): D.mode = "clear" D.sections = [] # Remove areas from thresholding elif key_press == ord('r'): if len(D.sections) > 0: D.mode = "subtract" else: print "Cannot switch modes, need a starting area first. Press 'i' " + \ "to select a starting area." # Add areas for thresholding elif key_press == ord('m'): if len(D.sections) > 0: D.mode = "add" else: print "Cannot switch modes, need a starting area first. Press 'i' " + \ "to select a starting area." elif key_press == ord('t'): D.current_threshold = D.threshed_image # Activate the robot for moving elif key_press == ord('A'): StateMachine.activate() # Activate robot as leader, following a white line elif key_press == ord('1'): print "Setting mode to \"leader\"." StateMachine.state_start("leader") # Activate robot as follower, following the defined target elif key_press == ord('2'): print "Setting mode to \"follower\"." StateMachine.state_start("follower") # Client activation, can send and recieve elif key_press == ord ('w'): serverHost = 'localhost' serverHost = '192.168.1.101' #serverHost = '134.173.195.75' #serverHost = "134.173.195.75" serverHost = "134.173.43.14" serverPort = 2012 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Create a TCP socket s.connect((serverHost, serverPort)) #Connect to server on the port # Figure out what to send message = "" if True: s.send("hi") #send the data data = s.recv(1024) #receive up to 1K bytes print "I received the message:", data s.close() print 'Good bye!' #Robot keyboard driving controls elif key_press == 82: #up arrow: drive forward R.move(250, 250) elif key_press == 84: #down arrow: drive backward R.move(-250, -250) elif key_press == 81: #left arrow: turn left R.move(-250, 250) elif key_press == 83: #right arrow: turn right R.move(250,-250) elif key_press == 32: #spacebar: stop R.move(0,0)
import StateMachine from bitstring import * bd_addr = Bits('0x2c7f94560f1b') kcp = Bits('0x2187f04aba9031d0780d4c53e0153a63') clk = Bits('0x5f1a00') + Bits('0b10') txt = Bits(bytes=' ') keystream,ciphertxt =StateMachine.encipher(bd_addr, kcp, clk, txt) f = open('sampledata4.txt') s = f.read() filebits = Bits(bin=s) l = min(len(keystream), len(filebits)) print keystream[:l] == filebits[:l] for i in range(l/8): print keystream[:l -l%8].hex[i], filebits[:l-l%8].hex[i]