Skip to main content

Getting started

On this page you will build a small two-player experiment, one piece at a time. Each participant will:

  1. pick a colour,
  2. wait until the other participant has picked one too,
  3. see both choices.

You will run both participants yourself, from two tabs of one browser. That needs no server and no account. The same file runs for real participants on different computers once you change one line; see Choosing a backend.

What you need: a recent Chrome, Edge, Firefox or Safari, Node.js to build the packages and serve the page, and git.

How the pieces fit together​

A multiplayer experiment has two kinds of parts:

  • One backend (an adapter). It decides where the data participants share is kept: in the browser for testing, or on a JATOS or Firebase server for a real study. You connect it once, before the timeline runs.
  • Multiplayer trials (plugins). They go in the timeline like any other trial. Most of them share a value with the group, wait until the group meets some condition, or show what other participants are doing.

Everything else in the experiment is ordinary jsPsych.

Before the release​

The multiplayer packages need the jsPsych.multiplayer API. It is in review as jsPsych#3694 and not yet in a jspsych release, and most of the packages are not on npm yet. Until both are released:

  • jsPsych loads from a preview build of #3694, pinned to one commit, as in the code below.

  • The multiplayer packages load from a local build. Clone the repository and build them:

    git clone https://github.com/jspsych/jspsych-multiplayer.git
    cd jspsych-multiplayer
    npm install && npm run build

    Then make a folder in the repository, for example my-experiment/, and put your HTML file there. The script tags below point from that folder to the built packages.

After the release, the first two script tags become the usual jspsych ones, and the multiplayer tags become https://unpkg.com/@jspsych-multiplayer/<package>@<version> URLs. The rest of this page stays the same.

Build the experiment​

  1. Load the packages​

    Create my-experiment/first-trial.html:

    <!doctype html>
    <html>
    <head>
    <!-- jsPsych: the #3694 preview build (see "Before the release") -->
    <script src="https://cdn.jsdelivr.net/gh/jspsych/jsPsych@1e77da41966f22832ee0d133d137d81b3e50639a/packages/jspsych/dist/index.browser.min.js"></script>
    <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/gh/jspsych/jsPsych@1e77da41966f22832ee0d133d137d81b3e50639a/packages/jspsych/css/jspsych.css"
    />
    <script src="https://unpkg.com/@jspsych/plugin-html-button-response@2"></script>

    <!-- The backend, and one multiplayer plugin -->
    <script src="../packages/adapter-multiplayer-local/dist/index.browser.min.js"></script>
    <script src="../packages/plugin-multiplayer-sync/dist/index.browser.min.js"></script>
    </head>
    <body></body>
    <script>
    // The code from the next steps goes here
    </script>
    </html>
  2. Connect a backend​

    const jsPsych = initJsPsych({
    on_finish: () => jsPsych.data.displayData(),
    });

    const adapter = new jsPsychAdapterMultiplayerLocal();

    The local adapter shares data between tabs of one browser. It is for building and testing only; it cannot connect participants on different computers. A tab that reloads keeps its participant ID, but reloading restarts the experiment, so it can't rejoin the game it left: the other tab counts it as having left (see Rejoining).

    You will hand the adapter to jsPsych in the last step, just before the timeline runs.

  3. Ask for a choice​

    An ordinary jsPsych trial. Nothing about it is multiplayer:

    let myColour;

    const choose = {
    type: jsPsychHtmlButtonResponse,
    stimulus: "<p>Pick a colour. Your partner will see it.</p>",
    choices: ["red", "blue"],
    on_finish: (data) => {
    myColour = ["red", "blue"][data.response];
    },
    };
  4. Share it and wait for the partner​

    This is the multiplayer trial. multiplayer-sync does two things in order: it saves write_data where everyone in the group can read it, then it waits until wait_for returns true.

    let partnerColour;

    const waitForPartner = {
    type: jsPsychMultiplayerSync,
    write_data: () => ({ colour: myColour }),
    participants: [], // don't end the trial if the partner leaves before choosing
    wait_for: (data, presence) => {
    let connected = 0;
    for (const id in presence) {
    if (presence[id] === "connected") {
    connected++;
    // A participant's entry in data is undefined until they share something in this trial
    if (data[id] === undefined || data[id].colour === undefined) {
    return false; // someone connected hasn't chosen yet
    }
    }
    }
    return connected >= 2;
    },
    message: "<p>Waiting for your partner to choose…</p>",
    save_group: true,
    on_finish: (data) => {
    // The partner is whoever in the group isn't this participant
    for (const id in data.group) {
    if (id !== jsPsych.multiplayer.participantId) {
    partnerColour = data.group[id].colour;
    }
    }
    },
    };

    wait_for gets two arguments:

    • data, what each participant has shared in this trial, keyed by participant ID. Here, after both have chosen, it looks like { "a1b2…": { colour: "red" }, "c3d4…": { colour: "blue" } }. Each trial starts with its own empty shared data, so nothing from an earlier trial can satisfy the condition by accident.
    • presence, whether each participant is "connected", "away" (their connection dropped) or "left".

    Read the condition aloud: at least two participants are connected, and each of them has shared a colour. Both tabs check the same condition against the same data, so both move on at the same moment.

    write_data is a function because myColour only has a value once the previous trial has finished. participants: [] tells the trial not to depend on any particular participant: at this point nobody knows who the partner will be. save_group: true saves the trial's shared data in data.group when the wait ends, which is where on_finish finds the partner's colour.

  5. Show the result and run​

    const result = {
    type: jsPsychHtmlButtonResponse,
    stimulus: () => `<p>You picked <b>${myColour}</b>. Your partner picked <b>${partnerColour}</b>.</p>`,
    choices: ["Finish"],
    };

    async function runExperiment() {
    await jsPsych.multiplayer.connect(adapter);
    await jsPsych.run([choose, waitForPartner, result]);
    }

    runExperiment();

    connect() must finish before jsPsych.run(), because the multiplayer trials need the connection from their first moment. The async function lets you use await in an ordinary <script> tag.

Run it in two tabs​

Browsers only share the local adapter's data between pages served from the same web address, so serve the repository instead of opening the file directly. From the repository folder:

npx http-server .

Open http://localhost:8080/my-experiment/first-trial.html. Pick a colour, and the page says it is waiting for your partner. The address bar now ends in ?mp_session=…: that is the session this tab joined.

Copy the whole address, including ?mp_session=…, into a second tab. A second tab without it would start its own session, and the two tabs would each wait forever. Pick a colour in the second tab, and both tabs show the result.

What the data looks like​

The sync trial adds these fields to the usual jsPsych data:

{
"trial_type": "multiplayer-sync",
"wait_time": 2310, // ms this participant waited
"multiplayer_outcome": "completed", // or "timeout", "participant_left", "connection_lost"
"left_participant": null, // who left, if someone did
"group": { // because of save_group: true
"a1b2…": { "colour": "red" },
"c3d4…": { "colour": "blue" }
},
"multiplayer_participant_id": "a1b2…",
"multiplayer_session_id": "k7x9…"
}

The data from each participant's own browser holds the choices of the whole group, so you can analyse a session from either participant's file. Every row of the data, not only the multiplayer trials, carries multiplayer_participant_id and multiplayer_session_id, so you can match up the files from the members of each group.

Next steps​

  • Read How it works for the rules behind the shared data and presence.
  • Build the ultimatum game: a complete two-player study with roles, a partner who might leave, and a real backend.
  • Browse the examples for chat, polls, pairing, scoreboards and more.