Building an ultimatum game
In the ultimatum game (Güth, Schmittberger & Schwarze, 1982), two players split $10. The proposer offers the responder some amount. If the responder accepts, both keep their share; if they reject it, both get nothing.
This guide walks through
examples/ultimatum-game-local.html,
a complete version you can run in two browser tabs. It adds three things to
Getting started:
- roles, decided the same way on both screens,
- a partner who might leave, without leaving the other player stuck,
- a real backend, by changing one line.
Run it first
Follow Running an example and open
examples/ultimatum-game-local.html in two tabs. One tab becomes the proposer, the other the
responder. Play a round, then use the button on the last screen to download that tab's data.
Build it
Wait in a lobby
const lobby = {
type: jsPsychMultiplayerSync,
participants: [], // someone leaving the lobby shouldn't end it
wait_for: (data, presence) => {
// Count the participants who are currently connected
let connected = 0;
for (const id in presence) {
if (presence[id] === "connected") {
connected++;
}
}
return connected >= 2;
},
message: "<p>Waiting for another player to join…</p>",
};The lobby holds each player until at least two are connected. It has no
timeout, because waiting for a partner to arrive is the point of a lobby, andparticipants: []keeps it waiting when someone leaves instead of ending it.Assign roles
let myRole, proposerId, responderId;
const assignRoles = {
type: jsPsychMultiplayerRole,
roles: ["proposer", "responder"],
strategy: "join_order",
overflow_role: "spectator",
ready: (snapshot, presence) => {
const ids = Object.keys(snapshot);
// Wait for at least two players, all connected, each with a joinedAt time
return (
ids.length >= 2 &&
ids.every((id) => presence[id] === "connected" && snapshot[id].joinedAt !== undefined)
);
},
message: "<p>Assigning roles…</p>",
on_finish: () => {
myRole = jsPsychMultiplayerRole.getMyRole();
// If the trial ended before roles were assigned (for example, a player left), there are
// no roles to read
if (myRole === undefined) {
return;
}
// participantsByRole() gives a list of IDs for each role; each role has one player here
const byRole = jsPsychMultiplayerRole.participantsByRole();
proposerId = byRole.proposer[0];
responderId = byRole.responder[0];
},
};multiplayer-rolewrites ajoinedAttime for each participant, and withstrategy: "join_order"the earliest becomes the proposer. Both browsers sort the same shared data the same way, so they agree on the roles without asking each other. A third player who arrives late gets theoverflow_role,"spectator", and is shown a "game full" screen.The
readyfunction says when the group is complete enough to assign roles over: at least two participants, all connected, and each with ajoinedAt. Without it, a browser could sort before the partner'sjoinedAtarrived and pick the wrong proposer.joinedAtis stored in the session scope, the part of the shared data that lasts the whole session (see How it works). So a spectator who arrives later still sorts the players the same way, however much the players have written since.on_finishkeeps what the rest of the game needs: this player's role and both players' IDs.Share one scope between the two roles
Each trial has its own part of the shared data, named after the trial's position in the timeline. Normally that is exactly right: both players run the same trial at the same position, so they share its data. But here the proposer and the responder run different trials, in different conditional timelines, so their positions differ and they would never see each other's writes.
The fix is to name the scope. Every sync trial of the round gets the same
multiplayer_scope:multiplayer_scope: "round",The proposer's offer and the responder's decision then land in one shared scope. With more than one round, build the name from the round number, such as
() => `round-${jsPsych.evaluateTimelineVariable("round")}`, so each round starts fresh (see Scopes).Play the two turns
The proposer chooses an offer with an ordinary button trial, then sends it and waits for the decision:
const PARTNER_TIMEOUT_MS = 60000;
let proposerOffer, responderDecision;
let partnerLeft = false;
const proposerWait = {
type: jsPsychMultiplayerSync,
multiplayer_scope: "round",
write_data: () => ({ offer: proposerOffer }),
wait_for: (data) => data[responderId]?.decision !== undefined,
participants: () => [responderId],
timeout: PARTNER_TIMEOUT_MS,
save_group: true,
message: "<p>Waiting for the responder…</p>",
on_finish: (data) => {
if (data.multiplayer_outcome !== "completed") {
partnerLeft = true;
return;
}
responderDecision = data.group[responderId].decision;
},
};write_dataadds the offer to the proposer's data in the round's scope, andwait_forholds the trial until the responder's decision appears there.save_group: truesaves the round's shared data in the trial'sgroupfield, whereon_finishreads the decision.The responder mirrors it, with the same
multiplayer_scope: "round": a sync trial that waits for the proposer'soffer, a button trial to accept or reject, and a sync trial that writes{ decision: responderDecision }.Each role's trials sit in a timeline with a
conditional_function, such as() => myRole === "proposer". Both players load the same file; the role decides which trials each one sees.Handle a partner who leaves
participants: () => [responderId]tells the trial which participant it depends on. If that participant leaves (disconnected for more than 10 seconds, or reloaded the page), the trial ends withmultiplayer_outcome: "participant_left"instead of waiting forever."connection_lost"means this player's own connection is gone.timeoutcovers a partner who stays connected but never acts, and ends the trial with"timeout".Any outcome other than
"completed"setspartnerLeft, and the timeline shows a "your partner left" screen instead of the outcome:const partnerLeftScreen = {
timeline: [/* "The other player left…" */],
conditional_function: () => partnerLeft,
};
const outcome = {
timeline: [outcomeTrial],
conditional_function: () => !partnerLeft,
};A timeout has one catch: the other player does not know it happened. If the responder decides after the proposer's timeout, the proposer sees "your partner left" while the responder sees an outcome. Make the timeout much longer than your slowest participant needs, or limit the decision screen with
trial_duration. Handling dropouts has more.A player who reloads can't rejoin: the reload restarted their experiment, so the other player already sees them as
left. The adapters keep the participant ID across a reload by default, which lets the reloaded page notice (jsPsych.multiplayer.restartedistrue) and show a message instead of starting the game over:const reloadedScreen = {
type: jsPsychHtmlButtonResponse,
stimulus: "<p>You reloaded the page, so you can't rejoin this game.</p>",
choices: ["Finish"],
};
async function runExperiment() {
await jsPsych.multiplayer.connect(adapter);
await jsPsych.run(jsPsych.multiplayer.restarted ? [reloadedScreen] : timeline);
}
runExperiment();Switch to a real backend
The local adapter only connects tabs of one browser. For a real study, change the connection code, and load that adapter's script instead. For JATOS (
examples/ultimatum-game-jatos.html):// Before: two tabs in one browser
const jsPsych = initJsPsych();
async function runExperiment() {
await jsPsych.multiplayer.connect(new jsPsychAdapterMultiplayerLocal());
await jsPsych.run(timeline);
}
runExperiment();
// After: a JATOS group study
jatos.onLoad(async () => {
const jsPsych = initJsPsych({
on_finish: () => jatos.endStudy(jsPsych.data.get().json()),
});
await jsPsych.multiplayer.connect(new jsPsychAdapterMultiplayerJatos());
await jsPsych.run(timeline);
});The lobby, roles, turns and dropout handling stay exactly as they are.
ultimatum-game-firebase.htmlis the same game on Firebase. See Choosing a backend.
The data
Each player's data includes the multiplayer trials. From the proposer's browser (IDs shortened):
{ "trial_type": "multiplayer-role", "role": "proposer",
"role_map": { "031c…": { "role": "proposer" }, "dbad…": { "role": "responder" } },
"multiplayer_outcome": "completed", "left_participant": null,
"multiplayer_participant_id": "031c…", "multiplayer_session_id": "7f2e…" }
{ "trial_type": "multiplayer-sync", "wait_time": 2359,
"multiplayer_outcome": "completed", "left_participant": null,
"group": { "031c…": { "offer": 9 }, "dbad…": { "decision": "accept" } },
"multiplayer_participant_id": "031c…", "multiplayer_session_id": "7f2e…" }
The proposer's sync trial's group holds both the offer and the decision, so either player's
file is enough to score the round. role_map lets you check that both browsers agreed on the
roles. Every row carries multiplayer_participant_id and multiplayer_session_id, so you can
match up the files from the two players of each game.
Where to go next
- More rounds or more players. The rounds are ordinary jsPsych, so loop them with a
timeline variable, and put the round number in
multiplayer_scope. For more than two players, add roles toroles;participantsByRole()returns a list of IDs for each. - Talking before deciding. Add a
multiplayer-chattrial before the offer.
Reference
Güth, W., Schmittberger, R., & Schwarze, B. (1982). An experimental analysis of ultimatum bargaining. Journal of Economic Behavior & Organization, 3(4), 367–388.