def input_serie(): global t if 't' not in globals(): t = myTvDB() else: logging.debug('connection saved') logging.debug('API initiator: %s', t) result = [] while len(result) < 1: serie = Prompt.promptSimple("Please type your TV Show ") serie = str(''.join(c for c in unicodedata.normalize('NFKD', unicode(serie, 'utf-8')) if unicodedata.category(c) != 'Mn')) result = t.search(serie) if len(result) == 0: print("Unknowned TV Show") elif len(result) > 1: choices = [] for val in result: if not 'firstaired' in val.keys(): val['firstaired'] = '????' choices.append([val['id'],val['seriesname']+' (' + val['firstaired'][0:4] + ')']) result = Prompt.promptChoice("Did you mean...",choices) result = t[result] elif len(result) == 1: result = t[result[0]['id']] return result
def select_episode(serie): s_choice = [] seasons = (season for season in serie.getSeasons() if season != "0" and 'firstaired' in serie[int(season)][1].keys() and serie[int(season)][1]['firstaired'] is not None ) for season in seasons: try: s_choice.append([season,"Season " + season + " aired from " + serie[int(season)][1]['firstaired']]) except: print(season) print(serie[int(season)][1].keys()) season = int(Prompt.promptChoice("Please select season number",s_choice,len(s_choice)-1)) s_choice = [] episodes = (key for key,episode in serie[season].items()) for episode in episodes: s_choice.append([str(episode),"\"" + serie[season][int(episode)]['episodename'] + "\" aired on " + serie[season][int(episode)]['firstaired']]) episode = Prompt.promptChoice("Please select episode number",s_choice,len(s_choice)-1) return { 'season':int(season), 'episode':int(episode), 'expected':serie[season][int(episode)]['firstaired'] }
def _action(s): s.__show_stats(s._player) s.__show_items(s._player) if (i := pmt.prompt( "Take an action:", ("Wait", "Walk", 'Bag', 'Quit'), #, "Stats", "Bag"), pmt.default)) == "Wait": s.w1.wipe() s.w1.print("{} waited".format(s._player))
def updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel = None): if pComponent["componenttype"] == Cassette.componentType: return Cassette.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Add.componentType: return Add.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Evaporate.componentType: return Evaporate.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Transfer.componentType: return Transfer.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == React.componentType: return React.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Prompt.componentType: return Prompt.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Install.componentType: return Install.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Comment.componentType: return Comment.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == TrapF18.componentType: return TrapF18.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == EluteF18.componentType: return EluteF18.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Initialize.componentType: return Initialize.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Mix.componentType: return Mix.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Move.componentType: return Move.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Summary.componentType: return Summary.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == ExternalAdd.componentType: return ExternalAdd.updateToComponent(pUnitOperation, nSequenceID, pComponent, username, database, systemModel) else: raise Exception("Unknown component type: " + pComponent["componenttype"])
def input_keywords(): keywords = [] keyword = 'start' while keyword != '': keyword = Prompt.promptSimple("Enter a keyword [keep blank to finish]") if keyword != '': keywords.append(keyword) return keywords
def __item_menu(s, u): i = pmt.prompt("Items:", [pmt.go_back] + [ "{} ({})".format(i, u.inventory.count(i)) for i in u.inventory.items ], pmt.default, return_option=True) if i != pmt.default: item = u.inventory.take(u.inventory.items[i - 2]) if item.consumable and pmt.prompt("Consume {}".format(item), ("Yes", "No"), pmt.default) == "Yes": s.w1.print("{} consumed {}".format(s._player, item)) u.use_item(item) return str(item) else: u.inventory.put(item) return s.__item_menu(u) return None
def cliPrompt(self, warning=''): while self.getStatus != 'disabled': reponse = Prompt.globalPrompt(self) if reponse == "" or reponse is None: self.setValue(self.default) return if self.validateSingle(reponse, not self.required): self.setValue(reponse) return warning = 'Incorrect answer'
def input_emails(): emails = [] email = 'start' while email != '': email = Prompt.promptSimple("Enter an email [keep blank to finish]") if email != '' and not re.match(r'[^@]+@[^@]+\.[^@]+',email): print('Incorrect format') elif re.match(r'[^@]+@[^@]+\.[^@]+',email): emails.append(email) return emails
def cliPrompt(self,warning=''): while self.getStatus != 'disabled': reponse = Prompt.globalPrompt(self) if reponse == "" or reponse is None: self.setValue(self.default) return if self.validateSingle(reponse,not self.required): self.setValue(reponse) return warning='Incorrect answer'
def createFromComponent(nSequenceID, pComponent, username, database, systemModel=None): if pComponent["componenttype"] == Cassette.componentType: return Cassette.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Add.componentType: return Add.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Evaporate.componentType: return Evaporate.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Transfer.componentType: return Transfer.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == React.componentType: return React.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Prompt.componentType: return Prompt.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Install.componentType: return Install.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Comment.componentType: return Comment.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == TrapF18.componentType: return TrapF18.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == EluteF18.componentType: return EluteF18.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Initialize.componentType: return Initialize.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Mix.componentType: return Mix.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Move.componentType: return Move.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == Summary.componentType: return Summary.createFromComponent(nSequenceID, pComponent, username, database, systemModel) elif pComponent["componenttype"] == ExternalAdd.componentType: return ExternalAdd.createFromComponent(nSequenceID, pComponent, username, database, systemModel) else: raise Exception("Unknown component type: " + pComponent["componenttype"])
def cliPrompt(self): if len(self) < 1: raise ParamExceptions.WrongValue('406','ParamMulti {0} is empty'.format(self.id)) while True: newitem = Param(id=self.id,multi=False,label=self.label,items=copy.deepcopy(self.items),filename=None,trigger=self.trigger) newitem.cliPrompt() if not newitem.isNone(): self.values.append(newitem) if not Prompt.promptYN('Another {0}?'.format(self.label),default='n'): break else: break
def __init__(self, pilas): # creo la instancia para cada movimiento q voy a realizar # se guarda de la forma de tupla (<instancia_felcha>,<instancia_numero>,int_numero) # sin int_numero==0 entonces <instancia_numero>==0, y no voy a tener un actor # como para eliminarlo o desplazarlo por el prompt. self.imag_avanzar = 'imag/Prompt/avanzar.png' self.imag_retroceder = 'imag/Prompt/retroceder.png' self.imag_derecha = 'imag/Prompt/derecha.png' self.imag_izquierda = 'imag/Prompt/izquierda.png' self.imag_cursor = 'imag/Prompt/cursor.png' self.imag_1 = 'imag/Prompt/1.png' self.imag_2 = 'imag/Prompt/2.png' self.imag_3 = 'imag/Prompt/3.png' self.imag_4 = 'imag/Prompt/4.png' self.imag_5 = 'imag/Prompt/5.png' self.imag_6 = 'imag/Prompt/6.png' self.imag_7 = 'imag/Prompt/7.png' self.imag_8 = 'imag/Prompt/8.png' self.imag_9 = 'imag/Prompt/9.png' self.pilas = pilas self.overfl = False self.prompt = Prompt.iniciar(3, 9) # Completo las posiciones de las flechas x = -765 y = -530 for i in range(0, 9): t = (x, y) self.prompt.set_coordenadas( 0, i, t ) # en la fila 0 estan las coordenadas de las flechas y los numeros x = x + 129 # Completo las posiciones de los numeros x = -720 y = -500 for i in range(0, 9): t = (x, y) self.prompt.set_coordenadas( 1, i, t) # en la fila 1 estan las coordenadas de los numeros x = x + 129 # Completo las posiciones del cusor x = -762 y = -530 for i in range(0, 9): t = (x, y) self.prompt.set_coordenadas( 2, i, t) # en la fila 2 estan las coordenadas del cursor x = x + 129
def __init__(self): # creo la instancia para cada movimiento q voy a realizar # se guarda de la forma de tupla (<instancia_felcha>,<instancia_numero>,int_numero) # sin int_numero==0 entonces <instancia_numero>==0, y no voy a tener un actor # como para eliminarlo o desplazarlo por el prompt. self.imag_avanzar='imag/Prompt/avanzar.png' self.imag_retroceder='imag/Prompt/retroceder.png' self.imag_derecha='imag/Prompt/derecha.png' self.imag_izquierda='imag/Prompt/izquierda.png' self.imag_cursor='imag/Prompt/cursor.png' self.imag_1='imag/Prompt/1.png' self.imag_2='imag/Prompt/2.png' self.imag_3='imag/Prompt/3.png' self.imag_4='imag/Prompt/4.png' self.imag_5='imag/Prompt/5.png' self.imag_6='imag/Prompt/6.png' self.imag_7='imag/Prompt/7.png' self.imag_8='imag/Prompt/8.png' self.imag_9='imag/Prompt/9.png' self.overfl=False self.prompt=Prompt.iniciar(3,9) # Completo las posiciones de las flechas x=-765 y=-530 for i in range(0,9): t=(x,y) self.prompt.set_coordenadas(0,i,t) # en la fila 0 estan las coordenadas de las flechas y los numeros x=x+129 # Completo las posiciones de los numeros x=-720 y=-500 for i in range(0,9): t=(x,y) self.prompt.set_coordenadas(1,i,t) # en la fila 1 estan las coordenadas de los numeros x=x+129 # Completo las posiciones del cusor x=-762 y=-530 for i in range(0,9): t=(x,y) self.prompt.set_coordenadas(2,i,t) # en la fila 2 estan las coordenadas del cursor x=x+129
def last_or_next(serie): last = serie.lastAired() next = serie.nextAired() if (last is None): if Prompt.promptYN("Last season not yet started. Do you want to schedule the Season pilot on " + next['firstaired'],'y'): return next else: sys.exit() elif (next is None): if Prompt.promptYN("Last season achieved. Do you want to download the Season final on " + last['firstaired'],'n'): return last else: episode = select_episode(serie) return serie[episode['season']][episode['episode']] else: print("Next episode download scheduled on " + next['firstaired']) str_last = 'Do you want also download the last aired : S{0:02}E{1:02} - {2} ?' if Prompt.promptYN(str_last.format(int(last['seasonnumber']),int(last['episodenumber']),last['firstaired']),'N'): return last else: return next
def cliChange(self): choices = {} width = len(max([i.label for i in self.items], key=len)) for key,item in enumerate(self.items): if isinstance(item,ConfigElement): value = item.value elif isinstance(item,ParamMulti): value = '{0} managed'.format(str(len(item))) else: value = '' line = ("{0:" + str(width)+"} - {1}").format(item.label,value) choices.update({key:line}) reponse = Prompt.promptChoice(str(self.label),choices,warning='',selected=[],default = None,mandatory=True,multi=False) if isinstance(self.items[reponse],ConfigElement): self.items[reponse].cliPrompt() else: self.items[reponse].cliChange()
def setUI(self): self.style = Style() self.prompt = Prompt(self.parent) self.style.theme_use("default") self.loadLogo() self.speed = ComboBox(self.parent) self.speed.pack(side=RIGHT) self.speed.box.bind("<<ComboboxSelected>>", self.pause) self.file = FileButton(self.parent) self.file.pack(fill=X) self.text = TypingField(self.parent) self.text.pack(fill=X) self.text.submit.bind("<Button-1>", self.startPause) self.parent.title("Autotest")
def cliPrompt(self): if len(self) < 1: raise ParamExceptions.WrongValue( '406', 'ParamMulti {0} is empty'.format(self.id)) while True: newitem = Param(id=self.id, multi=False, label=self.label, items=copy.deepcopy(self.items), filename=None, trigger=self.trigger) newitem.cliPrompt() if not newitem.isNone(): self.values.append(newitem) if not Prompt.promptYN('Another {0}?'.format(self.label), default='n'): break else: break
def action_add(m): result = input_serie() if m.getSerie(result.data['id'])['rtn']=='200': print(messages.returnCode['409']) sys.exit() last = result.lastAired() next = result.nextAired() next = last_or_next(result) if m.testConf(False)['rtn']=='200' and Prompt.promptYN('Voulez-vous rajouter des emails de notification ?'): emails = input_emails() else: emails = [] res = m.addSerie(result.data['id'],emails,next['seasonnumber'],next['episodenumber']) if res['rtn']!='200': print('Error during TV Show add: '+res['error']) sys.exit() print(result.data['seriesname'] + u" added") sys.exit()
def cliChange(self): choices = {} width = len(max([i.label for i in self.items], key=len)) for key, item in enumerate(self.items): if isinstance(item, ConfigElement): value = item.value elif isinstance(item, ParamMulti): value = '{0} managed'.format(str(len(item))) else: value = '' line = ("{0:" + str(width) + "} - {1}").format(item.label, value) choices.update({key: line}) reponse = Prompt.promptChoice(str(self.label), choices, warning='', selected=[], default=None, mandatory=True, multi=False) if isinstance(self.items[reponse], ConfigElement): self.items[reponse].cliPrompt() else: self.items[reponse].cliChange()
def action_del(m): '''Delete TV show from configuration file''' logging.debug('Call function action_del()') series = m.getSeries() if series['rtn'] == '300': print("No TV Show scheduled") sys.exit() if series['rtn'] != '200': print('Error during TV Show listing'+series['error']) sys.exit() choix = [] if len(series['result'])>0: for serie in series['result']: choix.append([serie['id'],serie['name']]) else: print("No TV Show scheduled") sys.exit() s_id = Prompt.promptChoice("Which TV Show do you want to unschedule?",choix) result = m.delSerie(s_id) if result['rtn'] != '200': print('Error during Tv Show deletion'+result['error']) else: print('TV Show ' + str(s_id) + ' unscheduled')
def joystick_buttons(self): if joystick.get_button(1): # X on PS4 controller self.active = True if self.color not in color_list: self.color = color_list[self.color_value] if 1 not in self.buttons_pressed: self.buttons_pressed.append(1) else: self.active = False if self.color in color_list: dark_color = [] for value in self.color: if value - 20 < 0: dark_color.append(0) else: dark_color.append(value - 20) self.color = tuple(dark_color) if joystick.get_button(2): # O on PS4 controller self.erase_mode = True if joystick.get_button( 0 ) and 0 not in self.buttons_pressed: # Square on PS4 controller if len(drawings) > 1: drawings.pop(-1) self.buttons_pressed.append(0) if joystick.get_button(5): # R1 on PS4 controller closest_rect_size = sum(self.size) / len(self.size) self.size = (closest_rect_size, closest_rect_size) if joystick.get_button( 4) and 4 not in self.buttons_pressed: # L1 on PS4 Controller self.equal_scale = True self.buttons_pressed.append(4) for i in range(6, 8): if joystick.get_button(i) and i not in self.buttons_pressed: self.speed *= 2 self.buttons_pressed.append(i) if joystick.get_button(8): # Share on PS4 controller global prompt prompt_pos = (win_size[0] / 2, win_size[1] / 3) prompt_size = (160, 90) button_yes = Prompt.Button((prompt_pos[0] - prompt_size[0] * 0.1, prompt_pos[1] + prompt_size[1] * 0.8), (32, 18), "Yes") input_field = Prompt.InputField( (prompt_pos[0] - prompt_size[0] * 0.4, prompt_pos[1] - prompt_size[1] * 0), "Drawing.png") prompt = (Prompt.Prompt(prompt_pos, prompt_size, "Would you like to save?", (button_yes, ), input_field)) self.freeze = True hat = joystick.get_hat(0) if abs(hat[0]) and not self.hats_pressed: self.color_value += hat[0] self.update_color() elif abs(hat[1]) and not self.hats_pressed: global win_color win_color += hat[1] update_win_color() self.ghost.color = color_list[win_color] if abs(hat[0]) or abs(hat[1]): self.hats_pressed = True else: self.hats_pressed = False for button in self.buttons_pressed: if not joystick.get_button(button): self.buttons_pressed.remove(button) if button in (6, 7): self.speed /= 2 if button == 4: self.equal_scale = False if button == 1: drawings.append(win.copy())
def action_edit(m): global t logging.debug('Call function action_edit()') result = m.getSeries() logging.debug('result => '+str(result)) if result['rtn']!='200' and result['rtn']!='300': print('Error during TV Shows reading: '+result['error']) sys.exit() if result['rtn'] == '300': print("No TV Show scheduled") sys.exit() pattern = '{0} - S{1:02}E{2:02} - expected on {3} (status: {4})' choice = [] for serie in result['result']: choice.append([serie['id'],pattern.format(serie['name'],serie['season'],serie['episode'],serie['expected'],serie['status'])]) serie_id = Prompt.promptChoice("Select TV Show to modify",choice,0) for serie in result['result']: if serie['id'] == serie_id: break logging.debug(serie) if (serie['keywords'] is not None): keywords = ' / '.join(serie['keywords']) else: keywords = '' if (serie['emails'] is not None): emails = ' / '.join(serie['emails']) else: emails = '' configData = Prompt.promptChoice( "Selection value you want modify for "+serie['name']+" ("+str(serie['id'])+"):", [ ['pattern', 'Pattern: '+serie['pattern']], ['episode', 'Episode: '+'S{0:02}E{1:02}'.format(serie['season'],serie['episode'])], ['keywords','Search keywords: '+keywords], ['emails', 'Notification emails: ' + emails] ]) if configData == 'pattern': pattern = Prompt.promptSimple("Please enter the new search pattern:",serie['pattern']) serie['pattern'] = pattern if configData == 'episode': if 't' not in globals(): t = myTvDB() else: logging.debug('connection saved') logging.debug('API initiator: %s', t) TVresult = t[serie['id']] episode = select_episode(TVresult) serie['season'] = episode['season'] serie['episode'] = episode['episode'] serie['expected'] = convert_date(episode['expected']) elif configData == 'emails': serie['emails'] = input_emails() elif configData == 'keywords': serie['keywords'] = input_keywords() else: sys.exit() rc = m.setSerie(serie['id'],{ 'pattern':serie['pattern'], 'season':serie['season'], 'episode':serie['episode'], 'emails':serie['emails'], 'keywords':serie['keywords'], 'expected':serie['expected'] },json_c=False) if rc['rtn'] == '200': print("TV Show updated") else: print("Error during TV Show update")
def _battle(s, u1, u2, turn=1): def __fight(u1, u2): if turn == int(turn): s.w1.wipe() s.w1.print('[{}] '.format(int(turn)) + "{} took {} damage from {}".format( u2, u2.take_damage(u1.get_damage()), u1)) def __guard(u): if turn == int(turn): s.w1.wipe() s.w1.print('[{}] '.format(int(turn)) + "{} is on guard!".format(u)) u.guard() def __run(u1, u2): if turn == int(turn): s.w1.wipe() if u1.run(u2): s.w1.print('[{}] '.format(int(turn)) + "{} ran away from combat".format(u1)) return True else: s.w1.print('[{}] '.format(int(turn)) + "{} tried to run away but failed!".format(u1)) return False if not u1.health > 0: s.w1.print("{} won".format(u2)) return u2 if not u2.health > 0: s.w1.print("{} won".format(u1)) return u1 u1.unguard() if type(u1) == Player: s.__show_stats(u1) # TODO: Isso aqui não dá certo para pular linha -> s.w2.print() # Nem \n no começo da string s.w2.print(' ') s.w2.print("{} has {}/{} health".format(u1, u1.health, u1.max_health)) s.w2.print("{} has {}/{} health".format(u2, u2.health, u2.max_health)) action = pmt.prompt( "Choose an action:", ("Fight", "Guard", "Show items", "Run"), #, "Show stats"), pmt.default) else: action = choice(["Fight"] * 2 + ["Guard"]) if action == "Fight": __fight(u1, u2) elif action == "Guard": __guard(u1) elif action == "Show items": if s.__item_menu(u1) is None: u1, u2 = u2, u1 elif action == "Run": if __run(u1, u2): return u2 #elif action == "Show stats": # s.__show_stats(u1) # u1, u2 = u2, u1 return s._battle(u2, u1, turn + 0.5)
def promptDialog(self): self.dialog = Prompt(self.master) self.master.wait_window(self.dialog.top)
def cliChange(self,json): self.validate(json) # Object ######## if self.getType() == 'object': choices = [] width = len(max([i['title'] for i in self['properties'].values()], key=len)) properties = sorted(self['properties'].iteritems(),key=lambda k:k[1]['order'] if 'order' in k[1].keys() else 0) for key,item in properties: if item.getType() in SIMPLE_TYPES: line = item.display(json[key],width=width,ident='') elif item.getType() == 'array': item_count = unicode(len(json[key])) if key in json.keys() else "0" value = '{0} managed'.format(item_count) line = ("{0:" + unicode(width)+"} - {1}").format(item['title'],value) elif item.getType() == 'hidden': continue else: value = 'Managed' line = ("{0:" + unicode(width)+"} - {1}").format(item['title'],value) choices.append(line) reponse = Prompt.promptChoice(unicode(self['title']),choices,warning='',selected=[],default = None,mandatory=True,multi=False) changed_item = properties[reponse][1] result = changed_item.cliChange(json[properties[reponse][0]]) json.update({properties[reponse][0]:result}) return json # array ######## elif self.getType() == 'array': lines = self.display(json) warning = '\n'.join(lines) choices = ['Add','Delete','Reset all'] reponse = Prompt.promptChoice('** Managed {0}'.format(self['title']),choices,warning=warning,selected=[],default = None,mandatory=True,multi=False) if reponse == 0: # Add element = self['items'].cliCreate() if element is not None: json.append(element) return json elif reponse == 1: # Delete result = Prompt.promptSingle( 'Which {0} must be deleted?'.format(self['items']['title']), choix=[self['items'].display(item) for item in json], password=False, mandatory=True, default=None, warning='' ) del json[result] return json elif reponse == 2: # Reset all del json return [] # Field ######## elif self.getType() in SIMPLE_TYPES: result = self.cliCreate() Prompt.print_question(self['title'] + ' changed!') return result # Hidden ######### elif self.getType() == 'hidden': return self['default']
def cliCreate(self,required=False,inList=False): # Object ######## if self.getType() == 'object': result = {} properties = sorted(self['properties'].iteritems(),key=lambda k:k[1]['order'] if 'order' in k[1].keys() else 0) for item in properties: status = '' if 'conditions' in self.keys(): conditions = [cond for cond in self['conditions'] if cond['then_prop'] == item[0]] for cond in conditions: if ( ( cond['if_prop'] in result.keys() and result[cond['if_prop']] in cond['if_val']) or ( cond['if_prop'] not in result.keys() and None in cond['if_val'] ) ): status = cond['then_status'] break if status != 'disabled': item_required = (item[0] in self['required']) if 'required' in self.keys() else False pre_result = item[1].cliCreate(required=item_required) if pre_result is not None: result[item[0]] = pre_result return result # Array ####### elif self.getType() == 'array': result = [] while True: reponse = self['items'].cliCreate(inList=True) if self['items'].getType() in SIMPLE_TYPES: if reponse is not None: result.append(reponse) else: return result elif self['items'].getType() == 'object': if not all(val is None for val in reponse.values()): result.append(reponse) if not Prompt.promptYN('Another {0}?'.format(self['title']),default='n'): return result else: return result # Field ####### elif self.getType() in SIMPLE_TYPES: default = self['default'] if 'default' in self.keys() else None if self.getType() == 'choices': matchObj = re.match(r'^#/choices/(\w+)$',self['$def'],re.M) choices = self['choices'][matchObj.group(1)] default = [item[0] for item in enumerate(self['choices']) if items[1] == default] if default is not None else None else: choices = {} warning = '' while True: description = self['placeholder'] if 'placeholder' in self.keys() else self['description'] if 'description' in self.keys() else self['title'] if inList: description += ' [keep blank to finish]' if self.getType() == 'boolean': result = Prompt.promptYN(self['title'],default=default) else: result = Prompt.promptSingle( description, choix=choices.values(), password=(self.getType() == 'password'), mandatory=required, default=default, warning=warning ) if result == "" or result is None: return default if self.getType() == 'choices': result = choices.keys()[result] try: result = self._convert(result) if result is None: if required: raise Exception else: self.validate(result) return result except: warning='Incorrect answer, {0} expected'.format(self.getType()) elif self.getType() == 'hidden': return self['default'] else: raise Exception
def __walk(s): if (i := pmt.prompt("Where to go:", [pmt.go_back] + s.__map.connections, pmt.default)) != pmt.go_back: s._change_map(i) s.w1.print("{} walked to {}".format(s._player, i)) s.w1.print(s.__map.desc())