Character Vault
Any Concept / Any System
Compendium
Your System Come To Life
Roll20 for Android
Streamlined for your Tablet
Roll20 for iPad
Streamlined for your Tablet

Personal tools

API:Objets (Français)

From Roll20 Wiki

Revision as of 22:31, 29 December 2014 by Brian (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Roll20 API

Getting Started


Reference


Cookbook (Examples)


Community Scripts

Contents

Types d'objets

Il existe plusieurs types d'objets utilisés dans l'API Roll20. Voici une courte liste de chacun de ces objets indiquant ce qu'ils sont et quels sont leurs attributs (ainsi que leurs valeurs par défaut). De manière générale, les attributs dont le nom commence par un underscore (_) sont en lecture seule et ne peuvent pas être modifiés. Vous devez accéder aux propriétés d'un objet en utilisant la méthode obj.get("attribut") et les modifier en utilisant la méthode obj.set("propriete", nouvelleValeur) ou obj.set({propriete: nouvelleValeur, propriete2: nouvelleValeur2}).

Note : L'attribut id d'un objet est un identifiant unique : il ne doit pas exister pas deux objets possédant le même, et ce même entre différents types d'objets. De plus, puisque l'identifiant d'un objet est souvent utilisé et ne change jamais, il est possible d'utiliser le raccourci obj.id pour y accéder au lieu de obj.get("_id") si vous préférez (mais les deux fonctionnent).

Path

Propriété Valeur par défaut Description
_id Un identifiant unique pour cet objet. Il est unique parmi tous les objets de cette campagne. Lecture seule.
_type "path" Peut être utilisé pour identifier le type d'objet ou chercher un certain objet. Lecture seule.
_pageid Identifiant de la page où se trouve l'objet. Lecture seule.
_path Une chaîne de caractères au format JSON listant les lignes formant le chemin. Lecture seule, sauf lorsque l'on crée un nouveau chemin. Voir Objets/Path pour plus d'informations.
fill "transparent" Couleur de remplissage. Utilisez la chaîne de caractère "transparent" ou un code couleur hexadécimal dans une chaîne de caractères, par exemple "#000000".
stroke "#000000" Couleur du contour.
rotation 0 Inclinaison (en degrés).
layer "" Calque courant parmi "gmlayer", "objects", "map" ou "walls". Le calque des murs est utilisé pour l'éclairage dynamiques et les chemins sur ce calque bloqueront la lumière.
stroke_width 5 Epaisseur du contour.
width 0 Largeur
height 0 Hauteur
top 0 Coordonnée Y du centre du chemin
left 0 Coordonnée X du centre du chemin
scaleX 1 Echelle de la largeur
scaleY 1 Echelle de la hauteur
controlledby "" Liste des identifiants des joueurs pouvant contrôler ce chemin, séparés par des virgules. Les joueurs le contrôlant peuvent supprimer ce chemin. Si le chemin est créé par un joueur, ce joueur fait automatiquement partie de cette liste.

Pour plus d'informations sur le format de l'attribut _path, voir Objets/Path.

Texte

Propriété Valeur par défaut Description
_id Un identifiant unique pour cet objet. Il est unique parmi tous les objets de cette campagne. Lecture seule.
_type "text" Peut être utilisé pour identifier le type d'objet ou chercher un certain objet. Lecture seule.
_pageid Identifiant de la page où se trouve l'objet. Lecture seule.
top 0 Position à droite
left 0 Position à gauche
width 0 Largeur
height 0 Hauteur
text "" Texte
font_size 16 Pour de meilleurs résultats, limitez-vous aux tailles prédéfinies dans le menu d'édition : 8, 10, 12, 14, 16, 18, 20, 22, 26, 32, 40, 56, 72, 100, 200, 300.
rotation 0 Inclinaison
color "rgb(0, 0, 0)" Couleur
font_family "unset" Voir les valeurs dans le menu édition de texte
layer "" Calque courant parmi "gmlayer", "objects", "map" ou "walls". Le calque des murs est utilisé pour l'éclairage dynamiques et les chemins sur ce calque bloqueront la lumière.
controlledby "" Liste des identifiants des joueurs pouvant contrôler ce texte, séparés par des virgules. Les joueurs le contrôlant peuvent supprimer ce texte. Si le texte est créé par un joueur, ce joueur fait automatiquement partie de cette liste.

Graphic (Jeton/Carte/Etc.)

Propriété Valeur par défaut Description
_id Un identifiant unique pour cet objet. Il est unique parmi tous les objets de cette campagne. Lecture seule.
_type "graphic" Peut être utilisé pour identifier le type d'objet ou chercher un certain objet. Lecture seule.
_subtype "token" Peut valoir "token" (pour les jetons et cartes) ou "carte" (pour les cartes à jouer). Lecture seule.
_cardid Un identifiant est indiqué si l'élément graphique est une carte. Lecture seule.
_pageid Identifiant de la page où se trouve l'objet. Lecture seule.
imgsrc URL de l'image liée à l'élément graphique. Voir la note à propos des restrictions sur les avatars et les attributs imgsrc ci-dessous.
bar1_link Un identifiant est indiqué si Bar 1 est lié à un personnage.
bar2_link
bar3_link
represents Identifiant du personnage que représente ce jeton. Lecture seule.
left 0 Nombre de pixels depuis le bord gauche de la carte du centre de l'élément graphique.
top 0 Nombre de pixels depuis le bord haut de la carte du centre de l'élément graphique.
width 0 Largeur de l'élément graphique, en pixels.
height 0 Hauteur de l'élément graphique, en pixels.
rotation 0 Inclinaison
layer "" Calque courant parmi "gmlayer", "objects", "map" ou "walls". Le calque des murs est utilisé pour l'éclairage dynamiques et les chemins sur ce calque bloqueront la lumière.
isdrawing false Cette propriété est modifiable dans le menu contextuel avancé.
flipv false Inverse l'image verticalement.
fliph false Inverse l'image horizontalement.
name "" Le nom du jeton.
gmnotes "" Notes du jeton visibles uniquement par le MJ.
controlledby "" Liste des identifiants des joueurs pouvant contrôler cet élément graphique, séparés par des virgules. Les joueurs le contrôlant peuvent supprimer cet élément. Si l'élément est créé par un joueur, ce joueur fait automatiquement partie de cette liste.
bar1_value "" Valeur actuelle de Bar 1. Ce peut être un nombre ou du texte.
bar2_value ""
bar3_value ""
bar1_max "" Valeur maximale de Bar 1. Si _value et _max sont tous les deux définis, une barre devrait s'afficher au dessus du jeton affichant le pourcentage de Bar 1.
bar2_max ""
bar3_max ""
aura1_radius "" Rayon de l'aura, utilisant l'unité définie dans les paramètres de la page. Cela peut être un entier ou un nombre décimal. Laissez une chaîne vide pour supprimer l'aura.
aura2_radius ""
aura1_color "#FFFF99" Un code couleur hexadécimal pour l'aura.
aura2_color "#59E594"
aura1_square false L'aura est-elle circulaire ou carrée ?
aura2_square false
tint_color "transparent" Code couleur hexadécimal, ou "transparent". Teintera l'élément graphique avec la couleur indiquée.
statusmarkers "" Un liste des marqueurs de statuts actuellement activés, séparés par des virgules. Voir les notes ci-dessous pour plus d'informations.
showname false Indique si le nom du jeton est affiché.
showplayers_name false Indique si le nom est visible aux joueurs.
showplayers_bar1 false Affiche Bar 1 à tous les joueurs.
showplayers_bar2 false
showplayers_bar3 false
showplayers_aura1 false Affiche l'aura 1 à tous les joueurs.
showplayers_aura2 false
playersedit_name true Autorise les joueurs contrôlant ce jeton à modifier son nom. Affiche aussi le nom aux joueurs le contrôlant, même si showplayers_name vaut false.
playersedit_bar1 true Autorise les joueurs contrôlant ce jeton à modifier Bar 1. Affiche aussi Bar 1 aux joueurs le contrôlant, même si showplayers_bar1 vaut false.
playersedit_bar2 true
playersedit_bar3 true
playersedit_aura1 true Autorise les joueurs contrôlant ce jeton à modifier l'aura 1. Affiche aussi l'aura 1 aux joueurs le contrôlant, même si showplayers_aura1 vaut false.
playersedit_aura2 true
light_radius "" Rayon de l'éclairage dynamique.
light_dimradius "" Rayon de démarrage de l'éclairage diminué. Si light_dimradius est une chaîne de caractères vide, le jeton émettra une lumière vive sur toute la distance de light_radius. Si light_dimradius a une valeur, le jeton émettra une lumière vive jusqu'à un rayon valant light_dimradius puis la lumière s'affaiblira jusqu'à un rayon valant light_radius.
light_otherplayers false Affiche la lumière du jeton à tous les joueurs.
light_hassight false The light has "sight" for controlling players for the purposes of the "Enforce Line of Sight" setting.
light_angle "360" Angle (in degrees) of the light's angle. For example, "180" means the light would show only for the front "half" of the "field of vision".
light_losangle "360" Angle (in degrees) of the field of vision of the graphic (assuming that light_hassight is set to true)
lastmove "" The last move of the token. It's a comma-delimited list of coordinates. For example, "300,400" would mean that the token started its last move at left=300, top=400. It's always assumed that the current top + left values of the token are the "ending point" of the last move. Waypoints are indicated by multiple sets of coordinates. For example, "300,400,350,450,400,500" would indicate that the token started at left=300, top=400, then set a waypoint at left=350, top=450, another waypoint at left=400, top=500, and then finished the move at its current top + left coordinates.

Important Notes About Linked Characters + Tokens

Note that for tokens that are linked to Characters, the controlledby field on the token is overridden by the controlledby field on the Character.

For token bars (e.g. bar1_value and bar1_max) where the token is linked to an Attribute (e.g. bar1_link is set), setting a value to the bar will automatically update the underlying Attribute's current and/or max values as well, so you don't have to set both manually.

In addition, when the Attribute (or token bar) is modified in-game, you will hear a change:attribute (and property-specific, e.g. change:attribute:current) event, followed by a change:graphic (and change:graphic:bar1_value) event. You can choose to respond to either event, but the underlying bar values will not yet be updated when the attribute event fires, since it fires first.

Important Notes About Status Markers

As of August 6, 2013 the way that status markers on tokens are handled has changed. The "statusmarkers" property of the Graphic object is now a comma-delimited list of all status marker colors/icons that should be active on the token. The format is as follows:

//Comma-delimited (use join to create or split to turn into an array). If a status icon/color is followed by an "@" symbol, the number after "@" will be shown as the badge on the icon
statusmarkers = "red,blue,skull,dead,brown@2,green@6"

While you can access the statusmarkers property directly, to maintain backward-compatibility with existing scripts, and to provide an easy way to work with the status markers without needing to write code to handle splitting up and parsing the string yourself, we provide a set of "virtual" properties on the object that you can set/get to work with the status markers. Each status marker has a "status_<markername>" property. For example:

obj.get("status_red"); //Will return false if the marker is not active, true if it is, and a string (e.g. "2" or "5") if there is currently a badge set on the marker
obj.get('status_bluemarker'); //Is still supported for backwards compatability, and is equivalent to doing obj.get("status_blue");
obj.set("status_red", false); //would remove the marker
obj.set("status_skull", "2"); //would set a badge of "2" on the skull icon, and add it to the token if it's not already active.

Note that these virtual properties do not have events, so you must use change:graphic:statusmarkers to listen for changes to the status markers of a token, and for example change:graphic:status_red is NOT a valid event that will ever fire.

The full list of status markers that are available (in the same order they appear in the marker tray):

"red", "blue", "green", "brown", "purple", "pink", "yellow", "dead", "skull", "sleepy", "half-heart", "half-haze", "interdiction", "snail", "lightning-helix", "spanner", "chained-heart", "chemical-bolt", "death-zone", "drink-me", "edge-crack", "ninja-mask", "stopwatch", "fishing-net", "overdrive", "strong", "fist", "padlock", "three-leaves", "fluffy-wing", "pummeled", "tread", "arrowed", "aura", "back-pain", "black-flag", "bleeding-eye", "bolt-shield", "broken-heart", "cobweb", "broken-shield", "flying-flag", "radioactive", "trophy", "broken-skull", "frozen-orb", "rolling-bomb", "white-tower", "grab", "screaming", "grenade", "sentry-gun", "all-for-one", "angel-outfit", "archery-target"

Page

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "page" Can be used to identify the object type or search for the object. Read-only.
_zorder "" Comma-delimited list of IDs specifying the ordering of objects on the page. toFront and toBack (and their associated context menu items) can re-order this list. Read-only.
name "" Page's title.
showgrid true Show the grid on the map.
showdarkness false Show fog of war on the map.
showlighting false Use dynamic lighting.
width 25 Width in units.
height 25 Height in units.
snapping_increment 1 Size of a grid space in units.
grid_opacity 0.5 Opacity of the grid lines.
fog_opacity 0.35 Opacity of the fog of war for the GM.
background_color "#FFFFFF" Hexadecimal color of the map background.
gridcolor "#C0C0C0" Hexadecimal color of the grid lines.
grid_type "square" One of "square", "hexv", or "hexh".
scale_number 5 The distance of one unit.
scale_units "ft" The type of units to use for the scale.
gridlabels false Show grid labels for hexagonal grid.
diagonaltype "foure" One of "foure", "pythagorean" (Euclidean), "threefive", or "manhattan".
archived false whether the page has been put into archive storage.

Campaign

Propriété Valeur par défaut Description
_id "root" A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "campaign" Can be used to identify the object type or search for the object — however, note that there is only one Campaign object, and it can be accessed via Campaign(). Read-only.
turnorder "" A JSON string of the turn order. See below.
initiativepage false ID of the page used for the tracker when the turn order window is open. When set to false, the turn order window closes.
playerpageid false ID of the page the player bookmark is set to. Players see this page by default, unless overridden by playerspecificpages below.
playerspecificpages false An object (NOT JSON STRING) of the format: {"player1_id": "page_id", "player2_id": "page_id" ... } Any player set to a page in this object will override the playerpageid.

Turn Order

The turn order is a JSON string representing the current turn order listing. It is an array of objects. Currently, the turn order can only contain objects from one page at a time -- the current Page ID for the turn order is the "initiativepage" attribute. Be sure to keep them both in-sync or you may end up with strange results.

To work with the turn order, you will want to use JSON.parse() to get an object representing the current turn order state (NOTE: Check to make sure it's not an empty string "" first...if it is, initialize it yourself with an empty array). Here's an example turn order object:

[
    {
     "id":"36CA8D77-CF43-48D1-8682-FA2F5DFD495F", //The ID of the Graphic object. If this is set, the turn order list will automatically pull the name and icon for the list based on the graphic on the tabletop.
     "pr":"0", //The current value for the item in the list. Can be a number or text.
     "custom":"" //Custom title for the item. Will be ignored if ID is set to a value other than "-1".
    },
    {
     "id":"-1", //For custom items, the ID MUST be set to "-1" (note that this is a STRING not a NUMBER.
     "pr":"12",
     "custom":"Test Custom" //The name to be displayed for custom items.
    }
]

To modify the turn order, edit the current turn order object and then use JSON.stringify() to change the attribute on the Campaign. Note that the ordering for the turn order in the list is the same as the order of the array, so for example push() adds an item onto the end of the list, unshift() adds to the beginning, etc.

var turnorder;
if(Campaign().get("turnorder") == "") turnorder = []; //NOTE: We check to make sure that the turnorder isn't just an empty string first. If it is treat it like an empty array.
else turnorder = JSON.parse(Campaign().get("turnorder"));

//Add a new custom entry to the end of the turn order.
turnorder.push({
    id: "-1",
    pr: "15",
    custom: "Turn Counter"
});
Campaign().set("turnorder", JSON.stringify(turnorder));

Player

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "player" Can be used to identify the object type or search for the object. Read-only.
_d20userid User ID — site-wide. For example, the player's user page on the wiki is /User:ID, where ID is the same value stored in _d20userid. Read-only.
_displayname "" The player's current display name. May be changed from the user's settings page. Read-only.
_online false Read-only.
_macrobar "" Comma-delimited string of the macros in the player's macro bar. Read-only.
speakingas "" The player or character ID of who the player has selected from the "As" dropdown. When set to the empty string, the player is speaking as him- or herself. When set to a character, the value is "character|ID", where ID is the character's ID. When the GM is speaking as another player, the value is "player|ID", where ID is the player's ID.
color "#13B9F0" The color of the square by the player's name, as well as the color of their measurements on the map, their ping circles, etc.
showmacrobar false Whether the player's macro bar is showing.

Macro

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "macro" Can be used to identify the object type or search for the object. Read-only.
_playerid The ID of the player that created this macro. Read-only.
name "" The macro's name.
action "" The text of the macro.
visibleto "" Comma-delimited list of player IDs who may view the macro in addition to the player that created it.
istokenaction false Is this macro a token action that should show up when tokens are selected?

Rollable Table

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "rollabletable" Can be used to identify the object type or search for the object. Read-only.
name "new-table"
showplayers true

Table Item

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "tableitem" Can be used to identify the object type or search for the object. Read-only.
_rollabletableid "" ID of the table this item belongs to. Read-only.
avatar "" URL to an image used for the table item. See the note about avatar and imgsrc restrictions below.
name ""
weight 1 Weight of the table item compared to the other items in the same table. Simply put, an item with weight 3 is three times more likely to be selected when rolling on the table than an item with weight 1.

Character

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "character" Can be used to identify the object type or search for the object. Read-only.
avatar "" URL to an image used for the character. See the note about avatar and imgsrc restrictions below.
name ""
bio "" The character's biography. See the note below about accessing the Notes, GMNotes, and bio fields.
gmnotes "" Notes on the character only viewable by the GM. See the note below about accessing the Notes, GMNotes, and bio fields.
archived false
inplayerjournals "" Comma-delimited list of player ID who can view this character. Use "all" to give all players the ability to view.
controlledby "" Comma-delimited list of player IDs who can control and edit this character. Use "all" to give all players the ability to edit.

Attribute

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "attribute" Can be used to identify the object type or search for the object. Read-only.
_characterid "" ID of the character this attribute belongs to. Read-only. Mandatory when using createObj.
name "Untitled"
current "" The current value of the attribute can be accessed in chat and macros with the syntax @{Character Name|Attribute Name} or in abilities with the syntax @{Attribute Name}.
max "" The max value of the attribute can be accessed in chat and macros with the syntax @{Character Name|Attribute Name|max} or in abilities with the syntax @{Attribute Name|max}.

Important: See the note below about working with Character Sheets for information on how Character Sheet default values affect the use of Attributes.

Ability

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "ability" Can be used to identify the object type or search for the object. Read-only.
_characterid "" The character this ability belongs to. Read-only. Mandatory when using createObj.
name "Untitled_Ability"
description "" The description does not appear in the character sheet interface.
action "" The text of the ability.
istokenaction false Is this ability a token action that should show up when tokens linked to its parent Character are selected?

Handout

Propriété Valeur par défaut Description
_id A unique ID for this object. Globally unique across all objects in this campaign. Read-only.
_type "handout" Can be used to identify the object type or search for the object. Read-only.
avatar "" URL to an image used for the handout. See the note about avatar and imgsrc restrictions below.
name "Mysterious Note"
notes "" Contains the text in the handout. See the note below about using Notes and GMNotes.
gmnotes "" Contains the text in the handout that only the GM sees. See the note below about using Notes and GMNotes.
inplayerjournals "" Comma-delimited list of player ID who can see this handout. Use "all" to display to all players.
archived false
controlledby "" Comma-delimited list of player IDs who can control and edit this handout.

Deck

//Note at this time you can't use the API to "draw", "deal", or "shuffle" cards from the Deck. We're working on helper functions to enable this functionality.
{
    _id: "", //id of the deck
    _type: "deck",     
    name: "", //name of the deck
    _currentDeck: "", //a comma-delimited list of cards which are currently in the deck (including those which have been played to the tabletop/hands). Changes when the deck is shuffled.
    _currentIndex: -1, //the current index of our place in the deck, 'what card will be drawn next?'
    _currentCardShown: true, //show the current card on top of the deck
    showplayers: true, //show the deck to the players
    playerscandraw: true, //can players draw cards?
    avatar: "", //the 'back' of the cards for this deck
    shown: false, //show the deck on the gameboard (is the deck currently visible?)
    players_seenumcards: true, //can players see the number of cards in other player's hands?
    players_seefrontofcards: false, //can players see the fronts of cards when looking in other player's hands?
    gm_seenumcards: true, //can the GM see the number of cards in each player's hand?
    gm_seefrontofcards: false, //can the GM see the fronts of cards when looking in each player's hand?
    infinitecards: false, //are there an 'infinite' number of cards in this deck?
    _cardSequencer: -1, //internally used to advance the deck when drawing cards.
    cardsplayed: "faceup", //how are cards from this deck played to the tabletop? 'faceup' or 'facedown'.
    defaultheight: "", //what's the default height for cards played to the tabletop?
    defaultwidth: "",
    discardpilemode: "none", //what type of discard pile does this deck have? 'none' = no discard pile, 'choosebacks' = allow players to see backs of cards and choose one, 'choosefronts' = see fronts and choose, 'drawtop' = draw the most recently discarded card, 'drawbottom' = draw the oldest discarded card.
    _discardPile: "" //what's the current discard pile for this deck? comma-delimited list of cards. These are cards which have been removed from play and will not be put back into the deck on a shuffle until a recall is performed.
  }

Card


{    
   name: "", //Name of the card
   avatar: "", //Front of the card
   _deckid: "", //ID of the deck   
   _type: "card",    
   _id: ""
}

Hand

//Note that each player should only have ONE hand.


{
    _currentHand: "", //comma-delimited list of cards currently in the hand
    _type: "hand",
    _parentid: "", //ID of the player to whom the hand belongs
    _id: "",
    currentView: "bydeck" //when player opens hand, is the view 'bydeck' or 'bycard'?
}

imgsrc and avatar property restrictions

While you can now edit the imgsrc and avatar properties, in order to provide safety to all Roll20's users we have put the following restrictions in place for those properties:


In the future we may add a tool so that images can be uploaded specifically for use with API scripts, but for now just use images uploaded to your own library. Note that if you delete an image from your library, it will be removed from all Campaigns which use that image, including Campaigns using your API scripts.

Using the Notes, GMNotes, and Bio fields

In order to access the "notes", "gmnotes", or "bio" fields on Characters and Handouts, you must pass a callback function as the second argument to the get() function. Here's an example:

var character = getObj("character", "-JMGkBaMgMWiQdNDwjjS");
character.get("bio", function(bio) {
    log(bio); //do something with the character bio here.
});

You can set the value of these fields as normal.

Working with Character Sheets

The new Character Sheets feature affects the usage of the Attributes object type, because the sheets have the capability of specifying a default value for each attribute on the sheet. However, if the attribute is set to the default value, there is not yet an actual Attribute object created in the game for that Character. We provide a convenience function which hides this complexity from you. You should use this function to get the value of an attribute going forward, especially if you know that a game is using a Character Sheet.

getAttrByName(character_id, attribute_name, value_type)

Simply specify the character's ID, the name (not ID) of the attribute (e.g. "HP" or "Str"), and then if you want the "current" or "max" for value_type. Here's an example:


var character = getObj("character", "-JMGkBaMgMWiQdNDwjjS");
getAttrByName(character.id, "str"); // the current value of str, for example "12"
getAttrByName(character.id, "str", "max"); //the max value of str, for example "[[floor(@{STR}/2-5)]]"

Note that fields which have auto-calculated values will return the formula rather than the result of the value. You can then pass that formula to sendChat() to use the dice engine to calculate the result for you automatically.

Be sure to also look at the Character Sheet documentation for more information on how the Character Sheets interact with the API.

Creating Objects

createObj(type, attributes)

Note: currently you can create 'graphic', 'text', 'path', 'character', 'ability', 'attribute', 'handout', 'rollabletable', 'tableitem', and 'macro' objects.

You can create a new object in the game using the createObj function. You must pass in the type of the object (one of the valid _type properties from the objects list above), as well as a an attributes object containing a list of properties for the object. Note that if the object is has a parent object (for example, attributes and abilities belong to characters, graphics, texts, and paths belong to pages, etc.), you must pass in the ID of the parent in the list of properties (for example, you must include the characterid property when creating an attribute). Also note that even when creating new objects, you can't set read-only properties, they will automatically be set to their default value. The one exception to this is when creating a Path, you must include the 'path' property, but it cannot be modified once the path is initially created.

createObj will return the new object, so you can continue working with it.

//Create a new Strength attribute on any Characters that are added to the game.
on("add:character", function(obj) {
    createObj("attribute", {
        name: "Strength",
        current: 0,
        max: 30,
        characterid: obj.id
    });
});

Global Objects

There are several objects that are globally available anywhere in your script.

Campaign() (function)

A function which returns the Campaign object. Since there is only one campaign, this global always points to the only campaign in the game. Useful for doing things like checking to see if an object is on the active page using Campaign().get("playerpageid").

state

This is an object that is initialized as a blank object whenver your script is loaded. You can set whatever properties you want on this object, and they are available to all of your event callbacks, and persist between callbacks. In addition, the state object is persisted between play sessions, so you can use this object to store long-term information about the state of the game.

You should use the state object to store information that is only related to the API, since it is not sent to player computers and does not make your campaign file larger, and store properties that are needed in-game in the objects themselves.

state.numTimesTokensMoved = 0;
on("change:graphic", function(obj) {    
  state.numTimesTokensMoved = state.numTimesTokensMoved + 1;
});

Finding/Filtering Objects

The API provides several helper functions which can be used to find objects.

getObj(type, id)

This function gets a single object if pass in the _type of the object and the _id. It's best to use this function over the other find functions whenever possible, as its the only one that doesn't have to iterate through the entire collection of objects.

on("change:graphic:represents", function(obj) {
    if(obj.get("represents") != "") {
       var character = getObj("character", obj.get("represents"));
    }
});


findObjs(attrs)

Pass this function a list of attributes, and it will return all objects that match. Note that this operates on all objects of all types across all pages -- so you probably want to include at least a filter for _type and _pageid if you're working with tabletop objects.

var currentPageGraphics = findObjs({                              
  _pageid: Campaign().get("playerpageid"),                              
  _type: "graphic",                          
});
_.each(currentPageGraphics, function(obj) {    
  //Do something with obj, which is in the current page and is a graphic.
});

You can also pass in an optional second argument which contains an object with a list of options, including:

  • caseInsensitive (true/false): If true, string properties will be compared without regard for the case of the string.


var targetTokens = findObjs({
    name: "target"
}, {caseInsensitive: true});
//Returns all tokens with a name of 'target', 'Target', 'TARGET', etc.


filterObjs(callback)

Will execute the provided callback funtion on each object, and if the callback returns true, the object will be included in the result array.

var results = filterObjs(function(obj) {    
  if(obj.get("left") < 200 && obj.get("top") < 200) return true;    
  else return false;
});
//Results is an array of all objects that are in the top-left corner of the tabletop.


getAllObjs()

Returns an array of all the objects in the Campaign (all types). Equivalent to calling filterObjs and just returning true for every object.


getAttrByName(character_id, attribute_name, value_type)

Gets the value of an attribute, using the default value from the character sheet if the attribute is not present. value_type is an optional parameter, which you can use to specify "current" or "max".

getAttrByName will only get the value of the attribute, not the attribute object itself. If you wish to reference properties of the attribute other than "current" or "max", or if you wish to change properties of the attribute, you must use one of the other functions above, such as findObjs.

You can achieve behavior equivalent to getAttrByNamewith the following:

// current and max are completely dependent on the attribute and game system
// in question; there is no function available for determining them automatically
function myGetAttrByName(character_id,
                         attribute_name,
                         attribute_default_current,
                         attribute_default_max,
                         value_type) {
    attribute_default_current = attribute_default_current || '';
    attribute_default_max = attribute_default_max || '';
    value_type = value_type || 'current';

    var attribute = findObjs({
        type: 'attribute',
        characterid: character_id,
        name: attribute_name
    })[0];
    if (!attribute) {
        attribute = createObj('attribute', {
            characterid: character_id,
            name: attribute_name,
            current: attribute_default_current,
            max: attribute_default_max
        });
    }

    if (value_type == 'max') {
        return attribute.get('max');
    } else {
        return attribute.get('current');
    }
}