can you please write in a single html file a simple call center model discrete…
- User
can you please write in a single html file a simple call center model discrete simulation that shows process steps, the time and a "real time" simulation that can be sped up? Thanks
Assistant
Okay, here is a single HTML file containing a simple discrete event simulation of a call center.
Key Features:
- HTML Structure: Sets up the display areas for controls, parameters, simulation status, and the event log.
- CSS Styling: Basic styling to make it readable.
- JavaScript Logic:
- Parameters: Number of agents, average arrival rate (calls/minute), average service time (seconds).
- Simulation Clock: Tracks simulation time in seconds.
- State Variables: Tracks available agents, calls in queue, calls currently being handled.
- Event Logic (Simplified Time-Stepped):
- Call Arrival: Uses a probability based on the arrival rate for each time step. (Approximates a Poisson process for simplicity).
- Service Start: Assigns waiting calls to available agents.
- Service Completion: Frees up agents when their service duration ends. Uses an exponential distribution for service times.
- Real-Time Simulation: Uses
setIntervalto run the simulation steps. - Speed Control: A slider allows changing the interval between simulation steps, speeding up or slowing down the visual simulation.
- Logging: Outputs key events (arrival, service start, service end) to a text area.
- Controls: Start, Pause, Reset buttons.
How it Works:
- The simulation advances in discrete time steps (defaulting to 1 simulation second per step).
- In each step, it checks if a new call arrives, if any ongoing calls finish, and if any waiting calls can be assigned to newly free agents.
- The "real time" aspect comes from the
setIntervaldelay. A shorter delay makes the simulation run faster relative to wall-clock time.
The Code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Call Center Simulation</title> <style> body { font-family: sans-serif; display: flex; flex-direction: column; align-items: center; padding: 20px; background-color: #f4f4f4; } .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); width: 90%; max-width: 800px; display: grid; grid-template-columns: 1fr 1fr; gap: 20px; } .controls, .parameters, .status, .log-container { grid-column: span 1; } .log-container { grid-column: span 2; } h1, h2 { text-align: center; color: #333; margin-top: 0; } h2 { border-bottom: 1px solid #eee; padding-bottom: 5px; margin-bottom: 15px; } .control-buttons button, .parameters button { padding: 8px 15px; margin: 5px; cursor: pointer; border: none; border-radius: 4px; font-size: 1em; } .control-buttons button#start-button { background-color: #4CAF50; color: white; } .control-buttons button#pause-button { background-color: #ff9800; color: white; } .control-buttons button#reset-button { background-color: #f44336; color: white; } .parameters label { display: block; margin-bottom: 5px; font-weight: bold; } .parameters input[type=number] { width: 60px; padding: 5px; margin-bottom: 10px; } .parameters button { background-color: #2196F3; color: white; } .speed-control label { display: block; margin-bottom: 5px; font-weight: bold; } .speed-control input[type=range] { width: 100%; cursor: pointer; } .status p { background-color: #e7f3fe; border-left: 4px solid #2196F3; padding: 10px; margin: 10px 0; font-size: 1.1em; } .status span { font-weight: bold; color: #333; } #log { width: 100%; height: 250px; border: 1px solid #ccc; padding: 10px; font-family: monospace; font-size: 0.9em; overflow-y: scroll; background-color: #fdfdfd; box-sizing: border-box; /* Include padding in width */ } /* Make controls stack on smaller screens */ @media (max-width: 600px) { .container { grid-template-columns: 1fr; /* Stack elements */ } .controls, .parameters, .status, .log-container { grid-column: span 1; } } </style> </head> <body> <h1>Simple Call Center Simulation</h1> <div class="container"> <div class="parameters"> <h2>Parameters</h2> <label for="num-agents">Number of Agents:</label> <input type="number" id="num-agents" value="3" min="1"> <label for="arrival-rate">Avg. Arrival Rate (calls/min):</label> <input type="number" id="arrival-rate" value="5" min="0.1" step="0.1"> <label for="service-time">Avg. Service Time (seconds):</label> <input type="number" id="service-time" value="30" min="1"> <button id="update-params-button">Update Parameters (Resets Sim)</button> </div> <div class="controls"> <h2>Controls</h2> <div class="control-buttons"> <button id="start-button">Start</button> <button id="pause-button" disabled>Pause</button> <button id="reset-button">Reset</button> </div> <div class="speed-control"> <label for="speed-slider">Simulation Speed:</label> <input type="range" id="speed-slider" min="1" max="100" value="50"> <span id="speed-value">Medium</span> </div> </div> <div class="status"> <h2>Status</h2> <p>Simulation Time: <span id="sim-time">0</span> s</p> <p>Agents Available: <span id="agents-available">0</span> / <span id="total-agents">0</span></p> <p>Calls in Queue: <span id="queue-length">0</span></p> <p>Calls in Service: <span id="calls-in-service">0</span></p> <p>Total Calls Arrived: <span id="total-calls-arrived">0</span></p> <p>Total Calls Handled: <span id="total-calls-handled">0</span></p> <!-- <p>Avg Wait Time: <span id="avg-wait-time">0.0</span> s</p> --> </div> <div class="log-container"> <h2>Event Log</h2> <textarea id="log" readonly></textarea> </div> </div> <script> // --- DOM Elements --- const numAgentsInput = document.getElementById('num-agents'); const arrivalRateInput = document.getElementById('arrival-rate'); const serviceTimeInput = document.getElementById('service-time'); const updateParamsButton = document.getElementById('update-params-button'); const startButton = document.getElementById('start-button'); const pauseButton = document.getElementById('pause-button'); const resetButton = document.getElementById('reset-button'); const speedSlider = document.getElementById('speed-slider'); const speedValueSpan = document.getElementById('speed-value'); const simTimeSpan = document.getElementById('sim-time'); const agentsAvailableSpan = document.getElementById('agents-available'); const totalAgentsSpan = document.getElementById('total-agents'); const queueLengthSpan = document.getElementById('queue-length'); const callsInServiceSpan = document.getElementById('calls-in-service'); const totalCallsArrivedSpan = document.getElementById('total-calls-arrived'); const totalCallsHandledSpan = document.getElementById('total-calls-handled'); // const avgWaitTimeSpan = document.getElementById('avg-wait-time'); const logTextArea = document.getElementById('log'); // --- Simulation State Variables --- let simulationTime = 0; // in seconds let numAgents = 3; let arrivalRatePerMin = 5; // calls per minute let avgServiceTime = 30; // seconds let availableAgents = 0; let callQueue = []; // Stores arrival times of calls waiting let callsInProgress = []; // Stores objects { agentId: number, callArrivalTime: number, serviceEndTime: number } let nextAgentId = 0; // Simple way to assign agents let totalCallsArrived = 0; let totalCallsHandled = 0; // let totalWaitTime = 0; // For avg wait time calculation let simulationIntervalId = null; let simStepMillis = 200; // Milliseconds between simulation steps (controls visual speed) const SIM_TIME_STEP = 1; // How many simulation seconds pass in one step // --- Simulation Logic --- function logEvent(message) { const timeStr = simulationTime.toFixed(0).padStart(6, ' '); logTextArea.value += `[${timeStr}s] ${message}\n`; logTextArea.scrollTop = logTextArea.scrollHeight; // Auto-scroll } // Simple Exponential Distribution for Service Time function generateServiceTime() { // Ensure avgServiceTime is positive to avoid issues with log(0) or negative results const safeAvgServiceTime = Math.max(1, avgServiceTime); // Use Math.random() in range (0, 1] to avoid log(0) = -Infinity return -safeAvgServiceTime * Math.log(1 - Math.random() + Number.EPSILON); } // Check for new arrivals based on rate (Simplified Poisson approximation) function checkArrivals() { const arrivalRatePerSecond = arrivalRatePerMin / 60.0; const probabilityOfArrival = arrivalRatePerSecond * SIM_TIME_STEP; if (Math.random() < probabilityOfArrival) { totalCallsArrived++; const arrivalTime = simulationTime; callQueue.push(arrivalTime); logEvent(`Call #${totalCallsArrived} arrived.`); } } // Check if any calls in progress have finished function checkCompletions() { const now = simulationTime; const stillInProgress = []; let agentsFreed = 0; callsInProgress.forEach(call => { if (now >= call.serviceEndTime) { agentsFreed++; totalCallsHandled++; // const waitTime = call.serviceStartTime - call.callArrivalTime; // totalWaitTime += waitTime; logEvent(`Agent ${call.agentId} finished call (arrived at ${call.callArrivalTime.toFixed(0)}s). Service time: ${(call.serviceEndTime - call.serviceStartTime).toFixed(1)}s.`); } else { stillInProgress.push(call); } }); callsInProgress = stillInProgress; availableAgents += agentsFreed; } // Assign calls from queue to available agents function assignCalls() { while (availableAgents > 0 && callQueue.length > 0) { availableAgents--; const callArrivalTime = callQueue.shift(); // Get the oldest call const serviceStartTime = simulationTime; const serviceDuration = generateServiceTime(); const serviceEndTime = serviceStartTime + serviceDuration; const agentId = nextAgentId++; // Assign a unique ID for logging callsInProgress.push({ agentId: agentId, callArrivalTime: callArrivalTime, serviceStartTime: serviceStartTime, serviceEndTime: serviceEndTime }); logEvent(`Agent ${agentId} started serving call (arrived at ${callArrivalTime.toFixed(0)}s). Est. end: ${serviceEndTime.toFixed(0)}s.`); } } // The main simulation step function simulationStep() { simulationTime += SIM_TIME_STEP; // 1. Check for completed calls (freeing up agents) checkCompletions(); // 2. Check for new call arrivals checkArrivals(); // 3. Assign queued calls to newly available agents assignCalls(); // 4. Update the display updateDisplay(); } // Update the HTML display elements function updateDisplay() { simTimeSpan.textContent = simulationTime.toFixed(0); agentsAvailableSpan.textContent = availableAgents; totalAgentsSpan.textContent = numAgents; queueLengthSpan.textContent = callQueue.length; callsInServiceSpan.textContent = callsInProgress.length; totalCallsArrivedSpan.textContent = totalCallsArrived; totalCallsHandledSpan.textContent = totalCallsHandled; // const avgWait = totalCallsHandled > 0 ? (totalWaitTime / totalCallsHandled).toFixed(1) : "0.0"; // avgWaitTimeSpan.textContent = avgWait; } // --- Control Functions --- function startSimulation() { if (simulationIntervalId === null) { // Only start if not already running logEvent("Simulation started."); startButton.disabled = true; pauseButton.disabled = false; updateParamsButton.disabled = true; // Disable param updates while running numAgentsInput.disabled = true; arrivalRateInput.disabled = true; serviceTimeInput.disabled = true; simulationIntervalId = setInterval(simulationStep, simStepMillis); } } function pauseSimulation() { if (simulationIntervalId !== null) { clearInterval(simulationIntervalId); simulationIntervalId = null; logEvent("Simulation paused."); startButton.disabled = false; pauseButton.disabled = true; updateParamsButton.disabled = false; // Re-enable param updates when paused numAgentsInput.disabled = false; arrivalRateInput.disabled = false; serviceTimeInput.disabled = false; } } function resetSimulation() { pauseSimulation(); // Stop interval if running // Reset state variables simulationTime = 0; numAgents = parseInt(numAgentsInput.value) || 1; arrivalRatePerMin = parseFloat(arrivalRateInput.value) || 1; avgServiceTime = parseFloat(serviceTimeInput.value) || 1; availableAgents = numAgents; callQueue = []; callsInProgress = []; nextAgentId = 0; totalCallsArrived = 0; totalCallsHandled = 0; // totalWaitTime = 0; // Reset UI logTextArea.value = ""; updateDisplay(); // Show initial state logEvent("Simulation reset."); logEvent(`Parameters: Agents=${numAgents}, ArrivalRate=${arrivalRatePerMin}/min, AvgService=${avgServiceTime}s`); // Ensure buttons are in correct state startButton.disabled = false; pauseButton.disabled = true; updateParamsButton.disabled = false; numAgentsInput.disabled = false; arrivalRateInput.disabled = false; serviceTimeInput.disabled = false; // Ensure initial display is correct after reset totalAgentsSpan.textContent = numAgents; agentsAvailableSpan.textContent = availableAgents; } function updateSpeed() { const speedVal = parseInt(speedSlider.value); // Map slider value (1-100) to millisecond interval (e.g., 1000ms down to 10ms) // Use an inverse or exponential scale for better feel const minMillis = 10; const maxMillis = 1000; // Linear mapping (inverted): simStepMillis = maxMillis - ((speedVal - 1) / 99) * (maxMillis - minMillis); // Exponential mapping (inverted): simStepMillis = Math.round(maxMillis * Math.pow((minMillis / maxMillis), (speedVal - 1) / 99)); // Update speed label if (speedVal < 20) speedValueSpan.textContent = "Very Slow"; else if (speedVal < 40) speedValueSpan.textContent = "Slow"; else if (speedVal < 60) speedValueSpan.textContent = "Medium"; else if (speedVal < 80) speedValueSpan.textContent = "Fast"; else speedValueSpan.textContent = "Very Fast"; // If simulation is running, clear and reset interval with new speed if (simulationIntervalId !== null) { clearInterval(simulationIntervalId); simulationIntervalId = setInterval(simulationStep, simStepMillis); } // Log speed change? Optional. // logEvent(`Simulation speed changed (Interval: ${simStepMillis}ms)`); } // --- Event Listeners --- startButton.addEventListener('click', startSimulation); pauseButton.addEventListener('click', pauseSimulation); resetButton.addEventListener('click', resetSimulation); updateParamsButton.addEventListener('click', resetSimulation); // Updating params forces reset speedSlider.addEventListener('input', updateSpeed); // --- Initial Setup --- window.addEventListener('load', () => { updateSpeed(); // Set initial speed text resetSimulation(); // Initialize state and display }); </script> </body> </html>How to Use:
- Save the code above as an HTML file (e.g.,
call_center_sim.html). - Open the file in your web browser.
- Adjust Parameters: Change the number of agents, arrival rate, and service time if desired. Click "Update Parameters" (this will reset the simulation).
- Control:
- Click "Start" to begin the simulation.
- Click "Pause" to halt it temporarily.
- Click "Reset" to stop and reset to initial conditions.
- Speed: Use the slider to control how fast the simulation clock advances relative to real time. Move it right for faster, left for slower.
- Observe: Watch the status section update and follow the process steps in the Event Log.
This provides a basic but functional visualization of call center dynamics like queue buildup and agent utilization based on the input parameters.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.