(Note: It would be nice if there were more code examples on this page. For instance bla.WriteKey(”buildinghp”, 100, 1) does not insert the key value “buildinghp 100” into bla. It would be nice to know what is wrong here since this wiki suggests that’s how it’s to be done. More code examples would clear up any confusion and allow new developers to more quickly pick up cf-python.)
Python plugin is a server plugin able to run Python scripts that manipulate Crossfire items, monsters, players, maps, ...
The latest version, 2.0, is a major rewrite which introduces Python objects to represent maps, Crossfire objects and players. The hooking system also changed.
Note that this guide doesn’t intend to teach you Python. Documentation for that is available on Python's official web site.
Also, advanced functions can require some knowledge of Crossfire’s inner workings. Developers seeking help should check Crossfire's page on development or Crossfire's resource page (which includes links to lists, IRC, how to contact people, ...). Another option is to check existing Python scripts, available in the maps source tree.
Old plugin’s reference can be found on plugin_python, for historical purposes.
Important note: the API, and other parts, are valid for code’s trunk. branch contains hopefully all the changes too, but there may be differences. Also, links to SVN are to trunk.
The plugin has access to all built-in functions of Python, and its regular libraries. Python version being used depends on the platform the server was built, but should be 2.3 or higher.
{is that always true?}
Using a library not part of Python’s default distribution is discouraged as this introduces new dependencies.
Scripts execute in their own context, and their state information is not kept between runs. There are functions to persist data, or share between scripts. Note that data persisted through those functions will not survive a server restart.
Scripts should import the Crossfire module to access Crossfire’s built-in functions.
Calling Crossfire functions with invalid arguments will result in a Python exception being raised. A function failure will also result in an exception.
Scripts will have the same access rights as the server itself. It may be able to write to some directories, but not others.
Data that should survive a server restart should be persisted in the PlayerDirectory (for specific player information) or DataDirectory (for regular information), where the server normally has write access.
Scripts for server releases after 9 November 2007 should prefer the use of new Crossfire.Log(level,message) method over the python build-in print method. The reason of this is to keep coherency between python scripts messages and server logging.
Python plugin is a server plugin, thus you need to insert in this object one of the event_xxx archetype (see /arch/system directory). The fields to fill are:
A script can then use WhoAmI(), WhoIsActivator(), WhoIsOther(), WhatIsMessage() functions of the Crossfire module to find the executing context.
Create a script, and put it in the /python/events/xxx subdirectory or the maps directory, where xxx is the event’s name in lowercase (create the directory if it doesn’t exist). Available events are listed on the server_plugin page. In addition, there is a special event, init, which is called just after the plugin has been loaded. It behaves like other events in every aspect, but is called only once when the plugin finished loading.
Check Crossfire.RegisterCommand.
The return value of the script can be manipulated through the GetReturnValue and SetReturnValue functions. Signification of this value depends on the event being handled.
Those Python scripts reside in the python subdirectory of the maps tree. They provide additional functionality, and may be considered as always present.
{describe existing ones}
Script location: /python/CFDialog.py
This script provides two utility classes a map maker can use to easily create complex dialogs. Go here for a complete explanation on how it works.
Script location: /python/misc/death_message.py
This script makes the monster/living thing containing it display a message when it dies. It should be hooked through an event_death archetype in monster’s inventory.
Message is specified in event object’s options field. It can contain %m and %k, which will be replaced by respectively dead item’s name and killer’s name (if no killer, replaced by an empty string).
Script location: /python/misc/greet_message.py
This script makes the monster/living thing containing it display a message when it attacks for the first time an enemy. It should be hooked through an event_time archetype in monster’s inventory.
Message is specified in event object’s options field. It can contain %m and %e, which will be replaced by respectively monster’s name and enemy’s name.
Script location: /python/items/experience_rewarder.py
This script will give experience to the “activating” player. It should be linked through the “trigger” event of an altar, or similar thing.
Options are specified in the event object’s fields.
A key/value will be used to store in the player if she activated the item already.
Available options are:
Scripts location: /python/tod/*.py
Those scripts add behaviour to items based on time of the day. Want to open doors at specific time, make werewolfes, deactivate a magic_mouth during the Season of Winter? Those scripts are ready to use. See time of day based python scripts
To use the crossfire module, add to your python script:
import Crossfire
The following functions and objects are available to all scripts using the Crossfire module through import Crossfire.
Convention: in the reference, xxx() specifies a method, xxx specifies a property.
Constants are available to wrap values used in Crossfire code like object types, movements, ... They are available through Crossfire.xxx.VALUE, where xxx is the constant type and VALUE the value as in the C source code, in uppercase, without specific prefix (ie F_TRUE becomes TRUE, AT_FIRE becomes FIRE, and so on).
For each constant group xxx there exists a xxxName dictionary object containing the name of the value as a string.
The following constant types exist:
AttackType: AT_xxx constants, as defined in include/attack.hAttackTypeNumber: ATNR_xxx constants, as defined in include/attack.hCostFlag: F_xxx constants, as defined in include/define.h (without the F_ prefix)Direction: contains NORTH, NORTHEAST, ..., NORTHWESTEventType: EVENT_xxx constants, as defined in include/plugin.hMessageFlag: NDI_xxx constants, as defined in include/newclient.hMove: movement types, as defined in include/define.hType: object type, as defined in include/define.h
MessageFlag and Move can be combined, using +, to build multiple values.
{
} do a nice table, with link to values?
Example:
whoami.Say("%s => %d"%(Crossfire.DirectionName[Crossfire.Direction.NORTH], Crossfire.Direction.NORTH))
will write
NORTH => 1
Warning: Python doesn’t know about constants, thus scripts can modify those values. Doing this can lead to weird results, and should be avoided at all cost. Note that the C code itself is immune to the changes, only the scripts would suffer.
Returns the Crossfire.Object from which the event being handled was raised, corresponds to the op parameter of the event. Can be None. For a map event, this is a Crossfire.Map
Returns the Crossfire.Object having caused the event being handled, corresponds to the activator parameter of the event. Can be None.
Returns the Crossfire.Object being part of the event, corresponds to the third parameter of the event. Can be None.
Returns the String that was sent as part of the event, corresponds to the message parameter of the event.
Returns the absolute path of the currently executing script.
This String variable contains:
born, gkill, ...)name field of the object
Crossfire.Object representing the event object that links to the plugin. Will be None for global events and custom commands.
Return current return value.
Parameters:
Sets the value the plugin will return to the server when the script exits. Value and effect depend on the event being handled.
Returns an integer representing the Python plugin version.
Returns the system directory containing the maps. Note that it is relative to the Data directory.
Returns the system directory where unique items and maps are stored.
Returns the system directory where temporary files are stored.
Returns the system directory containing configuration files.
Returns the system directory containing read/write files.
Returns the system directory containing player files.
Returns the system directory containing read-only data.
Parameter:
Returns a Crossfire.Player object for specified player, based on partial name matching, or None if not found. If only one player name can match, return this player, else return None.
Returns a Python list containing Crossfire.Archetype objects representing all archetypes the server knows. Should not be called lightly, as this can take some time.
Returns a Python list containing Crossfire.Map objects, one for each map currently being loaded. This includes random and unique maps.
Returns a Python list containing Crossfire.Party objects, one for each existing party on the server.
Returns a Python list containing Crossfire.Region objects, one for each region.
Returns a list of Crossfire.Object representing all items on the friendly list. Individual objects can be added/removed through their Friendly flag.
Returns a list containing Crossfire.Players objects, one for each player on the server
Returns a Python list corresponding to the in-game server time. Fields are (start at 0 to access):
Parameter:
String)
Returns the Crossfire.Map with specified path, or None if such a map isn’t loaded. Will not try to load the map, see Crossfire.ReadyMap for that.
Parameter:
String)
Returns the number of the specified face, 0 if it doesn’t exist. The face name is the name as it appears in the archetypes, ie dcross-red1.111, without the set name or extension.
Parameter:
String)
Returns the number of the specified animation, 0 if it doesn’t exist. The name is has it appears in the archetypes, ie campfire or bat.
Loads specified map, and returns a Crossfire.Map object wrapping it. Will return None if map couldn’t be found.
Parameter:
String, the map path to loadNumber, flags, optional. Combination of the following values:Returns an empty object which can then be manipulated and inserted in a map.
Parameters:
String)
Returns object with specified archetype or object name, or None if no object has the name, and archetype wasn’t found.
Parameters:
Number)Number)
Returns an empty map of specified dimensions. Unless map is removed immediately, Path should be set so the map correctly displays in the maps output.
Parameters:
Use the server logging facilities to output script messages in server console. This is the recommended method, instead of using the python build-in “print” method. Using this, scripts take advantage of Debug and Monster level which can be hidden at will by server admin (log level), and have access to the error level, mentioning to admin serious troubles.
Example:
Crossfire.Log(Crossfire.LogDebug,'Player %s entered guild %s' %obj.Name %guildName)
Parameters:
Registers a server command which will be mapped to specified script. See Registering a command for more information.
The script path is relative to the maps subdirectory. When the command is called, the following methods will provide information:
WhoAmI contains the playerScriptName contains the currently executing script’s nameScriptParameters contains any parameter the player added to the command.
{can NULL be passed?}Parameters:
Number, should be one of the Crossfire.EventType.xxx constants)
This instructs the server to call the Python plugin for all events of specified type. Python will then call scripts in the /python/events/xxx directory, where xx is the event’s name.
This function should not be used except in special circumstances, as Python by default registers all events anyway.
Parameters:
Number, should be one of the Crossfire.EventType.xxx constants)This instructs the server to stop calling the Python plugin for all events of specified type.
This function should not be used, except in special circumstances, as it can disable other scripts that use those events.
Removes a timer created through a call to Crossfire.Object.AddTimer.
Arguments:
Number: timer identifier.Returns:
Returns a Python dictionary the script can use to store data between runs. This data is not shared with other scripts.
Note that data will be lost in case of server restart.
Returns a Python dictionary the script can use to share data with other scripts.
Note that data will be lost in case of server restart.
Parameters:
Returns 1 if string matches the pattern, 0 else.
Pattern can be a regular expression
specifications
All classes below are part of Crossfire module
This represents an archetype, from which all objects are derived. Pointer to such item can be obtained through the Crossfire.Object.Archetype or the list returned by Crossfire.GetArchetypes().
A Crossfire.Object property representing the default values for items of that archetype. Will never be None. Its values can’t be changed (but trying to change one will not result in any error)
archetype to which this archetype is linked to. Will be None if not applicable
archetype’s name
next archetype in the archetype list. Will be None for last item
next archetype linked to current archetype. Will be None for last item
Returns a Crossfire.Object having this archetype as type. It isn’t on any map or in any inventory, so should be inserted somewhere or deleted if not used.
link to dev:objects ‘s fields? split flag & such info. Make a table with property / mapping to object / Python type Properties in bold are read-write, others are read-only. Most properties are mapped to fields of the object structure. Boolean values are mapped to the various flags.
String containing the object’s nameString containing the object’s plural nameStringStringCrossfire.Map containing the map the object is in. Changing that teleports the object to specified map, at default coordinates.StringStringBooleanBooleanNumberNumberCrossfire.ObjectCrossfire.ObjectCrossfire.ObjectNumberNumberNumberNumberBooleanStringBoolean, whether the item can be picked up or notNumber. Setting it to 0 removes the object.BooleanNumberNumberNumberNumberNumberNumber representing the face number. When writing, a String representing the face’s name (eg: cobblesto1.111). Will raise an error if invalid face.Number representing the animation number, 0 if none. When writing, a String representing the animation’s name (eg: fireplace). Will raise an error if invalid animation.Number, the animation speedNumberBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanBoolean, whether the monster can pickup items or not.BooleanBooleanBooleanBooleanBooleanBooleanBooleanBooleanNumber, returns the total money (in silver) the object ownsNumberNumberNumber, value of the objectString, name of this object’s archetypeCrossfire.ArchetypeBooleanCrossfire.Object. Can be None.Crossfire.Object representing the object’s enemy. Will probably be None except for monsters.BooleanBooleanBoolean
document all parameters. Link to relevant Crossfire function. Split in “standard function” and “helper function”?
Current object springs like a trap, hitting the victim.
Arguments:
Crossfire.Object that is the victim of the trap.Adds or subtracts experience to current object.
Arguments:
number, experience to addstring (optional), skill to add tonumber (optional), what to do if player doesn’t have the specified skill:Current object applies specified object. The effect depends on the object being applied, which can be a potion, a trigger, ...
Arguments:
Crossfire.Object to apply
meaning?Return value:
Current object casts a spell.
Arguments:
Crossfire.Object representing the spell to caseCrossfire.Direction, direction in which the object should castString, optional arguments to the spell (for food creation, ...)Return value:
Note that all checks related to spell-casting apply: enough sp/gp, knowing the skill, sufficient level, spot where magic isn’t forbidden, ...
The spell needn’t be known to be known to be cast, though.
Equivalent of Cast.
Displays relevant messages about resistances and so on changes.
Arguments:
Crossfire.Object which is a force effect, or something that changes a player’s attribute and was just added to inventory.Finds an object in current object’s inventory.
Arguments:
String representing the object name to findWill return the first object in inventory that has the specified name. Name must be the raw name, without bonuses and such.
Finds an object in current object’s inventory.
Arguments:
String representing the object to findWill return the first object in inventory that has the specified name. Matching is done on archetype, and also match on start of the object name.
Checks if current object should/can react to another object moving on it.
Arguments:
Crossfire.Object, cause that can cause current Object to react (altar, ...)Return value:
cause was destroyed, 0 if not.Create an object inside the current object.
Arguments:
String which is the name of the object to create
Will create a new Crossfire.Object from specified name (like Crossfire.CreateObjectByName) and insert it into the current object.
Fires an event_timer after the specified delay. Object should have a handler for this event.
Arguments:
number, delay for timernumber, timer mode
Returns: timer identifier, which can be used to remove the timer through a call to Crossfire.DestroyTimer
Current object drops specified object, which will be put on the ground, or in a container, depending on applied containers.
Argument:
Crossfire.Object to drop
Generates a user event to the object.
Arguments:
Crossfire.Object which is the activator of the eventCrossfire.Object which is the third object of the eventString which is the custom event’s nameinteger specifying whether to fix or not the objectCurrent object is reinitialized from its default values, values (ac, wc, Str, ...) are recomputed from items worn, in inventory, ...
Player forgets a spell.
Arguments:
Crossfire.Object representing the spell to forgetObject forgetting should be a player.
Gets the value of a resistance to an attacktype.
Arguments:
Number: attacktype for which to get the resistance
Return: Number with the value. Note that an invalid attacktype will return 0, which can’t be distinguished from a neutral resistance.
Insert the current object into another object.
Arguments:
Crossfire.Object, in which the current object will be insertedReturn:
Crossfire.Object representing the newly inserted object.
After using this function, you should not use the initial Crossfire.Object, as it can be merged with others.
Checks if current object knows a spell.
Arguments:
String, name of the spell to check forReturn:
Crossfire.Object representing the spell the object known, or None if this spell isn’t known to the currect Crossfire.Object.Make the current object learn a spell.
Arguments:
Crossfire.Object representing the spell to learnThere is no learning failure. Note that any spell can be learned this way. Player will receive the message that the spell was learnt correctly.
Tries to move the object in a direction.
Arguments:
Number, direction to move to. Should be one of Crossfire.Direction.xxx value.Return:
Check a position on the object’s map.
Arguments:
Number, x and y coordinatesReturn:
Note that this function takes into account maps tiling.
Buys an item.
Arguments:
Crossfire.Object to buyReturn value:
This function applies bargaining skill if applicable, and will handle shop-based price difference. Note that the object to buy doesn’t need to have the FLAG_UNPAID set.
Pays money.
Arguments:
Number, amount to pay for, in raw value units (silver coin)Return:
Finds the price of an object.
Arguments:
Crossfire.Object that current Crossfire.Object wants to know the price ofNumber, flags to apply, combination of Crossfire.CostFlag valuesReturn value:
Return: String containing the object’s full name.
Reads key associated to value.
Arguments:
String: key value to read
Return: String containing the value. Will be empty if NULL value.
Destroys current object, which then becomes invalid.
Moves current object to specified position on its current map.
Arguments:
Number, x and y, coordinates of position to teleport the object toCurrent object says something in current map.
Argument:
string to say.Current object says something in current map
Argument:
string to say.
Equivalent to Say.
Current object picks up specified object, which will be put in inventory, or in a container, depending on applied containers.
Argument:
Crossfire.Object to takeTeleports the object to specified place.
Arguments:
Crossfire.Map: map to insert into.Number: x coordinatesNumber: y coordinates
Return value: Number, 0 for success, 1 for failure.
Inserts specified key/value in the object.
Arguments:
String: key valueString: value to associate to the keyNumber (optional, defaults to 0): 0 to only update the key and not insert it, non zero to add it anyway. Properties in bold are read-write, others read only.
NumberStringStringStringNumberNumberNumber, number of players on the mapNumberNumberNumberNumberNumberNumberNumberNumberNumberNumberNumberNumberNumberNumberStringCrossfire.RegionFalse if cf map has been freed from memory, True otherwise)NumberPrints the specified message to all players on the map.
Arguments:
String, message to printNumber, optional flags, combination of Crossfire.MessageFlag (default is NDI_BLUE|NDI_UNIQUE).
Returns the first Crossfire.Object at specified location.
Arguments:
Number, x and y
Other objects on the position are available through the use of the Above field.
Creates an object on the map.
Arguments:
String, name of object to createInteger, x and y, coordinates
Equivalent of calling Crossfire.CreateObjectByName() (creates an item from archetype or name) and inserting it in the map at the specified location
Arguments:
String, name of object to check for. Should be a raw name, without the bonuses and title and such.Integer, optional x and y coordinatesReturn:
Change the map’s light level.
Arguments:
Number, specifying how to change the light. Negative value means map gets brighter, positive darker.
Note that light will never be negative or over 5 (MAX_DARKNESS)
Inserts an object at specified location.
Arguments:
Crossfire.Object to insertNumber, X and Y, coordinates where to insert
Return: Crossfire.Object representing the inserted object. Can be None if object was removed for some reason (eaten by an altar, ...)
This class inherits from Crossfire.Object, and introduces the new properties (bold = read-write):
String.string containing the map in which the player last saved.number containing the x coordinate of last savebed.number containing the y coordinate of last savebed.Crossfire.Object, item the player has marked.Crossfire.Party, party in which the player is. Note that changing it bypasses a potential party’s password.Checks if player can pay for unpaid items in inventory.
Return value:
This will print suitable messages if player can’t pay.
Sends a message to the player.
Arguments:
String, message to sayNumber, optional, combination of Crossfire.MessageFlag, default value is NDI_UNIQUE + NDI_ORANGE.Equivalent of Message.
This class merely encapsulates a party. Everything is read-only. Attributes:
StringStringCrossfire.Party
Return value: a list of Crossfire.Players
This class encapsulates an in-game region. Properties are read-only.
StringStringStringCrossfire.Region
Return value: a Crossfire.Region, or None if no parent region.
A section
This script will send its activator to jail, placing them in the 15 minute cell.
import Crossfire #we get the the object that triggered this script activator = Crossfire.WhoIsActivator() #make sure that the map is loaded, and get the object representing it #we could get the map's default entry coordinates with 'm.enter_x' and 'm.enter_y' m = Crossfire.ReadyMap('/scorn/misc/jail') #teleport the activating object to the x:15 y:1 coordinates of the map (m) we just readied activator.Teleport(m, 15, 1)
write an example