Part 2: Configuring the Experiment

Configuring the task page

The main file that determines what is displayed to the participant (i.e., the user-side) during a game is located at /client/game/Round.jsx.
By default, this is divided into two main components, Task and SocialExposure. The Task itself is composed of TaskStimulus which contains the stimulus (e.g., a survey question — or in this example, an estimation task) and TaskResponse which contains the input for users to response to the stimulus.
Let's start by adding a title to the /client/game/Task.jx so that the component looks like this:
1
import React from "react";
2
3
import TaskResponse from "./TaskResponse";
4
import TaskStimulus from "./TaskStimulus";
5
6
export default class Task extends React.Component {
7
render() {
8
return (
9
<div className="task">
10
<h3 className="title">Task</h3>
11
<TaskStimulus {...this.props} />
12
<TaskResponse {...this.props} />
13
</div>
14
);
15
}
16
}
17
Copied!

Adding content to the task stimulus

React components have a this.props object which contains elements passed into it. These props can be extracted with destructuring (the const {} = this.props part). Notice that the props here include round, stage, and player. These are your interface with Empirica, and allow you to both read and set data for the state of the experiment.
All we're doing here is adding an image and question to the client/game/TaskStimulus.jsx so that it looks like this:
1
import React from "react";
2
3
export default class TaskStimulus extends React.Component {
4
render() {
5
const { round, stage, player } = this.props;
6
7
const imagePath = "/experiment/images/candies.jpg";
8
const questionText = "How many candies are in the jar?";
9
return (
10
<div className="task-stimulus">
11
<div className="task-image">
12
<img src={imagePath} height={"300px"} />
13
</div>
14
<div className="task-question">
15
<b>Please answer the following question:</b>
16
<br />
17
{questionText}
18
</div>
19
</div>
20
);
21
}
22
}
Copied!

Adding the candy jar image

You can download the candy jar image we use here.
Then, in the public directory, create the following directories: /experiment/images/ and add the candy jar image there so that it matches the path we just set: "/experiment/images/candies.jpg" .
The public directory allows you to store static assets, such as images, that can then be accessed on the client side.

Customizing the input field

In this section, we are going to change the input type from a slider to a numeric input box. To do so, go to the client/game/TaskResponse.jsx file.
You can see that there are some "handle" functions (they don't need to be named this way, but clear names are helpful) that will execute on certain events.
There are also different "render" functions that will be called further down in the main render based on different conditions (e.g., if the player has already submitted for this stage).
Change the renderSlider function. First let's change it's name to renderInput . Then, replace the slider with a numeric input box. Because we're asking people to estimate the number of candies in a jar, we'll set the minimum value to one.
1
renderInput() {
2
const { player } = this.props;
3
const value = player.round.get("value");
4
return (
5
<input
6
type={"number"}
7
min={1}
8
onChange={this.handleChange}
9
value={value}
10
required
11
/>
12
);
13
}
Copied!
We recommend adding additional form verification methods beyond the default to ensure a smooth user experience. Note that if you do choose to use a slider input, we strongly recommend using the Empirica slider, which is made with experimenters in mind — no default values that might create anchoring effects.
Notice that this method uses the player data to control the form input. This player data is created with player.round.set() in the handleChange method which is called every time the input is updated. This method will save this data to the database on the server, automagically.
The sliders and inputs don't send exactly the same data format, so we have to change the handleChange function to look like this:
1
handleChange = event => {
2
const value = Number(event.currentTarget.value);
3
const { player } = this.props;
4
player.round.set("value", value);
5
};
Copied!
Because we changed the name of the "render" function to renderInput we need to change this in the main render ; instead of calling this.renderSlider() it should be called this.renderInput().
1
render() {
2
const { player } = this.props;
3
4
// If the player already submitted, don't show the slider or submit button
5
if (player.stage.submitted) {
6
return this.renderSubmitted();
7
}
8
9
return (
10
<div className="task-response">
11
<form className="task-response-form" onSubmit={this.handleSubmit}>
12
{this.renderInput()}
13
14
<button type="submit">Submit</button>
15
</form>
16
</div>
17
);
18
}
Copied!
Careful with the brackets!
You might notice that a react component, like TaskResponse.jsx has a few import lines at the top of the file and then starts with this type of line and opening of curly brackets {}
1
export default class TaskResponse extends React.Component {
Copied!
This curly bracket will close on the last line of the file.
You will also notice that the main render of a component also opens curly brackets {} which close before those of the overall component.
So when you are changing the render of a component, careful not to delete the final bracket that closes the component, otherwise you will get an error such as '}' expected.
Overall, TaskResponse.jsx should look like this:
1
import React from "react";
2
3
export default class TaskResponse extends React.Component {
4
handleChange = event => {
5
const value = Number(event.currentTarget.value);
6
const { player } = this.props;
7
player.round.set("value", value);
8
};
9
10
handleSubmit = event => {
11
event.preventDefault();
12
this.props.player.stage.submit();
13
};
14
15
renderSubmitted() {
16
return (
17
<div className="task-response">
18
<div className="response-submitted">
19
<h5>Waiting on other players...</h5>
20
Please wait until all players are ready
21
</div>
22
</div>
23
);
24
}
25
26
renderInput() {
27
const { player } = this.props;
28
const value = player.round.get("value");
29
return (
30
<input
31
type={"number"}
32
min={1}
33
onChange={this.handleChange}
34
value={value}
35
required
36
/>
37
);
38
}
39
40
render() {
41
const { player } = this.props;
42
43
// If the player already submitted, don't show the slider or submit button
44
if (player.stage.submitted) {
45
return this.renderSubmitted();
46
}
47
48
return (
49
<div className="task-response">
50
<form className="task-response-form" onSubmit={this.handleSubmit}>
51
{this.renderInput()}
52
53
<button type="submit">Submit</button>
54
</form>
55
</div>
56
);
57
}
58
}
59
Copied!

Configuring stimulus content

The next step is to allow the experimenter to modify the stimulus without having to update the experiment code directly. We'll accomplish this by adding a JavaScript object to a constants.js file (the name of the file in itself is not important, as long as you are consistent), that will contain all the stimulus information, and then use that in the experiment via the Empirica.gameInit method.
This all happens server-side, so you need to create this file in your server/ directory instead of your client/ directory. Create a file server/constants.js, and add the following code to it.
1
export const taskData = {
2
candies: {
3
path: "/experiment/images/candies.jpg",
4
questionText:
5
"The jar in this image contains nothing but standard M&M's. How many M&M's are in the jar?",
6
correctAnswer: 797
7
},
8
survey: {
9
questionText:
10
"A 2014 survey asked Americans whether science and technology make our lives better (easier, healthier, more comfortable). What percentage of respondents agreed that science and technology are making our lives better?",
11
correctAnswer: 80.5
12
}
13
};
Copied!
The export keyword allows us to access this JavaScript object in another .js or .jsx file.

Using data from constants.js

Next, we need to use this data in the Empirica.gameInit callback in /server/main.js. This is an important event that sets up the rounds and stages of a game.
For more about the life cycle of an Empirica app and its callback, consult our guide.
You can see that this file has a few imports and then most of the code is within Empirica.gameInit. In gameInit, you can see that it is going through each player and assigns them some data such as a score and an avatar. Then it is doing something 10 times (using _times() from underscore.js; a library of convenient JavaScript tools): It is creating 10 rounds, each with one stage.
First, we import the constants.js data with import { taskData } from "./constants"; added to at the top of server/main.js.
We are going to create a network of players. We prepared a node for each player based on their position, and then we assign each player a set of "neighbors": Every possible node except a player's own node. This means this is a full network. Of course, you could create a different type of network if you wanted to. The neighbours will see each other's responses in a social stage we are going to create.
Replace the code in your server/main.js with the following code:
1
import Empirica from "meteor/empirica:core";
2
3
import "./callbacks.js";
4
import "./bots.js";
5
6
import { taskData } from "./constants";
7
8
// gameInit is where the structure of a game is defined.
9
// Just before every game starts, once all the players needed are ready, this
10
// function is called with the treatment and the list of players.
11
// You must then add rounds and stages to the game, depending on the treatment
12
// and the players. You can also get/set initial values on your game, players,
13
// rounds and stages (with get/set methods), that will be able to use later in
14
// the game.
15
Empirica.gameInit(game => {
16
// Establish node list
17
const nodes = [];
18
for (let i = 0; i <= game.players.length; i++) {
19
nodes.push(i);
20
}
21
22
game.players.forEach((player, i) => {
23
player.set("avatar", `/avatars/jdenticon/${player._id}`);
24
player.set("score", 0);
25
26
// Give each player a nodeId based on their position
27
player.set("nodeId", i);
28
29
// Assign each node as a neighbor
30
const networkNeighbors = nodes.filter(node => node !== i);
31
player.set("neighbors", networkNeighbors);
32
});
33
34
Object.keys(taskData).forEach(taskName => {
35
const task = taskData[taskName];
36
const round = game.addRound({
37
data: {
38
taskName: taskName,
39
questionText: task.questionText,
40
imagePath: task.path,
41
correctAnswer: task.correctAnswer
42
}
43
});
44
45
round.addStage({
46
name: "response",
47
displayName: "Response",
48
durationInSeconds: 120
49
});
50
})
51
52
});
53
Copied!
An important part of what is being done is here is adding a data object to the rounds. Any value in this object can then be access with round.get() .

Incorporating dynamic round data in TaskStimulus.jsx

Finally, we're ready to incorporate our new configurable task data into TaskStimulus.jsx
All we do is change the value of the constants to pull dynamically with round.get() instead of setting them manually. Replace the lines that declare the imagePath and the questionText with these:
1
const imagePath = round.get("imagePath");
2
const questionText = round.get("questionText");
Copied!
We also add logic so that we only display an image if a path is given:
1
<div className="task-image">
2
{imagePath && <img src={imagePath} height={"300px"} />}
3
</div>
Copied!
Overall, it should look like this:
1
import React from "react";
2
3
export default class TaskStimulus extends React.Component {
4
render() {
5
const { round, stage, player } = this.props;
6
7
const imagePath = round.get("imagePath");
8
const questionText = round.get("questionText");
9
return (
10
<div className="task-stimulus">
11
<div className="task-image">
12
{imagePath && <img src={imagePath} height={"300px"} />}
13
</div>
14
<div className="task-question">
15
<b>Please answer the following question:</b>
16
<br />
17
{questionText}
18
</div>
19
</div>
20
);
21
}
22
}
Copied!

Calculating player score with callbacks

Empirica provides a set of methods that will run at the start and end of each round and stage. These can be found in server/callbacks.js.
To learn more about callbacks, see our guide on the life cycle of an Empirica experiment.
By default, the score is equal to the total sum of responses, but this is not very informative. We'll modify this to show percentage of error subtracted from 1. Replace the Empirica.onRoundEnd code in server/callbacks.js with this:
1
// onRoundEnd is triggered after each round.
2
// It receives the same options as onGameEnd, and the round that just ended.
3
Empirica.onRoundEnd((game, round) => {
4
game.players.forEach(player => {
5
let value = player.round.get("value") || 0;
6
const prevScore = player.get("score") || 0;
7
let newScore = 1 - value / round.get("correctAnswer");
8
if (newScore < 0) newScore = 0;
9
player.set("score", prevScore + newScore);
10
});
11
});
Copied!
These scores are compared to the correctAnswer from our constants.js file.
Last modified 3mo ago