def sell_to(self, caller): """ Buy this goods. Args: caller: the buyer Returns: """ # check price unit_number = caller.get_object_number(self.unit_key) if unit_number < self.price: caller.msg({"alert": _("Sorry, %s is not enough.") % self.unit_name}) return # check if can get these objects if not caller.can_get_object(self.db.goods.get_data_key(), self.number): caller.msg({"alert": _("Sorry, you can not take more %s.") % self.db.goods.get_name()}) return # Reduce price units. if not caller.remove_object(self.unit_key, self.price): caller.msg({"alert": _("Sorry, %s is not enough.") % self.unit_name}) return # Give goods. obj_list = [{"object": self.db.goods.get_data_key(), "number": self.number}] caller.receive_objects(obj_list)
def cast_skill(self, skill_key, target): """ Cast a skill. Args: skill_key: (string) skill's key. target: (object) skill's target. """ time_now = time.time() if time_now < self.gcd_finish_time: # In GCD. self.msg({"skill_cast": {"cast": _("Global cooling down!")}}) return if skill_key not in self.db.skills: self.msg({"skill_cast": {"cast": _("You do not have this skill.")}}) return skill = self.db.skills[skill_key] if not skill.cast_skill(target, passive=False): return if self.skill_gcd > 0: # set GCD self.gcd_finish_time = time_now + self.skill_gcd # send CD to the player cd = {"skill": skill_key, # skill's key "cd": skill.cd, # skill's cd "gcd": self.skill_gcd} self.msg({"skill_cd": cd}) return
def use_object(self, obj, number=1): """ Use an object. Args: obj: (object) object to use number: (int) number to use Returns: result: (string) the description of the result """ if not obj: return _("Can not find this object.") if obj.db.number < number: return _("Not enough number.") # take effect try: result, used = obj.take_effect(self, number) if used > 0: # remove used object self.remove_object(obj.get_data_key(), used) return result except Exception, e: ostring = "Can not use %s: %s" % (obj.get_data_key(), e) logger.log_tracemsg(ostring)
def func(self): "Use an object." caller = self.caller if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not self.args: caller.msg({"alert":_("You should discard something.")}) return obj = caller.search(self.args, location=caller) if not obj: # If the caller does not have this object. caller.msg({"alert":_("You don't have this object.")}) return # remove used object try: caller.remove_object(obj.get_data_key(), 1) except Exception, e: caller.msg({"alert": _("Can not discard this object.")}) logger.log_tracemsg("Can not discard object %s: %s" % (obj.get_data_key(), e)) return
def func(self): "Use an object." caller = self.caller if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not self.args: caller.msg({"alert":_("You should use something.")}) return obj = caller.search(self.args, location=caller) if not obj: # If the caller does not have this object. caller.msg({"alert":_("You don't have this object.")}) return result = "" try: # Use the object and get the result. result = caller.use_object(obj) except Exception, e: ostring = "Can not use %s: %s" % (obj.get_data_key(), e) logger.log_tracemsg(ostring)
def func(self): "Cast a skill." caller = self.caller if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not self.args: caller.msg({"alert":_("You should select a skill to cast.")}) return skill_key = None if isinstance(self.args, basestring): # If the args is a skill's key. skill_key = self.args else: # If the args is skill's key and target. if not "skill" in self.args: caller.msg({"alert":_("You should select a skill to cast.")}) return skill_key = self.args["skill"] # Get target target = None if "target" in self.args: target = caller.search(self.args["target"]) try: # Prepare to cast this skill. caller.prepare_skill(skill_key, target) except Exception, e: caller.msg({"alert":_("Can not cast this skill.")}) logger.log_tracemsg("Can not cast skill %s: %s" % (skill_key, e)) return
def func(self): """ Main puppet method """ session = self.session player = self.account args = self.args # Find the character to puppet. new_character = None if args: # search for a matching character new_character = [char for char in search.object_search(args) if char.access(player, "puppet")] if not new_character: session.msg({"alert":_("That is not a valid character choice.")}) return new_character = new_character[0] else: # Puppet last character. new_character = player.db._last_puppet if not new_character: session.msg({"alert":_("You should puppet a character.")}) return try: player.puppet_object(session, new_character) player.db._last_puppet = new_character except RuntimeError as exc: session.msg({"alert":_("{rYou cannot become {C%s{n: %s") % (new_character.name, exc)})
def func(self): "Handle command" caller = self.caller if not caller: return if caller.db.level < settings.MIN_HONOUR_LEVEL: caller.msg({"alert":_("You need to reach level %s." % settings.MIN_HONOUR_LEVEL)}) return try: # getcandidates ids = HONOURS_MAPPER.get_characters(caller, settings.HONOUR_OPPONENTS_NUMBER) characters = [caller.search_dbref("#%s" % id) for id in ids] candidates = [char for char in characters if char and not char.is_in_combat()] if candidates: match = random.choice(candidates) # create a new combat handler chandler = create_script(settings.HONOUR_COMBAT_HANDLER) # set combat team and desc chandler.set_combat({1:[match], 2:[caller]}, _("Fight of Honour"), settings.AUTO_COMBAT_TIMEOUT) else: caller.msg({"alert":_("Can not make match.")}) except Exception, e: logger.log_err("Find match error: %s" % e) caller.msg({"alert":_("Can not make match.")})
def func(self): "Continue a dialogue." caller = self.caller if not self.args: caller.msg({"alert":_("You should talk to someone.")}) return npc = None if "npc" in self.args: if self.args["npc"]: # get NPC npc = caller.search(self.args["npc"], location=caller.location) if not npc: caller.msg({"msg":_("Can not find it.")}) return # Get the current sentence. dialogue = "" sentence = 0 have_current_dlg = False try: dialogue = self.args["dialogue"] sentence = int(self.args["sentence"]) have_current_dlg = True except Exception, e: pass
def func(self): """ Handle the looking. """ caller = self.caller args = self.args if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if args: # Use search to handle duplicate/nonexistant results. looking_at_obj = caller.search(args, location=caller.location) if not looking_at_obj: caller.msg({"alert":_("Can not find it.")}) return else: # Observes the caller's location looking_at_obj = caller.location if not looking_at_obj: caller.msg({"msg":_("You have no location to look at!")}) return if not hasattr(looking_at_obj, 'return_appearance'): # this is likely due to us having a player instead looking_at_obj = looking_at_obj.character if not looking_at_obj.access(caller, "view"): # The caller does not have the permission to look. caller.msg({"msg":_("Can not find '%s'.") % looking_at_obj.name}) return if looking_at_obj == caller.location: # Clear caller's target. caller.clear_target() caller.show_location() if caller.is_in_combat(): # If the caller is in combat, add combat info. # This happens when a player is in combat and he logout and login again. # Send "joined_combat" message first. It will set the player to combat status. caller.msg({"joined_combat": True}) # Send combat infos. appearance = caller.ndb.combat_handler.get_appearance() message = {"combat_info": appearance, "combat_commands": caller.get_combat_commands()} caller.msg(message) else: # Set caller's target caller.set_target(looking_at_obj) # Get the object's appearance. appearance = looking_at_obj.get_appearance(caller) caller.msg({"look_obj": appearance}) # the object's at_desc() method. looking_at_obj.at_desc(looker=caller)
def take_off_position(self, position): """ Take off an object from position. """ if not position in self.db.equipments: raise MudderyError(_("Can not find this equipment.")) if not self.db.equipments[position]: raise MudderyError(_("Can not find this equipment.")) # Set object's attribute 'equipped' to False dbref = self.db.equipments[position] for obj in self.contents: if obj.dbref == dbref: obj.equipped = False find = True self.db.equipments[position] = None # reset character's attributes self.refresh_data() message = {"status": self.return_status(), "equipments": self.return_equipments(), "inventory": self.return_inventory()} self.msg(message)
def func(self): """ Implement the function. """ combat_handler = self.caller.ndb.combat_handler if not combat_handler: # caller is not in combat. return self.obj = self.caller odd = 0.0 if self.args: odd = self.args[0] rand = random.random() if rand >= odd: # escape failed return _("Failed.") # send skill's result to the combat handler manually # before the handler is removed from the character combat_handler.msg_all({"skill_cast": {"caller": self.caller.get_name(), "target": self.obj.get_name(), "skill": self.key, "cast": _("{c%s{n tried to escape.") % self.caller.get_name(), "result": _("Succeeded!")}}) combat_handler.skill_escape(self.caller)
def func(self): "Move caller to the exit." caller = self.caller if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not self.args: caller.msg({"alert":_("Should appoint an exit to go.")}) return obj = caller.search(self.args, location=caller.location) if not obj: # Can not find exit. caller.msg({"alert":_("Can not find exit.")}) return if obj.access(self.caller, 'traverse'): # we may traverse the exit. # MudderyLockedExit handles locks in at_before_traverse(). if obj.at_before_traverse(self.caller): obj.at_traverse(caller, obj.destination) else: # exit is locked if obj.db.err_traverse: # if exit has a better error message, let's use it. caller.msg({"alert": self.obj.db.err_traverse}) else: # No shorthand error message. Call hook. obj.at_failed_traverse(caller)
def func(self): "Handle command" caller = self.caller if not caller: return if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not self.args: caller.msg({"alert":_("You should select a target.")}) return target = caller.search_dbref(self.args) if not target: caller.msg({"alert":_("You should select a target.")}) return if not caller.location or caller.location.peaceful: if target.has_account: caller.msg({"alert":_("You can not attack in this place.")}) return if not target.is_alive(): caller.msg({"alert": _("%s is died." % target.get_name())}) return if caller.location != target.location: caller.msg({"alert": _("You can not attack %s." % target.get_name())}) return # Set caller's target. caller.set_target(target) # set up combat if caller.is_in_combat(): # caller is in battle message = {"alert": _("You are in another combat.")} caller.msg(message) return if target.is_in_combat(): # caller is in battle message = {"alert": _("%s is in another combat." % target.name)} caller.msg(message) return # create a new combat handler chandler = create_script(settings.NORMAL_COMBAT_HANDLER) # set combat team and desc chandler.set_combat({1: [target], 2:[caller]}, "", 0) caller.msg(_("You are attacking {c%s{n! You are in combat.") % target.get_name()) target.msg(_("{c%s{n is attacking you! You are in combat.") % caller.get_name())
def announce_move_to(self, source_location, msg=None, mapping=None, **kwargs): """ Called after the move if the move was not quiet. At this point we are standing in the new location. Args: source_location (Object): The place we came from msg (str, optional): the replacement message if location. mapping (dict, optional): additional mapping objects. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). Notes: You can override this method and call its parent with a message to simply change the default message. In the string, you can use the following as mappings (between braces): object: the object which is moving. exit: the exit from which the object is moving (if found). origin: the location of the object before the move. destination: the location of the object after moving. """ if not source_location and self.location.has_account: # This was created from nowhere and added to an account's # inventory; it's probably the result of a create command. string = "You now have %s in your possession." % self.get_display_name(self.location) self.location.msg(string) return if source_location: if msg: string = msg else: string = _("{object} arrives to {destination} from {origin}.") else: string = _("{object} arrives to {destination}.") origin = source_location destination = self.location exits = [] if origin: exits = [o for o in destination.contents if o.location is destination and o.destination is origin] if not mapping: mapping = {} mapping.update({ "object": self.get_name(), "exit": exits[0].get_name() if exits else "", "origin": origin.get_name() if origin else "", "destination": destination.get_name() if destination else "", }) destination.msg_contents(string.format(**mapping), exclude=(self, ))
def get_available_commands(self, caller): """ This returns a list of available commands. "args" must be a string without ' and ", usually it is self.dbref. """ commands = [] if self.db.number > 0: commands.append({"name": _("Use"), "cmd": "use", "args": self.dbref}) if self.location and self.can_discard: commands.append({"name": _("Discard"), "cmd": "discard", "args": self.dbref}) return commands
def create_normal_player(session, playername, password): """ Create a new player. """ # sanity checks if not re.findall('^[\w. @+-]+$', playername) or not (0 < len(playername) <= 32): # this echoes the restrictions made by django's auth # module (except not allowing spaces, for convenience of # logging in). string = "\n\r Playername can max be 32 characters or fewer. Letters, spaces, digits and @/./+/-/_ only." session.msg({"alert":string}) return # strip excessive spaces in playername playername = re.sub(r"\s+", " ", playername).strip() if AccountDB.objects.filter(username__iexact=playername): # player already exists (we also ignore capitalization here) session.msg({"alert":_("Sorry, there is already a player with the name '%s'.") % playername}) return # Reserve playernames found in GUEST_LIST if settings.GUEST_LIST and playername.lower() in (guest.lower() for guest in settings.GUEST_LIST): string = "\n\r That name is reserved. Please choose another Playername." session.msg({"alert":string}) return if not re.findall('^[\w. @+-]+$', password) or not (3 < len(password)): string = "\n\r Password should be longer than 3 characers. Letters, spaces, digits and @\.\+\-\_ only." \ "\nFor best security, make it longer than 8 characters. You can also use a phrase of" \ "\nmany words if you enclose the password in quotes." session.msg({"alert":string}) return # Check IP and/or name bans bans = ServerConfig.objects.conf("server_bans") if bans and (any(tup[0]==playername.lower() for tup in bans) or any(tup[2].match(session.address) for tup in bans if tup[2])): # this is a banned IP or name! string = "{rYou have been banned and cannot continue from here." \ "\nIf you feel this ban is in error, please email an admin.{x" session.msg({"alert":string}) session.execute_cmd('{"cmd":"quit","args":""}') return # everything's ok. Create the new player account. new_player = None try: new_player = create_player(playername, password) except Exception, e: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. session.msg({"alert":_("There was an error creating the Player: %s" % e)}) logger.log_tracemsg()
def func(self): "Do shopping." caller = self.caller if not self.args: caller.msg({"alert":_("You should shopping in someplace.")}) return shop = caller.search(self.args) if not shop: caller.msg({"alert":_("Can not find this shop.")}) return shop.show_shop(caller)
def func(self): """ Uses the Django admin api. Note that unlogged-in commands have a unique position in that their func() receives a session object instead of a source_object like all other types of logged-in commands (this is because there is no object yet before the player has logged in) """ session = self.caller args = self.args try: playername = args["playername"] password = args["password"] except Exception: string = 'Can not log in.' logger.log_errmsg(string) session.msg({"alert":string}) return # check for too many login errors too quick. if _throttle(session, maxlim=5, timeout=5*60, storage=_LATEST_FAILED_LOGINS): # timeout is 5 minutes. session.msg({"alert":_("{RYou made too many connection attempts. Try again in a few minutes.{n")}) return # Guest login if playername.lower() == "guest": enabled, new_player = create_guest_player(session) if new_player: session.msg({"login":{"name": playername, "dbref": new_player.dbref}}) session.sessionhandler.login(session, new_player) if enabled: return if not password: session.msg({"alert":_("Please input password.")}) return player = connect_normal_player(session, playername, password) if player: # actually do the login. This will call all other hooks: # session.at_login() # player.at_init() # always called when object is loaded from disk # player.at_first_login() # only once, for player-centric setup # player.at_pre_login() # player.at_post_login(session=session) session.msg({"login":{"name": playername, "dbref": player.dbref}}) session.sessionhandler.login(session, player)
def func(self): "Talk to an NPC." caller = self.caller if not self.args: caller.msg({"alert":_("You should talk to someone.")}) return npc = caller.search(self.args, location=caller.location) if not npc: # Can not find the NPC in the caller's location. caller.msg({"alert":_("Can not find the one to talk.")}) return caller.talk_to_npc(npc)
def check_available(self): """ Check this skill. Returns: message: (string) If the skill is not available, returns a string of reason. If the skill is available, return "". """ if self.passive: return _("This is a passive skill!") if self.is_cooling_down(): return _("This skill is not ready yet!") return ""
def get_appearance(self, caller): """ This is a convenient hook for a 'look' command to call. """ # Get name and description. if caller.is_exit_unlocked(self.get_data_key()): # If is unlocked, use common appearance. return super(MudderyLockedExit, self).get_appearance(caller) can_unlock = self.can_unlock(caller) if self.auto_unlock and can_unlock: # Automatically unlock the exit when a character looking at it. caller.unlock_exit(self) # If is unlocked, use common appearance. return super(MudderyLockedExit, self).get_appearance(caller) cmds = [] if can_unlock: # show unlock command verb = self.unlock_verb if not verb: verb = _("Unlock") cmds = [{"name": verb, "cmd": "unlock_exit", "args": self.dbref}] info = {"dbref": self.dbref, "name": self.name, "desc": self.locked_desc, "cmds": cmds} return info
def turn_in(self, quest_key): """ Turn in a quest. Args: quest_key: (string) quest's key Returns: None """ if quest_key not in self.current_quests: return if not self.current_quests[quest_key].is_accomplished: return # Get quest's name. name = self.current_quests[quest_key].get_name() # Call turn in function in the quest. self.current_quests[quest_key].turn_in() # Delete the quest. self.current_quests[quest_key].delete() del (self.current_quests[quest_key]) self.finished_quests.add(quest_key) self.owner.msg({"msg": _("Turned in quest {c%s{n.") % name}) self.show_quests() self.owner.show_location()
def cast_skill(self, target): """ Cast this skill. Args: target: (object) skill's target Returns: (result, cd): result: (dict) skill's result cd: (dice) skill's cd """ owner = self.db.owner time_now = time.time() if not self.passive: if time_now < self.db.cd_finish_time: # skill in CD if owner: owner.msg({"msg": _("This skill is not ready yet!")}) return # call skill function STATEMENT_HANDLER.do_skill(self.function, owner, target, key=self.get_data_key(), name=self.get_name(), message=self.message) if not self.passive: # set cd time_now = time.time() if self.cd > 0: self.db.cd_finish_time = time_now + self.cd return
def die(self, killers): """ This character is killed. Move it to it's home. """ # player's character can always reborn if self.reborn_time < 1: self.reborn_time = 1 super(MudderyPlayerCharacter, self).die(killers) self.msg({"msg": _("You died.")}) if self.reborn_time > 0: self.msg({"msg": _("You will be reborn at {c%(p)s{n in {c%(s)s{n seconds.") % {'p': self.home.get_name(), 's': self.reborn_time}})
def at_after_move(self, source_location): """ We make sure to look around after a move. """ self.msg({"msg": _("Moving to %s ...") % self.location.name}) self.show_location()
def func(self): "Cast a skill." caller = self.caller args = self.args if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not args: caller.msg({"alert":_("You should select a skill to cast.")}) return # find skill skill_key = None target = None if isinstance(args, basestring): # If the args is a skill's key. skill_key = args else: # If the args is skill's key and target. if not "skill" in args: caller.msg({"alert":_("You should select a skill to cast.")}) return skill_key = args["skill"] # Check combat if "combat" in args: if args["combat"]: # must be in a combat if not caller.is_in_combat(): return # Get target if "target" in args: target = caller.search_dbref(args["target"]) try: # Prepare to cast this skill. if caller.is_in_combat(): caller.ndb.combat_handler.prepare_skill(skill_key, caller, target) else: caller.cast_skill(skill_key, target) except Exception, e: caller.msg({"alert":_("Can not cast this skill.")}) logger.log_tracemsg("Can not cast skill %s: %s" % (skill_key, e)) return
def get_available_commands(self, caller): """ This returns a list of available commands. """ commands = [] if GAME_SETTINGS.get("can_give_up_quests"): commands.append({"name": _("Give Up"), "cmd": "giveup_quest", "args": self.get_data_key()}) return commands
def get_available_commands(self, caller): """ This returns a list of available commands. "args" must be a string without ' and ", usually it is self.dbref. """ commands = [] if self.db.number > 0: if getattr(self, "equipped", False): commands.append({"name":_("Take Off"), "cmd":"takeoff", "args":self.dbref}) else: commands.append({"name":_("Equip"), "cmd":"equip", "args":self.dbref}) # Can not discard when equipped if self.location and self.can_discard: commands.append({"name":_("Discard"), "cmd":"discard", "args":self.dbref}) return commands
def get_available_commands(self, caller): """ This returns a list of available commands. """ commands = [] if self.is_alive(): commands.append({"name": _("Attack"), "cmd": "attack", "args": self.dbref}) return commands
def reborn(self): """ Reborn after being killed. """ super(MudderyPlayerCharacter, self).reborn() self.show_status() self.msg( {"msg": _("You are reborn at {c%s{n.") % self.home.get_name()})
def check_available(self, passive): """ Check this skill. Args: passive: (boolean) cast a passive skill. Returns: message: (string) If the skill is not available, returns a string of reason. If the skill is available, return "". """ if not passive and self.passive: return _("{c%s{n is a passive skill!") % self.get_name() if self.is_cooling_down(): return _("{c%s{n is not ready yet!") % self.get_name() return ""
def func(self): "Handle command" caller = self.caller if not caller: return if not caller.is_alive(): caller.msg({"alert": _("You are died.")}) return if caller.location: peaceful = getattr(caller.location.dfield, "peaceful", False) if peaceful: caller.msg({"alert": _("You can not attack in this place.")}) return super(CmdAttack, self).func()
def query_tables(): """ Query all tables' names. """ models = model_mapper.get_all_models() models_info = [{"key": model.__name__, "name": _(model.__name__, category="models") + "(" + model.__name__ + ")"} for model in models if model._meta.app_label == "worlddata"] return models_info
def func(self): "Cast a skill." caller = self.caller args = self.args if not caller.is_alive(): caller.msg({"alert":_("You are died.")}) return if not args: caller.msg({"alert":_("You should select a skill to cast.")}) return # find skill skill_key = None target = None if isinstance(args, basestring): # If the args is a skill's key. skill_key = args else: # If the args is skill's key and target. if not "skill" in args: caller.msg({"alert":_("You should select a skill to cast.")}) return skill_key = args["skill"] # Check combat if "combat" in args: if args["combat"]: # must be in a combat if not caller.is_in_combat(): return # Get target if "target" in args: target = caller.search(args["target"]) try: # Prepare to cast this skill. caller.prepare_skill(skill_key, target) except Exception, e: caller.msg({"alert":_("Can not cast this skill.")}) logger.log_tracemsg("Can not cast skill %s: %s" % (skill_key, e)) return
def func(self): "create the new character" session = self.session player = self.account args = self.args if not args: session.msg({"alert":_("You should give the character a name.")}) return name = args["name"] if not name: session.msg({"alert":_("Name should not be empty.")}) return # sanity checks if not (0 < len(name) <= 30): # Nickname's length string = "\n\r Name can max be 30 characters or fewer." session.msg({"alert":string}) return # strip excessive spaces in playername nickname = re.sub(r"\s+", " ", name).strip() charmax = settings.MAX_NR_CHARACTERS if settings.MULTISESSION_MODE > 1 else 1 if player.db._playable_characters and len(player.db._playable_characters) >= charmax: session.msg({"alert":_("You may only create a maximum of %i characters.") % charmax}) return if utils.search_db_data_type("nickname", name, settings.BASE_PLAYER_CHARACTER_TYPECLASS): # check if this name already exists. session.msg({"alert":_("{rA character named '{w%s{r' already exists.{n") % name}) return try: create_character(player, name) except Exception, e: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. session.msg({"alert":_("There was an error creating the Player: %s" % e)}) logger.log_trace() return
def create_guest_player(session): """ Creates a guest player/character for this session, if one is available. Args: session (Session): the session which will use the guest player/character. Returns: GUEST_ENABLED (boolean), player (Player): the boolean is whether guest accounts are enabled at all. the Player which was created from an available guest name. """ # check if guests are enabled. if not settings.GUEST_ENABLED: return False, None # Check IP bans. bans = ServerConfig.objects.conf("server_bans") if bans and any(tup[2].match(session.address) for tup in bans if tup[2]): # this is a banned IP! string = "{rYou have been banned and cannot continue from here." \ "\nIf you feel this ban is in error, please email an admin.{x" session.msg(string) session.sessionhandler.disconnect(session, "Good bye! Disconnecting.") return True, None try: # Find an available guest name. playername = None for playername in settings.GUEST_LIST: if not AccountDB.objects.filter( username__iexact=playername).count(): break playername = None if playername == None: session.msg( "All guest accounts are in use. Please try again later.") return True, None password = "******" % getrandbits(64) permissions = settings.PERMISSION_GUEST_DEFAULT new_player = create_player(playername, password, permissions=permissions) if new_player: create_character(new_player, playername, permissions=permissions) except Exception as e: # We are in the middle between logged in and -not, so we have # to handle tracebacks ourselves at this point. If we don't, # we won't see any errors at all. session.msg( {"alert": _("There was an error creating the Player: %s" % e)}) logger.log_trace() finally: return True, new_player
class MudderyRoom(TYPECLASS("OBJECT"), DefaultRoom): """ Rooms are like any Object, except their location is None (which is default). They also use basetype_setup() to add locks so they cannot be puppeted or picked up. (to change that, use at_object_creation instead) See examples/object.py for a list of properties and methods available on all Objects. """ typeclass_key = "ROOM" typeclass_name = _("Room", "typeclasses") model_name = "world_rooms" def at_object_creation(self): """ Called once, when this object is first created. This is the normal hook to overload for most object types. """ super(MudderyRoom, self).at_object_creation() self.peaceful = False self.position = None self.background = None def after_data_loaded(self): """ Set data_info to the object. """ super(MudderyRoom, self).after_data_loaded() self.peaceful = getattr(self.dfield, "peaceful", False) self.position = None try: # set position position = getattr(self.dfield, "position", None) if position: self.position = ast.literal_eval(position) except Exception, e: logger.log_tracemsg("load position error: %s" % e) # get background self.background = None resource = getattr(self.dfield, "background", None) if resource: try: resource_info = IMAGE_RESOURCES.get(resource) self.background = { "resource": resource_info.resource, "width": resource_info.image_width, "height": resource_info.image_height } except Exception, e: logger.log_tracemsg("Load background %s error: %s" % (resource, e))
def func(self): "Run the say command" caller = self.caller if not self.args: return if not "channel" in self.args: caller.msg({"alert": _("You should choose a channel to say.")}) return if not "message" in self.args: caller.msg({"alert": _("You should say something.")}) return channel = self.args["channel"] message = self.args["message"] caller.say(channel, message)
def get_available_commands(self, caller): """ This returns a list of available commands. "args" must be a string without ' and ", usually it is self.dbref. """ commands = [] if self.db.number > 0: commands.append({ "name": _("Use"), "cmd": "use", "args": self.dbref }) if self.location and self.can_discard: commands.append({ "name": _("Discard"), "cmd": "discard", "args": self.dbref }) return commands
def world_editor(request): """ Render the world editor. """ data_handlers = DATA_SETS.all_handlers models = [{"key": data_handler.model_name, "name": _(data_handler.model_name, category="models") + "(" + data_handler.model_name + ")"} for data_handler in data_handlers] context = {"models": models, "writers": writers.get_writers()} return render(request, 'worldeditor.html', context)
def learn_skill(self, skill_key, is_default, silent): """ Learn a new skill. Args: skill_key: (string) skill's key is_default: (boolean) if it is a default skill silent: (boolean) do not show messages to the player Returns: (boolean) learned skill """ if skill_key in self.db.skills: self.msg({"msg": _("You have already learned this skill.")}) return False # Create skill object. skill_obj = build_object(skill_key) if not skill_obj: self.msg({"msg": _("Can not learn this skill.")}) return False # set default if is_default: skill_obj.set_default(is_default) # Store new skill. skill_obj.set_owner(self) self.db.skills[skill_key] = skill_obj # If it is a passive skill, player's status may change. if skill_obj.passive: self.refresh_properties() # Notify the player if not silent and self.has_account: self.show_status() self.show_skills() self.msg( {"msg": _("You learned skill {c%s{n.") % skill_obj.get_name()}) return True
def equip_object(self, obj): """ Equip an object. args: obj(object): the equipment object. """ if obj.location != self: raise MudderyError(_("Can not find this equipment.")) type = obj.type position = obj.position if position not in self.db.equipments: raise MudderyError(_("Can not equip it on this position.")) if not EQUIP_TYPE_HANDLER.can_equip(self.db.career, type): raise MudderyError(_("Can not use this equipment.")) # Take off old equipment if self.db.equipments[position]: dbref = self.db.equipments[position] for content in self.contents: if content.dbref == dbref: content.equipped = False # Put on new equipment, store object's dbref. self.db.equipments[position] = obj.dbref # Set object's attribute 'equipped' to True obj.equipped = True # reset character's attributes self.refresh_properties() message = { "status": self.return_status(), "equipments": self.return_equipments(), "inventory": self.return_inventory() } self.msg(message) return
def after_data_loaded(self): """ Set data_info to the object." """ super(MudderyObjectCreator, self).after_data_loaded() # Load creator info. self.loot_verb = getattr(self.dfield, "loot_verb", None) if not self.loot_verb: self.loot_verb = _("Loot") self.loot_condition = getattr(self.dfield, "loot_condition", None)
def level_up(self): """ Upgrade level. Returns: None """ super(MudderyPlayerCharacter, self).level_up() # notify the player self.msg({"msg": _("{c%s upgraded to level %s.{n") % (self.get_name(), self.db.level)})
def func(self): "Put on an equipment." caller = self.caller if not self.args: caller.msg({"alert":_("You should equip something.")}) return obj = caller.search(self.args, location=caller) if not obj: # If the caller does not have this equipment. caller.msg({"alert":_("You don't have this equipment.")}) return try: # equip caller.equip_object(obj) except MudderyError, e: caller.msg({"alert": str(e)}) return
def func(self): "Loot objects." caller = self.caller if not self.args: caller.msg({"alert":_("You should loot something.")}) return obj = caller.search(self.args, location=caller.location) if not obj: # Can not find the specified object. caller.msg({"alert":_("Can not find the object to loot.")}) return try: # do loot obj.loot(caller) except Exception, e: ostring = "Can not loot %s: %s" % (obj.get_data_key(), e) logger.log_tracemsg(ostring)
def at_after_move(self, source_location): """ We make sure to look around after a move. """ self.msg({"msg": _("Moved to %s ...") % self.location.name}) self.show_location() # trigger event if self.has_account: self.location.event.at_character_move_in(self)
def func(self): "Take off an equipment." caller = self.caller if not self.args: caller.msg({"alert":_("You should take off something.")}) return obj = caller.search(self.args, location=caller) if not obj: # If the caller does not have this equipment. caller.msg({"alert":_("You don't have this equipment.")}) return try: # Take off the equipment. caller.take_off_equipment(obj) except MudderyError, e: caller.msg({"alert": str(e)}) return
def level_up(self): """ Upgrade level. Returns: None """ super(MudderyPlayerCharacter, self).level_up() # set honour if self.db.level >= settings.MIN_HONOUR_LEVEL: HONOURS_MAPPER.set_honour(self, 0) self.msg({"alert": _("The honour hall is now opened.")}) # notify the player self.msg({ "msg": _("{c%s upgraded to level %s.{n") % (self.get_name(), self.db.level) })
def func(self): "Buy a goods." caller = self.caller if not self.args: caller.msg({"alert": _("You should buy something.")}) return goods = caller.search_dbref(self.args) if not goods: caller.msg({"alert": _("Can not find this goods.")}) return # buy goods try: goods.sell_to(caller) except Exception as e: caller.msg({"alert": _("Can not buy this goods.")}) logger.log_err("Can not buy %s: %s" % (goods.get_data_key(), e)) return
def get_available_commands(self, caller): """ This returns a list of available commands. """ commands = [] if self.is_alive(): if self.dialogues or self.default_dialogues: # If the character have something to talk, add talk command. commands.append({ "name": _("Talk"), "cmd": "talk", "args": self.dbref }) commands.append({ "name": _("Attack"), "cmd": "attack", "args": self.dbref }) return commands
def announce_move_from(self, destination, msg=None, mapping=None, **kwargs): """ Called if the move is to be announced. This is called while we are still standing in the old location. Args: destination (Object): The place we are going to. msg (str, optional): a replacement message. mapping (dict, optional): additional mapping objects. **kwargs (dict): Arbitrary, optional arguments for users overriding the call (unused by default). You can override this method and call its parent with a message to simply change the default message. In the string, you can use the following as mappings (between braces): object: the object which is moving. exit: the exit from which the object is moving (if found). origin: the location of the object before the move. destination: the location of the object after moving. """ if not self.location: return if msg: string = msg else: string = _( "{object} is leaving {origin}, heading for {destination}.") location = self.location exits = [ o for o in location.contents if o.location is location and o.destination is destination ] if not mapping: mapping = {} mapping.update({ "object": self.get_name(), "exit": exits[0].get_name() if exits else "", "origin": location.get_name() if location else "", "destination": destination.get_name() if destination else "", }) location.msg_contents(string.format(**mapping), exclude=(self, ))
def die(self, killers): """ This character is killed. Move it to it's home. """ # player's character can always reborn if self.reborn_time < 1: self.reborn_time = 1 super(MudderyPlayerCharacter, self).die(killers) self.msg({"msg": _("You died.")}) if self.reborn_time > 0: self.msg({ "msg": _("You will be reborn at {C%(p)s{n in {C%(s)s{n seconds.") % { 'p': self.home.get_name(), 's': self.reborn_time } })
def func(self): "hook function" session = self.session player = self.account args = self.args current_password = args["current"] new_password = args["new"] if not player.check_password(current_password): session.msg({"alert": _("Incorrect password.")}, session=session) return if len(new_password) < 4: session.msg({"alert": _("Password is too simple.")}, session=session) return player.set_password(new_password) player.save() session.msg({"alert": _("Password changed.")}, session=session)
def get_available_commands(self, caller): """ This returns a list of available commands. """ commands = [] if self.is_alive(): commands.append({ "name": _("Attack"), "cmd": "attack", "args": self.dbref }) return commands
def check_available(self): """ Check this skill. Returns: message: (string) If the skill is not available, returns a string of reason. If the skill is available, return "". """ if self.is_cooling_down(): return _("{C%s{n is not ready yet!") % self.get_name() return ""
def get_available_commands(self, caller): """ This returns a list of available commands. """ commands = [] if GAME_SETTINGS.get("can_give_up_quests"): commands.append({ "name": _("Give Up"), "cmd": "giveup_quest", "args": self.get_data_key() }) return commands
def func(self): """ Left the current combat. """ caller = self.caller if not caller.is_in_combat(): # If the caller is not in combat. caller.msg({"msg": _("You are not in combat!")}) return caller.leave_combat()
class MudderySkillBook(TYPECLASS("COMMON_OBJECT")): """ This is a skill book. Players can use it to learn a new skill. """ typeclass_key = "SKILL_BOOK" typeclass_name = _("Skill Book", "typeclasses") model_name = "skill_books" def get_available_commands(self, caller): """ This returns a list of available commands. "args" must be a string without ' and ", usually it is self.dbref. """ commands = [] if self.db.number > 0: commands.append({ "name": _("Use"), "cmd": "use", "args": self.dbref }) if self.location and self.can_discard: commands.append({ "name": _("Discard"), "cmd": "discard", "args": self.dbref }) return commands def take_effect(self, user, number): """ Use this object. Args: user: (object) the object who uses this number: (int) the number of the object to use Returns: (result, number): result: (string) a description of the result number: (int) actually used number """ if not user: raise ValueError("User should not be None.") skill_key = getattr(self.dfield, "skill", None) if not skill_key: return _("No effect."), 0 if user.learn_skill(skill_key, False, False): return _("You learned skill."), 1 else: return _("No effect."), 0