Application Programmer Interface (API)

The following are important global JavaScript functions you can call from your experiment.

submit(str, [callback])
After each player's move, you should call submit(str, callback) where str is a string (or XML or JSON) value corresponding to each player's move. If given, callback will be called with a JavaScript object of the response when the request finishes.
fetchMove(participant, round, index, callback)
Used to fetch a player's move for a round given a participant id, round number, move number within that round, and callback function. callback is called with the value of that player's move once the request returns.
getName(playerNum)
You can specify randomly assigned player names (gender specific) in the experiment configuration interface. This function gives you the player's assigned name. If you don't specify player names in the configuration, it will be Player 1,2, etc.
setRound(round)
Should be called with an integer every time the round changes. What defines a round is completely up to you. Typically there are several instruction or practice rounds.
Rounds are not required to be consecutive. We typically set our first "real" game round as round 101.
getFile(fileName)
Gets the full path to the latest version of the requested file. Useful for linking images or other external objects. Note that JavaScript and CSS files are automatically linked in each experiment.
getMatrixValue(matrix,row,column)
values in "matrix" in row, column. This is a shortcut to variables[matrix][row-1][column-1]
sendChat(val,to)
val is a string containing the message; to is a matrix containing the player numbers [1,2,4] etc; this will cause chatReceived(playerNum,val) to be called on everyone in the "to" array. You may want to include "myid" in the array if you want volunteer science to automatically call chatReceived(playerNum,val) locally.
Note that if you override
sendCom(val,com_type,to)
more abstract version of sendChat() used to send any kind of information to other players. com_type is user defined, but we use "-1" for chat.
writeScore(name, score, order, callback)
call this when the user has finished a game, we support multiple score types for each experiment. name is the type of score, score is how many points, order should be "high" or "low" to say whether a high score is good (like football) or a low score is good (like golf), callback is optional and should have the arguments (rank,count). Rank his how well the player did out of count players. So if the game has been played by 100 players, and the local player is the 77th best, then rank = 77, count = 100, so they are ranked 77 out of 100.
getTopScores(name, count, callback)
use this to request the top scorers for the award name, count is how many you want returned say 10 for top 10. callback should have 2 paramenters (count,scores); count is how many scores have been recorded, scores is the top XXX scores.
writeAward(name, val)
name is the name of your award, val is not necessary, but you may include specific details about this award.
HSVtoRGB(h, s, v)
handy function to convert colors
sendComBot(playerNum,val,com_type,to)
Used to send communication from bots or dropped players. Note that for security, this will fail if the human player is still active.
submitBot(playerNum, round, val, callback)
Call this to submit as a disconnected player or bot. Note that for security, this will fail if the human player is still active.
experimentComplete()
call this at the end of your experiment, to request the IRB consent form if the user hasn't already accepted it. The function is also a shortcut to the following calls:
  • disableQuitConfirm() -- if the user calls "quit" during the experiment, a popup discourages them from doing this. This function disables it.
  • enablePlayAgain() -- turns on the "Play Again" button.
  • enableSubmitFeedback() -- turns on the "Submit Feedback" button
payAMT(pay,bonus)
only needed for AMT enabled experiments.
  • pay is true/false depending if they did a good enough job to be paid
  • bonus is in US Dollars and should be how much more they should be paid above the base pay.
Note this automatically calls experimentComplete(), and does no harm to call in non-amt mode.
getUserData(callback, exp)
Get all data for the presently logged in user for a given experiment. Returns an array of all submits, ordered by date.
  • callbackfunction to be called when data loads; accepts data array as argument
  • expid of the experiment to load data for
log(string)
This is to help the developer debug problems. These are displayed to browser specific logs, such as "FireBug" in "Firefox"
1configureThanks(type, scoreName, scoreOrder, showRank, showPercentile)
Call this before experimentComplete() to change how the thank you page is displayed.
  • type is the one of "default", "award", or "score"
    • "default": shows the amount of money the user has saved for science by playing
    • "award": shows all awards the player earned during the game. Only visible awards with images earned during the test will be shown.
    • "score": shows the score as specified below
    • If you use the score version, you must specify an Object with the following parameters
      • name: is the name associated with the score (ie 'Total Points')
      • score: the score to give the user (ie 30)
      • order: specifies the order in which score will be sorted, "low" if low scores are better (ie golf), "high" if high scores are better (ie real sports)
      • show_rank (optional, default false): if true, rank relative to other players will be displayed
      • show_percentile (optional, default false): if true, score percentile (relative to other players) will be displayed
      Example: configureThanks("score", {"name": "points", "score": 30, "order": "high", "show_rank": true, "show_percentile": true})
2configureThanks(message, social_message optional)
Use this form of configureThanks to specify a custom message for the thank you page, instead of using one of the prescribed options. If specified, the second paramter will be used for the Facebook, Twitter, and Reddit messages. Otherwise, the message itself will be used.
getConsumables(class, set, amount, callback(data, err){} )
Request 1 or more consumables from Volunteer Science. "data" is a list of strings. You can configure/create classes/sets from your research page.
setConsumables(class, set, condition)
If / when the participant completes the consumable, then tell Volunteer Science that you used it. "condition" is a string from the list you received from getConsumables().
mailChimpSubscribe(experiment_id, subscription_title, subscription_message)
Launch a popup to ask permission to subscribe the user for MailChimp notifications. Ensure that the experiment has MailChimp support enabled.
Add a placeholder: <div id="mailchimp-popup-placeholder"></div>

The following JavaScript variables are set globally before initialize() is called:

myid
Current user's id (player 1 is "1")
numPlayers
Number of players in current game.
initialState
the value returned from buildInitialState() if you used this function; note, this is calculated on player 1's client, then delivered to the rest of the clients before calling initialize()
participants
JavaScript object consisting of a key of the user id and a value of a JavaScript object with the user's name. Note that both particpant ids and indexes start with 1, not 0.
variables["variable-name"]
JavaScript object consisting of key value pairs of the variables you set in your experiment's back end.
getFile("file-name.ext")
Get a link to your file (for example an image file).
/attachment/<file.ext>
Alternative approach to getting a link to a file
seed
Use this as the random seed to generate random choices the same on all clients. See more in Best Practices
currentRound
Your current round, set by setRound()
activePlayers[playerNum]
Array of true/false for which players are still active. Use this to decide if this client should manage the bots: See more in Best Practices
awards[playerNum][awardName]
Count of how many times playerNum has received awardName.
score[playerNum][scoreName]
Table showing playerNum's score for scoreName.
DEVICE_TYPE
User's type of device: UNKNOWN = 0; DESKTOP = 1; TABLET = 2; SMART_PHONE = 3;
IS_AMT
true if this experiment is called from Amazon Mechanical Turk
IS_AMT_PREVIEW
true if this experiment is called from Amazon Mechanical Turk but is only a Preview (not yet paid). See the AMT docs for more information about preview mode.
IS_FACEBOOK
Set to true if the user is logged in with a Facebook account
SUPPRESS_THANKS
Set to true by default. If false, the "thank you page" will be displayed when experimentComplete() is called.

These are functions you should define in your experiment.

buildInitialState()
called on player 1, return an object that will be available in initialize()
initialize()
This function is called after the experiment page is done loading -- after the "initialState" variable is available. You should define this function and initialize your experiment in it.
newMove(participantId, index)
This function is called after the server detects any participant has made a new move. Index is the number of new moves that participant has made. You have to define this yourself!
Note that you are only notified of moves in your currentRound. If a different client is in a different round, you will not be notified until you setRound().
chatReceived(from, val, to_parts)
Called when someone sent a chat. From is an integer of the playerNum, val is the string/json, to_parts is an array of playerNum
comReceived(index, newCom)
You may need to send communications other than chat. This function is called on all clients, not just the ones who should receive the message. You must internally decide whether to deliver the communication to the local user.
index is a unique internal index for the communication.
newCom is an object with the following attributes:
  • .com_type -- integer of the communication type. This is defined by you, the application developer, though we internally use "-1" for chat.
  • .val -- string or other JSON object sent from sendCom()
  • .from -- playerNum who sent it
  • .to_parts -- array of player numbers that received it
Note, overriding comReceived() prevents chatReceived() from being automatically called. You should check if com_type == -1 and call chatReceived() if needed.
playerDisconnect(playerNum)
related: activePlayers[playerNum] = true/false
Implement this to detect if a player dropped out. See Best Practices for more details.

VS Facebook API

The following variable pertaining to the VS Facebook API is set before initialize() is called.

IS_FACEBOOK
Set to true if the user is logged in with a Facebook account

The following functions pertaining to the VS Facebook API are globally accessible within tests.

fbPermissionStatus(end)
This function may be used to query the status of any VS Facebook permission for the logged in user.
  • denied -- Denied permissions are inaccesible and should not be requested.
  • revoked -- Revoked permissions are inaccesible in games and should not be requested.
  • open -- Open permissions have not yet been granted by the user. You may request them.
  • granted -- Data relating to granted permissions is ready for retrieval. Yes!
endmay be any of the following endpoints:
currency,devices,gender,id,locale,security_settings,timezone,picture,
age_range,about,bio,birthday,favorite_athletes,favorite_teams,
inspirational_people,languages,quotes,sports,books,games,likes,moves,
music,television,friends,feed,posts,tagged,cover,albums,photos,hometown,
location,significant_other,family,interested_in,meeting_for,relationship_status,
education,political,religion,work,events,videos,website
get_facebook_permission(end, callback)
If the permission is granted, all data will be returned in a JS object as an argument to your specified callback. If the permission is open, it will be requested, and if the user grants it your callback will be triggered automatically once the data is loaded. Otherwise, the function has no effect, so it's always a good idea to check the permission status before making a call to get_facebook_permission!

Note also that jQuery and Boostrap are included in every page.