evennia.contrib package¶
This sub-package holds Evennia’s contributions - code that may be useful but are deemed too game-specific to go into the core library.
See README.md for more info.
Subpackages¶
- evennia.contrib.ingame_python package
- Submodules
- evennia.contrib.ingame_python.callbackhandler module
- evennia.contrib.ingame_python.commands module
- evennia.contrib.ingame_python.eventfuncs module
- evennia.contrib.ingame_python.scripts module
- evennia.contrib.ingame_python.tests module
- evennia.contrib.ingame_python.typeclasses module
- evennia.contrib.ingame_python.utils module
- evennia.contrib.security package
- evennia.contrib.turnbattle package
- evennia.contrib.tutorial_examples package
- Submodules
- evennia.contrib.tutorial_examples.bodyfunctions module
- evennia.contrib.tutorial_examples.cmdset_red_button module
- evennia.contrib.tutorial_examples.example_batch_code module
- evennia.contrib.tutorial_examples.red_button module
- evennia.contrib.tutorial_examples.red_button_scripts module
- evennia.contrib.tutorial_examples.tests module
- evennia.contrib.tutorial_world package
Submodules¶
evennia.contrib.barter module¶
Barter system
Evennia contribution - Griatch 2012
This implements a full barter system - a way for players to safely trade items between each other using code rather than simple free-form talking. The advantage of this is increased buy/sell safety but it also streamlines the process and makes it faster when doing many transactions (since goods are automatically exchanged once both agree).
This system is primarily intended for a barter economy, but can easily be used in a monetary economy as well – just let the “goods” on one side be coin objects (this is more flexible than a simple “buy” command since you can mix coins and goods in your trade).
In this module, a “barter” is generally referred to as a “trade”.
Trade example
A trade (barter) action works like this: A and B are the parties.
opening a trade
A: trade B: Hi, I have a nice extra sword. You wanna trade? B sees: A says: “Hi, I have a nice extra sword. You wanna trade?”
A wants to trade with you. Enter ‘trade A <emote>’ to accept.
B: trade A: Hm, I could use a good sword … A sees: B says: “Hm, I could use a good sword …
B accepts the trade. Use ‘trade help’ for aid.
B sees: You are now trading with A. Use ‘trade help’ for aid.
negotiating
A: offer sword: This is a nice sword. I would need some rations in trade. B sees: A says: “This is a nice sword. I would need some rations in trade.”
[A offers Sword of might.]
B evaluate sword B sees: <Sword’s description and possibly stats> B: offer ration: This is a prime ration. A sees: B says: “This is a prime ration.”
[B offers iron ration]
A: say Hey, this is a nice sword, I need something more for it. B sees: A says: “Hey this is a nice sword, I need something more for it.” B: offer sword,apple: Alright. I will also include a magic apple. That’s my last offer. A sees: B says: “Alright, I will also include a magic apple. That’s my last offer.”
[B offers iron ration and magic apple]
A accept: You are killing me here, but alright. B sees: A says: “You are killing me here, but alright.”
[A accepts your offer. You must now also accept.]
- B accept: Good, nice making business with you.
You accept the deal. Deal is made and goods changed hands.
- A sees: B says: “Good, nice making business with you.”
B accepts the deal. Deal is made and goods changed hands.
At this point the trading system is exited and the negotiated items are automatically exchanged between the parties. In this example B was the only one changing their offer, but also A could have changed their offer until the two parties found something they could agree on. The emotes are optional but useful for RP-heavy worlds.
Technical info
The trade is implemented by use of a TradeHandler. This object is a common place for storing the current status of negotiations. It is created on the object initiating the trade, and also stored on the other party once that party agrees to trade. The trade request times out after a certain time - this is handled by a Script. Once trade starts, the CmdsetTrade cmdset is initiated on both parties along with the commands relevant for the trading.
Ideas for NPC bartering:
This module is primarily intended for trade between two players. But it can also in principle be used for a player negotiating with an AI-controlled NPC. If the NPC uses normal commands they can use it directly – but more efficient is to have the NPC object send its replies directly through the tradehandler to the player. One may want to add some functionality to the decline command, so players can decline specific objects in the NPC offer (decline <object>) and allow the AI to maybe offer something else and make it into a proper barter. Along with an AI that “needs” things or has some sort of personality in the trading, this can make bartering with NPCs at least moderately more interesting than just plain ‘buy’.
Installation:
Just import the CmdTrade command into (for example) the default cmdset. This will make the trade (or barter) command available in-game.
-
class
evennia.contrib.barter.CmdAccept(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBaseaccept the standing offer
- Usage:
accept [:emote] agreee [:emote]
This will accept the current offer. The other party must also accept for the deal to go through. You can use the ‘decline’ command to change your mind as long as the other party has not yet accepted. You can inspect the current offer using the ‘offers’ command.
-
_keyaliases= ('accept', 'agree')¶
-
_matchset= {'accept', 'agree'}¶
-
aliases= ['agree']¶
-
help_category= 'trading'¶
-
key= 'accept'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'agree', 'category': 'trading', 'key': 'accept', 'tags': '', 'text': "\n accept the standing offer\n\n Usage:\n accept [:emote]\n agreee [:emote]\n\n This will accept the current offer. The other party must also accept\n for the deal to go through. You can use the 'decline' command to change\n your mind as long as the other party has not yet accepted. You can inspect\n the current offer using the 'offers' command.\n "}¶
-
class
evennia.contrib.barter.CmdDecline(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBasedecline the standing offer
- Usage:
decline [:emote]
This will decline a previously ‘accept’ed offer (so this allows you to change your mind). You can only use this as long as the other party has not yet accepted the deal. Also, changing the offer will automatically decline the old offer.
-
_keyaliases= ('decline',)¶
-
_matchset= {'decline'}¶
-
aliases= []¶
-
help_category= 'trading'¶
-
key= 'decline'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'trading', 'key': 'decline', 'tags': '', 'text': "\n decline the standing offer\n\n Usage:\n decline [:emote]\n\n This will decline a previously 'accept'ed offer (so this allows you to\n change your mind). You can only use this as long as the other party\n has not yet accepted the deal. Also, changing the offer will automatically\n decline the old offer.\n "}¶
-
class
evennia.contrib.barter.CmdEvaluate(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBaseevaluate objects on offer
- Usage:
evaluate <offered object>
This allows you to examine any object currently on offer, to determine if it’s worth your while.
-
_keyaliases= ('eval', 'evaluate')¶
-
_matchset= {'eval', 'evaluate'}¶
-
aliases= ['eval']¶
-
help_category= 'trading'¶
-
key= 'evaluate'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'eval', 'category': 'trading', 'key': 'evaluate', 'tags': '', 'text': "\n evaluate objects on offer\n\n Usage:\n evaluate <offered object>\n\n This allows you to examine any object currently on offer, to\n determine if it's worth your while.\n "}¶
-
class
evennia.contrib.barter.CmdFinish(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBaseend the trade prematurely
- Usage:
end trade [:say] finish trade [:say]
This ends the trade prematurely. No trade will take place.
-
_keyaliases= ('finish trade', 'end trade')¶
-
_matchset= {'end trade', 'finish trade'}¶
-
aliases= ['finish trade']¶
-
help_category= 'trading'¶
-
key= 'end trade'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'finish trade', 'category': 'trading', 'key': 'end trade', 'tags': '', 'text': '\n end the trade prematurely\n\n Usage:\n end trade [:say]\n finish trade [:say]\n\n This ends the trade prematurely. No trade will take place.\n\n '}¶
-
class
evennia.contrib.barter.CmdOffer(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBaseoffer one or more items in trade.
- Usage:
offer <object> [, object2, …][:emote]
Offer objects in trade. This will replace the currently standing offer.
-
_keyaliases= ('offer',)¶
-
_matchset= {'offer'}¶
-
aliases= []¶
-
help_category= 'trading'¶
-
key= 'offer'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'trading', 'key': 'offer', 'tags': '', 'text': '\n offer one or more items in trade.\n\n Usage:\n offer <object> [, object2, ...][:emote]\n\n Offer objects in trade. This will replace the currently\n standing offer.\n '}¶
-
class
evennia.contrib.barter.CmdStatus(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBaseshow a list of the current deal
- Usage:
status deal offers
Shows the currently suggested offers on each sides of the deal. To accept the current deal, use the ‘accept’ command. Use ‘offer’ to change your deal. You might also want to use ‘say’, ‘emote’ etc to try to influence the other part in the deal.
-
_keyaliases= ('deal', 'offers', 'status')¶
-
_matchset= {'deal', 'offers', 'status'}¶
-
aliases= ['deal', 'offers']¶
-
help_category= 'trading'¶
-
key= 'status'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'deal offers', 'category': 'trading', 'key': 'status', 'tags': '', 'text': "\n show a list of the current deal\n\n Usage:\n status\n deal\n offers\n\n Shows the currently suggested offers on each sides of the deal. To\n accept the current deal, use the 'accept' command. Use 'offer' to\n change your deal. You might also want to use 'say', 'emote' etc to\n try to influence the other part in the deal.\n "}¶
-
class
evennia.contrib.barter.CmdTrade(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandInitiate trade with another party
- Usage:
trade <other party> [:say] trade <other party> accept [:say] trade <other party> decline [:say]
Initiate trade with another party. The other party needs to repeat this command with trade accept/decline within a minute in order to properly initiate the trade action. You can use the decline option yourself if you want to retract an already suggested trade. The optional say part works like the say command and allows you to add info to your choice.
-
_keyaliases= ('barter', 'trade')¶
-
_matchset= {'barter', 'trade'}¶
-
aliases= ['barter']¶
-
help_category= 'general'¶
-
key= 'trade'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'barter', 'category': 'general', 'key': 'trade', 'tags': '', 'text': '\n Initiate trade with another party\n\n Usage:\n trade <other party> [:say]\n trade <other party> accept [:say]\n trade <other party> decline [:say]\n\n Initiate trade with another party. The other party needs to repeat\n this command with trade accept/decline within a minute in order to\n properly initiate the trade action. You can use the decline option\n yourself if you want to retract an already suggested trade. The\n optional say part works like the say command and allows you to add\n info to your choice.\n '}¶
-
class
evennia.contrib.barter.CmdTradeBase(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandBase command for Trade commands to inherit from. Implements the custom parsing.
-
_keyaliases= ('command',)¶
-
_matchset= {'command'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'command'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'command', 'tags': '', 'text': '\n Base command for Trade commands to inherit from. Implements the\n custom parsing.\n '}¶
-
-
class
evennia.contrib.barter.CmdTradeHelp(**kwargs)[source]¶ Bases:
evennia.contrib.barter.CmdTradeBasehelp command for the trade system.
- Usage:
trade help
Displays help for the trade commands.
-
_keyaliases= ('trade help',)¶
-
_matchset= {'trade help'}¶
-
aliases= []¶
-
help_category= 'trade'¶
-
key= 'trade help'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'trade', 'key': 'trade help', 'tags': '', 'text': '\n help command for the trade system.\n\n Usage:\n trade help\n\n Displays help for the trade commands.\n '}¶
-
class
evennia.contrib.barter.CmdsetTrade(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetThis cmdset is added when trade is initated. It is handled by the trade event handler.
-
key= 'cmdset_trade'¶
-
path= 'evennia.contrib.barter.CmdsetTrade'¶
-
-
class
evennia.contrib.barter.TradeHandler(part_a, part_b)[source]¶ Bases:
objectObjects of this class handles the ongoing trade, notably storing the current offers from each side and wether both have accepted or not.
-
__init__(part_a, part_b)[source]¶ Initializes the trade. This is called when part A tries to initiate a trade with part B. The trade will not start until part B repeats this command (B will then call the self.join() command)
- Parameters
part_a (object) – The party trying to start barter.
part_b (object) – The party asked to barter.
Notes
We also store the back-reference from the respective party to this object.
-
accept(party)[source]¶ Accept the current offer.
- Parameters
party (object) – The party accepting the deal.
- Returns
- True if this closes the deal, False
otherwise
- Return type
result (object)
Notes
This will only close the deal if both parties have accepted independently. This is done by calling the finish() method.
-
decline(party)[source]¶ Decline the offer (or change one’s mind).
- Parameters
party (object) – Party declining the deal.
- Returns
- True if there was really an
accepted status to change, False otherwise.
- Return type
did_decline (bool)
Notes
If previously having used the accept command, this function will only work as long as the other party has not yet accepted.
-
finish(force=False)[source]¶ Conclude trade - move all offers and clean up
- Parameters
force (bool, optional) – Force cleanup regardless of if the trade was accepted or not (if not, no goods will change hands but trading will stop anyway)
- Returns
If the finish was successful.
- Return type
result (bool)
-
get_other(party)[source]¶ Returns the other party of the trade
- Parameters
party (object) – One of the parties of the negotiation
- Returns
The other party, not the first party.
- Return type
party_other (object)
-
join(part_b)[source]¶ This is used once B decides to join the trade
- Parameters
part_b (object) – The party accepting the barter.
-
list()[source]¶ List current offers.
- Returns
A tuple with two lists, (A_offers, B_offers).
- Return type
offers (tuple)
-
msg_other(sender, string)[source]¶ Relay a message to the other party without needing to know which party that is. This allows the calling command to not have to worry about which party they are in the handler.
- Parameters
sender (object) – One of A or B. The method will figure out the other party to send to.
string (str) – Text to send.
-
offer(party, *args)[source]¶ Change the current standing offer. We leave it up to the command to do the actual checks that the offer consists of real, valid, objects.
- Parameters
party (object) – Who is making the offer
args (objects or str) – Offerings.
-
-
class
evennia.contrib.barter.TradeTimeout(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptThis times out the trade request, in case player B did not reply in time.
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_meta= <Options for TradeTimeout>¶
-
path= 'evennia.contrib.barter.TradeTimeout'¶
-
typename= 'TradeTimeout'¶
-
exception
evennia.contrib.chargen module¶
Contribution - Griatch 2011
> Note - with the advent of MULTISESSION_MODE=2, this is not really as necessary anymore - the ooclook and @charcreate commands in that mode replaces this module with better functionality. This remains here for inspiration.
This is a simple character creation commandset for the Account level. It shows some more info and gives the Account the option to create a character without any more customizations than their name (further options are unique for each game anyway).
In MULTISESSION_MODEs 0 and 1, you will automatically log into an existing Character. When using @ooc you will then end up in this cmdset.
Installation:
Import this module to mygame/commands/default_cmdsets.py and add chargen.OOCCMdSetCharGen to the AccountCmdSet class (it says where to add it). Reload.
-
class
evennia.contrib.chargen.CmdOOCCharacterCreate(**kwargs)[source]¶ Bases:
evennia.commands.command.Commandcreates a character
- Usage:
create <character name>
This will create a new character, assuming the given character name does not already exist.
-
_keyaliases= ('create',)¶
-
_matchset= {'create'}¶
-
aliases= []¶
-
func()[source]¶ Tries to create the Character object. We also put an attribute on ourselves to remember it.
-
help_category= 'general'¶
-
key= 'create'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'create', 'tags': '', 'text': '\n creates a character\n\n Usage:\n create <character name>\n\n This will create a new character, assuming\n the given character name does not already exist.\n '}¶
-
class
evennia.contrib.chargen.CmdOOCLook(**kwargs)[source]¶ Bases:
evennia.commands.default.general.CmdLookooc look
- Usage:
look look <character>
This is an OOC version of the look command. Since an Account doesn’t have an in-game existence, there is no concept of location or “self”.
If any characters are available for you to control, you may look at them with this command.
-
_keyaliases= ('look', 'l', 'ls')¶
-
_matchset= {'l', 'look', 'ls'}¶
-
aliases= ['l', 'ls']¶
-
func()[source]¶ Implements the ooc look command
We use an attribute _character_dbrefs on the account in order to figure out which characters are “theirs”. A drawback of this is that only the CmdCharacterCreate command adds this attribute, and thus e.g. account #1 will not be listed (although it will work). Existence in this list does not depend on puppeting rights though, that is checked by the @ic command directly.
-
help_category= 'general'¶
-
key= 'look'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'l ls', 'category': 'general', 'key': 'look', 'tags': '', 'text': '\n ooc look\n\n Usage:\n look\n look <character>\n\n This is an OOC version of the look command. Since an Account doesn\'t\n have an in-game existence, there is no concept of location or\n "self".\n\n If any characters are available for you to control, you may look\n at them with this command.\n '}¶
-
class
evennia.contrib.chargen.OOCCmdSetCharGen(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.default.cmdset_account.AccountCmdSetExtends the default OOC cmdset.
-
path= 'evennia.contrib.chargen.OOCCmdSetCharGen'¶
-
evennia.contrib.clothing module¶
Clothing - Provides a typeclass and commands for wearable clothing, which is appended to a character’s description when worn.
Evennia contribution - Tim Ashley Jenkins 2017
Clothing items, when worn, are added to the character’s description in a list. For example, if wearing the following clothing items:
a thin and delicate necklace a pair of regular ol’ shoes one nice hat a very pretty dress
A character’s description may look like this:
Superuser(#1) This is User #1.
Superuser is wearing one nice hat, a thin and delicate necklace, a very pretty dress and a pair of regular ol’ shoes.
Characters can also specify the style of wear for their clothing - I.E. to wear a scarf ‘tied into a tight knot around the neck’ or ‘draped loosely across the shoulders’ - to add an easy avenue of customization. For example, after entering:
wear scarf draped loosely across the shoulders
The garment appears like so in the description:
Superuser(#1) This is User #1.
Superuser is wearing a fanciful-looking scarf draped loosely across the shoulders.
Items of clothing can be used to cover other items, and many options are provided to define your own clothing types and their limits and behaviors. For example, to have undergarments automatically covered by outerwear, or to put a limit on the number of each type of item that can be worn. The system as-is is fairly freeform - you can cover any garment with almost any other, for example - but it can easily be made more restrictive, and can even be tied into a system for armor or other equipment.
To install, import this module and have your default character inherit from ClothedCharacter in your game’s characters.py file:
from evennia.contrib.clothing import ClothedCharacter
class Character(ClothedCharacter):
And then add ClothedCharacterCmdSet in your character set in your game’s commands/default_cmdsets.py:
from evennia.contrib.clothing import ClothedCharacterCmdSet
- class CharacterCmdSet(default_cmds.CharacterCmdSet):
… at_cmdset_creation(self):
super().at_cmdset_creation() … self.add(ClothedCharacterCmdSet) # <– add this
From here, you can use the default builder commands to create clothes with which to test the system:
@create a pretty shirt : evennia.contrib.clothing.Clothing @set shirt/clothing_type = ‘top’ wear shirt
-
class
evennia.contrib.clothing.ClothedCharacter(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultCharacterCharacter that displays worn clothing when looked at. You can also just copy the return_appearance hook defined below to your own game’s character typeclass.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for ClothedCharacter>¶
-
path= 'evennia.contrib.clothing.ClothedCharacter'¶
-
return_appearance(looker)[source]¶ This formats a description. It is the hook a ‘look’ command should call.
- Parameters
looker (Object) – Object doing the looking.
Notes
The name of every clothing item carried and worn by the character is appended to their description. If the clothing’s db.worn value is set to True, only the name is appended, but if the value is a string, the string is appended to the end of the name, to allow characters to specify how clothing is worn.
-
typename= 'ClothedCharacter'¶
-
exception
-
class
evennia.contrib.clothing.ClothedCharacterCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.default.cmdset_character.CharacterCmdSetCommand set for clothing, including new versions of ‘give’ and ‘drop’ that take worn and covered clothing into account, as well as a new version of ‘inventory’ that differentiates between carried and worn items.
-
key= 'DefaultCharacter'¶
-
path= 'evennia.contrib.clothing.ClothedCharacterCmdSet'¶
-
-
class
evennia.contrib.clothing.Clothing(id, db_key, db_typeclass_path, db_date_created, db_lock_storage, db_account, db_sessid, db_location, db_home, db_destination, db_cmdset_storage)[source]¶ Bases:
evennia.objects.objects.DefaultObject-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for Clothing>¶
-
at_get(getter)[source]¶ Makes absolutely sure clothes aren’t already set as ‘worn’ when they’re picked up, in case they’ve somehow had their location changed without getting removed.
-
path= 'evennia.contrib.clothing.Clothing'¶
-
remove(wearer, quiet=False)[source]¶ Removes worn clothes and optionally echoes to the room.
- Parameters
wearer (obj) – character object wearing this clothing object
- Kwargs:
quiet (bool): If false, does not message the room
-
typename= 'Clothing'¶
-
wear(wearer, wearstyle, quiet=False)[source]¶ Sets clothes to ‘worn’ and optionally echoes to the room.
- Parameters
wearer (obj) – character object wearing this clothing object
wearstyle (True or str) – string describing the style of wear or True for none
- Kwargs:
quiet (bool): If false, does not message the room
Notes
Optionally sets db.worn with a ‘wearstyle’ that appends a short passage to the end of the name of the clothing to describe how it’s worn that shows up in the wearer’s desc - I.E. ‘around his neck’ or ‘tied loosely around her waist’. If db.worn is set to ‘True’ then just the name will be shown.
-
exception
-
class
evennia.contrib.clothing.CmdCover(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandCovers a worn item of clothing with another you’re holding or wearing.
- Usage:
cover <obj> [with] <obj>
When you cover a clothing item, it is hidden and no longer appears in your description until it’s uncovered or the item covering it is removed. You can’t remove an item of clothing if it’s covered.
-
_keyaliases= ('cover',)¶
-
_matchset= {'cover'}¶
-
aliases= []¶
-
help_category= 'clothing'¶
-
key= 'cover'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'clothing', 'key': 'cover', 'tags': '', 'text': "\n Covers a worn item of clothing with another you're holding or wearing.\n\n Usage:\n cover <obj> [with] <obj>\n\n When you cover a clothing item, it is hidden and no longer appears in\n your description until it's uncovered or the item covering it is removed.\n You can't remove an item of clothing if it's covered.\n "}¶
-
class
evennia.contrib.clothing.CmdDrop(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommanddrop something
- Usage:
drop <obj>
Lets you drop an object from your inventory into the location you are currently in.
-
_keyaliases= ('drop',)¶
-
_matchset= {'drop'}¶
-
aliases= []¶
-
arg_regex= re.compile('\\s|$', re.IGNORECASE)¶
-
help_category= 'general'¶
-
key= 'drop'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'drop', 'tags': '', 'text': '\n drop something\n\n Usage:\n drop <obj>\n\n Lets you drop an object from your inventory into the\n location you are currently in.\n '}¶
-
class
evennia.contrib.clothing.CmdGive(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandgive away something to someone
- Usage:
give <inventory obj> = <target>
Gives an items from your inventory to another character, placing it in their inventory.
-
_keyaliases= ('give',)¶
-
_matchset= {'give'}¶
-
aliases= []¶
-
arg_regex= re.compile('\\s|$', re.IGNORECASE)¶
-
help_category= 'general'¶
-
key= 'give'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'give', 'tags': '', 'text': '\n give away something to someone\n\n Usage:\n give <inventory obj> = <target>\n\n Gives an items from your inventory to another character,\n placing it in their inventory.\n '}¶
-
class
evennia.contrib.clothing.CmdInventory(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandview inventory
- Usage:
inventory inv
Shows your inventory.
-
_keyaliases= ('inv', 'i', 'inventory')¶
-
_matchset= {'i', 'inv', 'inventory'}¶
-
aliases= ['inv', 'i']¶
-
arg_regex= re.compile('$', re.IGNORECASE)¶
-
help_category= 'general'¶
-
key= 'inventory'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'inv i', 'category': 'general', 'key': 'inventory', 'tags': '', 'text': '\n view inventory\n\n Usage:\n inventory\n inv\n\n Shows your inventory.\n '}¶
-
class
evennia.contrib.clothing.CmdRemove(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandTakes off an item of clothing.
- Usage:
remove <obj>
Removes an item of clothing you are wearing. You can’t remove clothes that are covered up by something else - you must take off the covering item first.
-
_keyaliases= ('remove',)¶
-
_matchset= {'remove'}¶
-
aliases= []¶
-
help_category= 'clothing'¶
-
key= 'remove'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'clothing', 'key': 'remove', 'tags': '', 'text': "\n Takes off an item of clothing.\n\n Usage:\n remove <obj>\n\n Removes an item of clothing you are wearing. You can't remove\n clothes that are covered up by something else - you must take\n off the covering item first.\n "}¶
-
class
evennia.contrib.clothing.CmdUncover(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandReveals a worn item of clothing that’s currently covered up.
- Usage:
uncover <obj>
When you uncover an item of clothing, you allow it to appear in your description without having to take off the garment that’s currently covering it. You can’t uncover an item of clothing if the item covering it is also covered by something else.
-
_keyaliases= ('uncover',)¶
-
_matchset= {'uncover'}¶
-
aliases= []¶
-
help_category= 'clothing'¶
-
key= 'uncover'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'clothing', 'key': 'uncover', 'tags': '', 'text': "\n Reveals a worn item of clothing that's currently covered up.\n\n Usage:\n uncover <obj>\n\n When you uncover an item of clothing, you allow it to appear in your\n description without having to take off the garment that's currently\n covering it. You can't uncover an item of clothing if the item covering\n it is also covered by something else.\n "}¶
-
class
evennia.contrib.clothing.CmdWear(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandPuts on an item of clothing you are holding.
- Usage:
wear <obj> [wear style]
Examples
wear shirt wear scarf wrapped loosely about the shoulders
All the clothes you are wearing are appended to your description. If you provide a ‘wear style’ after the command, the message you provide will be displayed after the clothing’s name.
-
_keyaliases= ('wear',)¶
-
_matchset= {'wear'}¶
-
aliases= []¶
-
help_category= 'clothing'¶
-
key= 'wear'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'clothing', 'key': 'wear', 'tags': '', 'text': "\n Puts on an item of clothing you are holding.\n\n Usage:\n wear <obj> [wear style]\n\n Examples:\n wear shirt\n wear scarf wrapped loosely about the shoulders\n\n All the clothes you are wearing are appended to your description.\n If you provide a 'wear style' after the command, the message you\n provide will be displayed after the clothing's name.\n "}¶
-
evennia.contrib.clothing.clothing_type_count(clothes_list)[source]¶ Returns a dictionary of the number of each clothing type in a given list of clothing objects.
- Parameters
clothes_list (list) – A list of clothing items from which to count the number of clothing types represented among them.
- Returns
- A dictionary of clothing types represented
in the given list and the number of each clothing type represented.
- Return type
types_count (dict)
-
evennia.contrib.clothing.get_worn_clothes(character, exclude_covered=False)[source]¶ Get a list of clothes worn by a given character.
- Parameters
character (obj) – The character to get a list of worn clothes from.
- Kwargs:
- exclude_covered (bool): If True, excludes clothes covered by other
clothing from the returned list.
- Returns
- A list of clothing items worn by the
given character, ordered according to the CLOTHING_TYPE_ORDER option specified in this module.
- Return type
ordered_clothes_list (list)
-
evennia.contrib.clothing.order_clothes_list(clothes_list)[source]¶ Orders a given clothes list by the order specified in CLOTHING_TYPE_ORDER.
- Parameters
clothes_list (list) – List of clothing items to put in order
- Returns
- The same list as passed, but re-ordered
according to the hierarchy of clothing types specified in CLOTHING_TYPE_ORDER.
- Return type
ordered_clothes_list (list)
-
evennia.contrib.clothing.single_type_count(clothes_list, type)[source]¶ Returns an integer value of the number of a given type of clothing in a list.
- Parameters
clothes_list (list) – List of clothing objects to count from
type (str) – Clothing type to count
- Returns
- Number of garments of the specified type in the given
list of clothing objects
- Return type
type_count (int)
evennia.contrib.color_markups module¶
Color markups
Contribution, Griatch 2017
Additional color markup styles for Evennia (extending or replacing the default |r, |234 etc).
Installation:
Import the desired style variables from this module into mygame/server/conf/settings.py and add them to these settings variables. Each are specified as a list, and multiple such lists can be added to each variable to support multiple formats. Note that list order affects which regexes are applied first. You must restart both Portal and Server for color tags to update.
Assign to the following settings variables:
COLOR_ANSI_EXTRA_MAP - a mapping between regexes and ANSI colors COLOR_XTERM256_EXTRA_FG - regex for defining XTERM256 foreground colors COLOR_XTERM256_EXTRA_BG - regex for defining XTERM256 background colors COLOR_XTERM256_EXTRA_GFG - regex for defining XTERM256 grayscale foreground colors COLOR_XTERM256_EXTRA_GBG - regex for defining XTERM256 grayscale background colors COLOR_ANSI_BRIGHT_BG_EXTRA_MAP = ANSI does not support bright backgrounds; we fake
this by mapping ANSI markup to matching bright XTERM256 backgrounds
- COLOR_NO_DEFAULT - Set True/False. If False (default), extend the default markup, otherwise
replace it completely.
To add the {- “curly-bracket” style, add the following to your settings file, then reboot both Server and Portal:
from evennia.contrib import color_markups COLOR_ANSI_EXTRA_MAP = color_markups.CURLY_COLOR_ANSI_EXTRA_MAP COLOR_XTERM256_EXTRA_FG = color_markups.CURLY_COLOR_XTERM256_EXTRA_FG COLOR_XTERM256_EXTRA_BG = color_markups.CURLY_COLOR_XTERM256_EXTRA_BG COLOR_XTERM256_EXTRA_GFG = color_markups.CURLY_COLOR_XTERM256_EXTRA_GFG COLOR_XTERM256_EXTRA_GBG = color_markups.CURLY_COLOR_XTERM256_EXTRA_GBG COLOR_ANSI_BRIGHT_BG_EXTRA_MAP = color_markups.CURLY_COLOR_ANSI_BRIGHT_BG_EXTRA_MAP
To add the %c- “mux/mush” style, add the following to your settings file, then reboot both Server and Portal:
from evennia.contrib import color_markups COLOR_ANSI_EXTRA_MAP = color_markups.MUX_COLOR_ANSI_EXTRA_MAP COLOR_XTERM256_EXTRA_FG = color_markups.MUX_COLOR_XTERM256_EXTRA_FG COLOR_XTERM256_EXTRA_BG = color_markups.MUX_COLOR_XTERM256_EXTRA_BG COLOR_XTERM256_EXTRA_GFG = color_markups.MUX_COLOR_XTERM256_EXTRA_GFG COLOR_XTERM256_EXTRA_GBG = color_markups.MUX_COLOR_XTERM256_EXTRA_GBG COLOR_ANSI_BRIGHT_BGS_EXTRA_MAP = color_markups.CURLY_COLOR_ANSI_BRIGHT_BGS_EXTRA_MAP
evennia.contrib.custom_gametime module¶
Custom gametime
Contrib - Griatch 2017, vlgeoff 2017
This implements the evennia.utils.gametime module but supporting a custom calendar for your game world. It allows for scheduling events to happen at given in-game times, taking this custom calendar into account.
Usage:
Use as the normal gametime module, that is by importing and using the helper functions in this module in your own code. The calendar can be customized by adding the TIME_UNITS dictionary to your settings file. This maps unit names to their length, expressed in the smallest unit. Here’s the default as an example:
- TIME_UNITS = {
“sec”: 1, “min”: 60, “hr”: 60 * 60, “hour”: 60 * 60, “day”: 60 * 60 * 24, “week”: 60 * 60 * 24 * 7, “month”: 60 * 60 * 24 * 7 * 4, “yr”: 60 * 60 * 24 * 7 * 4 * 12, “year”: 60 * 60 * 24 * 7 * 4 * 12, }
When using a custom calendar, these time unit names are used as kwargs to the converter functions in this module.
-
class
evennia.contrib.custom_gametime.GametimeScript(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptGametime-sensitive script.
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_meta= <Options for GametimeScript>¶
-
path= 'evennia.contrib.custom_gametime.GametimeScript'¶
-
typename= 'GametimeScript'¶
-
exception
-
evennia.contrib.custom_gametime.custom_gametime(absolute=False)[source]¶ Return the custom game time as a tuple of units, as defined in settings.
- Parameters
absolute (bool, optional) – return the relative or absolute time.
- Returns
The tuple describing the game time. The length of the tuple is related to the number of unique units defined in the settings. By default, the tuple would be (year, month, week, day, hour, minute, second).
-
evennia.contrib.custom_gametime.gametime_to_realtime(format=False, **kwargs)[source]¶ This method helps to figure out the real-world time it will take until an in-game time has passed. E.g. if an event should take place a month later in-game, you will be able to find the number of real-world seconds this corresponds to (hint: Interval events deal with real life seconds).
- Kwargs:
format (bool): Formatting the output. days, month etc (int): These are the names of time units that must
match the settings.TIME_UNITS dict keys.
- Returns
- The realtime difference or the same
time split up into time units.
- Return type
time (float or tuple)
Example
- gametime_to_realtime(days=2) -> number of seconds in real life from
now after which 2 in-game days will have passed.
-
evennia.contrib.custom_gametime.real_seconds_until(**kwargs)[source]¶ Return the real seconds until game time.
If the game time is 5:00, TIME_FACTOR is set to 2 and you ask the number of seconds until it’s 5:10, then this function should return 300 (5 minutes).
- Parameters
(str (times) – int): the time units.
Example
real_seconds_until(hour=5, min=10, sec=0)
- Returns
The number of real seconds before the given game time is up.
-
evennia.contrib.custom_gametime.realtime_to_gametime(secs=0, mins=0, hrs=0, days=0, weeks=0, months=0, yrs=0, format=False)[source]¶ This method calculates how much in-game time a real-world time interval would correspond to. This is usually a lot less interesting than the other way around.
- Kwargs:
times (int): The various components of the time. format (bool): Formatting the output.
- Returns
- The gametime difference or the same
time split up into time units.
- Return type
time (float or tuple)
- Example:
realtime_to_gametime(days=2) -> number of game-world seconds
-
evennia.contrib.custom_gametime.schedule(callback, repeat=False, **kwargs)[source]¶ Call the callback when the game time is up.
- Parameters
callback (function) – The callback function that will be called. This must be a top-level function since the script will be persistent.
repeat (bool, optional) – Should the callback be called regularly?
month, etc (str (day,) – int): The time units to call the callback; should match the keys of TIME_UNITS.
- Returns
The created script.
- Return type
script (Script)
Examples
schedule(func, min=5, sec=0) # Will call next hour at :05. schedule(func, hour=2, min=30, sec=0) # Will call the next day at 02:30.
Notes
This function will setup a script that will be called when the time corresponds to the game time. If the game is stopped for more than a few seconds, the callback may be called with a slight delay. If repeat is set to True, the callback will be called again next time the game time matches the given time. The time is given in units as keyword arguments.
-
evennia.contrib.custom_gametime.time_to_tuple(seconds, *divisors)[source]¶ Helper function. Creates a tuple of even dividends given a range of divisors.
- Parameters
seconds (int) – Number of seconds to format
*divisors (int) – a sequence of numbers of integer dividends. The number of seconds will be integer-divided by the first number in this sequence, the remainder will be divided with the second and so on.
- Returns
- This tuple has length len(*args)+1, with the
last element being the last remaining seconds not evenly divided by the supplied dividends.
- Return type
time (tuple)
evennia.contrib.dice module¶
Dice - rolls dice for roleplaying, in-game gambling or GM:ing
Evennia contribution - Griatch 2012
This module implements a full-fledged dice-roller and a ‘dice’ command to go with it. It uses standard RPG ‘d’-syntax (e.g. 2d6 to roll two six-sided die) and also supports modifiers such as 3d6 + 5.
One can also specify a standard Python operator in order to specify eventual target numbers and get results in a fair and guaranteed unbiased way. For example a GM could (using the dice command) from the start define the roll as 2d6 < 8 to show that a roll below 8 is required to succeed. The command will normally echo this result to all parties (although it also has options for hidden and secret rolls).
Installation:
To use in your code, just import the roll_dice function from this module.
To use the dice/roll command, just import this module in your custom cmdset module and add the following line to the end of DefaultCmdSet’s at_cmdset_creation():
self.add(dice.CmdDice())
After a reload the dice (or roll) command will be available in-game.
-
class
evennia.contrib.dice.CmdDice(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandroll dice
- Usage:
dice[/switch] <nr>d<sides> [modifier] [success condition]
- Switch:
hidden - tell the room the roll is being done, but don’t show the result secret - don’t inform the room about neither roll nor result
Examples
dice 3d6 + 4 dice 1d100 - 2 < 50
This will roll the given number of dice with given sides and modifiers. So e.g. 2d6 + 3 means to ‘roll a 6-sided die 2 times and add the result, then add 3 to the total’. Accepted modifiers are +, -, * and /. A success condition is given as normal Python conditionals (<,>,<=,>=,==,!=). So e.g. 2d6 + 3 > 10 means that the roll will succeed only if the final result is above 8. If a success condition is given, the outcome (pass/fail) will be echoed along with how much it succeeded/failed with. The hidden/secret switches will hide all or parts of the roll from everyone but the person rolling.
-
_keyaliases= ('roll', 'dice', '@dice')¶
-
_matchset= {'@dice', 'dice', 'roll'}¶
-
aliases= ['@dice', 'roll']¶
-
help_category= 'general'¶
-
key= 'dice'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '@dice roll', 'category': 'general', 'key': 'dice', 'tags': '', 'text': "\n roll dice\n\n Usage:\n dice[/switch] <nr>d<sides> [modifier] [success condition]\n\n Switch:\n hidden - tell the room the roll is being done, but don't show the result\n secret - don't inform the room about neither roll nor result\n\n Examples:\n dice 3d6 + 4\n dice 1d100 - 2 < 50\n\n This will roll the given number of dice with given sides and modifiers.\n So e.g. 2d6 + 3 means to 'roll a 6-sided die 2 times and add the result,\n then add 3 to the total'.\n Accepted modifiers are +, -, * and /.\n A success condition is given as normal Python conditionals\n (<,>,<=,>=,==,!=). So e.g. 2d6 + 3 > 10 means that the roll will succeed\n only if the final result is above 8. If a success condition is given, the\n outcome (pass/fail) will be echoed along with how much it succeeded/failed\n with. The hidden/secret switches will hide all or parts of the roll from\n everyone but the person rolling.\n "}¶
-
class
evennia.contrib.dice.DiceCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSeta small cmdset for testing purposes. Add with @py self.cmdset.add(“contrib.dice.DiceCmdSet”)
-
path= 'evennia.contrib.dice.DiceCmdSet'¶
-
-
evennia.contrib.dice.roll_dice(dicenum, dicetype, modifier=None, conditional=None, return_tuple=False)[source]¶ This is a standard dice roller.
- Parameters
dicenum (int) – Number of dice to roll (the result to be added).
dicetype (int) – Number of sides of the dice to be rolled.
modifier (tuple) – A tuple (operator, value), where operator is one of “+”, “-“, “/” or “*”. The result of the dice roll(s) will be modified by this value.
conditional (tuple) – A tuple (conditional, value), where conditional is one of “==”,`”<”,”>”,”>=”,”<=`” or “!=”. This allows the roller to directly return a result depending on if the conditional was passed or not.
return_tuple (bool) – Return a tuple with all individual roll results or not.
- Returns
- The result of the roll + modifiers. This is the
default return.
- condition_result (bool): A True/False value returned if conditional
is set but not return_tuple. This effectively hides the result of the roll.
- full_result (tuple): If, return_tuple` is True, instead
return a tuple (result, outcome, diff, rolls). Here, result is the normal result of the roll + modifiers. outcome and diff are the boolean result of the roll and absolute difference to the conditional input; they will be will be None if conditional is not set. rolls is itself a tuple holding all the individual rolls in the case of multiple die-rolls.
- Return type
roll_result (int)
- Raises
TypeError if non-supported modifiers or conditionals are given. –
Notes
All input numbers are converted to integers.
Examples
print roll_dice(2, 6) # 2d6 <<< 7 print roll_dice(1, 100, (‘+’, 5) # 1d100 + 5 <<< 34 print roll_dice(1, 20, conditional=(‘<’, 10) # let’say we roll 3 <<< True print roll_dice(3, 10, return_tuple=True) <<< (11, None, None, (2, 5, 4)) print roll_dice(2, 20, (‘-‘, 2), conditional=(‘>=’, 10), return_tuple=True) <<< (8, False, 2, (4, 6)) # roll was 4 + 6 - 2 = 8
evennia.contrib.email_login module¶
Email-based login system
Evennia contrib - Griatch 2012
This is a variant of the login system that requires an email-address instead of a username to login.
This used to be the default Evennia login before replacing it with a more standard username + password system (having to supply an email for some reason caused a lot of confusion when people wanted to expand on it. The email is not strictly needed internally, nor is any confirmation email sent out anyway).
Installation is simple:
To your settings file, add/edit the line:
`python
CMDSET_UNLOGGEDIN = "contrib.email_login.UnloggedinCmdSet"
`
That’s it. Reload the server and try to log in to see it.
The initial login “graphic” will still not mention email addresses after this change. The login splashscreen is taken from strings in the module given by settings.CONNECTION_SCREEN_MODULE.
-
class
evennia.contrib.email_login.CmdUnconnectedConnect(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandConnect to the game.
- Usage (at login screen):
connect <email> <password>
Use the create command to first create an account before logging in.
-
_keyaliases= ('connect', 'co', 'conn', 'con')¶
-
_matchset= {'co', 'con', 'conn', 'connect'}¶
-
aliases= ['co', 'conn', 'con']¶
-
func()[source]¶ 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 account has logged in)
-
help_category= 'general'¶
-
key= 'connect'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'co conn con', 'category': 'general', 'key': 'connect', 'tags': '', 'text': '\n Connect to the game.\n\n Usage (at login screen):\n connect <email> <password>\n\n Use the create command to first create an account before logging in.\n '}¶
-
class
evennia.contrib.email_login.CmdUnconnectedCreate(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandCreate a new account.
- Usage (at login screen):
create “accountname” <email> <password>
This creates a new account account.
-
_keyaliases= ('cr', 'cre', 'create')¶
-
_matchset= {'cr', 'cre', 'create'}¶
-
aliases= ['cre', 'cr']¶
-
help_category= 'general'¶
-
key= 'create'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
parse()[source]¶ The parser must handle the multiple-word account name enclosed in quotes:
connect “Long name with many words” my@myserv.com mypassw
-
search_index_entry= {'aliases': 'cre cr', 'category': 'general', 'key': 'create', 'tags': '', 'text': '\n Create a new account.\n\n Usage (at login screen):\n create "accountname" <email> <password>\n\n This creates a new account account.\n\n '}¶
-
class
evennia.contrib.email_login.CmdUnconnectedQuit(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandWe maintain a different version of the quit command here for unconnected accounts for the sake of simplicity. The logged in version is a bit more complicated.
-
_keyaliases= ('q', 'quit', 'qu')¶
-
_matchset= {'q', 'qu', 'quit'}¶
-
aliases= ['q', 'qu']¶
-
help_category= 'general'¶
-
key= 'quit'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'q qu', 'category': 'general', 'key': 'quit', 'tags': '', 'text': '\n We maintain a different version of the `quit` command\n here for unconnected accounts for the sake of simplicity. The logged in\n version is a bit more complicated.\n '}¶
-
-
class
evennia.contrib.email_login.CmdUnconnectedLook(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandThis is an unconnected version of the look command for simplicity.
This is called by the server and kicks everything in gear. All it does is display the connect screen.
-
_keyaliases= ('look', '__unloggedin_look_command', 'l')¶
-
_matchset= {'__unloggedin_look_command', 'l', 'look'}¶
-
aliases= ['look', 'l']¶
-
help_category= 'general'¶
-
key= '__unloggedin_look_command'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'look l', 'category': 'general', 'key': '__unloggedin_look_command', 'tags': '', 'text': '\n This is an unconnected version of the `look` command for simplicity.\n\n This is called by the server and kicks everything in gear.\n All it does is display the connect screen.\n '}¶
-
-
class
evennia.contrib.email_login.CmdUnconnectedHelp(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandThis is an unconnected version of the help command, for simplicity. It shows a pane of info.
-
_keyaliases= ('help', 'h', '?')¶
-
_matchset= {'?', 'h', 'help'}¶
-
aliases= ['h', '?']¶
-
help_category= 'general'¶
-
key= 'help'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'h ?', 'category': 'general', 'key': 'help', 'tags': '', 'text': '\n This is an unconnected version of the help command,\n for simplicity. It shows a pane of info.\n '}¶
-
evennia.contrib.extended_room module¶
Extended Room
Evennia Contribution - Griatch 2012, vincent-lg 2019
This is an extended Room typeclass for Evennia. It is supported by an extended Look command and an extended desc command, also in this module.
Features:
Time-changing description slots
This allows to change the full description text the room shows depending on larger time variations. Four seasons (spring, summer, autumn and winter) are used by default. The season is calculated on-demand (no Script or timer needed) and updates the full text block.
There is also a general description which is used as fallback if one or more of the seasonal descriptions are not set when their time comes.
An updated desc command allows for setting seasonal descriptions.
The room uses the evennia.utils.gametime.GameTime global script. This is started by default, but if you have deactivated it, you need to supply your own time keeping mechanism.
In-description changing tags
Within each seasonal (or general) description text, you can also embed time-of-day dependent sections. Text inside such a tag will only show during that particular time of day. The tags looks like <timeslot> … </timeslot>. By default there are four timeslots per day - morning, afternoon, evening and night.
Details
The Extended Room can be “detailed” with special keywords. This makes use of a special Look command. Details are “virtual” targets to look at, without there having to be a database object created for it. The Details are simply stored in a dictionary on the room and if the look command cannot find an object match for a look <target> command it will also look through the available details at the current location if applicable. The @detail command is used to change details.
Extra commands
CmdExtendedRoomLook - look command supporting room details CmdExtendedRoomDesc - desc command allowing to add seasonal descs, CmdExtendedRoomDetail - command allowing to manipulate details in this room
as well as listing them
- CmdExtendedRoomGameTime - A simple time command, displaying the current
time and season.
Installation/testing:
Adding the ExtendedRoomCmdset to the default character cmdset will add all new commands for use.
In more detail, in mygame/commands/default_cmdsets.py:
```¶
from evennia.contrib import extended_room # <-new
- class CharacterCmdset(default_cmds.Character_CmdSet):
… def at_cmdset_creation(self):
… self.add(extended_room.ExtendedRoomCmdSet) # <-new
Then reload to make the bew commands available. Note that they only work on rooms with the typeclass ExtendedRoom. Create new rooms with the right typeclass or use the typeclass command to swap existing rooms.
-
class
evennia.contrib.extended_room.CmdExtendedRoomDesc(**kwargs)[source]¶ Bases:
evennia.commands.default.building.CmdDescdesc - describe an object or room.
- Usage:
desc[/switch] [<obj> =] <description>
- Switches for desc:
spring - set description for <season> in current room. summer autumn winter
Sets the “desc” attribute on an object. If an object is not given, describe the current room.
You can also embed special time markers in your room description, like this:
` <night>In the darkness, the forest looks foreboding.</night>. `Text marked this way will only display when the server is truly at the given timeslot. The available times are night, morning, afternoon and evening.
Note that seasons and time-of-day slots only work on rooms in this version of the desc command.
-
_keyaliases= ('describe', 'desc')¶
-
_matchset= {'desc', 'describe'}¶
-
aliases= ['describe']¶
-
help_category= 'building'¶
-
key= 'desc'¶
-
lock_storage= 'cmd:perm(desc) or perm(Builder)'¶
-
search_index_entry= {'aliases': 'describe', 'category': 'building', 'key': 'desc', 'tags': '', 'text': '\n `desc` - describe an object or room.\n\n Usage:\n desc[/switch] [<obj> =] <description>\n\n Switches for `desc`:\n spring - set description for <season> in current room.\n summer\n autumn\n winter\n\n Sets the "desc" attribute on an object. If an object is not given,\n describe the current room.\n\n You can also embed special time markers in your room description, like this:\n\n ```\n <night>In the darkness, the forest looks foreboding.</night>.\n ```\n\n Text marked this way will only display when the server is truly at the given\n timeslot. The available times are night, morning, afternoon and evening.\n\n Note that seasons and time-of-day slots only work on rooms in this\n version of the `desc` command.\n\n '}¶
-
switch_options= ()¶
-
class
evennia.contrib.extended_room.CmdExtendedRoomDetail(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandsets a detail on a room
- Usage:
@detail[/del] <key> [= <description>] @detail <key>;<alias>;… = description
Example
@detail @detail walls = The walls are covered in … @detail castle;ruin;tower = The distant ruin … @detail/del wall @detail/del castle;ruin;tower
This command allows to show the current room details if you enter it without any argument. Otherwise, sets or deletes a detail on the current room, if this room supports details like an extended room. To add new detail, just use the @detail command, specifying the key, an equal sign and the description. You can assign the same description to several details using the alias syntax (replace key by alias1;alias2;alias3;…). To remove one or several details, use the @detail/del switch.
-
_keyaliases= ('@detail',)¶
-
_matchset= {'@detail'}¶
-
aliases= []¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'building'¶
-
key= '@detail'¶
-
lock_storage= 'cmd:perm(Builder)'¶
-
locks= 'cmd:perm(Builder)'¶
-
search_index_entry= {'aliases': '', 'category': 'building', 'key': '@detail', 'tags': '', 'text': '\n sets a detail on a room\n\n Usage:\n @detail[/del] <key> [= <description>]\n @detail <key>;<alias>;... = description\n\n Example:\n @detail\n @detail walls = The walls are covered in ...\n @detail castle;ruin;tower = The distant ruin ...\n @detail/del wall\n @detail/del castle;ruin;tower\n\n This command allows to show the current room details if you enter it\n without any argument. Otherwise, sets or deletes a detail on the current\n room, if this room supports details like an extended room. To add new\n detail, just use the @detail command, specifying the key, an equal sign\n and the description. You can assign the same description to several\n details using the alias syntax (replace key by alias1;alias2;alias3;...).\n To remove one or several details, use the @detail/del switch.\n\n '}¶
-
class
evennia.contrib.extended_room.CmdExtendedRoomGameTime(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandCheck the game time
- Usage:
time
Shows the current in-game time and season.
-
_keyaliases= ('time',)¶
-
_matchset= {'time'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'time'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'time', 'tags': '', 'text': '\n Check the game time\n\n Usage:\n time\n\n Shows the current in-game time and season.\n '}¶
-
class
evennia.contrib.extended_room.CmdExtendedRoomLook(**kwargs)[source]¶ Bases:
evennia.commands.default.general.CmdLooklook
- Usage:
look look <obj> look <room detail> look *<account>
Observes your location, details at your location or objects in your vicinity.
-
_keyaliases= ('look', 'l', 'ls')¶
-
_matchset= {'l', 'look', 'ls'}¶
-
aliases= ['l', 'ls']¶
-
help_category= 'general'¶
-
key= 'look'¶
-
lock_storage= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'l ls', 'category': 'general', 'key': 'look', 'tags': '', 'text': '\n look\n\n Usage:\n look\n look <obj>\n look <room detail>\n look *<account>\n\n Observes your location, details at your location or objects in your vicinity.\n '}¶
-
class
evennia.contrib.extended_room.ExtendedRoom(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultRoomThis room implements a more advanced look functionality depending on time. It also allows for “details”, together with a slightly modified look command.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for ExtendedRoom>¶
-
del_detail(detailkey, description)[source]¶ Delete a detail.
The description is ignored.
- Parameters
detailkey (str) – the detail to remove (case-insensitive).
description (str, ignored) – the description.
The description is only included for compliance but is completely ignored. Note that this method doesn’t raise any exception if the detail doesn’t exist in this room.
-
path= 'evennia.contrib.extended_room.ExtendedRoom'¶
-
replace_timeslots(raw_desc, curr_time)[source]¶ Filter so that only time markers <timeslot>…</timeslot> of the correct timeslot remains in the description.
- Parameters
raw_desc (str) – The unmodified description.
curr_time (str) – A timeslot identifier.
- Returns
A possibly moified description.
- Return type
description (str)
-
return_appearance(looker, **kwargs)[source]¶ This is called when e.g. the look command wants to retrieve the description of this object.
- Parameters
looker (Object) – The object looking at us.
**kwargs (dict) – Arbitrary, optional arguments for users overriding the call (unused by default).
- Returns
Our description.
- Return type
description (str)
-
return_detail(key)[source]¶ This will attempt to match a “detail” to look for in the room.
- Parameters
key (str) – A detail identifier.
- Returns
A detail matching the given key.
- Return type
detail (str or None)
Notes
A detail is a way to offer more things to look at in a room without having to add new objects. For this to work, we require a custom look command that allows for look <detail> - the look command should defer to this method on the current location (if it exists) before giving up on finding the target.
Details are not season-sensitive, but are parsed for timeslot markers.
-
set_detail(detailkey, description)[source]¶ This sets a new detail, using an Attribute “details”.
- Parameters
detailkey (str) – The detail identifier to add (for aliases you need to add multiple keys to the same description). Case-insensitive.
description (str) – The text to return when looking at the given detailkey.
-
typename= 'ExtendedRoom'¶
-
exception
-
class
evennia.contrib.extended_room.ExtendedRoomCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetGroups the extended-room commands.
-
at_cmdset_creation()[source]¶ Hook method - this should be overloaded in the inheriting class, and should take care of populating the cmdset by use of self.add().
-
path= 'evennia.contrib.extended_room.ExtendedRoomCmdSet'¶
-
evennia.contrib.fieldfill module¶
Easy fillable form
Contrib - Tim Ashley Jenkins 2018
This module contains a function that calls an easily customizable EvMenu - this menu presents the player with a fillable form, with fields that can be filled out in any order. Each field’s value can be verified, with the function allowing easy checks for text and integer input, minimum and maximum values / character lengths, or can even be verified by a custom function. Once the form is submitted, the form’s data is submitted as a dictionary to any callable of your choice.
The function that initializes the fillable form menu is fairly simple, and includes the caller, the template for the form, and the callback(caller, result) to which the form data will be sent to upon submission.
init_fill_field(formtemplate, caller, formcallback)
Form templates are defined as a list of dictionaries - each dictionary represents a field in the form, and contains the data for the field’s name and behavior. For example, this basic form template will allow a player to fill out a brief character profile:
PROFILE_TEMPLATE = [ {“fieldname”:”Name”, “fieldtype”:”text”}, {“fieldname”:”Age”, “fieldtype”:”number”}, {“fieldname”:”History”, “fieldtype”:”text”}, ]
This will present the player with an EvMenu showing this basic form:
- Name:
Age:
History:
While in this menu, the player can assign a new value to any field with the syntax <field> = <new value>, like so:
> name = Ashley Field ‘Name’ set to: Ashley
Typing ‘look’ by itself will show the form and its current values.
> look
- Name: Ashley
Age:
History:
Number fields require an integer input, and will reject any text that can’t be converted into an integer.
> age = youthful Field ‘Age’ requires a number. > age = 31 Field ‘Age’ set to: 31
Form data is presented as an EvTable, so text of any length will wrap cleanly.
> history = EVERY MORNING I WAKE UP AND OPEN PALM SLAM[…] Field ‘History’ set to: EVERY MORNING I WAKE UP AND[…] > look
- Name: Ashley
Age: 31
- History: EVERY MORNING I WAKE UP AND OPEN PALM SLAM A VHS INTO THE SLOT.
IT’S CHRONICLES OF RIDDICK AND RIGHT THEN AND THERE I START DOING THE MOVES ALONGSIDE WITH THE MAIN CHARACTER, RIDDICK. I DO EVERY MOVE AND I DO EVERY MOVE HARD.
When the player types ‘submit’ (or your specified submit command), the menu quits and the form’s data is passed to your specified function as a dictionary, like so:
formdata = {“Name”:”Ashley”, “Age”:31, “History”:”EVERY MORNING I[…]”}
You can do whatever you like with this data in your function - forms can be used to set data on a character, to help builders create objects, or for players to craft items or perform other complicated actions with many variables involved.
The data that your form will accept can also be specified in your form template - let’s say, for example, that you won’t accept ages under 18 or over 100. You can do this by specifying “min” and “max” values in your field’s dictionary:
PROFILE_TEMPLATE = [ {“fieldname”:”Name”, “fieldtype”:”text”}, {“fieldname”:”Age”, “fieldtype”:”number”, “min”:18, “max”:100}, {“fieldname”:”History”, “fieldtype”:”text”} ]
Now if the player tries to enter a value out of range, the form will not acept the given value.
> age = 10 Field ‘Age’ reqiures a minimum value of 18. > age = 900 Field ‘Age’ has a maximum value of 100.
Setting ‘min’ and ‘max’ for a text field will instead act as a minimum or maximum character length for the player’s input.
There are lots of ways to present the form to the player - fields can have default values or show a custom message in place of a blank value, and player input can be verified by a custom function, allowing for a great deal of flexibility. There is also an option for ‘bool’ fields, which accept only a True / False input and can be customized to represent the choice to the player however you like (E.G. Yes/No, On/Off, Enabled/Disabled, etc.)
This module contains a simple example form that demonstrates all of the included functionality - a command that allows a player to compose a message to another online character and have it send after a custom delay. You can test it by importing this module in your game’s default_cmdsets.py module and adding CmdTestMenu to your default character’s command set.
FIELD TEMPLATE KEYS: Required:
fieldname (str): Name of the field, as presented to the player. fieldtype (str): Type of value required: ‘text’, ‘number’, or ‘bool’.
- Optional:
max (int): Maximum character length (if text) or value (if number). min (int): Minimum charater length (if text) or value (if number). truestr (str): String for a ‘True’ value in a bool field.
(E.G. ‘On’, ‘Enabled’, ‘Yes’)
- falsestr (str): String for a ‘False’ value in a bool field.
(E.G. ‘Off’, ‘Disabled’, ‘No’)
default (str): Initial value (blank if not given). blankmsg (str): Message to show in place of value when field is blank. cantclear (bool): Field can’t be cleared if True. required (bool): If True, form cannot be submitted while field is blank. verifyfunc (callable): Name of a callable used to verify input - takes
(caller, value) as arguments. If the function returns True, the player’s input is considered valid - if it returns False, the input is rejected. Any other value returned will act as the field’s new value, replacing the player’s input. This allows for values that aren’t strings or integers (such as object dbrefs). For boolean fields, return ‘0’ or ‘1’ to set the field to False or True.
-
class
evennia.contrib.fieldfill.CmdTestMenu(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandThis test command will initialize a menu that presents you with a form. You can fill out the fields of this form in any order, and then type in ‘send’ to send a message to another online player, which will reach them after a delay you specify.
- Usage:
<field> = <new value> clear <field> help look quit send
-
_keyaliases= ('testmenu',)¶
-
_matchset= {'testmenu'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'testmenu'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'testmenu', 'tags': '', 'text': "\n This test command will initialize a menu that presents you with a form.\n You can fill out the fields of this form in any order, and then type in\n 'send' to send a message to another online player, which will reach them\n after a delay you specify.\n\n Usage:\n <field> = <new value>\n clear <field>\n help\n look\n quit\n send\n "}¶
-
class
evennia.contrib.fieldfill.FieldEvMenu(caller, menudata, startnode='start', cmdset_mergetype='Replace', cmdset_priority=1, auto_quit=True, auto_look=True, auto_help=True, cmd_on_exit='look', persistent=False, startnode_input='', session=None, debug=False, **kwargs)[source]¶ Bases:
evennia.utils.evmenu.EvMenuCustom EvMenu type with its own node formatter - removes extraneous lines
-
node_formatter(nodetext, optionstext)[source]¶ Formats the entirety of the node.
- Parameters
nodetext (str) – The node text as returned by self.nodetext_formatter.
optionstext (str) – The options display as returned by self.options_formatter.
caller (Object, Account or None, optional) – The caller of the node.
- Returns
The formatted node to display.
- Return type
node (str)
-
-
evennia.contrib.fieldfill.display_formdata(formtemplate, formdata, pretext='', posttext='', borderstyle='cells')[source]¶ Displays a form’s current data as a table. Used in the form menu.
- Parameters
formtemplate (list of dicts) – Template for the form
formdata (dict) – Form’s current data
- Options:
pretext (str): Text to put before the form table. posttext (str): Text to put after the form table. borderstyle (str): EvTable’s border style.
-
evennia.contrib.fieldfill.form_template_to_dict(formtemplate)[source]¶ Initializes a dictionary of form data from the given list-of-dictionaries form template, as formatted above.
- Parameters
formtemplate (list of dicts) – Tempate for the form to be initialized.
- Returns
Dictionary of initalized form data.
- Return type
formdata (dict)
-
evennia.contrib.fieldfill.init_delayed_message(caller, formdata)[source]¶ Initializes a delayed message, using data from the example form.
- Parameters
caller (obj) – Character submitting the message.
formdata (dict) – Data from submitted form.
-
evennia.contrib.fieldfill.init_fill_field(formtemplate, caller, formcallback, pretext='', posttext='', submitcmd='submit', borderstyle='cells', formhelptext=None, persistent=False, initial_formdata=None)[source]¶ Initializes a menu presenting a player with a fillable form - once the form is submitted, the data will be passed as a dictionary to your chosen function.
- Parameters
formtemplate (list of dicts) – The template for the form’s fields.
caller (obj) – Player who will be filling out the form.
formcallback (callable) – Function to pass the completed form’s data to.
- Options:
pretext (str): Text to put before the form in the menu. posttext (str): Text to put after the form in the menu. submitcmd (str): Command used to submit the form. borderstyle (str): Form’s EvTable border style. formhelptext (str): Help text for the form menu (or default is provided). persistent (bool): Whether to make the EvMenu persistent across reboots. initial_formdata (dict): Initial data for the form - a blank form with
defaults specified in the template will be generated otherwise. In the case of a form used to edit properties on an object or a similar application, you may want to generate the initial form data dynamically before calling init_fill_field.
This is an EvMenu node, which calls itself over and over in order to allow a player to enter values into a fillable form. When the form is submitted, the form data is passed to a callback as a dictionary.
-
evennia.contrib.fieldfill.sendmessage(obj, text)[source]¶ Callback to send a message to a player.
- Parameters
obj (obj) – Player to message.
text (str) – Message.
-
evennia.contrib.fieldfill.verify_online_player(caller, value)[source]¶ Example ‘verify function’ that matches player input to an online character or else rejects their input as invalid.
- Parameters
caller (obj) – Player entering the form data.
value (str) – String player entered into the form, to be verified.
- Returns
- dbref to a currently logged in
character object - reference to the object will be stored in the form instead of a string. Returns False if no match is made.
- Return type
matched_character (obj or False)
evennia.contrib.gendersub module¶
Gendersub
Griatch 2015
This is a simple gender-aware Character class for allowing users to insert custom markers in their text to indicate gender-aware messaging. It relies on a modified msg() and is meant as an inspiration and starting point to how to do stuff like this.
- An object can have the following genders:
male (he/his)
female (her/hers)
neutral (it/its)
ambiguous (they/them/their/theirs)
When in use, messages can contain special tags to indicate pronouns gendered based on the one being addressed. Capitalization will be retained.
|s, |S: Subjective form: he, she, it, He, She, It, They
|o, |O: Objective form: him, her, it, Him, Her, It, Them
|p, |P: Possessive form: his, her, its, His, Her, Its, Their
|a, |A: Absolute Possessive form: his, hers, its, His, Hers, Its, Theirs
For example,
`
char.msg("%s falls on |p face with a thud." % char.key)
"Tom falls on his face with a thud"
`
The default gender is “ambiguous” (they/them/their/theirs).
To use, have DefaultCharacter inherit from this, or change setting.DEFAULT_CHARACTER to point to this class.
The @gender command is used to set the gender. It needs to be added to the default cmdset before it becomes available.
-
class
evennia.contrib.gendersub.GenderCharacter(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultCharacterThis is a Character class aware of gender.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_get_pronoun(regex_match)[source]¶ Get pronoun from the pronoun marker in the text. This is used as the callable for the re.sub function.
- Parameters
regex_match (MatchObject) – the regular expression match.
Notes
|s, |S: Subjective form: he, she, it, He, She, It, They
|o, |O: Objective form: him, her, it, Him, Her, It, Them
|p, |P: Possessive form: his, her, its, His, Her, Its, Their
|a, |A: Absolute Possessive form: his, hers, its, His, Hers, Its, Theirs
-
_meta= <Options for GenderCharacter>¶
-
msg(text, from_obj=None, session=None, **kwargs)[source]¶ Emits something to a session attached to the object. Overloads the default msg() implementation to include gender-aware markers in output.
- Parameters
text (str or tuple, optional) – The message to send. This is treated internally like any send-command, so its value can be a tuple if sending multiple arguments to the text oob command.
from_obj (obj, optional) – object that is sending. If given, at_msg_send will be called
session (Session or list, optional) – session or list of sessions to relay to, if any. If set, will force send regardless of MULTISESSION_MODE.
Notes
at_msg_receive will be called on this Object. All extra kwargs will be passed on to the protocol.
-
path= 'evennia.contrib.gendersub.GenderCharacter'¶
-
typename= 'GenderCharacter'¶
-
exception
-
class
evennia.contrib.gendersub.SetGender(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandSets gender on yourself
- Usage:
@gender male||female||neutral||ambiguous
-
_keyaliases= ('@sex', '@gender')¶
-
_matchset= {'@gender', '@sex'}¶
-
aliases= ['@sex']¶
-
help_category= 'general'¶
-
key= '@gender'¶
-
lock_storage= 'cmd:all();call:all()'¶
-
locks= 'cmd:all();call:all()'¶
-
search_index_entry= {'aliases': '@sex', 'category': 'general', 'key': '@gender', 'tags': '', 'text': '\n Sets gender on yourself\n\n Usage:\n @gender male||female||neutral||ambiguous\n\n '}¶
evennia.contrib.health_bar module¶
Health Bar
Contrib - Tim Ashley Jenkins 2017
The function provided in this module lets you easily display visual bars or meters - “health bar” is merely the most obvious use for this, though these bars are highly customizable and can be used for any sort of appropriate data besides player health.
Today’s players may be more used to seeing statistics like health, stamina, magic, and etc. displayed as bars rather than bare numerical values, so using this module to present this data this way may make it more accessible. Keep in mind, however, that players may also be using a screen reader to connect to your game, which will not be able to represent the colors of the bar in any way. By default, the values represented are rendered as text inside the bar which can be read by screen readers.
The health bar will account for current values above the maximum or below 0, rendering them as a completely full or empty bar with the values displayed within.
-
evennia.contrib.health_bar.display_meter(cur_value, max_value, length=30, fill_color=['R', 'Y', 'G'], empty_color='B', text_color='w', align='left', pre_text='', post_text='', show_values=True)[source]¶ Represents a current and maximum value given as a “bar” rendered with ANSI or xterm256 background colors.
- Parameters
cur_value (int) – Current value to display
max_value (int) – Maximum value to display
- Options:
length (int): Length of meter returned, in characters fill_color (list): List of color codes for the full portion
of the bar, sans any sort of prefix - both ANSI and xterm256 colors are usable. When the bar is empty, colors toward the start of the list will be chosen - when the bar is full, colors towards the end are picked. You can adjust the ‘weights’ of the changing colors by adding multiple entries of the same color - for example, if you only want the bar to change when it’s close to empty, you could supply [‘R’,’Y’,’G’,’G’,’G’]
empty_color (str): Color code for the empty portion of the bar. text_color (str): Color code for text inside the bar. align (str): “left”, “right”, or “center” - alignment of text in the bar pre_text (str): Text to put before the numbers in the bar post_text (str): Text to put after the numbers in the bar show_values (bool): If true, shows the numerical values represented by
the bar. It’s highly recommended you keep this on, especially if there’s no info given in pre_text or post_text, as players on screen readers will be unable to read the graphical aspect of the bar.
evennia.contrib.mail module¶
In-Game Mail system
Evennia Contribution - grungies1138 2016
A simple Brandymail style @mail system that uses the Msg class from Evennia Core. It has two Commands, both of which can be used on their own:
CmdMail - this should sit on the Account cmdset and makes the @mail command
available both IC and OOC. Mails will always go to Accounts (other players).
CmdMailCharacter - this should sit on the Character cmdset and makes the @mail
command ONLY available when puppeting a character. Mails will be sent to other Characters only and will not be available when OOC.
If adding both commands to their respective cmdsets, you’ll get two separate
IC and OOC mailing systems, with different lists of mail for IC and OOC modes.
Installation:
Install one or both of the following (see above):
CmdMail (IC + OOC mail, sent between players)
# mygame/commands/default_cmds.py
from evennia.contrib import mail
- # in AccountCmdSet.at_cmdset_creation:
self.add(mail.CmdMail())
CmdMailCharacter (optional, IC only mail, sent between characters)
# mygame/commands/default_cmds.py
from evennia.contrib import mail
- # in CharacterCmdSet.at_cmdset_creation:
self.add(mail.CmdMailCharacter())
Once installed, use help mail in game for help with the mail command. Use @ic/@ooc to switch in and out of IC/OOC modes.
-
class
evennia.contrib.mail.CmdMail(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxAccountCommandCommunicate with others by sending mail.
- Usage:
@mail - Displays all the mail an account has in their mailbox @mail <#> - Displays a specific message @mail <accounts>=<subject>/<message>
Sends a message to the comma separated list of accounts.
@mail/delete <#> - Deletes a specific message @mail/forward <account list>=<#>[/<Message>]
Forwards an existing message to the specified list of accounts, original message is delivered with optional Message prepended.
- @mail/reply <#>=<message>
Replies to a message #. Prepends message to the original message text.
- Switches:
delete - deletes a message forward - forward a received message to another object with an optional message attached. reply - Replies to a received message, appending the original message to the bottom.
Examples
@mail 2 @mail Griatch=New mail/Hey man, I am sending you a message! @mail/delete 6 @mail/forward feend78 Griatch=4/You guys should read this. @mail/reply 9=Thanks for the info!
-
_keyaliases= ('@mail', 'mail')¶
-
_matchset= {'@mail', 'mail'}¶
-
aliases= ['mail']¶
-
get_all_mail()[source]¶ - Returns a list of all the messages where the caller is a recipient. These
are all messages tagged with tags of the mail category.
- Returns
Matching Msg objects.
- Return type
messages (QuerySet)
-
help_category= 'general'¶
-
key= '@mail'¶
-
lock= 'cmd:all()'¶
-
lock_storage= 'cmd:all();'¶
-
parse()[source]¶ Add convenience check to know if caller is an Account or not since this cmd will be able to add to either Object- or Account level.
-
search_index_entry= {'aliases': 'mail', 'category': 'general', 'key': '@mail', 'tags': '', 'text': '\n Communicate with others by sending mail.\n\n Usage:\n @mail - Displays all the mail an account has in their mailbox\n @mail <#> - Displays a specific message\n @mail <accounts>=<subject>/<message>\n - Sends a message to the comma separated list of accounts.\n @mail/delete <#> - Deletes a specific message\n @mail/forward <account list>=<#>[/<Message>]\n - Forwards an existing message to the specified list of accounts,\n original message is delivered with optional Message prepended.\n @mail/reply <#>=<message>\n - Replies to a message #. Prepends message to the original\n message text.\n Switches:\n delete - deletes a message\n forward - forward a received message to another object with an optional message attached.\n reply - Replies to a received message, appending the original message to the bottom.\n Examples:\n @mail 2\n @mail Griatch=New mail/Hey man, I am sending you a message!\n @mail/delete 6\n @mail/forward feend78 Griatch=4/You guys should read this.\n @mail/reply 9=Thanks for the info!\n\n '}¶
-
search_targets(namelist)[source]¶ Search a list of targets of the same type as caller.
- Parameters
caller (Object or Account) – The type of object to search.
namelist (list) – List of strings for objects to search for.
- Returns
Any target matches.
- Return type
targetlist (Queryset)
-
send_mail(recipients, subject, message, caller)[source]¶ Function for sending new mail. Also useful for sending notifications from objects or systems.
- Parameters
recipients (list) – list of Account or Character objects to receive the newly created mails.
subject (str) – The header or subject of the message to be delivered.
message (str) – The body of the message being sent.
caller (obj) – The object (or Account or Character) that is sending the message.
-
class
evennia.contrib.mail.CmdMailCharacter(**kwargs)[source]¶ Bases:
evennia.contrib.mail.CmdMailCommunicate with others by sending mail.
- Usage:
@mail - Displays all the mail an account has in their mailbox @mail <#> - Displays a specific message @mail <accounts>=<subject>/<message>
Sends a message to the comma separated list of accounts.
@mail/delete <#> - Deletes a specific message @mail/forward <account list>=<#>[/<Message>]
Forwards an existing message to the specified list of accounts, original message is delivered with optional Message prepended.
- @mail/reply <#>=<message>
Replies to a message #. Prepends message to the original message text.
- Switches:
delete - deletes a message forward - forward a received message to another object with an optional message attached. reply - Replies to a received message, appending the original message to the bottom.
Examples
@mail 2 @mail Griatch=New mail/Hey man, I am sending you a message! @mail/delete 6 @mail/forward feend78 Griatch=4/You guys should read this. @mail/reply 9=Thanks for the info!
-
_keyaliases= ('@mail', 'mail')¶
-
_matchset= {'@mail', 'mail'}¶
-
account_caller= False¶
-
aliases= ['mail']¶
-
help_category= 'general'¶
-
key= '@mail'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': 'mail', 'category': 'general', 'key': '@mail', 'tags': '', 'text': '\n Communicate with others by sending mail.\n\n Usage:\n @mail - Displays all the mail an account has in their mailbox\n @mail <#> - Displays a specific message\n @mail <accounts>=<subject>/<message>\n - Sends a message to the comma separated list of accounts.\n @mail/delete <#> - Deletes a specific message\n @mail/forward <account list>=<#>[/<Message>]\n - Forwards an existing message to the specified list of accounts,\n original message is delivered with optional Message prepended.\n @mail/reply <#>=<message>\n - Replies to a message #. Prepends message to the original\n message text.\n Switches:\n delete - deletes a message\n forward - forward a received message to another object with an optional message attached.\n reply - Replies to a received message, appending the original message to the bottom.\n Examples:\n @mail 2\n @mail Griatch=New mail/Hey man, I am sending you a message!\n @mail/delete 6\n @mail/forward feend78 Griatch=4/You guys should read this.\n @mail/reply 9=Thanks for the info!\n\n '}¶
evennia.contrib.mapbuilder module¶
Evennia World Builder
Contribution - Cloud_Keeper 2016
Build a map from a 2D ASCII map.
This is a command which takes two inputs:
≈≈≈≈≈ ≈♣n♣≈ MAP_LEGEND = {(“♣”, “♠”): build_forest, ≈∩▲∩≈ (“∩”, “n”): build_mountains, ≈♠n♠≈ (“▲”): build_temple} ≈≈≈≈≈
A string of ASCII characters representing a map and a dictionary of functions containing build instructions. The characters of the map are iterated over and compared to a list of trigger characters. When a match is found the corresponding function is executed generating the rooms, exits and objects as defined by the users build instructions. If a character is not a match to a provided trigger character (including spaces) it is simply skipped and the process continues.
For instance, the above map represents a temple (▲) amongst mountains (n,∩) in a forest (♣,♠) on an island surrounded by water (≈). Each character on the first line is iterated over but as there is no match with our MAP_LEGEND it is skipped. On the second line it finds “♣” which is a match and so the build_forest function is called. Next the build_mountains function is called and so on until the map is completed. Building instructions are passed the following arguments:
x - The rooms position on the maps x axis y - The rooms position on the maps y axis caller - The account calling the command iteration - The current iterations number (0, 1 or 2) room_dict - A dictionary containing room references returned by build
functions where tuple coordinates are the keys (x, y). ie room_dict[(2, 2)] will return the temple room above.
Building functions should return the room they create. By default these rooms are used to create exits between valid adjacent rooms to the north, south, east and west directions. This behaviour can turned off with the use of switch arguments. In addition to turning off automatic exit generation the switches allow the map to be iterated over a number of times. This is important for something like custom exit building. Exits require a reference to both the exits location and the exits destination. During the first iteration it is possible that an exit is created pointing towards a destination that has not yet been created resulting in error. By iterating over the map twice the rooms can be created on the first iteration and room reliant code can be be used on the second iteration. The iteration number and a dictionary of references to rooms previously created is passed to the build commands.
Use by importing and including the command in your default_cmdsets module. For example:
# mygame/commands/default_cmdsets.py
from evennia.contrib import mapbuilder
…
self.add(mapbuilder.CmdMapBuilder())
You then call the command in-game using the path to the MAP and MAP_LEGEND vars The path you provide is relative to the evennia or mygame folder.
- Usage:
@mapbuilder[/switch] <path.to.file.MAPNAME> <path.to.file.MAP_LEGEND>
- Switches:
one - execute build instructions once without automatic exit creation. two - execute build instructions twice without automatic exit creation.
Example
@mapbuilder world.gamemap.MAP world.maplegend.MAP_LEGEND @mapbuilder evennia.contrib.mapbuilder.EXAMPLE1_MAP EXAMPLE1_LEGEND @mapbuilder/two evennia.contrib.mapbuilder.EXAMPLE2_MAP EXAMPLE2_LEGEND
(Legend path defaults to map path)
Below are two examples showcasing the use of automatic exit generation and custom exit generation. Whilst located, and can be used, from this module for convenience The below example code should be in mymap.py in mygame/world.
-
class
evennia.contrib.mapbuilder.CmdMapBuilder(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandBuild a map from a 2D ASCII map.
- Usage:
@mapbuilder[/switch] <path.to.file.MAPNAME> <path.to.file.MAP_LEGEND>
- Switches:
one - execute build instructions once without automatic exit creation two - execute build instructions twice without automatic exit creation
Example
@mapbuilder world.gamemap.MAP world.maplegend.MAP_LEGEND @mapbuilder evennia.contrib.mapbuilder.EXAMPLE1_MAP EXAMPLE1_LEGEND @mapbuilder/two evennia.contrib.mapbuilder.EXAMPLE2_MAP EXAMPLE2_LEGEND
(Legend path defaults to map path)
This is a command which takes two inputs: A string of ASCII characters representing a map and a dictionary of functions containing build instructions. The characters of the map are iterated over and compared to a list of trigger characters. When a match is found the corresponding function is executed generating the rooms, exits and objects as defined by the users build instructions. If a character is not a match to a provided trigger character (including spaces) it is simply skipped and the process continues. By default exits are automatically generated but is turned off by switches which also determines how many times the map is iterated over.
-
_keyaliases= ('@mapbuilder', '@buildmap')¶
-
_matchset= {'@buildmap', '@mapbuilder'}¶
-
aliases= ['@buildmap']¶
-
help_category= 'building'¶
-
key= '@mapbuilder'¶
-
lock_storage= 'cmd:superuser()'¶
-
locks= 'cmd:superuser()'¶
-
search_index_entry= {'aliases': '@buildmap', 'category': 'building', 'key': '@mapbuilder', 'tags': '', 'text': '\n Build a map from a 2D ASCII map.\n\n Usage:\n @mapbuilder[/switch] <path.to.file.MAPNAME> <path.to.file.MAP_LEGEND>\n\n Switches:\n one - execute build instructions once without automatic exit creation\n two - execute build instructions twice without automatic exit creation\n\n Example:\n @mapbuilder world.gamemap.MAP world.maplegend.MAP_LEGEND\n @mapbuilder evennia.contrib.mapbuilder.EXAMPLE1_MAP EXAMPLE1_LEGEND\n @mapbuilder/two evennia.contrib.mapbuilder.EXAMPLE2_MAP EXAMPLE2_LEGEND\n (Legend path defaults to map path)\n\n This is a command which takes two inputs:\n A string of ASCII characters representing a map and a dictionary of\n functions containing build instructions. The characters of the map are\n iterated over and compared to a list of trigger characters. When a match\n is found the corresponding function is executed generating the rooms,\n exits and objects as defined by the users build instructions. If a\n character is not a match to a provided trigger character (including spaces)\n it is simply skipped and the process continues. By default exits are\n automatically generated but is turned off by switches which also determines\n how many times the map is iterated over.\n '}¶
-
evennia.contrib.mapbuilder._map_to_list(game_map)[source]¶ Splits multi line map string into list of rows.
- Parameters
game_map (str) – An ASCII map
- Returns
The map split into rows
- Return type
list (list)
-
evennia.contrib.mapbuilder.build_map(caller, game_map, legend, iterations=1, build_exits=True)[source]¶ Receives the fetched map and legend vars provided by the player.
- Parameters
caller (Object) – The creator of the map.
game_map (str) – An ASCII map string.
legend (dict) – Mapping of map symbols to object types.
iterations (int) – The number of iteration passes.
build_exits (bool) – Create exits between new rooms.
Notes
The map is iterated over character by character, comparing it to the trigger characters in the legend var and executing the build instructions on finding a match. The map is iterated over according to the iterations value and exits are optionally generated between adjacent rooms according to the build_exits value.
-
evennia.contrib.mapbuilder.example1_build_forest(x, y, **kwargs)[source]¶ A basic example of build instructions. Make sure to include **kwargs in the arguments and return an instance of the room for exit generation.
-
evennia.contrib.mapbuilder.example1_build_mountains(x, y, **kwargs)[source]¶ A room that is a little more advanced
-
evennia.contrib.mapbuilder.example1_build_temple(x, y, **kwargs)[source]¶ A unique room that does not need to be as general
evennia.contrib.multidescer module¶
Evennia Mutltidescer
Contrib - Griatch 2016
A “multidescer” is a concept from the MUSH world. It allows for creating, managing and switching between multiple character descriptions. This multidescer will not require any changes to the Character class, rather it will use the multidescs Attribute (a list) and create it if it does not exist.
This contrib also works well together with the rpsystem contrib (which also adds the short descriptions and the sdesc command).
Installation:
Edit mygame/commands/default_cmdsets.py and add from evennia.contrib.multidescer import CmdMultiDesc to the top.
Next, look up the at_cmdset_create method of the CharacterCmdSet class and add a line self.add(CmdMultiDesc()) to the end of it.
Reload the server and you should have the +desc command available (it will replace the default desc command).
-
class
evennia.contrib.multidescer.CmdMultiDesc(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandManage multiple descriptions
- Usage:
+desc [key] - show current desc desc with <key> +desc <key> = <text> - add/replace desc with <key> +desc/list - list descriptions (abbreviated) +desc/list/full - list descriptions (full texts) +desc/edit <key> - add/edit desc <key> in line editor +desc/del <key> - delete desc <key> +desc/swap <key1>-<key2> - swap positions of <key1> and <key2> in list +desc/set <key> [+key+…] - set desc as default or combine multiple descs
Notes
When combining multiple descs with +desc/set <key> + <key2> + …, any keys not matching an actual description will be inserted as plain text. Use e.g. ansi line break ||/ to add a new paragraph and + + or ansi space ||_ to add extra whitespace.
-
_keyaliases= ('+desc', 'desc')¶
-
_matchset= {'+desc', 'desc'}¶
-
aliases= ['desc']¶
-
func()[source]¶ Implements the multidescer. We will use db.desc for the description in use and db.multidesc to store all descriptions.
-
help_category= 'general'¶
-
key= '+desc'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'desc', 'category': 'general', 'key': '+desc', 'tags': '', 'text': '\n Manage multiple descriptions\n\n Usage:\n +desc [key] - show current desc desc with <key>\n +desc <key> = <text> - add/replace desc with <key>\n +desc/list - list descriptions (abbreviated)\n +desc/list/full - list descriptions (full texts)\n +desc/edit <key> - add/edit desc <key> in line editor\n +desc/del <key> - delete desc <key>\n +desc/swap <key1>-<key2> - swap positions of <key1> and <key2> in list\n +desc/set <key> [+key+...] - set desc as default or combine multiple descs\n\n Notes:\n When combining multiple descs with +desc/set <key> + <key2> + ...,\n any keys not matching an actual description will be inserted\n as plain text. Use e.g. ansi line break ||/ to add a new\n paragraph and + + or ansi space ||_ to add extra whitespace.\n\n '}¶
-
exception
evennia.contrib.multidescer.DescValidateError[source]¶ Bases:
ValueErrorUsed for tracebacks from desc systems
-
evennia.contrib.multidescer._save_editor(caller, buffer)[source]¶ Called when the editor saves its contents
-
evennia.contrib.multidescer._update_store(caller, key=None, desc=None, delete=False, swapkey=None)[source]¶ Helper function for updating the database store.
- Parameters
caller (Object) – The caller of the command.
key (str) – Description identifier
desc (str) – Description text.
delete (bool) – Delete given key.
swapkey (str) – Swap list positions of key and this key.
evennia.contrib.puzzles module¶
Puzzles System - Provides a typeclass and commands for objects that can be combined (i.e. ‘use’d) to produce new objects.
Evennia contribution - Henddher 2018
A Puzzle is a recipe of what objects (aka parts) must be combined by a player so a new set of objects (aka results) are automatically created.
Consider this simple Puzzle:
orange, mango, yogurt, blender = fruit smoothie
As a Builder:
@create/drop orange @create/drop mango @create/drop yogurt @create/drop blender @create/drop fruit smoothie
@puzzle smoothie, orange, mango, yogurt, blender = fruit smoothie … Puzzle smoothie(#1234) created successfuly.
@destroy/force orange, mango, yogurt, blender, fruit smoothie
@armpuzzle #1234 Part orange is spawned at … Part mango is spawned at … …. Puzzle smoothie(#1234) has been armed successfully
As Player:
use orange, mango, yogurt, blender … Genius, you blended all fruits to create a fruit smoothie!
Details:
Puzzles are created from existing objects. The given objects are introspected to create prototypes for the puzzle parts and results. These prototypes become the puzzle recipe. (See PuzzleRecipe and @puzzle command). Once the recipe is created, all parts and result can be disposed (i.e. destroyed).
At a later time, a Builder or a Script can arm the puzzle and spawn all puzzle parts in their respective locations (See @armpuzzle).
A regular player can collect the puzzle parts and combine them (See use command). If player has specified all pieces, the puzzle is considered solved and all its puzzle parts are destroyed while the puzzle results are spawened on their corresponding location.
Installation:
Add the PuzzleSystemCmdSet to all players. Alternatively:
@py self.cmdset.add(‘evennia.contrib.puzzles.PuzzleSystemCmdSet’)
-
class
evennia.contrib.puzzles.CmdArmPuzzle(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandArms a puzzle by spawning all its parts.
- Usage:
@armpuzzle <puzzle #dbref>
Notes
Create puzzles with @puzzle; get list of defined puzzles using @lspuzzlerecipes.
-
_keyaliases= ('@armpuzzle',)¶
-
_matchset= {'@armpuzzle'}¶
-
aliases= []¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'puzzles'¶
-
key= '@armpuzzle'¶
-
lock_storage= 'cmd:perm(armpuzzle) or perm(Builder)'¶
-
locks= 'cmd:perm(armpuzzle) or perm(Builder)'¶
-
search_index_entry= {'aliases': '', 'category': 'puzzles', 'key': '@armpuzzle', 'tags': '', 'text': '\n Arms a puzzle by spawning all its parts.\n\n Usage:\n @armpuzzle <puzzle #dbref>\n\n Notes:\n Create puzzles with `@puzzle`; get list of\n defined puzzles using `@lspuzzlerecipes`.\n\n '}¶
-
class
evennia.contrib.puzzles.CmdCreatePuzzleRecipe(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandCreates a puzzle recipe. A puzzle consists of puzzle-parts that the player can ‘use’ together to create a specified result.
- Usage:
@puzzle name,<part1[,part2,…>] = <result1[,result2,…]>
Example
create/drop balloon create/drop glass of water create/drop water balloon @puzzle waterballon,balloon,glass of water = water balloon @del ballon, glass of water, water balloon @armpuzzle #1
Notes: Each part and result are objects that must (temporarily) exist and be placed in their corresponding location in order to create the puzzle. After the creation of the puzzle, these objects are not needed anymore and can be deleted. Components of the puzzle will be re-created by use of the @armpuzzle command later.
-
_keyaliases= ('@puzzle', '@puzzlerecipe')¶
-
_matchset= {'@puzzle', '@puzzlerecipe'}¶
-
aliases= ['@puzzlerecipe']¶
-
confirm= True¶
-
default_confirm= 'no'¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'puzzles'¶
-
key= '@puzzle'¶
-
lock_storage= 'cmd:perm(puzzle) or perm(Builder)'¶
-
locks= 'cmd:perm(puzzle) or perm(Builder)'¶
-
search_index_entry= {'aliases': '@puzzlerecipe', 'category': 'puzzles', 'key': '@puzzle', 'tags': '', 'text': "\n Creates a puzzle recipe. A puzzle consists of puzzle-parts that\n the player can 'use' together to create a specified result.\n\n Usage:\n @puzzle name,<part1[,part2,...>] = <result1[,result2,...]>\n\n Example:\n create/drop balloon\n create/drop glass of water\n create/drop water balloon\n @puzzle waterballon,balloon,glass of water = water balloon\n @del ballon, glass of water, water balloon\n @armpuzzle #1\n\n Notes:\n Each part and result are objects that must (temporarily) exist and be placed in their\n corresponding location in order to create the puzzle. After the creation of the puzzle,\n these objects are not needed anymore and can be deleted. Components of the puzzle\n will be re-created by use of the `@armpuzzle` command later.\n\n "}¶
-
class
evennia.contrib.puzzles.CmdEditPuzzle(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandEdits puzzle properties
- Usage:
@puzzleedit[/delete] <#dbref> @puzzleedit <#dbref>/use_success_message = <Custom message> @puzzleedit <#dbref>/use_success_location_message = <Custom message from {caller} producing {result_names}> @puzzleedit <#dbref>/mask = attr1[,attr2,…]> @puzzleedit[/addpart] <#dbref> = <obj[,obj2,…]> @puzzleedit[/delpart] <#dbref> = <obj[,obj2,…]> @puzzleedit[/addresult] <#dbref> = <obj[,obj2,…]> @puzzleedit[/delresult] <#dbref> = <obj[,obj2,…]>
- Switches:
addpart - adds parts to the puzzle delpart - removes parts from the puzzle addresult - adds results to the puzzle delresult - removes results from the puzzle delete - deletes the recipe. Existing parts and results aren’t modified
mask - attributes to exclude during matching (e.g. location, desc, etc.) use_success_location_message containing {result_names} and {caller} will
automatically be replaced with correct values. Both are optional.
When removing parts/results, it’s possible to remove all.
-
_keyaliases= ('@puzzleedit',)¶
-
_matchset= {'@puzzleedit'}¶
-
aliases= []¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'puzzles'¶
-
key= '@puzzleedit'¶
-
lock_storage= 'cmd:perm(puzzleedit) or perm(Builder)'¶
-
locks= 'cmd:perm(puzzleedit) or perm(Builder)'¶
-
search_index_entry= {'aliases': '', 'category': 'puzzles', 'key': '@puzzleedit', 'tags': '', 'text': "\n Edits puzzle properties\n\n Usage:\n @puzzleedit[/delete] <#dbref>\n @puzzleedit <#dbref>/use_success_message = <Custom message>\n @puzzleedit <#dbref>/use_success_location_message = <Custom message from {caller} producing {result_names}>\n @puzzleedit <#dbref>/mask = attr1[,attr2,...]>\n @puzzleedit[/addpart] <#dbref> = <obj[,obj2,...]>\n @puzzleedit[/delpart] <#dbref> = <obj[,obj2,...]>\n @puzzleedit[/addresult] <#dbref> = <obj[,obj2,...]>\n @puzzleedit[/delresult] <#dbref> = <obj[,obj2,...]>\n\n Switches:\n addpart - adds parts to the puzzle\n delpart - removes parts from the puzzle\n addresult - adds results to the puzzle\n delresult - removes results from the puzzle\n delete - deletes the recipe. Existing parts and results aren't modified\n\n mask - attributes to exclude during matching (e.g. location, desc, etc.)\n use_success_location_message containing {result_names} and {caller} will\n automatically be replaced with correct values. Both are optional.\n\n When removing parts/results, it's possible to remove all.\n\n "}¶
-
class
evennia.contrib.puzzles.CmdListArmedPuzzles(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandSearches for all armed puzzles
- Usage:
@lsarmedpuzzles
-
_keyaliases= ('@lsarmedpuzzles',)¶
-
_matchset= {'@lsarmedpuzzles'}¶
-
aliases= []¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'puzzles'¶
-
key= '@lsarmedpuzzles'¶
-
lock_storage= 'cmd:perm(lsarmedpuzzles) or perm(Builder)'¶
-
locks= 'cmd:perm(lsarmedpuzzles) or perm(Builder)'¶
-
search_index_entry= {'aliases': '', 'category': 'puzzles', 'key': '@lsarmedpuzzles', 'tags': '', 'text': '\n Searches for all armed puzzles\n\n Usage:\n @lsarmedpuzzles\n '}¶
-
class
evennia.contrib.puzzles.CmdListPuzzleRecipes(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandSearches for all puzzle recipes
- Usage:
@lspuzzlerecipes
-
_keyaliases= ('@lspuzzlerecipes',)¶
-
_matchset= {'@lspuzzlerecipes'}¶
-
aliases= []¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'puzzles'¶
-
key= '@lspuzzlerecipes'¶
-
lock_storage= 'cmd:perm(lspuzzlerecipes) or perm(Builder)'¶
-
locks= 'cmd:perm(lspuzzlerecipes) or perm(Builder)'¶
-
search_index_entry= {'aliases': '', 'category': 'puzzles', 'key': '@lspuzzlerecipes', 'tags': '', 'text': '\n Searches for all puzzle recipes\n\n Usage:\n @lspuzzlerecipes\n '}¶
-
class
evennia.contrib.puzzles.CmdUsePuzzleParts(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandUse an object, or a group of objects at once.
Example
You look around you and see a pole, a long string, and a needle.
use pole, long string, needle
Genius! You built a fishing pole.
- Usage:
use <obj1> [,obj2,…]
-
_keyaliases= ('use', 'combine')¶
-
_matchset= {'combine', 'use'}¶
-
aliases= ['combine']¶
-
func()[source]¶ This is the hook function that actually does all the work. It is called by the cmdhandler right after self.parser() finishes, and so has access to all the variables defined therein.
-
help_category= 'puzzles'¶
-
key= 'use'¶
-
lock_storage= 'cmd:pperm(use) or pperm(Player)'¶
-
locks= 'cmd:pperm(use) or pperm(Player)'¶
-
search_index_entry= {'aliases': 'combine', 'category': 'puzzles', 'key': 'use', 'tags': '', 'text': '\n Use an object, or a group of objects at once.\n\n\n Example:\n You look around you and see a pole, a long string, and a needle.\n\n use pole, long string, needle\n\n Genius! You built a fishing pole.\n\n\n Usage:\n use <obj1> [,obj2,...]\n '}¶
-
class
evennia.contrib.puzzles.PuzzleRecipe(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptDefinition of a Puzzle Recipe
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_meta= <Options for PuzzleRecipe>¶
-
path= 'evennia.contrib.puzzles.PuzzleRecipe'¶
-
typename= 'PuzzleRecipe'¶
-
exception
-
class
evennia.contrib.puzzles.PuzzleSystemCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetCmdSet to create, arm and resolve Puzzles
-
at_cmdset_creation()[source]¶ Hook method - this should be overloaded in the inheriting class, and should take care of populating the cmdset by use of self.add().
-
path= 'evennia.contrib.puzzles.PuzzleSystemCmdSet'¶
-
-
evennia.contrib.puzzles._matching_puzzles(puzzles, puzzlename_tags_dict, puzzle_ingredients)[source]¶
evennia.contrib.random_string_generator module¶
Pseudo-random generator and registry
Evennia contribution - Vincent Le Goff 2017
This contrib can be used to generate pseudo-random strings of information with specific criteria. You could, for instance, use it to generate phone numbers, license plate numbers, validation codes, non-sensivite passwords and so on. The strings generated by the generator will be stored and won’t be available again in order to avoid repetition. Here’s a very simple example:
`python
from evennia.contrib.random_string_generator import RandomStringGenerator
# Create a generator for phone numbers
phone_generator = RandomStringGenerator("phone number", r"555-[0-9]{3}-[0-9]{4}")
# Generate a phone number (555-XXX-XXXX with X as numbers)
number = phone_generator.get()
# `number` will contain something like: "555-981-2207"
# If you call `phone_generator.get`, it won't give the same anymore.phone_generator.all()
# Will return a list of all currently-used phone numbers
phone_generator.remove("555-981-2207")
# The number can be generated again
`
To use it, you will need to:
Import the RandomStringGenerator class from the contrib.
Create an instance of this class taking two arguments: - The name of the gemerator (like “phone number”, “license plate”…). - The regular expression representing the expected results.
Use the generator’s all, get and remove methods as shown above.
To understand how to read and create regular expressions, you can refer to [the documentation on the re module](https://docs.python.org/2/library/re.html). Some examples of regular expressions you could use:
r”555-d{3}-d{4}”: 555, a dash, 3 digits, another dash, 4 digits.
r”[0-9]{3}[A-Z][0-9]{3}”: 3 digits, a capital letter, 3 digits.
r”[A-Za-z0-9]{8,15}”: between 8 and 15 letters and digits.
…
Behind the scenes, a script is created to store the generated information for a single generator. The RandomStringGenerator object will also read the regular expression you give to it to see what information is required (letters, digits, a more restricted class, simple characters…)… More complex regular expressions (with branches for instance) might not be available.
-
exception
evennia.contrib.random_string_generator.ExhaustedGenerator[source]¶ Bases:
RuntimeErrorThe generator hasn’t any available strings to generate anymore.
-
class
evennia.contrib.random_string_generator.RandomStringGenerator(name, regex)[source]¶ Bases:
objectA generator class to generate pseudo-random strings with a rule.
The “rule” defining what the generator should provide in terms of string is given as a regular expression when creating instances of this class. You can use the all method to get all generated strings, the get method to generate a new string, the remove method to remove a generated string, or the clear method to remove all generated strings.
Bear in mind, however, that while the generated strings will be stored to avoid repetition, the generator will not concern itself with how the string is stored on the object you use. You probably want to create a tag to mark this object. This is outside of the scope of this class.
-
__init__(name, regex)[source]¶ Create a new generator.
- Parameters
name (str) – name of the generator to create.
regex (str) – regular expression describing the generator.
Notes
name should be an explicit name. If you use more than one generator in your game, be sure to give them different names. This name will be used to store the generated information in the global script, and in case of errors.
The regular expression should describe the generator, what it should generate: a phone number, a license plate, a password or something else. Regular expressions allow you to use pretty advanced criteria, but be aware that some regular expressions will be rejected if not specific enough.
- Raises
RejectedRegex – the provided regular expression couldn’t be
accepted as a valid generator description. –
-
_find_elements(regex)[source]¶ Find the elements described in the regular expression. This will analyze the provided regular expression and try to find elements.
- Parameters
regex (str) – the regular expression.
-
all()[source]¶ Return all generated strings for this generator.
- Returns
the list of strings that are already used. The strings that were generated first come first in the list.
- Return type
strings (list of strr)
-
get(store=True, unique=True)[source]¶ Generate a pseudo-random string according to the regular expression.
- Parameters
store (bool, optional) – store the generated string in the script.
unique (bool, optional) – keep on trying if the string is already used.
- Returns
The newly-generated string.
- Raises
ExhaustedGenerator – if there’s no available string in this generator.
Note
Unless asked explicitly, the returned string can’t repeat itself.
-
remove(element)[source]¶ Remove a generated string from the list of stored strings.
- Parameters
element (str) – the string to remove from the list of generated strings.
- Raises
ValueError – the specified value hasn’t been generated and is not present.
Note
The specified string has to be present in the script (so has to have been generated). It will remove this entry from the script, so this string could be generated again by calling the get method.
-
script= None¶
-
-
class
evennia.contrib.random_string_generator.RandomStringGeneratorScript(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptThe global script to hold all generators.
It will be automatically created the first time generate is called on a RandomStringGenerator object.
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_meta= <Options for RandomStringGeneratorScript>¶
-
path= 'evennia.contrib.random_string_generator.RandomStringGeneratorScript'¶
-
typename= 'RandomStringGeneratorScript'¶
-
exception
-
exception
evennia.contrib.random_string_generator.RejectedRegex[source]¶ Bases:
RuntimeErrorThe provided regular expression has been rejected.
More details regarding why this error occurred will be provided in the message. The usual reason is the provided regular expression is not specific enough and could lead to inconsistent generating.
evennia.contrib.rplanguage module¶
Language and whisper obfuscation system
Evennia contrib - Griatch 2015
This module is intented to be used with an emoting system (such as contrib/rpsystem.py). It offers the ability to obfuscate spoken words in the game in various ways:
- Language: The language functionality defines a pseudo-language map
to any number of languages. The string will be obfuscated depending on a scaling that (most likely) will be input as a weighted average of the language skill of the speaker and listener.
- Whisper: The whisper functionality will gradually “fade out” a
whisper along as scale 0-1, where the fading is based on gradually removing sections of the whisper that is (supposedly) easier to overhear (for example “s” sounds tend to be audible even when no other meaning can be determined).
Usage:
```python from evennia.contrib import rplanguage
# need to be done once, here we create the “default” lang rplanguage.add_language()
say = “This is me talking.” whisper = “This is me whispering.
print rplanguage.obfuscate_language(say, level=0.0) <<< “This is me talking.” print rplanguage.obfuscate_language(say, level=0.5) <<< “This is me byngyry.” print rplanguage.obfuscate_language(say, level=1.0) <<< “Daly ly sy byngyry.”
result = rplanguage.obfuscate_whisper(whisper, level=0.0) <<< “This is me whispering” result = rplanguage.obfuscate_whisper(whisper, level=0.2) <<< “This is m- whisp-ring” result = rplanguage.obfuscate_whisper(whisper, level=0.5) <<< “—s -s – —s——” result = rplanguage.obfuscate_whisper(whisper, level=0.7) <<< “—- – – ———-” result = rplanguage.obfuscate_whisper(whisper, level=1.0) <<< “…”
To set up new languages, import and use the add_language() helper method in this module. This allows you to customize the “feel” of the semi-random language you are creating. Especially the word_length_variance helps vary the length of translated words compared to the original and can help change the “feel” for the language you are creating. You can also add your own dictionary and “fix” random words for a list of input words.
Below is an example of “elvish”, using “rounder” vowels and sounds:
```python phonemes = “oi oh ee ae aa eh ah ao aw ay er ey ow ia ih iy ” “oy ua uh uw y p b t d f v t dh s z sh zh ch jh k ” “ng g m n l r w”, vowels = “eaoiuy” grammar = “v vv vvc vcc vvcc cvvc vccv vvccv vcvccv vcvcvcc vvccvvcc ” “vcvvccvvc cvcvvcvvcc vcvcvvccvcvv”, word_length_variance = 1 noun_postfix = “‘la” manual_translations = {“the”:”y’e”, “we”:”uyi”, “she”:”semi”, “he”:”emi”,
“you”: “do”, ‘me’:’mi’,’i’:’me’, ‘be’:”hy’e”, ‘and’:’y’}
- rplanguage.add_language(key=”elvish”, phonemes=phonemes, grammar=grammar,
word_length_variance=word_length_variance, noun_postfix=noun_postfix, vowels=vowels, manual_translations=manual_translations auto_translations=”my_word_file.txt”)
This will produce a decicively more “rounded” and “soft” language than the default one. The few manual_translations also make sure to make it at least look superficially “reasonable”.
The auto_translations keyword is useful, this accepts either a list or a path to a file of words (one per line) to automatically create fixed translations for according to the grammatical rules. This allows to quickly build a large corpus of translated words that never change (if this is desired).
-
class
evennia.contrib.rplanguage.LanguageHandler(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptThis is a storage class that should usually not be created on its own. It’s automatically created by a call to obfuscate_language or add_language below.
Languages are implemented as a “logical” pseudo- consistent language algorith here. The idea is that a language is built up from phonemes. These are joined together according to a “grammar” of possible phoneme- combinations and allowed characters. It may sound simplistic, but this allows to easily make “similar-sounding” languages. One can also custom-define a dictionary of some common words to give further consistency. Optionally, the system also allows an input list of common words to be loaded and given random translations. These will be stored to disk and will thus not change. This gives a decent “stability” of the language but if the goal is to obfuscate, this may allow players to eventually learn to understand the gist of a sentence even if their characters can not. Any number of languages can be created this way.
This nonsense language will partially replace the actual spoken language when so desired (usually because the speaker/listener don’t know the language well enough).
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_meta= <Options for LanguageHandler>¶
-
_translate_sub(match)[source]¶ Replacer method called by re.sub when traversing the language string.
- Parameters
match (re.matchobj) – Match object from regex.
- Returns
converted word.
Notes
Assumes self.lastword and self.level is available on the object.
-
add(key='default', phonemes='ea oh ae aa eh ah ao aw ai er ey ow ia ih iy oy ua uh uw a e i u y p b t d f v t dh s z sh zh ch jh k ng g m n l r w', grammar='v cv vc cvv vcc vcv cvcc vccv cvccv cvcvcc cvccvcv vccvccvc cvcvccvv cvcvcvcvv', word_length_variance=0, noun_translate=False, noun_prefix='', noun_postfix='', vowels='eaoiuy', manual_translations=None, auto_translations=None, force=False)[source]¶ Add a new language. Note that you generally only need to do this once per language and that adding an existing language will re-initialize all the random components to new permanent values.
- Parameters
key (str, optional) – The name of the language. This will be used as an identifier for the language so it should be short and unique.
phonemes (str, optional) – Space-separated string of all allowed phonemes in this language. If either of the base phonemes (c, v, cc, vv) are present in the grammar, the phoneme list must at least include one example of each.
grammar (str) – All allowed consonant (c) and vowel (v) combinations allowed to build up words. Grammars are broken into the base phonemes (c, v, cc, vv) prioritizing the longer bases. So cvv would be a the c + vv (would allow for a word like ‘die’ whereas cvcvccc would be c+v+c+v+cc+c (a word like ‘galosch’).
word_length_variance (real) – The variation of length of words. 0 means a minimal variance, higher variance may mean words have wildly varying length; this strongly affects how the language “looks”.
noun_translate (bool, optional) – If a proper noun, identified as a capitalized word, should be translated or not. By default they will not, allowing for e.g. the names of characters to be understandable.
noun_prefix (str, optional) – A prefix to go before every noun in this language (if any).
noun_postfix (str, optuonal) – A postfix to go after every noun in this language (if any, usually best to avoid combining with noun_prefix or language becomes very wordy).
vowels (str, optional) – Every vowel allowed in this language.
manual_translations (dict, optional) – This allows for custom-setting certain words in the language to mean the same thing. It is on the form {real_word: fictional_word}, for example {“the”, “y’e”} .
auto_translations (str or list, optional) – These are lists words that should be auto-translated with a random, but fixed, translation. If a path to a file, this file should contain a list of words to produce translations for, one word per line. If a list, the list’s elements should be the words to translate. The manual_translations will always override overlapping translations created automatically.
force (bool, optional) – Unless true, will not allow the addition of a language that is already created.
- Raises
LanguageExistsError – Raised if trying to adding a language with a key that already exists, without force being set.
Notes
The word_file is for example a word-frequency list for the N most common words in the host language. The translations will be random, but will be stored persistently to always be the same. This allows for building a quick, decently-sounding fictive language that tend to produce the same “translation” (mostly) with the same input sentence.
-
path= 'evennia.contrib.rplanguage.LanguageHandler'¶
-
translate(text, level=0.0, language='default')[source]¶ Translate the text according to the given level.
- Parameters
text (str) – The text to translate
level (real) – Value between 0.0 and 1.0, where 0.0 means no obfuscation (text returned unchanged) and 1.0 means full conversion of every word. The closer to 1, the shorter words will be translated.
language (str) – The language key identifier.
- Returns
A translated string.
- Return type
text (str)
-
typename= 'LanguageHandler'¶
-
exception
-
evennia.contrib.rplanguage.add_language(**kwargs)[source]¶ Access function to creating a new language. See the docstring of LanguageHandler.add for list of keyword arguments.
-
evennia.contrib.rplanguage.available_languages()[source]¶ Returns all available language keys.
- Returns
List of key strings of all available languages.
- Return type
languages (list)
-
evennia.contrib.rplanguage.obfuscate_language(text, level=0.0, language='default')[source]¶ Main access method for the language parser.
- Parameters
text (str) – Text to obfuscate.
level (real, optional) – A value from 0.0-1.0 determining the level of obfuscation where 0 means no jobfuscation (string returned unchanged) and 1.0 means the entire string is obfuscated.
language (str, optional) – The identifier of a language the system understands.
- Returns
The translated text.
- Return type
translated (str)
-
evennia.contrib.rplanguage.obfuscate_whisper(whisper, level=0.0)[source]¶ Obfuscate whisper depending on a pre-calculated level (that may depend on distance, listening skill etc)
- Parameters
whisper (str) – The whisper string to obscure. The entire string will be considered in the obscuration.
level (real, optional) – This is a value 0-1, where 0 means not obscured (whisper returned unchanged) and 1 means fully obscured.
evennia.contrib.rpsystem module¶
Roleplaying base system for Evennia
Contribution - Griatch, 2015
This module contains the ContribRPObject, ContribRPRoom and ContribRPCharacter typeclasses. If you inherit your objects/rooms/character from these (or make them the defaults) from these you will get the following features:
Objects/Rooms will get the ability to have poses and will report
the poses of items inside them (the latter most useful for Rooms). - Characters will get poses and also sdescs (short descriptions) that will be used instead of their keys. They will gain commands for managing recognition (custom sdesc-replacement), masking themselves as well as an advanced free-form emote command.
To use, simply import the typclasses you want from this module and use them to create your objects, or set them to default.
In more detail, This RP base system introduces the following features to a game, common to many RP-centric games:
- emote system using director stance emoting (names/sdescs).
This uses a customizable replacement noun (/me, @ etc) to represent you in the emote. You can use /sdesc, /nick, /key or /alias to reference objects in the room. You can use any number of sdesc sub-parts to differentiate a local sdesc, or use /1-sdesc etc to differentiate them. The emote also identifies nested says.
- sdesc obscuration of real character names for use in emotes
and in any referencing such as object.search(). This relies on an SdescHandler sdesc being set on the Character and makes use of a custom Character.get_display_name hook. If sdesc is not set, the character’s key is used instead. This is particularly used in the emoting system.
- recog system to assign your own nicknames to characters, can then
be used for referencing. The user may recog a user and assign any personal nick to them. This will be shown in descriptions and used to reference them. This is making use of the nick functionality of Evennia.
masks to hide your identity (using a simple lock).
- pose system to set room-persistent poses, visible in room
descriptions and when looking at the person/object. This is a simple Attribute that modifies how the characters is viewed when in a room as sdesc + pose.
- in-emote says, including seamless integration with language
obscuration routine (such as contrib/rplanguage.py)
Examples:
> look Tavern The tavern is full of nice people
A tall man is standing by the bar.
Above is an example of a player with an sdesc “a tall man”. It is also an example of a static pose: The “standing by the bar” has been set by the player of the tall man, so that people looking at him can tell at a glance what is going on.
> emote /me looks at /tall and says “Hello!”
- I see:
Griatch looks at Tall man and says “Hello”.
- Tall man (assuming his name is Tom) sees:
The godlike figure looks at Tom and says “Hello”.
Verbose Installation Instructions:
In typeclasses/character.py: Import the ContribRPCharacter class:
from evennia.contrib.rpsystem import ContribRPCharacter
- Inherit ContribRPCharacter:
Change “class Character(DefaultCharacter):” to class Character(ContribRPCharacter):
- If you have any overriden calls in at_object_creation(self):
Add super().at_object_creation() as the top line.
- In typeclasses/rooms.py:
Import the ContribRPRoom class: from evennia.contrib.rpsystem import ContribRPRoom
- Inherit ContribRPRoom:
Change class Room(DefaultRoom): to class Room(ContribRPRoom):
- In typeclasses/objects.py
Import the ContribRPObject class: from evennia.contrib.rpsystem import ContribRPObject
- Inherit ContribRPObject:
Change class Object(DefaultObject): to class Object(ContribRPObject):
Reload the server (@reload or from console: “evennia reload”)
- Force typeclass updates as required. Example for your character:
@type/reset/force me = typeclasses.characters.Character
-
class
evennia.contrib.rpsystem.CmdEmote(**kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.RPCommandEmote an action, allowing dynamic replacement of text in the emote.
- Usage:
emote text
Example
emote /me looks around. emote With a flurry /me attacks /tall man with his sword. emote “Hello”, /me says.
Describes an event in the world. This allows the use of /ref markers to replace with the short descriptions or recognized strings of objects in the same room. These will be translated to emotes to match each person seeing it. Use “…” for saying things and langcode”…” without spaces to say something in a different language.
-
_keyaliases= (':', 'emote')¶
-
_matchset= {':', 'emote'}¶
-
aliases= [':']¶
-
help_category= 'general'¶
-
key= 'emote'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': ':', 'category': 'general', 'key': 'emote', 'tags': '', 'text': '\n Emote an action, allowing dynamic replacement of\n text in the emote.\n\n Usage:\n emote text\n\n Example:\n emote /me looks around.\n emote With a flurry /me attacks /tall man with his sword.\n emote "Hello", /me says.\n\n Describes an event in the world. This allows the use of /ref\n markers to replace with the short descriptions or recognized\n strings of objects in the same room. These will be translated to\n emotes to match each person seeing it. Use "..." for saying\n things and langcode"..." without spaces to say something in\n a different language.\n\n '}¶
-
class
evennia.contrib.rpsystem.CmdMask(**kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.RPCommandWear a mask
- Usage:
mask <new sdesc> unmask
This will put on a mask to hide your identity. When wearing a mask, your sdesc will be replaced by the sdesc you pick and people’s recognitions of you will be disabled.
-
_keyaliases= ('mask', 'unmask')¶
-
_matchset= {'mask', 'unmask'}¶
-
aliases= ['unmask']¶
-
func()[source]¶ This is the actual executing part of the command. It is called directly after self.parse(). See the docstring of this module for which object properties are available (beyond those set in self.parse())
-
help_category= 'general'¶
-
key= 'mask'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': 'unmask', 'category': 'general', 'key': 'mask', 'tags': '', 'text': "\n Wear a mask\n\n Usage:\n mask <new sdesc>\n unmask\n\n This will put on a mask to hide your identity. When wearing\n a mask, your sdesc will be replaced by the sdesc you pick and\n people's recognitions of you will be disabled.\n\n "}¶
-
class
evennia.contrib.rpsystem.CmdPose(**kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.RPCommandSet a static pose
- Usage:
pose <pose> pose default <pose> pose reset pose obj = <pose> pose default obj = <pose> pose reset obj =
Examples
pose leans against the tree pose is talking to the barkeep. pose box = is sitting on the floor.
Set a static pose. This is the end of a full sentence that starts with your sdesc. If no full stop is given, it will be added automatically. The default pose is the pose you get when using pose reset. Note that you can use sdescs/recogs to reference people in your pose, but these always appear as that person’s sdesc in the emote, regardless of who is seeing it.
-
_keyaliases= ('pose',)¶
-
_matchset= {'pose'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'pose'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'pose', 'tags': '', 'text': "\n Set a static pose\n\n Usage:\n pose <pose>\n pose default <pose>\n pose reset\n pose obj = <pose>\n pose default obj = <pose>\n pose reset obj =\n\n Examples:\n pose leans against the tree\n pose is talking to the barkeep.\n pose box = is sitting on the floor.\n\n Set a static pose. This is the end of a full sentence that starts\n with your sdesc. If no full stop is given, it will be added\n automatically. The default pose is the pose you get when using\n pose reset. Note that you can use sdescs/recogs to reference\n people in your pose, but these always appear as that person's\n sdesc in the emote, regardless of who is seeing it.\n\n "}¶
-
class
evennia.contrib.rpsystem.CmdRecog(**kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.RPCommandRecognize another person in the same room.
- Usage:
recog recog sdesc as alias forget alias
Example
recog tall man as Griatch forget griatch
This will assign a personal alias for a person, or forget said alias. Using the command without arguments will list all current recogs.
-
_keyaliases= ('recognize', 'recog', 'forget')¶
-
_matchset= {'forget', 'recog', 'recognize'}¶
-
aliases= ['recognize', 'forget']¶
-
help_category= 'general'¶
-
key= 'recog'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': 'recognize forget', 'category': 'general', 'key': 'recog', 'tags': '', 'text': '\n Recognize another person in the same room.\n\n Usage:\n recog\n recog sdesc as alias\n forget alias\n\n Example:\n recog tall man as Griatch\n forget griatch\n\n This will assign a personal alias for a person, or forget said alias.\n Using the command without arguments will list all current recogs.\n\n '}¶
-
class
evennia.contrib.rpsystem.CmdSay(**kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.RPCommandspeak as your character
- Usage:
say <message>
Talk to those in your current location.
-
_keyaliases= ('say', '"', "'")¶
-
_matchset= {'"', "'", 'say'}¶
-
aliases= ['"', "'"]¶
-
help_category= 'general'¶
-
key= 'say'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '" \'', 'category': 'general', 'key': 'say', 'tags': '', 'text': '\n speak as your character\n\n Usage:\n say <message>\n\n Talk to those in your current location.\n '}¶
-
class
evennia.contrib.rpsystem.CmdSdesc(**kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.RPCommandAssign yourself a short description (sdesc).
- Usage:
sdesc <short description>
Assigns a short description to yourself.
-
_keyaliases= ('sdesc',)¶
-
_matchset= {'sdesc'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'sdesc'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'sdesc', 'tags': '', 'text': '\n Assign yourself a short description (sdesc).\n\n Usage:\n sdesc <short description>\n\n Assigns a short description to yourself.\n\n '}¶
-
class
evennia.contrib.rpsystem.ContribRPCharacter(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultCharacter,evennia.contrib.rpsystem.ContribRPObjectThis is a character class that has poses, sdesc and recog.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist,evennia.contrib.rpsystem.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned,evennia.contrib.rpsystem.MultipleObjectsReturned
-
_meta= <Options for ContribRPCharacter>¶
-
at_before_say(message, **kwargs)[source]¶ Called before the object says or whispers anything, return modified message.
- Parameters
message (str) – The suggested say/whisper text spoken by self.
- Kwargs:
whisper (bool): If True, this is a whisper rather than a say.
-
get_display_name(looker, **kwargs)[source]¶ Displays the name of the object in a viewer-aware manner.
- Parameters
looker (TypedObject) – The object or account that is looking at/getting inforamtion for this object.
- Kwargs:
pose (bool): Include the pose (if available) in the return.
- Returns
A string of the sdesc containing the name of the object, if this is defined.
including the DBREF if this user is privileged to control said object.
- Return type
name (str)
Notes
The RPCharacter version of this method colors its display to make characters stand out from other objects.
-
path= 'evennia.contrib.rpsystem.ContribRPCharacter'¶
-
process_language(text, speaker, language, **kwargs)[source]¶ Allows to process the spoken text, for example by obfuscating language based on your and the speaker’s language skills. Also a good place to put coloring.
- Parameters
text (str) – The text to process.
speaker (Object) – The object delivering the text.
language (str) – An identifier string for the language.
- Returns
The optionally processed text.
- Return type
text (str)
Notes
This is designed to work together with a string obfuscator such as the obfuscate_language or obfuscate_whisper in the evennia.contrib.rplanguage module.
-
process_recog(recog, obj, **kwargs)[source]¶ Allows to customize how a recog string is displayed.
- Parameters
recog (str) – The recog string. It has already been translated from the original sdesc at this point.
obj (Object) – The object the recog:ed string belongs to. This is not used by default.
- Returns
The modified recog string.
- Return type
recog (str)
-
process_sdesc(sdesc, obj, **kwargs)[source]¶ Allows to customize how your sdesc is displayed (primarily by changing colors).
- Parameters
sdesc (str) – The sdesc to display.
obj (Object) – The object to which the adjoining sdesc belongs. If this object is equal to yourself, then you are viewing yourself (and sdesc is your key). This is not used by default.
- Returns
- The processed sdesc ready
for display.
- Return type
sdesc (str)
-
typename= 'ContribRPCharacter'¶
-
exception
-
class
evennia.contrib.rpsystem.ContribRPObject(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultObjectThis class is meant as a mix-in or parent for objects in an rp-heavy game. It implements the base functionality for poses.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for ContribRPObject>¶
-
get_display_name(looker, **kwargs)[source]¶ Displays the name of the object in a viewer-aware manner.
- Parameters
looker (TypedObject) – The object or account that is looking at/getting inforamtion for this object.
- Kwargs:
pose (bool): Include the pose (if available) in the return.
- Returns
A string of the sdesc containing the name of the object, if this is defined.
including the DBREF if this user is privileged to control said object.
- Return type
name (str)
Notes
The RPObject version doesn’t add color to its display.
-
path= 'evennia.contrib.rpsystem.ContribRPObject'¶
-
return_appearance(looker)[source]¶ This formats a description. It is the hook a ‘look’ command should call.
- Parameters
looker (Object) – Object doing the looking.
-
search(searchdata, global_search=False, use_nicks=True, typeclass=None, location=None, attribute_name=None, quiet=False, exact=False, candidates=None, nofound_string=None, multimatch_string=None, use_dbref=None)[source]¶ Returns an Object matching a search string/condition, taking sdescs into account.
Perform a standard object search in the database, handling multiple results and lack thereof gracefully. By default, only objects in the current location of self or its inventory are searched for.
- Parameters
searchdata (str or obj) –
Primary search criterion. Will be matched against object.key (with object.aliases second) unless the keyword attribute_name specifies otherwise. Special strings: - #<num>: search by unique dbref. This is always
a global search.
me,self: self-reference to this object
- <num>-<string> - can be used to differentiate
between multiple same-named matches
global_search (bool) – Search all objects globally. This is overruled by location keyword.
use_nicks (bool) – Use nickname-replace (nicktype “object”) on searchdata.
typeclass (str or Typeclass, or list of either) – Limit search only to Objects with this typeclass. May be a list of typeclasses for a broader search.
location (Object or list) – Specify a location or multiple locations to search. Note that this is used to query the contents of a location and will not match for the location itself - if you want that, don’t set this or use candidates to specify exactly which objects should be searched.
attribute_name (str) – Define which property to search. If set, no key+alias search will be performed. This can be used to search database fields (db_ will be automatically appended), and if that fails, it will try to return objects having Attributes with this name and value equal to searchdata. A special use is to search for “key” here if you want to do a key-search without including aliases.
quiet (bool) – don’t display default error messages - this tells the search method that the user wants to handle all errors themselves. It also changes the return value type, see below.
exact (bool) – if unset (default) - prefers to match to beginning of string rather than not matching at all. If set, requires exact matching of entire string.
candidates (list of objects) – this is an optional custom list of objects to search (filter) between. It is ignored if global_search is given. If not set, this list will automatically be defined to include the location, the contents of location and the caller’s contents (inventory).
nofound_string (str) – optional custom string for not-found error message.
multimatch_string (str) – optional custom string for multimatch error header.
use_dbref (bool or None) – If None, only turn off use_dbref if we are of a lower permission than Builder. Otherwise, honor the True/False value.
- Returns
- will return an Object/None if quiet=False,
otherwise it will return a list of 0, 1 or more matches.
- Return type
match (Object, None or list)
Notes
To find Accounts, use eg. evennia.account_search. If quiet=False, error messages will be handled by settings.SEARCH_AT_RESULT and echoed automatically (on error, return will be None). If quiet=True, the error messaging is assumed to be handled by the caller.
-
typename= 'ContribRPObject'¶
-
exception
-
class
evennia.contrib.rpsystem.ContribRPRoom(*args, **kwargs)[source]¶ Bases:
evennia.contrib.rpsystem.ContribRPObjectDummy inheritance for rooms.
-
exception
DoesNotExist¶ Bases:
evennia.contrib.rpsystem.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.contrib.rpsystem.MultipleObjectsReturned
-
_meta= <Options for ContribRPRoom>¶
-
path= 'evennia.contrib.rpsystem.ContribRPRoom'¶
-
typename= 'ContribRPRoom'¶
-
exception
-
class
evennia.contrib.rpsystem.RPCommand(**kwargs)[source]¶ Bases:
evennia.commands.command.Commandsimple parent
-
_keyaliases= ('command',)¶
-
_matchset= {'command'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'command'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'command', 'tags': '', 'text': 'simple parent'}¶
-
-
class
evennia.contrib.rpsystem.RPSystemCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetMix-in for adding rp-commands to default cmdset.
-
at_cmdset_creation()[source]¶ Hook method - this should be overloaded in the inheriting class, and should take care of populating the cmdset by use of self.add().
-
path= 'evennia.contrib.rpsystem.RPSystemCmdSet'¶
-
-
class
evennia.contrib.rpsystem.RecogHandler(obj)[source]¶ Bases:
objectThis handler manages the recognition mapping of an Object.
The handler stores data in Attributes as dictionaries of the following names:
_recog_ref2recog _recog_obj2recog _recog_obj2regex
-
__init__(obj)[source]¶ Initialize the handler
- Parameters
obj (Object) – The entity on which this handler is stored.
-
add(obj, recog, max_length=60)[source]¶ Assign a custom recog (nick) to the given object.
- Parameters
obj (Object) – The object ot associate with the recog string. This is usually determined from the sdesc in the room by a call to parse_sdescs_and_recogs, but can also be given.
recog (str) – The replacement string to use with this object.
max_length (int, optional) – The max length of the recog string.
- Returns
The (possibly cleaned up) recog string actually set.
- Return type
recog (str)
- Raises
SdescError – When recog could not be set or sdesc longer than max_length.
-
all()[source]¶ Get a mapping of the recogs stored in handler.
- Returns
A mapping of {recog: obj} stored in handler.
- Return type
recogs (dict)
-
get(obj)[source]¶ Get recog replacement string, if one exists, otherwise get sdesc and as a last resort, the object’s key.
- Parameters
obj (Object) – The object, whose sdesc to replace
- Returns
The replacement string to use.
- Return type
recog (str)
Notes
This method will respect a “enable_recog” lock set on obj (True by default) in order to turn off recog mechanism. This is useful for adding masks/hoods etc.
-
-
class
evennia.contrib.rpsystem.SdescHandler(obj)[source]¶ Bases:
objectThis Handler wraps all operations with sdescs. We need to use this since we do a lot preparations on sdescs when updating them, in order for them to be efficient to search for and query.
The handler stores data in the following Attributes
_sdesc - a string _regex - an empty dictionary
-
__init__(obj)[source]¶ Initialize the handler
- Parameters
obj (Object) – The entity on which this handler is stored.
-
add(sdesc, max_length=60)[source]¶ Add a new sdesc to object, replacing the old one.
- Parameters
sdesc (str) – The sdesc to set. This may be stripped of control sequences before setting.
max_length (int, optional) – The max limit of the sdesc.
- Returns
The actually set sdesc.
- Return type
sdesc (str)
- Raises
SdescError – If the sdesc is empty, can not be set or is
longer than max_length. –
-
-
evennia.contrib.rpsystem.ordered_permutation_regex(sentence)[source]¶ Builds a regex that matches ‘ordered permutations’ of a sentence’s words.
- Parameters
sentence (str) – The sentence to build a match pattern to
- Returns
- Compiled regex object represented the
possible ordered permutations of the sentence, from longest to shortest.
- Return type
regex (re object)
Example
The sdesc_regex for an sdesc of ” very tall man” will result in the following allowed permutations, regex-matched in inverse order of length (case-insensitive): “the very tall man”, “the very tall”, “very tall man”, “very tall”, “the very”, “tall man”, “the”, “very”, “tall”, and “man”. We also add regex to make sure it also accepts num-specifiers, like /2-tall.
-
evennia.contrib.rpsystem.parse_language(speaker, emote)[source]¶ Parse the emote for language. This is used with a plugin for handling languages.
- Parameters
speaker (Object) – The object speaking.
emote (str) – An emote possibly containing language references.
- Returns
- A tuple where the
emote is the emote string with all says (including quotes) replaced with reference markers on the form {##n} where n is a running number. The mapping is a dictionary between the markers and a tuple (langname, saytext), where langname can be None.
- Return type
(emote, mapping) (tuple)
- Raises
LanguageError – If an invalid language was specified.
Notes
Note that no errors are raised if the wrong language identifier is given. This data, together with the identity of the speaker, is intended to be used by the “listener” later, since with this information the language skill of the speaker can be offset to the language skill of the listener to determine how much information is actually conveyed.
-
evennia.contrib.rpsystem.parse_sdescs_and_recogs(sender, candidates, string, search_mode=False)[source]¶ Read a raw emote and parse it into an intermediary format for distributing to all observers.
- Parameters
sender (Object) – The object sending the emote. This object’s recog data will be considered in the parsing.
candidates (iterable) – A list of objects valid for referencing in the emote.
string (str): The string (like an emote) we want to analyze for keywords. search_mode (bool, optional): If True, the “emote” is a query string
we want to analyze. If so, the return value is changed.
- Returns
- If search_mode is False
(default), a tuple where the emote is the emote string, with all references replaced with internal-representation {#dbref} markers and mapping is a dictionary {“#dbref”:obj, …}.
- result (list): If search_mode is True we are
performing a search query on string, looking for a specific object. A list with zero, one or more matches.
- Return type
(emote, mapping) (tuple)
- Raises
EmoteException – For various ref-matching errors.
Notes
The parser analyzes and should understand the following _PREFIX-tagged structures in the emote: - self-reference (/me) - recogs (any part of it) stored on emoter, matching obj in candidates. - sdesc (any part of it) from any obj in candidates. - N-sdesc, N-recog separating multi-matches (1-tall, 2-tall) - says, “…” are
-
evennia.contrib.rpsystem.regex_tuple_from_key_alias(obj)[source]¶ This will build a regex tuple for any object, not just from those with sdesc/recog handlers. It’s used as a legacy mechanism for being able to mix this contrib with objects not using sdescs, but note that creating the ordered permutation regex dynamically for every object will add computational overhead.
- Parameters
obj (Object) – This object’s key and eventual aliases will be used to build the tuple.
- Returns
- A tuple
(ordered_permutation_regex, obj, key/alias)
- Return type
regex_tuple (tuple)
-
evennia.contrib.rpsystem.send_emote(sender, receivers, emote, anonymous_add='first')[source]¶ Main access function for distribute an emote.
- Parameters
sender (Object) – The one sending the emote.
receivers (iterable) – Receivers of the emote. These will also form the basis for which sdescs are ‘valid’ to use in the emote.
emote (str) – The raw emote string as input by emoter.
anonymous_add (str or None, optional) – If sender is not self-referencing in the emote, this will auto-add sender’s data to the emote. Possible values are - None: No auto-add at anonymous emote - ‘last’: Add sender to the end of emote as [sender] - ‘first’: Prepend sender to start of emote.
evennia.contrib.simpledoor module¶
SimpleDoor
Contribution - Griatch 2016
A simple two-way exit that represents a door that can be opened and closed. Can easily be expanded from to make it lockable, destroyable etc. Note that the simpledoor is based on Evennia locks, so it will not work for a superuser (which bypasses all locks) - the superuser will always appear to be able to close/open the door over and over without the locks stopping you. To use the door, use @quell or a non-superuser account.
Installation:
Import this module in mygame/commands/default_cmdsets and add the CmdOpen and CmdOpenCloseDoor commands to the CharacterCmdSet; then reload the server.
To try it out, @dig a new room and then use the (overloaded) @open commmand to open a new doorway to it like this:
@open doorway:contrib.simpledoor.SimpleDoor = otherroom
You can then use open doorway’ and `close doorway to change the open state. If you are not superuser (@quell yourself) you’ll find you cannot pass through either side of the door once it’s closed from the other side.
-
class
evennia.contrib.simpledoor.CmdOpen(**kwargs)[source]¶ Bases:
evennia.commands.default.building.CmdOpenopen a new exit from the current room
- Usage:
open <new exit>[;alias;alias..][:typeclass] [,<return exit>[;alias;..][:typeclass]]] = <destination>
Handles the creation of exits. If a destination is given, the exit will point there. The <return exit> argument sets up an exit at the destination leading back to the current room. Destination name can be given both as a #dbref and a name, if that name is globally unique.
-
_keyaliases= ('open',)¶
-
_matchset= {'open'}¶
-
aliases= []¶
-
create_exit(exit_name, location, destination, exit_aliases=None, typeclass=None)[source]¶ Simple wrapper for the default CmdOpen.create_exit
-
help_category= 'building'¶
-
key= 'open'¶
-
lock_storage= 'cmd:perm(open) or perm(Builder)'¶
-
search_index_entry= {'aliases': '', 'category': 'building', 'key': 'open', 'tags': '', 'text': '\n open a new exit from the current room\n\n Usage:\n open <new exit>[;alias;alias..][:typeclass] [,<return exit>[;alias;..][:typeclass]]] = <destination>\n\n Handles the creation of exits. If a destination is given, the exit\n will point there. The <return exit> argument sets up an exit at the\n destination leading back to the current room. Destination name\n can be given both as a #dbref and a name, if that name is globally\n unique.\n\n '}¶
-
class
evennia.contrib.simpledoor.CmdOpenCloseDoor(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandOpen and close a door
- Usage:
open <door> close <door>
-
_keyaliases= ('open', 'close')¶
-
_matchset= {'close', 'open'}¶
-
aliases= ['close']¶
-
help_category= 'general'¶
-
key= 'open'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': 'close', 'category': 'general', 'key': 'open', 'tags': '', 'text': '\n Open and close a door\n\n Usage:\n open <door>\n close <door>\n\n '}¶
-
class
evennia.contrib.simpledoor.SimpleDoor(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultExitA two-way exit “door” with some methods for affecting both “sides” of the door at the same time. For example, set a lock on either of the two sides using exitname.setlock(“traverse:false())
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for SimpleDoor>¶
-
at_failed_traverse(traversing_object)[source]¶ Called when door traverse: lock fails.
- Parameters
traversing_object (Typeclassed entity) – The object attempting the traversal.
-
path= 'evennia.contrib.simpledoor.SimpleDoor'¶
-
setdesc(description)[source]¶ Sets identical descs on both sides of the door.
- Parameters
setdesc (str) – A description.
-
setlock(lockstring)[source]¶ Sets identical locks on both sides of the door.
- Parameters
lockstring (str) – A lockstring, like “traverse:true()”.
-
typename= 'SimpleDoor'¶
-
exception
evennia.contrib.slow_exit module¶
Slow Exit typeclass
Contribution - Griatch 2014
This is an example of an Exit-type that delays its traversal.This simulates slow movement, common in many different types of games. The contrib also contains two commands, CmdSetSpeed and CmdStop for changing the movement speed and abort an ongoing traversal, respectively.
To try out an exit of this type, you could connect two existing rooms using something like this:
@open north:contrib.slow_exit.SlowExit = <destination>
Installation:
To make this your new default exit, modify mygame/typeclasses/exits.py to import this module and change the default Exit class to inherit from SlowExit instead.
To get the ability to change your speed and abort your movement, simply import and add CmdSetSpeed and CmdStop from this module to your default cmdset (see tutorials on how to do this if you are unsure).
Notes:
This implementation is efficient but not persistent; so incomplete movement will be lost in a server reload. This is acceptable for most game types - to simulate longer travel times (more than the couple of seconds assumed here), a more persistent variant using Scripts or the TickerHandler might be better.
-
class
evennia.contrib.slow_exit.CmdSetSpeed(**kwargs)[source]¶ Bases:
evennia.commands.command.Commandset your movement speed
- Usage:
setspeed stroll|walk|run|sprint
This will set your movement speed, determining how long time it takes to traverse exits. If no speed is set, ‘walk’ speed is assumed.
-
_keyaliases= ('setspeed',)¶
-
_matchset= {'setspeed'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'setspeed'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'setspeed', 'tags': '', 'text': "\n set your movement speed\n\n Usage:\n setspeed stroll|walk|run|sprint\n\n This will set your movement speed, determining how long time\n it takes to traverse exits. If no speed is set, 'walk' speed\n is assumed.\n "}¶
-
class
evennia.contrib.slow_exit.CmdStop(**kwargs)[source]¶ Bases:
evennia.commands.command.Commandstop moving
- Usage:
stop
Stops the current movement, if any.
-
_keyaliases= ('stop',)¶
-
_matchset= {'stop'}¶
-
aliases= []¶
-
func()[source]¶ This is a very simple command, using the stored deferred from the exit traversal above.
-
help_category= 'general'¶
-
key= 'stop'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'stop', 'tags': '', 'text': '\n stop moving\n\n Usage:\n stop\n\n Stops the current movement, if any.\n '}¶
-
class
evennia.contrib.slow_exit.SlowExit(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultExitThis overloads the way moving happens.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for SlowExit>¶
-
at_traverse(traversing_object, target_location)[source]¶ Implements the actual traversal, using utils.delay to delay the move_to.
-
path= 'evennia.contrib.slow_exit.SlowExit'¶
-
typename= 'SlowExit'¶
-
exception
evennia.contrib.talking_npc module¶
Evennia Talkative NPC
Contribution - Griatch 2011, grungies1138, 2016
This is a static NPC object capable of holding a simple menu-driven conversation. It’s just meant as an example. Create it by creating an object of typeclass contrib.talking_npc.TalkingNPC, For example using @create:
@create/drop John : contrib.talking_npc.TalkingNPC
Walk up to it and give the talk command to strike up a conversation. If there are many talkative npcs in the same room you will get to choose which one’s talk command to call (Evennia handles this automatically). This use of EvMenu is very simplistic; See EvMenu for a lot more complex possibilities.
-
class
evennia.contrib.talking_npc.CmdTalk(**kwargs)[source]¶ Bases:
evennia.commands.default.muxcommand.MuxCommandTalks to an npc
- Usage:
talk
This command is only available if a talkative non-player-character (NPC) is actually present. It will strike up a conversation with that NPC and give you options on what to talk about.
-
_keyaliases= ('talk',)¶
-
_matchset= {'talk'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'talk'¶
-
lock_storage= 'cmd:all()'¶
-
locks= 'cmd:all()'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'talk', 'tags': '', 'text': '\n Talks to an npc\n\n Usage:\n talk\n\n This command is only available if a talkative non-player-character\n (NPC) is actually present. It will strike up a conversation with\n that NPC and give you options on what to talk about.\n '}¶
-
class
evennia.contrib.talking_npc.TalkingCmdSet(cmdsetobj=None, key=None)[source]¶ Bases:
evennia.commands.cmdset.CmdSetStores the talk command.
-
key= 'talkingcmdset'¶
-
path= 'evennia.contrib.talking_npc.TalkingCmdSet'¶
-
-
class
evennia.contrib.talking_npc.TalkingNPC(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultObjectThis implements a simple Object using the talk command and using the conversation defined above.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for TalkingNPC>¶
-
path= 'evennia.contrib.talking_npc.TalkingNPC'¶
-
typename= 'TalkingNPC'¶
-
exception
evennia.contrib.test_traits module¶
Unit test module for Trait classes.
-
class
evennia.contrib.test_traits.TestNumericTraitOperators(methodName='runTest')[source]¶ Bases:
django.test.testcases.TestCaseTest case for numeric magic method implementations.
-
class
evennia.contrib.test_traits.TestTrait(methodName='runTest')[source]¶ Bases:
evennia.contrib.test_traits._TraitHandlerBaseTest the base Trait class
-
class
evennia.contrib.test_traits.TestTraitCounter(methodName='runTest')[source]¶ Bases:
evennia.contrib.test_traits._TraitHandlerBaseTest for counter- Traits
-
class
evennia.contrib.test_traits.TestTraitCounterTimed(methodName='runTest')[source]¶ Bases:
evennia.contrib.test_traits._TraitHandlerBaseTest for trait with timer component
-
class
evennia.contrib.test_traits.TestTraitGaugeTimed(methodName='runTest')[source]¶ Bases:
evennia.contrib.test_traits._TraitHandlerBaseTest for trait with timer component
-
class
evennia.contrib.test_traits.TestTraitStatic(methodName='runTest')[source]¶ Bases:
evennia.contrib.test_traits._TraitHandlerBaseTest for static Traits
-
class
evennia.contrib.test_traits.TraitHandlerTest(methodName='runTest')[source]¶ Bases:
evennia.contrib.test_traits._TraitHandlerBaseTesting for TraitHandler
evennia.contrib.tests module¶
Testing suite for contrib folder
-
class
evennia.contrib.tests.CmdDummy(**kwargs)[source]¶ Bases:
evennia.contrib.unixcommand.UnixCommandA dummy UnixCommand.
-
_keyaliases= ('dummy',)¶
-
_matchset= {'dummy'}¶
-
aliases= []¶
-
help_category= 'general'¶
-
key= 'dummy'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'dummy', 'tags': '', 'text': 'A dummy UnixCommand.'}¶
-
Bases:
evennia.contrib.building_menu.BuildingMenuCreate the sub-menu to edit the specified object.
- Parameters
obj (Object) – the object to edit.
Note
This method is probably to be overridden in your subclasses. Use add_choice and its variants to create menu choices.
-
class
evennia.contrib.tests.TestBuildingMenu(methodName='runTest')[source]¶ Bases:
evennia.commands.default.tests.CommandTestTest to add sub-menus.
-
class
evennia.contrib.tests.TestColorMarkup(methodName='runTest')[source]¶ Bases:
evennia.utils.test_resources.EvenniaTestNote: Normally this would be tested by importing the ansi parser and run the mappings through it. This is not possible since the ansi module creates its mapping at the module/class level; since the ansi module is used by so many other modules it appears that trying to overload settings to test it causes issues with unrelated tests.
-
class
evennia.contrib.tests.TestExtendedRoom(methodName='runTest')[source]¶ Bases:
evennia.commands.default.tests.CommandTest-
DETAIL_DESC= 'A test detail.'¶
-
OLD_DESC= 'Old description.'¶
-
SPRING_DESC= 'A spring description.'¶
-
room_typeclass¶
-
-
class
evennia.contrib.tests.TestRPSystem(methodName='runTest')[source]¶ Bases:
evennia.utils.test_resources.EvenniaTest-
maxDiff= None¶
-
-
class
evennia.contrib.tests.TestTutorialWorldObjects(methodName='runTest')[source]¶ Bases:
twisted.trial._asynctest.TestCase,evennia.commands.default.tests.CommandTest
evennia.contrib.traits module¶
Traits
Whitenoise 2014, Ainneve contributors, Griatch 2020
A Trait represents a modifiable property on (usually) a Character. They can be used to represent everything from attributes (str, agi etc) to skills (hunting 10, swords 14 etc) and dynamically changing things like HP, XP etc.
Traits use Evennia Attributes under the hood, making them persistent (they survive a server reload/reboot).
## Adding Traits to a typeclass
To access and manipulate traits on an object, its Typeclass needs to have a TraitHandler assigned it. Usually, the handler is made available as .traits (in the same way as .tags or .attributes).
Here’s an example for adding the TraitHandler to the base Object class:
After a reload you can now try adding some example traits:
## Using traits
A trait is added to the traithandler, after which one can access it as a property on the handler (similarly to how you can do .db.attrname for Attributes in Evennia).
```python # this is an example using the “static” trait, described below >>> obj.traits.add(“hunting”, “Hunting Skill”, trait_type=”static”, base=4) >>> obj.traits.hunting.value 4 >>> obj.traits.hunting.value += 5 >>> obj.traits.hunting.value 9 >>> obj.traits.add(“hp”, “Health”, trait_type=”gauge”, min=0, max=100) >>> obj.traits.hp.value 100 >>> obj.traits.hp -= 200 >>> obj.traits.hp.value 0 >>> obj.traits.hp.reset() >>> obj.traits.hp.value 100 # you can also access property with getitem >>> obj.traits.hp[“value”] 100 # you can store arbitrary data persistently as well >>> obj.traits.hp.effect = “poisoned!” >>> obj.traits.hp.effect “poisoned!”
When adding the trait, you supply the name of the property (hunting) along with a more human-friendly name (“Hunting Skill”). The latter will show if you print the trait etc. The trait_type is important, this specifies which type of trait this is.
## Trait types
All default traits have a read-only .value property that shows the relevant or ‘current’ value of the trait. Exactly what this means depends on the type of trait.
Traits can also be combined to do arithmetic with their .value, if both have a compatible type.
```python >>> trait1 + trait2 54 >>> trait1.value 3 >>> trait1 + 2 >>> trait1.value 5
Two numerical traits can also be compared (bigger-than etc), which is useful in all sorts of rule-resolution.
- if trait1 > trait2:
# do stuff
``` ## Static trait
value = base + mod
The static trait has a base value and an optional mod-ifier. A typical use of a static trait would be a Strength stat or Skill value. That is, something that varies slowly or not at all, and which may be modified in-place.
```python >>> obj.traits.add(“str”, “Strength”, trait_type=”static”, base=10, mod=2) >>> obj.traits.mytrait.value 12 # base + mod >>> obj.traits.mytrait.base += 2 >>> obj.traits.mytrait.mod += 1 >>> obj.traits.mytrait.value 15 >>> obj.traits.mytrait.mod = 0 >>> obj.traits.mytrait.value 12
### Counter
- min/unset base base+mod max/unset
- |--------------|——–|---------X--------X------------|
- current value
= current + mod
A counter describes a value that can move from a base. The current property is the thing usually modified. It starts at the base. One can also add a modifier, which will both be added to the base and to current (forming .value). The min/max of the range are optional, a boundary set to None will remove it.
```python >>> obj.traits.add(“hunting”, “Hunting Skill”, trait_type=”counter”,
base=10, mod=1, min=0, max=100)
>>> obj.traits.hunting.value
11 # current starts at base + mod
>>> obj.traits.hunting.current += 10
>>> obj.traits.hunting.value
21
# reset back to base+mod by deleting current
>>> del obj.traits.hunting.current
>>> obj.traits.hunting.value
11
>>> obj.traits.hunting.max = None # removing upper bound
Counters have some extra properties:
descs is a dict {upper_bound:text_description}. This allows for easily storing a more human-friendly description of the current value in the interval. Here is an example for skill values between 0 and 10:
{0: “unskilled”, 1: “neophyte”, 5: “trained”, 7: “expert”, 9: “master”}
The keys must be supplied from smallest to largest. Any values below the lowest and above the highest description will be considered to be included in the closest description slot. By calling .desc() on the Counter, will you get the text matching the current value value.
```python # (could also have passed descs= to traits.add()) >>> obj.traits.hunting.descs = {
0: “unskilled”, 10: “neophyte”, 50: “trained”, 70: “expert”, 90: “master”}
>>> obj.traits.hunting.value
11
>>> obj.traits.hunting.desc()
"neophyte"
>>> obj.traits.hunting.current += 60
>>> obj.traits.hunting.value
71
>>> obj.traits.hunting.desc()
"expert"
#### .rate
The rate property defaults to 0. If set to a value different from 0, it allows the trait to change value dynamically. This could be used for example for an attribute that was temporarily lowered but will gradually (or abruptly) recover after a certain time. The rate is given as change of the current per-second, and the .value will still be restrained by min/max boundaries, if those are set.
It is also possible to set a “.ratetarget”, for the auto-change to stop at (rather than at the min/max boundaries). This allows the value to return to a previous value.
>>> obj.traits.hunting.value
71
>>> obj.traits.hunting.ratetarget = 71
# debuff hunting for some reason
>>> obj.traits.hunting.current -= 30
>>> obj.traits.hunting.value
41
>>> obj.traits.hunting.rate = 1 # 1/s increase
# Waiting 5s
>>> obj.traits.hunting.value
46
# Waiting 8s
>>> obj.traits.hunting.value
54
# Waiting 100s
>>> obj.traits.hunting.value
71 # we have stopped at the ratetarget
>>> obj.traits.hunting.rate = 0 # disable auto-change
``` Note that if rate is a non-integer, the resulting .value (at least until it reaches the boundary) will likely also come out a float. If you expect an integer, you must run run int() on the result yourself.
#### .percentage()
If both min and max are defined, the .percentage() method of the trait will return the value as a percentage.
```python >>> obj.traits.hunting.percentage() “71.0%”
### Gauge
This emulates a [fuel-] gauge that empties from a base+mod value.
- min/0 max=base+mod
- |-----------------------X---------------------------|
value
= current
The ‘current’ value will start from a full gauge. The .max property is read-only and is set by .base + .mod. So contrary to a Counter, the modifier only applies to the max value of the gauge and not the current value. The minimum bound defaults to 0. This trait is useful for showing resources that can deplete, like health, stamina and the like.
```python >>> obj.traits.add(“hp”, “Health”, trait_type=”gauge”, base=100) >>> obj.traits.hp.value # (or .current) 100 >>> obj.traits.hp.mod = 10 >>> obj.traits.hp.value 110 >>> obj.traits.hp.current -= 30 >>> obj.traits.hp.value 80
Same as Counters, Gauges can also have descs to describe the interval and can also have rate and ratetarget to auto-update the value. The rate is particularly useful for gauges, for everything from poison slowly draining your health, to resting gradually increasing it. You can also use the .percentage() function to show the current value as a percentage.
### Trait
A single value of any type.
This is the ‘base’ Trait, meant to inherit from if you want to make your own trait-types (see below). Its .value can be anything (that can be stored in an Attribute) and if it’s a integer/float you can do arithmetic with it, but otherwise it acts just like a glorified Attribute.
```python >>> obj.traits.add(“mytrait”, “My Trait”, trait_type=”trait”, value=30) >>> obj.traits.mytrait.value 30 >>> obj.traits.mytrait.value = “stringvalue” >>> obj.traits.mytrait.value “stringvalue”
## Expanding with your own Traits
A Trait is a class inhering from evennia.contrib.traits.Trait (or from one of the existing Trait classes).
```python # in a file, say, ‘mygame/world/traits.py’
from evennia.contrib.traits import Trait
class RageTrait(Trait):
trait_type = “rage” default_keys = {
“rage”: 0
}
Above is an example custom-trait-class “rage” that stores a property “rage” on itself, with a default value of 0. This has all the functionality of a Trait - for example, if you do del on the rage property, it will be set back to its default (0). If you wanted to customize what it does, you just add rage property get/setters/deleters on the class.
To add your custom RageTrait to Evennia, add the following to your settings file (assuming your class is in mygame/world/traits.py):
TRAIT_CLASS_PATHS = [“world.traits.RageTrait”]
Reload the server and you should now be able to use your trait:
```python >>> obj.traits.add(“mood”, “A dark mood”, rage=30) >>> obj.traits.mood.rage 30
-
class
evennia.contrib.traits.CounterTrait(trait_data)[source]¶ Bases:
evennia.contrib.traits.TraitCounter Trait.
This includes modifications and min/max limits as well as the notion of a current value. The value can also be reset to the base value.
- min/unset base base+mod max/unset
- |--------------|——–|---------X--------X------------|
- current value
= current + mod
value = current + mod, starts at base + mod
if min or max is None, there is no upper/lower bound (default)
if max is set to “base”, max will be equal ot base+mod
descs are used to optionally describe each value interval. The desc of the current value value can then be retrieved with .desc(). The property is set as {lower_bound_inclusive:desc} and should be given smallest-to-biggest. For example, for a skill rating between 0 and 10:
- {0: “unskilled”,
1: “neophyte”, 5: “traited”, 7: “expert”, 9: “master”}
rate/ratetarget are optional settings to include a rate-of-change of the current value. This is calculated on-demand and allows for describing a value that is gradually growing smaller/bigger. The increase will stop when either reaching a boundary (if set) or ratetarget. Setting the rate to 0 (default) stops any change.
-
property
base¶
-
property
current¶ The current value of the Trait. This does not have .mod added.
-
default_keys= {'base': 0, 'descs': None, 'max': None, 'min': None, 'mod': 0, 'rate': 0, 'ratetarget': None}¶
-
desc()[source]¶ Retrieve descriptions of the current value, if available.
This must be a mapping {upper_bound_inclusive: text}, ordered from small to big. Any value above the highest upper bound will be included as being in the highest bound. rely on Python3.7+ dicts retaining ordering to let this describe the interval.
- Returns
- The description describing the value value.
If not found, returns the empty string.
- Return type
str
-
property
max¶
-
property
min¶
-
property
mod¶
-
percent(formatting='{:3.1f}%')[source]¶ Return the current value as a percentage.
- Parameters
formatting (str, optional) – Should contain a format-tag which will receive the value. If this is set to None, the raw float will be returned.
- Returns
- Depending of if a formatting string
is supplied or not.
- Return type
float or str
-
property
ratetarget¶
-
trait_type= 'counter'¶
-
property
value¶ The value of the Trait (current + mod)
-
class
evennia.contrib.traits.GaugeTrait(trait_data)[source]¶ Bases:
evennia.contrib.traits.CounterTraitGauge Trait.
This emulates a gauge-meter that empties from a base+mod value.
- min/0 max=base+mod
- |-----------------------X---------------------------|
value
= current
min defaults to 0
max value is always base + mad
.max is an alias of .base
value = current and varies from min to max.
- descs is a mapping {upper_bound_inclusive: desc}. These
are checked with .desc() and can be retrieve a text description for a given current value.
For example, this could be used to describe health values between 0 and 100:
- {0: “Dead”
10: “Badly hurt”, 30: “Bleeding”, 50: “Hurting”, 90: “Healthy”}
-
property
base¶
-
property
current¶ The current value of the gauge.
-
default_keys= {'base': 0, 'descs': None, 'min': 0, 'mod': 0, 'rate': 0, 'ratetarget': None}¶
-
property
max¶ The max is always base + mod.
-
property
min¶
-
property
mod¶
-
percent(formatting='{:3.1f}%')[source]¶ Return the current value as a percentage.
- Parameters
formatting (str, optional) – Should contain a format-tag which will receive the value. If this is set to None, the raw float will be returned.
- Returns
- Depending of if a formatting string
is supplied or not.
- Return type
float or str
-
trait_type= 'gauge'¶
-
property
value¶ The value of the trait
-
class
evennia.contrib.traits.MandatoryTraitKey[source]¶ Bases:
objectThis represents a required key that must be supplied when a Trait is initialized. It’s used by Trait classes when defining their required keys.
-
class
evennia.contrib.traits.StaticTrait(trait_data)[source]¶ Bases:
evennia.contrib.traits.TraitStatic Trait. This is a single value with a modifier, with no concept of a ‘current’ value.
value = base + mod
-
default_keys= {'base': 0, 'mod': 0}¶
-
property
mod¶ The trait’s modifier.
-
trait_type= 'static'¶
-
property
value¶ The value of the Trait
-
-
class
evennia.contrib.traits.Trait(trait_data)[source]¶ Bases:
objectRepresents an object or Character trait. This simple base is just storing anything in it’s ‘value’ property, so it’s pretty much just a different wrapper to an Attribute. It does no type-checking of what is stored.
Note
See module docstring for configuration details.
value
-
__init__(trait_data)[source]¶ This both initializes and validates the Trait on creation. It must raise exception if validation fails. The TraitHandler will call this when the trait is furst added, to make sure it validates before storing.
- Parameters
trait_data (any) – Any pickle-able values to store with this trait. This must contain any cls.default_keys that do not have a default value in cls.data_default_values. Any extra kwargs will be made available as extra properties on the Trait, assuming the class variable allow_extra_properties is set.
- Raises
TraitException – If input-validation failed.
-
allow_extra_properties= True¶
-
default_keys= {'value': None}¶
-
property
key¶ Display name for the trait.
-
property
name¶ Display name for the trait.
-
trait_type= 'trait'¶
-
static
validate_input(cls, trait_data)[source]¶ Validate input
- Parameters
trait_data (dict or _SaverDict) – Data to be used for initialization of this trait.
- Returns
- Validated data, possibly complemented with default
values from default_keys.
- Return type
dict
- Raises
TraitException – If finding unset keys without a default.
-
property
value¶ Store a value
-
-
exception
evennia.contrib.traits.TraitException(msg)[source]¶ Bases:
RuntimeErrorBase exception class raised by Trait objects.
- Parameters
msg (str) – informative error message
-
class
evennia.contrib.traits.TraitHandler(obj, db_attribute_key='traits', db_attribute_category='traits')[source]¶ Bases:
objectFactory class that instantiates Trait objects.
-
__init__(obj, db_attribute_key='traits', db_attribute_category='traits')[source]¶ Initialize the handler and set up its internal Attribute-based storage.
- Parameters
obj (Object) – Parent Object typeclass for this TraitHandler
db_attribute_key (str) – Name of the DB attribute for trait data storage
-
_get_trait_class(trait_type=None, trait_key=None)[source]¶ Helper to retrieve Trait class based on type (like “static”) or trait-key (like “hp”).
-
add(trait_key, name=None, trait_type='static', force=True, **trait_properties)[source]¶ Create a new Trait and add it to the handler.
- Parameters
trait_key (str) – This is the name of the property that will be made available on this handler (example ‘hp’).
name (str, optional) – Name of the Trait, like “Health”. If not given, will use trait_key starting with a capital letter.
trait_type (str, optional) – One of ‘static’, ‘counter’ or ‘gauge’.
force_add (bool) – If set, create a new Trait even if a Trait with the same trait_key already exists.
trait_properties (dict) – These will all be use to initialize the new trait. See the properties class variable on each Trait class to see which are required.
- Raises
TraitException – If specifying invalid values for the given Trait, the trait_type is not recognized, or an existing trait already exists (and force is unset).
-
property
all¶ Get all trait keys in this handler.
- Returns
All Trait keys.
- Return type
list
-
-
class
evennia.contrib.traits.UpdatingTrait(trait_data)[source]¶ Bases:
evennia.contrib.traits.CounterTraitThis is a trait that
-
evennia.contrib.traits._DA()¶ Implement delattr(self, name).
-
evennia.contrib.traits._GA()¶ Return getattr(self, name).
-
evennia.contrib.traits._SA()¶ Implement setattr(self, name, value).
evennia.contrib.tree_select module¶
Easy menu selection tree
Contrib - Tim Ashley Jenkins 2017
This module allows you to create and initialize an entire branching EvMenu instance with nothing but a multi-line string passed to one function.
EvMenu is incredibly powerful and flexible, but using it for simple menus can often be fairly cumbersome - a simple menu that can branch into five categories would require six nodes, each with options represented as a list of dictionaries.
This module provides a function, init_tree_selection, which acts as a frontend for EvMenu, dynamically sourcing the options from a multi-line string you provide. For example, if you define a string as such:
TEST_MENU = ‘’’Foo Bar Baz Qux’’’
And then use TEST_MENU as the ‘treestr’ source when you call init_tree_selection on a player:
init_tree_selection(TEST_MENU, caller, callback)
The player will be presented with an EvMenu, like so:
Foo Bar Baz Qux
Making a selection will pass the selection’s key to the specified callback as a string along with the caller, as well as the index of the selection (the line number on the source string) along with the source string for the tree itself.
In addition to specifying selections on the menu, you can also specify categories. Categories are indicated by putting options below it preceded with a ‘-‘ character. If a selection is a category, then choosing it will bring up a new menu node, prompting the player to select between those options, or to go back to the previous menu. In addition, categories are marked by default with a ‘[+]’ at the end of their key. Both this marker and the option to go back can be disabled.
Categories can be nested in other categories as well - just go another ‘-‘ deeper. You can do this as many times as you like. There’s no hard limit to the number of categories you can go down.
For example, let’s add some more options to our menu, turning ‘Bar’ into a category.
TEST_MENU = ‘’’Foo Bar -You’ve got to know –When to hold em –When to fold em –When to walk away Baz Qux’’’
Now when we call the menu, we can see that ‘Bar’ has become a category instead of a selectable option.
Foo Bar [+] Baz Qux
Note the [+] next to ‘Bar’. If we select ‘Bar’, it’ll show us the option listed under it.
You’ve got to know [+] << Go Back: Return to the previous menu.
Just the one option, which is a category itself, and the option to go back, which will take us back to the previous menu. Let’s select ‘You’ve got to know’.
When to hold em When to fold em When to walk away << Go Back: Return to the previous menu.
Now we see the three options listed under it, too. We can select one of them or use ‘Go Back’ to return to the ‘Bar’ menu we were just at before. It’s very simple to make a branching tree of selections!
One last thing - you can set the descriptions for the various options simply by adding a ‘:’ character followed by the description to the option’s line. For example, let’s add a description to ‘Baz’ in our menu:
TEST_MENU = ‘’’Foo Bar -You’ve got to know –When to hold em –When to fold em –When to walk away Baz: Look at this one: the best option. Qux’’’
Now we see that the Baz option has a description attached that’s separate from its key:
Foo Bar [+] Baz: Look at this one: the best option. Qux
Once the player makes a selection - let’s say, ‘Foo’ - the menu will terminate and call your specified callback with the selection, like so:
callback(caller, TEST_MENU, 0, “Foo”)
The index of the selection is given along with a string containing the selection’s key. That way, if you have two selections in the menu with the same key, you can still differentiate between them.
And that’s all there is to it! For simple branching-tree selections, using this system is much easier than manually creating EvMenu nodes. It also makes generating menus with dynamic options much easier - since the source of the menu tree is just a string, you could easily generate that string procedurally before passing it to the init_tree_selection function. For example, if a player casts a spell or does an attack without specifying a target, instead of giving them an error, you could present them with a list of valid targets to select by generating a multi-line string of targets and passing it to init_tree_selection, with the callable performing the maneuver once a selection is made.
This selection system only works for simple branching trees - doing anything really complicated like jumping between categories or prompting for arbitrary input would still require a full EvMenu implementation. For simple selections, however, I’m sure you will find using this function to be much easier!
Included in this module is a sample menu and function which will let a player change the color of their name - feel free to mess with it to get a feel for how this system works by importing this module in your game’s default_cmdsets.py module and adding CmdNameColor to your default character’s command set.
-
class
evennia.contrib.tree_select.CmdNameColor(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandSet or remove a special color on your name. Just an example for the easy menu selection tree contrib.
-
_keyaliases= ('namecolor',)¶
-
_matchset= {'namecolor'}¶
-
aliases= []¶
-
func()[source]¶ This is the actual executing part of the command. It is called directly after self.parse(). See the docstring of this module for which object properties are available (beyond those set in self.parse())
-
help_category= 'general'¶
-
key= 'namecolor'¶
-
lock_storage= 'cmd:all();'¶
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'namecolor', 'tags': '', 'text': '\n Set or remove a special color on your name. Just an example for the\n easy menu selection tree contrib.\n '}¶
-
-
evennia.contrib.tree_select.change_name_color(caller, treestr, index, selection)[source]¶ Changes a player’s name color.
- Parameters
caller (obj) – Character whose name to color.
treestr (str) – String for the color change menu - unused
index (int) – Index of menu selection - unused
selection (str) – Selection made from the name color menu - used to determine the color the player chose.
-
evennia.contrib.tree_select.dashcount(entry)[source]¶ Counts the number of dashes at the beginning of a string. This is needed to determine the depth of options in categories.
- Parameters
entry (str) – String to count the dashes at the start of
- Returns
Number of dashes at the start
- Return type
dashes (int)
-
evennia.contrib.tree_select.go_up_one_category(treestr, index)[source]¶ Given a menu tree string and an index, returns the category that the given option belongs to. Used for the ‘go back’ option.
- Parameters
treestr (str) – Multi-line string representing menu options
index (int) – Index to determine the parent category of
- Returns
Index of parent category
- Return type
parent_category (int)
-
evennia.contrib.tree_select.index_to_selection(treestr, index, desc=False)[source]¶ Given a menu tree string and an index, returns the corresponding selection’s name as a string. If ‘desc’ is set to True, will return the selection’s description as a string instead.
- Parameters
treestr (str) – Multi-line string representing menu options
index (int) – Index to convert to selection key or description
- Options:
desc (bool): If true, returns description instead of key
- Returns
Selection key or description if ‘desc’ is set
- Return type
selection (str)
-
evennia.contrib.tree_select.init_tree_selection(treestr, caller, callback, index=None, mark_category=True, go_back=True, cmd_on_exit='look', start_text='Make your selection:')[source]¶ Prompts a player to select an option from a menu tree given as a multi-line string.
- Parameters
treestr (str) – Multi-lne string representing menu options
caller (obj) – Player to initialize the menu for
callback (callable) – Function to run when a selection is made. Must take 4 args: caller (obj): Caller given above treestr (str): Menu tree string given above index (int): Index of final selection selection (str): Key of final selection
- Options:
index (int or None): Index to start the menu at, or None for top level mark_category (bool): If True, marks categories with a [+] symbol in the menu go_back (bool): If True, present an option to go back to previous categories start_text (str): Text to display at the top level of the menu cmd_on_exit(str): Command to enter when the menu exits - ‘look’ by default
Notes
This function will initialize an instance of EvMenu with options generated dynamically from the source string, and passes the menu user’s selection to a function of your choosing. The EvMenu is made of a single, repeating node, which will call itself over and over at different levels of the menu tree as categories are selected.
Once a non-category selection is made, the user’s selection will be passed to the given callable, both as a string and as an index number. The index is given to ensure every selection has a unique identifier, so that selections with the same key in different categories can be distinguished between.
The menus called by this function are not persistent and cannot perform complicated tasks like prompt for arbitrary input or jump multiple category levels at once - you’ll have to use EvMenu itself if you want to take full advantage of its features.
-
evennia.contrib.tree_select.is_category(treestr, index)[source]¶ Determines whether an option in a tree string is a category by whether or not there are additional options below it.
- Parameters
treestr (str) – Multi-line string representing menu options
index (int) – Which line of the string to test
- Returns
Whether the option is a category
- Return type
is_category (bool)
This is the repeating menu node that handles the tree selection.
Takes a list of options processed by parse_opts and turns it into a list/dictionary of menu options for use in menunode_treeselect.
- Parameters
treestr (str) – Multi-line string representing menu options
optlist (list) – List of options to convert to EvMenu’s option format
index (int) – Index of current category
mark_category (bool) – Whether or not to mark categories with [+]
go_back (bool) – Whether or not to add an option to go back in the menu
- Returns
- List of menu options formatted for use
in EvMenu, each passing a different “newindex” kwarg that changes the menu level or makes a selection
- Return type
menuoptions (list of dicts)
-
evennia.contrib.tree_select.parse_opts(treestr, category_index=None)[source]¶ Parses a tree string and given index into a list of options. If category_index is none, returns all the options at the top level of the menu. If category_index corresponds to a category, returns a list of options under that category. If category_index corresponds to an option that is not a category, it’s a selection and returns True.
- Parameters
treestr (str) – Multi-line string representing menu options
category_index (int) – Index of category or None for top level
- Returns
- Either a list of options in the selected
category or True if a selection was made
- Return type
kept_opts (list or True)
evennia.contrib.unixcommand module¶
Unix-like Command style parent
Evennia contribution, Vincent Le Geoff 2017
This module contains a command class that allows for unix-style command syntax in-game, using –options, positional arguments and stuff like -n 10 etc similarly to a unix command. It might not the best syntax for the average player but can be really useful for builders when they need to have a single command do many things with many options. It uses the ArgumentParser from Python’s standard library under the hood.
To use, inherit UnixCommand from this module from your own commands. You need to override two methods:
- The init_parser method, which adds options to the parser. Note that you should normally
not override the normal parse method when inheriting from UnixCommand.
The func method, called to execute the command once parsed (like any Command).
Here’s a short example:
```python class CmdPlant(UnixCommand):
‘’’ Plant a tree or plant.
This command is used to plant something in the room you are in.
- Examples:
plant orange -a 8 plant strawberry –hidden plant potato –hidden –age 5
‘’’
key = “plant”
- def init_parser(self):
“Add the arguments to the parser.” # ‘self.parser’ inherits argparse.ArgumentParser self.parser.add_argument(“key”,
help=”the key of the plant to be planted here”)
- self.parser.add_argument(“-a”, “–age”, type=int,
default=1, help=”the age of the plant to be planted”)
- self.parser.add_argument(“–hidden”, action=”store_true”,
help=”should the newly-planted plant be hidden to players?”)
- def func(self):
“func is called only if the parser succeeded.” # ‘self.opts’ contains the parsed options key = self.opts.key age = self.opts.age hidden = self.opts.hidden self.msg(“Going to plant ‘{}’, age={}, hidden={}.”.format(
key, age, hidden))
To see the full power of argparse and the types of supported options, visit [the documentation of argparse](https://docs.python.org/2/library/argparse.html).
-
class
evennia.contrib.unixcommand.HelpAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]¶ Bases:
argparse.ActionOverride the -h/–help action in the default parser.
Using the default -h/–help will call the exit function in different ways, preventing the entire help message to be provided. Hence this override.
-
exception
evennia.contrib.unixcommand.ParseError[source]¶ Bases:
ExceptionAn error occurred during parsing.
-
class
evennia.contrib.unixcommand.UnixCommand(**kwargs)[source]¶ Bases:
evennia.commands.command.CommandUnix-type commands, supporting short and long options.
This command syntax uses the Unix-style commands with short options (-X) and long options (–something). The argparse module is used to parse the command.
In order to use it, you should override two methods: - init_parser: this method is called when the command is created.
It can be used to set options in the parser. self.parser contains the argparse.ArgumentParser, so you can add arguments here.
func: this method is called to execute the command, but after the parser has checked the arguments given to it are valid. You can access the namespace of valid arguments in self.opts at this point.
The help of UnixCommands is derived from the docstring, in a slightly different way than usual: the first line of the docstring is used to represent the program description (the very short line at the top of the help message). The other lines below are used as the program’s “epilog”, displayed below the options. It means in your docstring, you don’t have to write the options. They will be automatically provided by the parser and displayed accordingly. The argparse module provides a default ‘-h’ or ‘–help’ option on the command. Typing |whelp commandname|n will display the same as |wcommandname -h|n, though this behavior can be changed.
-
__init__(**kwargs)[source]¶ The lockhandler works the same as for objects. optional kwargs will be set as properties on the Command at runtime, overloading evential same-named class properties.
-
_keyaliases= ('command',)¶
-
_matchset= {'command'}¶
-
aliases= []¶
-
get_help(caller, cmdset)[source]¶ Return the help message for this command and this caller.
- Parameters
caller (Object or Player) – the caller asking for help on the command.
cmdset (CmdSet) – the command set (if you need additional commands).
- Returns
the help text to provide the caller for this command.
- Return type
docstring (str)
-
help_category= 'general'¶
-
init_parser()[source]¶ Configure the argument parser, adding in options.
Note
This method is to be overridden in order to add options to the argument parser. Use self.parser, which contains the argparse.ArgumentParser. You can, for instance, use its add_argument method.
-
key= 'command'¶
-
lock_storage= 'cmd:all();'¶
-
parse()[source]¶ Process arguments provided in self.args.
Note
You should not override this method. Consider overriding init_parser instead.
-
search_index_entry= {'aliases': '', 'category': 'general', 'key': 'command', 'tags': '', 'text': '\n Unix-type commands, supporting short and long options.\n\n This command syntax uses the Unix-style commands with short options\n (-X) and long options (--something). The `argparse` module is\n used to parse the command.\n\n In order to use it, you should override two methods:\n - `init_parser`: this method is called when the command is created.\n It can be used to set options in the parser. `self.parser`\n contains the `argparse.ArgumentParser`, so you can add arguments\n here.\n - `func`: this method is called to execute the command, but after\n the parser has checked the arguments given to it are valid.\n You can access the namespace of valid arguments in `self.opts`\n at this point.\n\n The help of UnixCommands is derived from the docstring, in a\n slightly different way than usual: the first line of the docstring\n is used to represent the program description (the very short\n line at the top of the help message). The other lines below are\n used as the program\'s "epilog", displayed below the options. It\n means in your docstring, you don\'t have to write the options.\n They will be automatically provided by the parser and displayed\n accordingly. The `argparse` module provides a default \'-h\' or\n \'--help\' option on the command. Typing |whelp commandname|n will\n display the same as |wcommandname -h|n, though this behavior can\n be changed.\n\n '}¶
-
class
evennia.contrib.unixcommand.UnixCommandParser(prog, description='', epilog='', command=None, **kwargs)[source]¶ Bases:
argparse.ArgumentParserA modifier command parser for unix commands.
This parser is used to replace argparse.ArgumentParser. It is aware of the command calling it, and can more easily report to the caller. Some features (like the “brutal exit” of the original parser) are disabled or replaced. This parser is used by UnixCommand and creating one directly isn’t recommended nor necessary. Even adding a sub-command will use this replaced parser automatically.
-
__init__(prog, description='', epilog='', command=None, **kwargs)[source]¶ Build a UnixCommandParser with a link to the command using it.
- Parameters
prog (str) – the program name (usually the command key).
description (str) – a very brief line to show in the usage text.
epilog (str) – the epilog to show below options.
command (Command) – the command calling the parser.
- Kwargs:
Additional keyword arguments are directly sent to argparse.ArgumentParser. You will find them on the [parser’s documentation](https://docs.python.org/2/library/argparse.html).
Note
It’s doubtful you would need to create this parser manually. The UnixCommand does that automatically. If you create sub-commands, this class will be used.
-
format_help()[source]¶ Return the parser help, including its epilog.
Note
This method is present to return the raw-escaped help, in order to avoid unintentional color codes. Color codes in the epilog (the command docstring) are supported.
-
format_usage()[source]¶ Return the usage line.
Note
This method is present to return the raw-escaped usage line, in order to avoid unintentional color codes.
-
evennia.contrib.wilderness module¶
Wilderness system
Evennia contrib - titeuf87 2017
This contrib provides a wilderness map. This is an area that can be huge where the rooms are mostly similar, except for some small cosmetic changes like the room name.
Usage:
This contrib does not provide any commands. Instead the @py command can be used.
A wilderness map needs to created first. There can be different maps, all with their own name. If no name is provided, then a default one is used. Internally, the wilderness is stored as a Script with the name you specify. If you don’t specify the name, a script named “default” will be created and used.
@py from evennia.contrib import wilderness; wilderness.create_wilderness()
Once created, it is possible to move into that wilderness map:
@py from evennia.contrib import wilderness; wilderness.enter_wilderness(me)
All coordinates used by the wilderness map are in the format of (x, y) tuples. x goes from left to right and y goes from bottom to top. So (0, 0) is the bottom left corner of the map.
Customisation:
The defaults, while useable, are meant to be customised. When creating a new wilderness map it is possible to give a “map provider”: this is a python object that is smart enough to create the map.
The default provider, WildernessMapProvider, just creates a grid area that is unlimited in size. This WildernessMapProvider can be subclassed to create more interesting maps and also to customize the room/exit typeclass used.
There is also no command that allows players to enter the wilderness. This still needs to be added: it can be a command or an exit, depending on your needs.
Customisation example:
To give an example of how to customize, we will create a very simple (and small) wilderness map that is shaped like a pyramid. The map will be provided as a string: a “.” symbol is a location we can walk on.
Let’s create a file world/pyramid.py:
.
…
“””
from evennia.contrib import wilderness
class PyramidMapProvider(wilderness.WildernessMapProvider):
- def is_valid_coordinates(self, wilderness, coordinates):
“Validates if these coordinates are inside the map” x, y = coordinates try:
lines = map_str.split(“
- “)
# The reverse is needed because otherwise the pyramid will be # upside down lines.reverse() line = lines[y] column = line[x] return column == “.”
- except IndexError:
return False
- def get_location_name(self, coordinates):
“Set the location name” x, y = coordinates if y == 3:
return “Atop the pyramid.”
- else:
return “Inside a pyramid.”
- def at_prepare_room(self, coordinates, caller, room):
“Any other changes done to the room before showing it” x, y = coordinates desc = “This is a room in the pyramid.” if y == 3 :
desc = “You can see far and wide from the top of the pyramid.”
room.db.desc = desc
Now we can use our new pyramid-shaped wilderness map. From inside Evennia we create a new wilderness (with the name “default”) but using our new map provider:
``` @py from world import pyramid as p; p.wilderness.create_wilderness(mapprovider=p.PyramidMapProvider())
@py from evennia.contrib import wilderness; wilderness.enter_wilderness(me, coordinates=(4, 1))
Implementation details:
When a character moves into the wilderness, they get their own room. If they move, instead of moving the character, the room changes to match the new coordinates. If a character meets another character in the wilderness, then their room merges. When one of the character leaves again, they each get their own separate rooms. Rooms are created as needed. Unneeded rooms are stored away to avoid the overhead cost of creating new rooms again in the future.
-
class
evennia.contrib.wilderness.WildernessExit(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultExitThis is an Exit object used inside a WildernessRoom. Instead of changing the location of an Object traversing through it (like a traditional exit would do) it changes the coordinates of that traversing Object inside the wilderness map.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for WildernessExit>¶
-
at_traverse(traversing_object, target_location)[source]¶ This implements the actual traversal. The traverse lock has already been checked (in the Exit command) at this point.
- Parameters
traversing_object (Object) – Object traversing us.
target_location (Object) – Where target is going.
- Returns
True if the traverse is allowed to happen
- Return type
bool
-
at_traverse_coordinates(traversing_object, current_coordinates, new_coordinates)[source]¶ Called when an object wants to travel from one place inside the wilderness to another place inside the wilderness.
If this returns True, then the traversing can happen. Otherwise it will be blocked.
This method is similar how the at_traverse works on normal exits.
- Parameters
traversing_object (Object) – The object doing the travelling.
current_coordinates (tuple) – (x, y) coordinates where traversing_object currently is.
new_coordinates (tuple) – (x, y) coordinates of where traversing_object wants to travel to.
- Returns
True if traversing_object is allowed to traverse
- Return type
bool
-
property
mapprovider¶ Shortcut property to the map provider.
- Returns
- the mapprovider object used with this
wilderness map.
- Return type
MapProvider object
-
path= 'evennia.contrib.wilderness.WildernessExit'¶
-
typename= 'WildernessExit'¶
-
property
wilderness¶ Shortcut property to the wilderness script.
- Returns
the WildernessScript attached to this exit’s room
- Return type
-
exception
-
class
evennia.contrib.wilderness.WildernessMapProvider[source]¶ Bases:
objectDefault Wilderness Map provider.
This is a simple provider that just creates an infinite large grid area.
-
at_prepare_room(coordinates, caller, room)[source]¶ Called when a room gets activated for certain coordinates. This happens after every object is moved in it. This can be used to set a custom room desc for instance or run other customisations on the room.
- Parameters
coordinates (tuple) – the coordinates as (x, y) where room is located at
caller (Object) – the object that moved into this room
room (WildernessRoom) – the room object that will be used at that wilderness location
Example
An example use of this would to plug in a randomizer to show different descriptions for different coordinates, or place a treasure at a special coordinate.
-
exit_typeclass¶ alias of
WildernessExit
-
get_location_name(coordinates)[source]¶ Returns a name for the position at coordinates.
- Parameters
coordinates (tuple) – the coordinates as (x, y) tuple.
- Returns
name (str)
-
is_valid_coordinates(wilderness, coordinates)[source]¶ Returns True if coordinates is valid and can be walked to.
- Parameters
wilderness – the wilderness script
coordinates (tuple) – the coordinates to check as (x, y) tuple.
- Returns
True if the coordinates are valid
- Return type
bool
-
room_typeclass¶ alias of
WildernessRoom
-
-
class
evennia.contrib.wilderness.WildernessRoom(*args, **kwargs)[source]¶ Bases:
evennia.objects.objects.DefaultRoomThis is a single room inside the wilderness. This room provides a “view” into the wilderness map. When an account moves around, instead of going to another room as with traditional rooms, they stay in the same room but the room itself changes to display another area of the wilderness.
-
exception
DoesNotExist¶ Bases:
evennia.objects.objects.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.objects.objects.MultipleObjectsReturned
-
_meta= <Options for WildernessRoom>¶
-
at_object_leave(moved_obj, target_location)[source]¶ Called just before an object leaves from inside this object. This is a default Evennia hook.
- Parameters
moved_obj (Object) – The object leaving
target_location (Object) – Where moved_obj is going.
-
at_object_receive(moved_obj, source_location)[source]¶ Called after an object has been moved into this object. This is a default Evennia hook.
- Parameters
moved_obj (Object) – The object moved into this one.
source_location (Object) – Where moved_obj came from.
-
property
coordinates¶ Returns the coordinates of this room into the wilderness.
- Returns
- (x, y) coordinates of where this room is inside the
wilderness.
- Return type
tuple
-
get_display_name(looker, **kwargs)[source]¶ Displays the name of the object in a viewer-aware manner.
- Parameters
looker (TypedObject) – The object or account that is looking at/getting inforamtion for this object.
- Returns
- A string containing the name of the object,
including the DBREF if this user is privileged to control said object and also its coordinates into the wilderness map.
- Return type
name (str)
Notes
This function could be extended to change how object names appear to users in character, but be wary. This function does not change an object’s keys or aliases when searching, and is expected to produce something useful for builders.
-
property
location_name¶ Returns the name of the wilderness at this room’s coordinates.
- Returns
name (str)
-
path= 'evennia.contrib.wilderness.WildernessRoom'¶
-
set_active_coordinates(new_coordinates, obj)[source]¶ Changes this room to show the wilderness map from other coordinates.
- Parameters
new_coordinates (tuple) – coordinates as tuple of (x, y)
obj (Object) – the object that moved into this room and caused the coordinates to change
-
typename= 'WildernessRoom'¶
-
property
wilderness¶ Shortcut property to the wilderness script this room belongs to.
- Returns
the WildernessScript attached to this room
- Return type
-
exception
-
class
evennia.contrib.wilderness.WildernessScript(*args, **kwargs)[source]¶ Bases:
evennia.scripts.scripts.DefaultScriptThis is the main “handler” for the wilderness system: inside here the coordinates of every item currently inside the wilderness is stored. This script is responsible for creating rooms as needed and storing rooms away into storage when they are not needed anymore.
-
exception
DoesNotExist¶ Bases:
evennia.scripts.scripts.DoesNotExist
-
exception
MultipleObjectsReturned¶ Bases:
evennia.scripts.scripts.MultipleObjectsReturned
-
_create_room(coordinates, report_to)[source]¶ Gets a new WildernessRoom to be used for the provided coordinates.
It first tries to retrieve a room out of storage. If there are no rooms left a new one will be created.
- Parameters
coordinates (tuple) – coordinate tuple of (x, y)
report_to (object) – the obj to return error messages to
-
_destroy_room(room)[source]¶ Moves a room back to storage. If room is not a WildernessRoom or there is a player inside the room, then this does nothing.
- Parameters
room (WildernessRoom) – the room to put in storage
-
_meta= <Options for WildernessScript>¶
-
at_after_object_leave(obj)[source]¶ Called after an object left this wilderness map. Used for cleaning up.
- Parameters
obj (object) – the object that left
-
at_script_creation()[source]¶ Only called once, when the script is created. This is a default Evennia hook.
-
get_obj_coordinates(obj)[source]¶ Returns the coordinates of obj in the wilderness.
Returns (x, y)
- Parameters
obj (object) – an object inside the wilderness
- Returns
(x, y) tuple of where obj is located
- Return type
tuple
-
get_objs_at_coordinates(coordinates)[source]¶ Returns a list of every object at certain coordinates.
Imeplementation detail: this uses a naive iteration through every object inside the wilderness which could cause slow downs when there are a lot of objects in the map.
- Parameters
coordinates (tuple) – a coordinate tuple like (x, y)
- Returns
list of Objects at coordinates
- Return type
[Object, ]
-
is_valid_coordinates(coordinates)[source]¶ Returns True if coordinates are valid (and can be travelled to). Otherwise returns False
- Parameters
coordinates (tuple) – coordinates as (x, y) tuple
- Returns
True if the coordinates are valid
- Return type
bool
-
property
itemcoordinates¶ Returns a dictionary with the coordinates of every item inside this wilderness map. The key is the item, the value are the coordinates as (x, y) tuple.
- Returns
coordinates}
- Return type
{item
-
property
mapprovider¶ Shortcut property to the map provider.
- Returns
the mapprovider used with this wilderness
- Return type
MapProvider
-
move_obj(obj, new_coordinates)[source]¶ Moves obj to new coordinates in this wilderness.
- Parameters
obj (object) – the object to move
new_coordinates (tuple) – tuple of (x, y) where to move obj to.
-
path= 'evennia.contrib.wilderness.WildernessScript'¶
-
typename= 'WildernessScript'¶
-
exception
-
evennia.contrib.wilderness.create_wilderness(name='default', mapprovider=None)[source]¶ Creates a new wilderness map. Does nothing if a wilderness map already exists with the same name.
- Parameters
name (str, optional) – the name to use for that wilderness map
mapprovider (WildernessMap instance, optional) – an instance of a WildernessMap class (or subclass) that will be used to provide the layout of this wilderness map. If none is provided, the default infinite grid map will be used.
-
evennia.contrib.wilderness.enter_wilderness(obj, coordinates=(0, 0), name='default')[source]¶ Moves obj into the wilderness. The wilderness needs to exist first and the provided coordinates needs to be valid inside that wilderness.
- Parameters
obj (object) – the object to move into the wilderness
coordinates (tuple), optional) – the coordinates to move obj to into the wilderness. If not provided, defaults (0, 0)
name (str, optional) – name of the wilderness map, if not using the default one
- Returns
True if obj successfully moved into the wilderness.
- Return type
bool