def parse_dict(self, dict_data): printme("[Debug] SimpleGrammar.parse_dict - parsing grammar: %s" % (dict_data, ), debug=True) for key in dict_data: self.add_tag(key, dict_data[key]) return self.evaluate("#text#")
def parse_concept(self, concept, meaning): printme("MetaGame:parse_concept - " + concept, debug=True) if "event_subscriber" in meaning: event_data = meaning["event_subscriber"] for event in event_data: self.action_parser.register_event_subscriber(event, concept) if "concept_type" in meaning: if meaning["concept_type"] == "action": self.action_parser.add_custom_action(concept, meaning["actions"]) elif meaning["concept_type"] == "player_action": if meaning["action_name"].__class__ == list: for player_action in meaning["action_name"]: self.action_parser.add_player_action( player_action, meaning["actions"]) else: self.action_parser.add_player_action( meaning["action_name"], meaning["actions"]) elif meaning["concept_type"] == "instance": parent_meaning = meaning["instanceof"] new_meaning = copy.deepcopy( self.knownledge_base[parent_meaning]) for subconcept in meaning: new_meaning[subconcept] = meaning[subconcept] new_meaning["concept_type"] = "definition" meaning = new_meaning elif meaning.__class__ == dict: meaning["concept_type"] = "definition" self.knownledge_base[concept] = meaning
def parse_contextual_arg(self, arg, action_name, parent_args): if (action_name != "verify" and action_name != "for_each_concept") and arg.__class__ == list: arg = self.run_actions(arg, parent_args) if arg.__class__ == str: for global_var in self.global_vars: arg = arg.replace("#" + str(global_var) + "#", str(self.global_vars[global_var])) if parent_args.__class__ == dict: for key in parent_args: arg = arg.replace("#" + key + "#", parent_args[key]) elif parent_args.__class__ == list: for index, arg_value in enumerate(parent_args): arg_index = "#arg" + str(index + 1) + "#" printme("attempt to replace %s in %s with data %s " % (arg_index, arg, arg_value), debug=True) if arg == arg_index: arg = arg_value break else: arg = arg.replace(arg_index, str(arg_value)) if arg.__class__ == str and "#" in arg: arg = self.parse_concept_inside_string(arg) return arg
def parse_concept_inside_string(self, arg): target_concepts = [] current_concept = "" inside_concept = False for s in arg: if not inside_concept: if current_concept == "" and s == '#': inside_concept = True else: if s == '#': target_concepts.append(current_concept) current_concept = "" inside_concept = False else: current_concept += s for concept in target_concepts: printme("attempt to replace concept inside string: %s" % (concept, ), debug=True) arg = arg.replace("#" + concept + "#", str(self.get_concept(concept))) return arg
def load_game(self, game_files): printme("MetaGame:load_game - " + str(game_files), debug=True) if game_files.__class__ == list: for game_file in game_files: self.load_game(game_file) elif os.path.isdir(game_files): self.load_game( list( map(lambda x: os.path.join(game_files, x), sorted(os.listdir(game_files))))) else: self.load_game_data(game_files)
def _search_for_concept(concept_root, concept_condition): result = None for prop in concept_root: printme("searching_for_concept in property %s" % (prop,), debug=True) prop_value = concept_root[prop] if prop_value.__class__ == dict: if concept_condition(prop_value): return prop_value else: result = _search_for_concept(prop_value, concept_condition) if result is not None: return result return result
def play(self): if "history" in self.knownledge_base["game"]: for history_log in self.knownledge_base["game"]["history"]: print(history_log) else: self.knownledge_base["game"]["history"] = [] printmodule.set_game_buffer(self.knownledge_base["game"]) printme("=" * 8 + " Starting game " + "=" * 8 + "\n\n") self.action_parser.propagate_event("on_game_started") while not self.knownledge_base["game"]["finished"]: player_cmd = self.action_parser.run_action( "get_player_command_action") printme(">> %s" % (player_cmd, ), only_history=True) self.action_parser.run_player_action(player_cmd)
def run_search_for_concept_action(action_parser, data, parent_args): # Update references on action arguments data = data[0].copy() for key in data: data[key] = action_parser.parse_contextual_arg(data[key], "search_for_concept", parent_args) printme("searching_for_concept using args %s" % (data,), debug=True) concept_root = action_parser.get_concept(data["root"]) def concept_condition(concept): condition_result = None condition_value = None if concept.__class__ in [list, dict]: if 'has_property' in data: target_property = data['has_property'] if target_property in concept: target_value = concept[target_property] if 'property_value_contains' in data: if data['property_value_contains'].__class__ == str and target_value.__class__ == str: condition_value = data['property_value_contains'].lower() in target_value.lower() else: condition_value = data['property_value_contains'] in target_value if condition_result is None: condition_result = condition_value else: condition_result = condition_value and condition_result return condition_result concept_found = _search_for_concept(concept_root, concept_condition) return concept_found
def run_verify_action(action_parser, data, parent_args): verify_result = True true_action = None false_action = None if data[0].__class__ == list: verify_result = action_parser.run_actions(data[0], parent_args) true_action = data[1] if len(data) > 2: # Optional argument false_action = data[2] elif data[0] == "concept_exists": verify_result = False printme("verify - concept_exists? %s" % (data[1],), debug=True) if action_parser.get_concept(data[1], verify=True): verify_result = True true_action = data[2] if len(data) > 3: # Optional argument false_action = data[3] elif data[0] == "equals": # print(str(data)) if data[1].__class__ == list: data[1] = action_parser.run_actions(data[1], parent_args) if data[2].__class__ == list: data[2] = action_parser.run_actions(data[2], parent_args) verify_result = (data[1] == data[2]) true_action = data[3] if len(data) > 4: # Optional argument false_action = data[4] elif data[0] == 'less_or_equal_than': if data[1].__class__ == list: data[1] = action_parser.run_actions(data[1], parent_args) data[1] = action_parser.parse_contextual_arg(data[1], '', parent_args) if data[2].__class__ == list: data[2] = action_parser.run_actions(data[2], parent_args) data[2] = action_parser.parse_contextual_arg(data[2], '', parent_args) verify_result = (int(data[1]) <= int(data[2])) true_action = data[3] if len(data) > 4: # Optional argument false_action = data[4] if verify_result: printme("verify - running true action", debug=True) return action_parser.run_actions(true_action, parent_args) else: printme("verify - running false action", debug=True) return action_parser.run_actions(false_action, parent_args)
def run_player_action(self, player_action): # player_cmds = player_action.split(" ") # action_name = player_cmds[0] if player_action == "help": printme("The following commands are available:") for action in self.game["game"]["available_actions"]: printme("- %s" % (action, )) for action in self.player_actions: printme("- %s" % (action, )) else: for action in self.player_actions: if self.actions_matches(player_action, action): self.run_actions( self.player_actions[action], self.parse_actions_args(player_action, action))
def actions_matches(self, player_action, registered_action): words_player_action = player_action.strip().split(" ") words_registered_action = registered_action.strip().split(" ") if len(words_registered_action) != len(words_player_action): return False for action, register in zip(words_player_action, words_registered_action): printme("actions_matches: %s - %s" % (action, register), debug=True) if action != register and not register.isupper(): printme("actions_matches: %s - %s - return False" % (action, register), debug=True) return False printme("actions_matches: %s - %s - return True" % (player_action, registered_action), debug=True) return True
def parse(self, data): printme("[Debug] SimpleGrammar.parse - parsing grammar: %s" % (data, ), debug=True) if data.__class__ == dict: return self.parse_dict(data)
def run_action(self, action_name, data=None, parent_args=None): printme("running action: %s with data %s and parent args: %s" % (action_name, data, parent_args), debug=True) if data is not None: new_data = [] for arg in data: arg = self.parse_contextual_arg(arg, action_name, parent_args) printme("final arg: %s" % (arg, ), debug=True) new_data.append(arg) data = new_data if action_name == "get_player_command_action": return self.session.prompt(">> ") elif action_name == "print": print_msg = "" for print_arg in data: msg = print_arg if msg.__class__ == list: msg = self.run_action(msg[0], msg[1:], parent_args) print_msg += str(msg) printme(print_msg) elif action_name == "exit": sys.exit() elif action_name == "save": with open(data[0], 'w') as f: json.dump(self.game, f) elif action_name == "get_concept": current_concept = self.get_concept(data[0]) printme("Returns concept %s" % (current_concept, ), debug=True) return current_concept elif action_name == "get_concept_list": current_concept_list = self.get_concept(data[0]) if current_concept_list.__class__ == dict: current_concept_list = list(current_concept_list.keys()) printme("Returns concept list %s" % (current_concept_list, ), debug=True) return current_concept_list elif action_name == "set_concept": self.set_concept(data[0], data[1:]) elif action_name == "remove_concept": target_keywords = data[0].split("/") current_concept = self.game for keyword in target_keywords[:-1]: if keyword not in current_concept: # Create a subconcept current_concept[keyword] = {} current_concept = current_concept[keyword] if current_concept.__class__ == list: current_concept.remove(target_keywords[-1]) else: current_concept.pop(target_keywords[-1]) elif action_name == "grammar": grammar = SimpleGrammar() target_grammar = data[0] if target_grammar.__class__ == list: target_grammar = target_grammar[0] printme("loading grammar: %s" % (target_grammar, ), debug=True) text = grammar.parse(target_grammar) printme("grammar generated text: %s" % (text, ), debug=True) return text elif action_name == "run": target_actions = data[0] if target_actions.__class__ == str: target_actions = ast.literal_eval(target_actions) return self.run_actions(target_actions, parent_args) elif action_name == "return": return data[0] elif action_name == "instantiate": target_concept = self.get_concept(data[0]) store_concept = data[1] new_concept_name = data[0].split("/")[-1] + ("instance_%4d" % (randint(0, 9999), )) new_concept = store_concept + "/" + new_concept_name self.global_vars["LAST_INSTANTIATE_ENTITY"] = new_concept self.set_concept(new_concept, target_concept) elif action_name == "propagate_event": self.propagate_event(data[0]) elif action_name in self.custom_actions: self.run_actions(self.custom_actions[action_name], data) elif action_name == "toggle_debug": metagame.utils.printme.show_debug = not metagame.utils.printme.show_debug elif action_name in self.action_parsers: return self.action_parsers[action_name](self, data, parent_args) else: if "#" in action_name: action_name = self.parse_contextual_arg( action_name, "", parent_args) possible_concept = self.get_concept(action_name) if possible_concept and possible_concept.__class__ == list: concept_path = action_name.strip().split("/") if len(concept_path) > 1: concept_path = concept_path[:-1] root_concept = "/".join(concept_path) printme("root concept: " + str(root_concept), debug=True) self.global_vars["SELF"] = root_concept action_value = self.run_actions(possible_concept, data) self.global_vars["SELF"] = None return action_value else: return str([action_name] + data)
def add_player_action(self, action_name, actions): printme("ActionParser:add_player_action - action_name: " + action_name, debug=True) self.player_actions[action_name] = actions