Goal: Implement adaptive elements, like an AI opponent, that learn from and respond to participant behavior in real time.
This step teaches you to add sophisticated interactions to psychology experiments. You'll learn to implement adaptive algorithms, dynamic feedback, and intelligent opponents using research-validated approaches.
What You'll Learn:
This demo features an AI opponent that learns from your choices. The AI algorithm and learning rate are loaded from your Step 5 configuration. Can you beat an AI that adapts to your strategy?
Make your choice:
Ready to play! The AI will adapt its strategy as you play.
Configuration loaded from Step 5. AI algorithm and learning rate set.
Our RPS example uses adaptive AI opponents whose logic is based on published cognitive science research on human learning. The key achievement in this step is implementing a version of the ELPH algorithm, from a 2014 study on sequential decision-making, as a live opponent. While its primary scientific use is for data analysis (as you'll see in Step 7), using it here makes our experiment more dynamic and psychologically interesting.
This is the primary adaptive AI used in our demo. It's designed to find and exploit patterns in an opponent's behavior.
To appreciate the adaptive nature of ELPH, the demo also includes several simpler AIs. You can select these in your configuration from Step 5 to see how they perform differently.
This is where you combine the concepts from the previous steps to build the core of your own interactive experiment. The structure involves three main parts: loading your configuration (Step 5), handling participant input (from your UI in Step 3), and recording the data (in the format from Step 4).
The following sections break down the template for your own experiment.js file into logical pieces.
First, you need to set up the "memory" for your experiment. This code creates variables to keep track of the experiment's current state (like the trial number) and to hold the settings you load from your Step 5 configuration.
// Holds the dynamic state of the experiment (e.g., current trial number, score).
let experimentState = {
currentTrial: 0,
totalTrials: 30, // Default value, will be overwritten by config
data: [] // Holds all trial data, mirroring Step 4.
};
// Holds the static configuration loaded from Step 5.
let experimentConfig = {};
// Function to load settings from localStorage.
function loadExperimentConfig() {
const savedConfig = localStorage.getItem('experimentConfig'); // Use the key from Step 5
if (savedConfig) {
experimentConfig = JSON.parse(savedConfig);
experimentState.totalTrials = experimentConfig.numTrials;
console.log('📝 Configuration loaded:', experimentConfig);
} else {
console.log('No configuration found. Using defaults.');
}
}
This is the heart of your experiment. The runTrial function runs every time the participant does something, like clicking a button. Inside, it calls helper functions to get the computer's action, determine the outcome, and record the data before checking if the experiment should end.
// This function runs once per trial (e.g., each time the participant clicks a button).
function runTrial(participantResponse) {
// Get the computer's action for this trial (e.g., show an image, play a sound).
const computerAction = getComputerAction();
// Determine the outcome based on your experiment's rules.
const result = determineOutcome(participantResponse, computerAction);
// Record all data for this trial in a structured object.
const trialData = {
trial: experimentState.currentTrial,
participantAction: participantResponse,
computerAction: computerAction,
outcome: result,
timestamp: new Date().toISOString()
};
experimentState.data.push(trialData);
console.log(`Trial ${experimentState.currentTrial}:`, trialData);
// Update the UI to give the participant feedback.
updateUIAfterTrial(result);
// Check if the experiment is over.
experimentState.currentTrial++;
if (experimentState.currentTrial >= experimentState.totalTrials) {
endExperiment();
}
}
// This function determines what the computer does. It can be simple (show an image)
// or complex (have an AI make a strategic decision).
function getComputerAction() {
// This is a placeholder. You will customize this for your experiment.
// For example, you might return a value from your config file.
return 'some_computer_action';
}
This is the "glue" code. It defines placeholder functions for interacting with your HTML, like updating text or listening for button clicks. Finally, it kicks everything off by loading the configuration and setting up those listeners when the page loads.
// --- Helper Functions (connect to your HTML) ---
function determineOutcome(participantAction, computerAction) {
// TODO: Implement your experiment's logic here.
// For example, check if an answer is correct.
return 'some_outcome'; // Placeholder
}
function updateUIAfterTrial(result) {
// TODO: Update your HTML to show feedback.
}
function setupUIListeners() {
// TODO: Add event listeners to your interactive elements.
}
function endExperiment() {
console.log('Experiment complete.');
saveData();
}
function saveData() {
localStorage.setItem('experimentData', JSON.stringify(experimentState.data));
console.log('Data saved!', experimentState.data);
}
// --- Start the Experiment ---
// This is the entry point that kicks everything off.
loadExperimentConfig();
setupUIListeners();
Now that you have the three template parts in your experiment.js file, you can ask the AI to write the custom logic for your study. Instead of manually describing your goals, you will provide the AI with the files you have already created. This is the most powerful way to work with an AI assistant.
Make sure the following files are open in your editor, then copy the prompt below:
my-research-plan.md)index.html)experiment.js file containing the templates from this step.I am building a browser-based psychology experiment. Please complete the script in my open experiment.js file, which currently contains the three-part template from the Step 6 instructions.
Use the following files for context:
experimentConfig object in the script itself.Based on the context from these files, please implement the placeholder functions (getComputerAction, determineOutcome, updateUIAfterTrial, and setupUIListeners) to create a complete, working experiment.
Return only the complete, updated JavaScript code for my experiment.js file.
These interactive elements can be adapted for various psychology experiments: