def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME + '/music/' + self.party['map']['music'] + '.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME + "/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME + "/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME + "/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME + "/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME + "/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask, 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start()
def run(self): for i in range(self.sec): self.netTest() try: if self.netFalg: # 網路旗標 有無網路 if self.falg: # 第一次近來不做 因為沒有上次車子的位置 carNow = AT.GPS() print(carNow) carState = final.mydata(carNow, self.carLast) # 車狀態[時速,方向] while 1: values_list = self.sheet.row_values( 3) # 取得救護車 最新位置 values_list1 = self.sheet.row_values( 4) # 取得救護車 上次位置 if (values_list and values_list1): break print("sheet 抓不到資料...") time.sleep(0.5) ambCarM = final.AMBandmy( carNow, values_list[1]) # 車跟救護車[距離(M),方向] ambState = final.AMBdata(values_list[1], values_list1[1]) # 救護車[時速,方向] self.carLast = carNow self.state = [ str(carState[0]) + " KM/H", str(ambCarM[1]), str(ambCarM[0]), str(self.netFalg) ] else: self.carLast = AT.GPS() self.falg = 1 self.state = [ "0 KM/H", "無", "99999", str(self.netFalg) ] else: self.state = ["0 KM/H", "無", "99999", str(self.netFalg)] except: self.state = ["0 KM/H", "無", "99999", str(self.netFalg)] self.sec_changed_signal.emit(self.state) # 觸發函式 time.sleep(self.timerTime)
def main_menu(): os.system('clear') print('Welcome to Auto Reistration System') print('Input the following number for features') print('1.New Vehicle Registration') print('2.Auto Transaction') print('3.Driver License Registration') print('4.Violation Record') print('5.Search Engine') print('0.Exit Program') cmd = input('Please enter your choice: ') if cmd not in {'0','1','2','3','4','5'}: print('Invalid input, please try again!') cmd = input('Please enter your choice: ') if cmd == '0': exit() elif cmd == '1': NVR.NVR_main() main_menu() elif cmd == '2': AT.AT_main() main_menu() elif cmd == '3': DLR.DLR_main() main_menu() elif cmd == '4': VR.VR_main() main_menu() elif cmd == '5': SE.SE_main() main_menu() else: main_menu()
def access(): while 1: data,accaddr = outsock.recvfrom(1024) dstaddr = AT.text2addr(data) print dstaddr addAddrlist(dstaddr) outsock.close()
def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME+'/music/'+self.party['map']['music']+'.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME+"/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME+"/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME+"/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME+"/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME+"/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask , 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start()
def __init__(self, atHandle=None, serialHandle=None, logger=None, event=None): self._serial = serialHandle or serial.Serial() self._at = atHandle or AT.AT() if logger == None: logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger() else: self.logger = logger self.event = event
def __init__(self, atHandle=None, serialHandle=None, logger=None, gpioPin=None, event=None): if logger == None: logging.basicConfig(level=logging.DEBUG) self.logger = logging.getLogger() else: self.logger = logger self.event = event self._serial = serialHandle or self.startSerial(self._device, 9600, self._timeout) if not self._serial: sys.exit(1) self._at = atHandle or AT.AT(self._serial, self.logger, gpioPin, self.event)
def __GetPhonebook( self ): print( 'GetPhonebook started' ) pbapContacts = Pbap.Pbap( self.__device ) if( pbapContacts.SupportsPhonebook() ): self.__phonebook.FromPbapVCards( pbapContacts.GetVCards() ) self.__drawPhonebook = self.__phonebook return True else: atContacts = AT.AT( self.__device ) if( atContacts.SupportsPhonebook() ): self.__phonebook = atContacts.GetPhonebook() self.__drawPhonebook = self.__phonebook return True return False
def get_teams(PIL_image, debug=False): """ Analyzes sidebar panel and returns an array of all available teams. :param cv2_gray: if provided, searches in the image instead, otherwise makes a new screenshot :param debug: boolean, if true, shows an image with highlighted ATs and their type :return: an array of assault teams with [type, XY, [0, 0, 0], [maxsoldiers, maxvehicles, maxmorale]] elements """ cv2_gray = convert_PILToCV2(PIL_image, cv2.COLOR_RGB2GRAY) # Excluding parts of the picture that do not contain AT panel cv2.rectangle(cv2_gray, (0, 0), (CLOSE_PANEL_POS[0], SCREEN_RESOLUTION[1]), 0, -1) # Preallocating memory for our Assault Teams teams = [] for elem in AT_TEMPLATES: template, type, maxStats = elem w, h = template.shape[::-1] res = cv2.matchTemplate(cv2_gray, template, cv2.TM_CCOEFF_NORMED) threshold = 0.9 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): # First we need to check if there is any other team placed at these coordinates # In order to do that, we calculate the minimum distance between pt and locations of teams we found before mindist = 1000 for t in teams: d = distance(pt, t.getPos()) if d < mindist: mindist = d # multiple recognition of the same template in the small area usually fall on the next pixels, so 5px is enough to rule that out if mindist < 5: continue # If pt is far enough from teams we've already counted, it must be an uncounted team # Therefore we should add this team in the list of teams status = parse_team_status(PIL_image, pt, maxStats) team = AT.AssaultTeam(type, pt, maxStats) team.setStatus(status) teams.append(team) if debug: print status cv2.rectangle(cv2_gray, pt, (pt[0] + w, pt[1] + h), 255, 2) cv2.putText(cv2_gray, '%s' % type, (pt[0], pt[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 1) if debug: cv2.imwrite(DEBUG_DIR + get_screenshot_name(), cv2_gray) return teams
def Connect(self): index = self.comport_list.curselection() if index: comport = self.comport_list.get(index) self.logger.info("Connecting: " + comport) try: self.atDevice = AT.ATDevice(comport) except: self.logger.warn("Device taken") else: self.logger.info("Comport opened") self.Disconnect_Btn.config(state="normal") self.Connect_Btn.config(state="disable") else: self.logger.warn("Wrong COM port selected")
def _restartClasses(self, baudrate): try: self.ser = serial.Serial(self.args.device, baudrate, timeout=self.args.timeout) except serial.SerialException as e: self.logger.error("Failed to open port {}: {}".format( self.args.device, e.strerror)) sys.exit(1) try: if self.args.gpio: self.at = AT.AT(self.ser, self.logger, self.args.gpio) else: self.at = AT.AT(self.ser, self.logger) except Exception as e: self.logger.error("Failed to create AT class: {}".format(e)) sys.exit(1) try: self.fw = FW.FW(self.at, self.ser, self.logger) except serial.SerialException as e: self.logger.error("Failed to create FW class: {}".format(e)) sys.exit(1)
from numpy import linalg as LA import AT data_path = "data_BBA/" std_IP = 0.00452646 * 0.1 # 0.1px, for ref. std_IP2 = 0.00122331 * 0.1 # 0.1px, for smart std_GPS = 0.0001 # 0.0001m, for ref. std_INS = np.deg2rad(0.0001) # 0.0001deg, for ref std_GPS2 = 1 # 1m, for smart std_INS2 = np.deg2rad(1.) # 1deg, for smart ## Import Data Files print("(1) Import Data Files") # Import IOP of Reference & Target Images IO_ref = AT.import_IOP_with_Name(data_path + "IO_ref.txt", "Reference Images") # Reference - UAV Images IO_tar = AT.import_IOP_with_Name(data_path + "IO_tar.txt", "Target Images") # Target - Smartphone Images IO = np.asarray([IO_ref[0:3], IO_tar]) # Import EOP of Reference Images to be used for EOP Constraints EO_c = AT.import_EOP_with_Name(data_path + "EO_c_ref.txt", "Reference Images") no_EO_c = EO_c.shape[0] # Import Initial EOP of Target Images EO_i_tar = AT.import_EOP_with_Name(data_path + "EO_i_tar.txt", "Target Images") EO_i_tar[:, 0] = no_EO_c + 1 EO_i_tar[:, 1:4] = EO_i_tar[:, 1:4] #+ np.random.randn(1,3) * std_GPS2 EO_i_tar[:, 4:7] = EO_i_tar[:, 4:7] #+ np.random.randn(1,3) * std_INS2 no_EO_tar = EO_i_tar.shape[0]
import numpy as np import AT data_path = "data_Pre/" # Reference Images pixCnt_ref = np.asarray([5304, 7952]) # px pixSize_ref = 0.00452646 # mm/px ## Read TP & Image list & EO # iPhone 7 pixCnt_acq = np.asarray([3024, 4032]) # px pixSize_acq = 0.00122331 # mm/px TP = AT.import_IP(data_path + 'TP.txt') #TP = AT.import_IP('ResultText/' + 'TP.txt') imgList = AT.import_ImageList(data_path + 'ImgList.txt') for n in range(len(imgList)): imgList[n] = imgList[n].replace('\n', '') idxAcqImg = len(imgList) # Index of the acquired image idxRef = AT.import_IndexRef(data_path + 'indexRef.txt') EO_ref = AT.import_EOP(data_path + 'EO_ref_true.txt') EO_ref[:, 4:7] = np.deg2rad(EO_ref[:, 4:7]) EO_acq = AT.import_EOP(data_path + 'EO_smart_true.txt') EO_acq[:, 4:7] = np.deg2rad(EO_acq[:, 4:7]) ## 1. Converting coordinate system from ICS to CCS
class Client(object): def __init__(self): self.music = base.loader.loadSfx(GAME+'/music/24.ogg') self.music.setLoop(True) self.music.play() self.background = GUI.Background(self.loginScreen) # Display the login window def loginScreen(self): self.loginwindow = GUI.LoginWindow(self.authenticate) def processData(self, datagram): iterator = PyDatagramIterator(datagram) source = datagram.getConnection() callback = iterator.getString() getattr(globals()[callback], 'execute')(self, iterator) # This task process data sent by the server, if any def tskReaderPolling(self, taskdata): if self.cReader.dataAvailable(): datagram=NetDatagram() if self.cReader.getData(datagram): self.processData(datagram) return Task.cont # Setup connection and send the LOGIN datagram with credentials def authenticate(self): login = self.loginwindow.loginEntry.get() password = self.loginwindow.passwordEntry.get() self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cReader.setTcpHeaderSize(4) self.myConnection = self.cManager.openTCPClientConnection(IP, PORT, 5000) if self.myConnection: self.cReader.addConnection(self.myConnection) self.send = Send(self.cManager, self.myConnection) print 'Client listening on', IP, ':', PORT taskMgr.add(self.tskReaderPolling, "Poll the connection reader") self.send.LOGIN_MESSAGE(login, password) else: print 'Can\'t connect to server on', IP, ':', PORT # The battle begins def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME+'/music/'+self.party['map']['music']+'.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME+"/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME+"/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME+"/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME+"/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME+"/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask , 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start() def updateAllSpritesAnimations(self, animation): for i,charid in enumerate(self.matrix.sprites): Sequence( Wait(float(i)/6.0), Func(self.updateSpriteAnimation, charid, animation), ).start() def end(self): taskMgr.remove('characterDirectionTask') for child in render.getChildren(): child.removeNode() self.camhandler.destroy() self.coords.destroy() self.sky.remove() self.background = GUI.Background(self.send.GET_PARTIES) def showMenu(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() canmove = self.party['chars'][charid]['canmove'] canact = self.party['chars'][charid]['canact'] columns = [ { 'x': -25, 'font': GUI.regularfont, 'align': TextNode.ALeft }, ] rows = [ { 'cells': ['Move' ], 'enabled': canmove, 'callback': lambda: self.send.GET_WALKABLES (charid) }, { 'cells': ['Act' ], 'enabled': canact , 'callback': lambda: self.onAttackClicked(charid) }, { 'cells': ['Wait' ], 'enabled': True , 'callback': lambda: self.onWaitClicked (charid) }, { 'cells': ['Status' ], 'enabled': False , 'callback': lambda: self.onWaitClicked (charid) }, { 'cells': ['Auto-Battle' ], 'enabled': False , 'callback': lambda: self.onWaitClicked (charid) }, ] GUI.ScrollableList( 'shadowed', 73, -8, 62.0, 91.0, 16, columns, rows, 5, lambda: self.onCancelClicked(charid), 'Menu' ) def moveCheck(self, charid, orig, origdir, dest): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.MoveCheck( lambda: self.send.MOVE_TO(charid, dest), lambda: self.cancelMove(charid, orig, origdir) ) def cancelMove(self, charid, orig, origdir): self.matrix.sprites[charid].node.setPos(self.battleGraphics.logic2terrain(orig)) self.matrix.sprites[charid].setRealDir(origdir) self.send.UPDATE_PARTY() # Makes a character look at another one def characterLookAt(self, charid, targetid): (x1, y1, z1) = self.matrix.getCharacterCoords(charid) (x2, y2, z2) = self.matrix.getCharacterCoords(targetid) if x1 > x2: self.matrix.sprites[charid].setRealDir(3) if x1 < x2: self.matrix.sprites[charid].setRealDir(1) if y1 > y2: self.matrix.sprites[charid].setRealDir(4) if y1 < y2: self.matrix.sprites[charid].setRealDir(2) # Update the status (animation) of a sprite after something happened def updateSpriteAnimation(self, charid, animation=False): if animation: self.matrix.sprites[charid].animation = animation else: stats = self.party['chars'][charid] if stats['hp'] >= (stats['hpmax']/2): self.matrix.sprites[charid].animation = 'walk' if stats['hp'] < (stats['hpmax']/2): self.matrix.sprites[charid].animation = 'weak' if stats['hp'] <= 0: self.matrix.sprites[charid].animation = 'dead' self.die_snd.play() h = self.camhandler.container.getH() self.matrix.sprites[charid].updateDisplayDir( h, True ) def updateCursorPos(self, pos): self.camhandler.move(self.battleGraphics.logic2terrain(pos)) (x, y, z) = pos tile = self.party['map']['tiles'][x][y][z] self.cursor.move(x, y, z, tile) if self.charbars: self.charbars.hide() if self.party['map']['tiles'][x][y][z].has_key('char'): charid = self.party['map']['tiles'][x][y][z]['char'] char = self.party['chars'][charid] if self.subphase == 'attack': self.charbars = GUI.CharBarsRight(char) else: self.charbars = GUI.CharBarsLeft(char) try: self.coords.update(tile) except: self.coords = GUI.Coords(tile) ### Events # Battle func def setupWalkableTileChooser(self, charid, walkables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'move' self.matrix.setupWalkableZone(charid, walkables) if self.charcard: self.charcard.hide() # Battle func def setupAttackableTileChooser(self, charid, attackables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'attack' self.matrix.setupAttackableZone(charid, attackables) if self.charcard: self.charcard.hide() # Battle func def setupDirectionChooser(self, charid): self.inputs.ignoreAll() self.camhandler.acceptAll() self.at.hide() DirectionChooser(charid, self.matrix.sprites[charid], self.camhandler, self.send.WAIT, self.send.UPDATE_PARTY) # Attack button clicked def onAttackClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 155, 44, 'shadowed', 'Check', 'Specify the target with the cursor.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.send.GET_ATTACKABLES(charid), self.send.UPDATE_PARTY, ) # Wait menu item chosen def onWaitClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 135, 60, 'shadowed', 'Check', 'Specify the direction with\nthe Directional buttons.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.setupDirectionChooser(charid), self.send.UPDATE_PARTY, ) # Cancel menu item chosen def onCancelClicked(self, charid): self.inputs.acceptAll() self.camhandler.acceptAll() if self.charcard: self.charcard.hide() ### Tasks # Updates the displayed direction of a character according to the camera angle def characterDirectionTask(self, task): h = self.camhandler.container.getH() for charid in self.matrix.sprites: self.matrix.sprites[charid].updateDisplayDir( h ); return Task.cont
class Client(object): def __init__(self): self.music = base.loader.loadSfx(GAME + '/music/24.ogg') self.music.setLoop(True) self.music.play() self.background = GUI.Background(self.loginScreen) # Display the login window def loginScreen(self): self.loginwindow = GUI.LoginWindow(self.authenticate) def processData(self, datagram): iterator = PyDatagramIterator(datagram) source = datagram.getConnection() callback = iterator.getString() getattr(globals()[callback], 'execute')(self, iterator) # This task process data sent by the server, if any def tskReaderPolling(self, taskdata): if self.cReader.dataAvailable(): datagram = NetDatagram() if self.cReader.getData(datagram): self.processData(datagram) return Task.cont # Setup connection and send the LOGIN datagram with credentials def authenticate(self): login = self.loginwindow.loginEntry.get() password = self.loginwindow.passwordEntry.get() self.cManager = QueuedConnectionManager() self.cListener = QueuedConnectionListener(self.cManager, 0) self.cReader = QueuedConnectionReader(self.cManager, 0) self.cReader.setTcpHeaderSize(4) self.myConnection = self.cManager.openTCPClientConnection( IP, PORT, 5000) if self.myConnection: self.cReader.addConnection(self.myConnection) self.send = Send(self.cManager, self.myConnection) print 'Client listening on', IP, ':', PORT taskMgr.add(self.tskReaderPolling, "Poll the connection reader") self.send.LOGIN_MESSAGE(login, password) else: print 'Can\'t connect to server on', IP, ':', PORT # The battle begins def battle_init(self): self.subphase = None # Instanciate the camera handler self.camhandler = CameraHandler() # Instanciate the keyboard tile traverser self.inputs = KeyboardTileTraverser(self) # Instanciate the battle graphics self.battleGraphics = BattleGraphics(self.party['map']) # Light the scene self.battleGraphics.lightScene() # Display the terrain self.battleGraphics.displayTerrain() # Play the background music self.music = base.loader.loadSfx(GAME + '/music/' + self.party['map']['music'] + '.ogg') self.music.setLoop(True) self.music.play() # Load sounds self.hover_snd = base.loader.loadSfx(GAME + "/sounds/hover.ogg") self.clicked_snd = base.loader.loadSfx(GAME + "/sounds/clicked.ogg") self.cancel_snd = base.loader.loadSfx(GAME + "/sounds/cancel.ogg") self.attack_snd = base.loader.loadSfx(GAME + "/sounds/attack.ogg") self.die_snd = base.loader.loadSfx(GAME + "/sounds/die.ogg") # Place highlightable tiles on the map self.matrix = Matrix(self.battleGraphics, self.party['map']) self.matrix.placeChars(self.party['chars']) # Instanciate and hide the AT flag self.at = AT() self.at.hide() self.charbars = None self.charcard = None self.actionpreview = None # Generate the sky and attach it to the camera self.sky = Sky(self.party['map']) # Tasks taskMgr.add(self.characterDirectionTask, 'characterDirectionTask') # Cursor stuff self.cursor = Cursor(self.battleGraphics, self.matrix.container) # Add the special effects self.battleGraphics.addEffects() # Battle intro animation SequenceBuilder.battleIntroduction(self).start() def updateAllSpritesAnimations(self, animation): for i, charid in enumerate(self.matrix.sprites): Sequence( Wait(float(i) / 6.0), Func(self.updateSpriteAnimation, charid, animation), ).start() def end(self): taskMgr.remove('characterDirectionTask') for child in render.getChildren(): child.removeNode() self.camhandler.destroy() self.coords.destroy() self.sky.remove() self.background = GUI.Background(self.send.GET_PARTIES) def showMenu(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() canmove = self.party['chars'][charid]['canmove'] canact = self.party['chars'][charid]['canact'] columns = [ { 'x': -25, 'font': GUI.regularfont, 'align': TextNode.ALeft }, ] rows = [ { 'cells': ['Move'], 'enabled': canmove, 'callback': lambda: self.send.GET_WALKABLES(charid) }, { 'cells': ['Act'], 'enabled': canact, 'callback': lambda: self.onAttackClicked(charid) }, { 'cells': ['Wait'], 'enabled': True, 'callback': lambda: self.onWaitClicked(charid) }, { 'cells': ['Status'], 'enabled': False, 'callback': lambda: self.onWaitClicked(charid) }, { 'cells': ['Auto-Battle'], 'enabled': False, 'callback': lambda: self.onWaitClicked(charid) }, ] GUI.ScrollableList('shadowed', 73, -8, 62.0, 91.0, 16, columns, rows, 5, lambda: self.onCancelClicked(charid), 'Menu') def moveCheck(self, charid, orig, origdir, dest): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.MoveCheck(lambda: self.send.MOVE_TO(charid, dest), lambda: self.cancelMove(charid, orig, origdir)) def cancelMove(self, charid, orig, origdir): self.matrix.sprites[charid].node.setPos( self.battleGraphics.logic2terrain(orig)) self.matrix.sprites[charid].setRealDir(origdir) self.send.UPDATE_PARTY() # Makes a character look at another one def characterLookAt(self, charid, targetid): (x1, y1, z1) = self.matrix.getCharacterCoords(charid) (x2, y2, z2) = self.matrix.getCharacterCoords(targetid) if x1 > x2: self.matrix.sprites[charid].setRealDir(3) if x1 < x2: self.matrix.sprites[charid].setRealDir(1) if y1 > y2: self.matrix.sprites[charid].setRealDir(4) if y1 < y2: self.matrix.sprites[charid].setRealDir(2) # Update the status (animation) of a sprite after something happened def updateSpriteAnimation(self, charid, animation=False): if animation: self.matrix.sprites[charid].animation = animation else: stats = self.party['chars'][charid] if stats['hp'] >= (stats['hpmax'] / 2): self.matrix.sprites[charid].animation = 'walk' if stats['hp'] < (stats['hpmax'] / 2): self.matrix.sprites[charid].animation = 'weak' if stats['hp'] <= 0: self.matrix.sprites[charid].animation = 'dead' self.die_snd.play() h = self.camhandler.container.getH() self.matrix.sprites[charid].updateDisplayDir(h, True) def updateCursorPos(self, pos): self.camhandler.move(self.battleGraphics.logic2terrain(pos)) (x, y, z) = pos tile = self.party['map']['tiles'][x][y][z] self.cursor.move(x, y, z, tile) if self.charbars: self.charbars.hide() if self.party['map']['tiles'][x][y][z].has_key('char'): charid = self.party['map']['tiles'][x][y][z]['char'] char = self.party['chars'][charid] if self.subphase == 'attack': self.charbars = GUI.CharBarsRight(char) else: self.charbars = GUI.CharBarsLeft(char) try: self.coords.update(tile) except: self.coords = GUI.Coords(tile) ### Events # Battle func def setupWalkableTileChooser(self, charid, walkables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'move' self.matrix.setupWalkableZone(charid, walkables) if self.charcard: self.charcard.hide() # Battle func def setupAttackableTileChooser(self, charid, attackables): self.inputs.acceptAll() self.camhandler.acceptAll() self.subphase = 'attack' self.matrix.setupAttackableZone(charid, attackables) if self.charcard: self.charcard.hide() # Battle func def setupDirectionChooser(self, charid): self.inputs.ignoreAll() self.camhandler.acceptAll() self.at.hide() DirectionChooser(charid, self.matrix.sprites[charid], self.camhandler, self.send.WAIT, self.send.UPDATE_PARTY) # Attack button clicked def onAttackClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 155, 44, 'shadowed', 'Check', 'Specify the target with the cursor.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.send.GET_ATTACKABLES(charid), self.send.UPDATE_PARTY, ) # Wait menu item chosen def onWaitClicked(self, charid): self.inputs.ignoreAll() self.camhandler.ignoreAll() GUI.Help( 0, 25, 135, 60, 'shadowed', 'Check', 'Specify the direction with\nthe Directional buttons.\nPress the %c button to select.' % CIRCLE_BTN.upper(), lambda: self.setupDirectionChooser(charid), self.send.UPDATE_PARTY, ) # Cancel menu item chosen def onCancelClicked(self, charid): self.inputs.acceptAll() self.camhandler.acceptAll() if self.charcard: self.charcard.hide() ### Tasks # Updates the displayed direction of a character according to the camera angle def characterDirectionTask(self, task): h = self.camhandler.container.getH() for charid in self.matrix.sprites: self.matrix.sprites[charid].updateDisplayDir(h) return Task.cont
def run(self): """ This is the main entry point """ self._checkArgs() # pull in the command line options if (self.args.debug == True): self.logger.info("Setting output level to DEBUG") self._ch.setLevel(logging.DEBUG) # TODO: Check panID and EncrytpionKey args are valid if (self.args.panID): pass if (self.args.encKey): pass # setup the serial port self._serial = serial.Serial() if (self.args.port): self._serial.port = self.args.port else: self._serial.port = self._port if (self.args.baudrate): self._serial.baudrate = self.args.baudrate else: self._serial.baudrate = self._baudrate self._serial.timeout = self._serialTimeout # setup the at class self._at = AT.AT(serialHandle=self._serial, logger=self.logger) self.logger.info( "This app will attempt to read the current PANID and encryption setting from the radio on port {}." .format(self._serial.port)) self.logger.info( "If factory default setting are found we will generate a new PANID and encryption key to setup your radio network" ) self.logger.debug("Attempting to open the serial port") self._serial.open() self.logger.debug("Port open") if self._readCurrent(): if self._defaultPANID == self._panID and self._encryption == False and self._encryptionKey == self._defaultEncryptionKey: self.logger.info("Default settings found") self._generateNewSetings() if self._applySettings(): if self._saveSettings(): self.logger.info( "New setting have been successfully applied") self._printSettings() else: self.logger.info( "Failed to correctly apply setting, no changes have been saved to the device" ) self.exit(1) else: self.logger.info( "Non default settings found, no changes have been made") self._printSettings() if (self.args.force): self.logger.info("Setting update forced via command line") self._generateNewSetings() if self._applySettings(): if self._saveSettings(): self.logger.info( "New setting have been successfully applied") self._printSettings() else: self.logger.info( "Failed to correctly apply setting, no changes have been saved to the device" ) self.exit(1) else: self.logger.info( "Failed to read the current setting from your radio") self.exit(1) self.exit(0)