Step 6: Interactive Elements

Goal: Implement adaptive elements, like an AI opponent, that learn from and respond to participant behavior in real time.

🎯 Goal: Implement Interactive Experiment Components

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:

⭐ Our Example: Rock-Paper-Scissors with an Adaptive AI

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?

Player 0
AI 0
Ties 0
Round 1 of 30

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.

📚 AI Opponents for Experiments

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.

🧠 ELPH (Exploitative Learning of Pattern and Heuristics)

This is the primary adaptive AI used in our demo. It's designed to find and exploit patterns in an opponent's behavior.

  • How it works: It tracks the history of your moves to find patterns (e.g., "Rock is often followed by Paper"). It then predicts your next move based on these statistical patterns and chooses the direct counter.
  • Research Parameters: Its behavior is controlled by `memoryLength` (how many past moves to consider for a pattern, typically 1-3) from your Step 5 configuration.
  • Psychology: This models how people learn to anticipate others' actions by recognizing their habits and tendencies.

⚙️ Other AI Models for Comparison

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.

  • Random: Chooses a move completely at random.
  • Biased Random: Can be configured to prefer certain moves over others.
  • Counter: Assumes you will repeat your last move and plays the counter to it.
  • Frequency Counter: Plays the move that would have beaten your most frequent past choice.

For more technical details on the algorithms, you can review the AI algorithm implementation notes or inspect the code files directly, like elph-ai.js.

🏗️ Putting It All Together: Your Experiment Logic

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.

Part 1: Initializing the Experiment

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.'); } }

Part 2: The Core Trial Logic

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'; }

Part 3: Connecting the UI and Starting the Experiment

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();

🤖 Generate Your Full Experiment Script with AI

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:

  • Your research plan from Step 0 (e.g., my-research-plan.md)
  • Your experiment's HTML file (e.g., index.html)
  • Your experiment.js file containing the templates from this step.
AI Prompt: Complete Experiment Script

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:

  • My research plan, which outlines the study's goal, the participant's task, and what defines an outcome, is in @[your-research-plan.md].
  • My UI, including the necessary HTML elements, is defined in @[your-index.html].
  • My experimental parameters from Step 5 are loaded into the 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.

🔬 Psychology Applications

These interactive elements can be adapted for various psychology experiments:

🎯 Decision-Making Studies

  • Strategic Thinking: How do people adapt to intelligent opponents?
  • Risk Assessment: Adaptive difficulty based on risk tolerance
  • Learning Curves: Track how quickly people learn optimal strategies

🧠 Learning & Memory Studies

  • Adaptive Testing: Difficulty adjusts to maintain optimal challenge
  • Spaced Repetition: AI determines optimal review timing
  • Forgetting Curves: Dynamic scheduling based on memory performance

⚡ Attention & Performance Studies

  • Vigilance Tasks: AI varies signal frequency to maintain attention
  • Workload Management: Adaptive task difficulty prevents overload
  • Flow States: AI maintains optimal challenge-skill balance

✅ Step 6 Checklist