'use strict';
/* ═══════════════════════════════════════════════════════════
Интерактив «Системы и обратная связь» — 11 класс
Симуляция системы с визуализацией компонентов, связей и графика
═══════════════════════════════════════════════════════════ */
// Сценарии
const SCENARIOS = {
thermostat: {
name: 'Термостат',
components: [
{ id: 'sensor', label: 'Датчик', icon: '🌡️', x: 30, y: 100 },
{ id: 'controller', label: 'Термостат', icon: '🎛️', x: 200, y: 100 },
{ id: 'actuator', label: 'Обогреватель', icon: '🔥', x: 370, y: 100 },
],
connections: [
{ from: 'sensor', to: 'controller' },
{ from: 'controller', to: 'actuator' },
{ from: 'actuator', to: 'sensor' },
],
initialValue: 15,
targetValue: 22,
step: 0.4,
feedbackType: 'negative',
description: 'Температура в комнате (°C)',
minVal: 0,
maxVal: 50,
},
cooling: {
name: 'Охлаждение ПК',
components: [
{ id: 'sensor', label: 'Датчик CPU', icon: '🌡️', x: 30, y: 100 },
{ id: 'controller', label: 'Контроллер', icon: '🖥️', x: 200, y: 100 },
{ id: 'actuator', label: 'Вентилятор', icon: '💨', x: 370, y: 100 },
],
connections: [
{ from: 'sensor', to: 'controller' },
{ from: 'controller', to: 'actuator' },
{ from: 'actuator', to: 'sensor' },
],
initialValue: 85,
targetValue: 60,
step: 0.5,
feedbackType: 'negative',
description: 'Температура процессора (°C)',
minVal: 20,
maxVal: 120,
},
population: {
name: 'Популяция',
components: [
{ id: 'sensor', label: 'Наблюдение', icon: '🔭', x: 30, y: 100 },
{ id: 'controller', label: 'Модель роста', icon: '📊', x: 200, y: 100 },
{ id: 'actuator', label: 'Популяция', icon: '🦠', x: 370, y: 100 },
],
connections: [
{ from: 'sensor', to: 'controller' },
{ from: 'controller', to: 'actuator' },
{ from: 'actuator', to: 'sensor' },
],
initialValue: 10,
targetValue: 0,
step: 0.1,
feedbackType: 'positive',
description: 'Размер популяции',
minVal: 0,
maxVal: 1000,
},
};
let currentScenario = 'thermostat';
let running = false;
let animFrame = null;
let graphData = [];
let currentValue = 0;
let feedbackType = 'negative';
let lastTime = 0;
// DOM
const field = document.getElementById('sysField');
const svg = document.getElementById('sysSvg');
const componentsDiv = document.getElementById('sysComponents');
const statusEl = document.getElementById('sysStatus');
const graphCanvas = document.getElementById('sysGraph');
const ctx = graphCanvas.getContext('2d');
/* ═══════════════════════════════════════════════════════════
РЕНДЕР
═══════════════════════════════════════════════════════════ */
function renderComponents() {
const scenario = SCENARIOS[currentScenario];
componentsDiv.innerHTML = '';
svg.innerHTML = '';
// Рисуем связи
scenario.connections.forEach(conn => {
const fromComp = scenario.components.find(c => c.id === conn.from);
const toComp = scenario.components.find(c => c.id === conn.to);
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', fromComp.x + 60);
line.setAttribute('y1', fromComp.y + 40);
line.setAttribute('x2', toComp.x + 60);
line.setAttribute('y2', toComp.y + 40);
line.id = 'conn-' + conn.from + '-' + conn.to;
svg.appendChild(line);
});
// Рисуем компоненты
scenario.components.forEach(comp => {
const el = document.createElement('div');
el.className = 'sys-component';
el.id = 'comp-' + comp.id;
el.style.left = comp.x + 'px';
el.style.top = comp.y + 'px';
el.innerHTML = '
' + comp.icon + '
' + comp.label + '
';
componentsDiv.appendChild(el);
});
}
function renderGraph() {
const w = graphCanvas.width = graphCanvas.offsetWidth * 2;
const h = graphCanvas.height = graphCanvas.offsetHeight * 2;
ctx.clearRect(0, 0, w, h);
const scenario = SCENARIOS[currentScenario];
const minV = scenario.minVal;
const maxV = scenario.maxVal;
const range = maxV - minV || 1;
// Сетка
ctx.strokeStyle = 'rgba(106,169,255,.1)';
ctx.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = h - (i / 4) * h;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(w, y);
ctx.stroke();
}
// Целевая линия
if (scenario.targetValue > 0) {
const targetY = h - ((scenario.targetValue - minV) / range) * h;
ctx.strokeStyle = 'rgba(253,230,138,.4)';
ctx.lineWidth = 1;
ctx.setLineDash([6, 4]);
ctx.beginPath();
ctx.moveTo(0, targetY);
ctx.lineTo(w, targetY);
ctx.stroke();
ctx.setLineDash([]);
}
// Данные
if (graphData.length < 2) return;
ctx.strokeStyle = '#6aa9ff';
ctx.lineWidth = 2;
ctx.beginPath();
const step = w / (graphData.length - 1);
graphData.forEach((val, i) => {
const x = i * step;
const y = h - ((val - minV) / range) * h;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
// Последняя точка
if (graphData.length > 0) {
const lastVal = graphData[graphData.length - 1];
const lastX = (graphData.length - 1) * step;
const lastY = h - ((lastVal - minV) / range) * h;
ctx.fillStyle = '#4ade80';
ctx.beginPath();
ctx.arc(lastX, lastY, 4, 0, Math.PI * 2);
ctx.fill();
}
}
/* ═══════════════════════════════════════════════════════════
СИМУЛЯЦИЯ
═══════════════════════════════════════════════════════════ */
function simulate(timestamp) {
if (!running) return;
if (!lastTime) lastTime = timestamp;
const dt = (timestamp - lastTime) / 1000;
lastTime = timestamp;
const scenario = SCENARIOS[currentScenario];
let newValue = currentValue;
if (currentScenario === 'population') {
// Популяция: положительная связь = экспоненциальный рост, отрицательная = логистический рост
const rate = 0.5;
const capacity = 100;
if (feedbackType === 'positive') {
// Экспоненциальный рост
newValue = currentValue + currentValue * rate * dt;
} else {
// Логистический рост (отрицательная связь)
newValue = currentValue + currentValue * rate * (1 - currentValue / capacity) * dt;
}
} else {
// Термостат и охлаждение: управляем к цели
const diff = scenario.targetValue - currentValue;
const gain = 2.0;
if (feedbackType === 'negative') {
// Отрицательная связь — стремимся к цели
newValue = currentValue + diff * gain * dt;
} else {
// Положительная связь — уходим от цели
newValue = currentValue - diff * gain * dt;
}
}
// Ограничения
newValue = Math.max(scenario.minVal, Math.min(scenario.maxVal, newValue));
// Если популяция ушла за пределы — останавливаем
if (currentScenario === 'population' && newValue >= scenario.maxVal * 0.99) {
newValue = scenario.maxVal;
running = false;
statusEl.className = 'sys-status err';
statusEl.innerHTML = '⚠️ Система вышла из-под контроля! Популяция достигла максимума. Положительная обратная связь усилила рост до предела.';
}
currentValue = newValue;
graphData.push(currentValue);
// Ограничиваем график
if (graphData.length > 500) graphData.shift();
// Подсветка связей
scenario.connections.forEach(conn => {
const line = document.getElementById('conn-' + conn.from + '-' + conn.to);
if (line) line.classList.add('active');
});
// Подсветка компонентов
scenario.components.forEach(comp => {
const el = document.getElementById('comp-' + comp.id);
if (el) el.classList.add('active');
});
// Обновляем статус
const unit = currentScenario === 'population' ? '' : '°C';
const diff = scenario.targetValue - currentValue;
if (currentScenario !== 'population') {
if (Math.abs(diff) < 0.5) {
statusEl.className = 'sys-status ok';
statusEl.innerHTML = '✓ Равновесие! ' + scenario.description + ': ' + currentValue.toFixed(1) + unit + '. Система стабилизировалась.';
} else {
statusEl.className = 'sys-status';
const arrow = diff > 0 ? '↑' : '↓';
statusEl.innerHTML = scenario.description + ': ' + currentValue.toFixed(1) + unit + ' ' + arrow + ' (цель: ' + scenario.targetValue + unit + ')';
}
}
renderGraph();
animFrame = requestAnimationFrame(simulate);
}
/* ═══════════════════════════════════════════════════════════
ДЕЙСТВИЯ
═══════════════════════════════════════════════════════════ */
function startSim() {
if (running) return;
running = true;
lastTime = 0;
graphData = [];
const scenario = SCENARIOS[currentScenario];
currentValue = scenario.initialValue;
graphData.push(currentValue);
animFrame = requestAnimationFrame(simulate);
statusEl.className = 'sys-status';
statusEl.innerHTML = 'Симуляция запущена. ' + scenario.description + ': ' + currentValue.toFixed(1) + '.';
}
function stopSim() {
running = false;
if (animFrame) cancelAnimationFrame(animFrame);
statusEl.className = 'sys-status warn';
statusEl.innerHTML = 'Симуляция остановлена. ' + scenario.description + ': ' + currentValue.toFixed(1) + '.';
}
function resetSim() {
stopSim();
const scenario = SCENARIOS[currentScenario];
currentValue = scenario.initialValue;
graphData = [currentValue];
lastTime = 0;
renderGraph();
// Убираем подсветку
document.querySelectorAll('.sys-component').forEach(el => el.classList.remove('active'));
document.querySelectorAll('.sys-svg line').forEach(el => el.classList.remove('active'));
statusEl.className = 'sys-status';
statusEl.innerHTML = 'Сброс. ' + scenario.description + ': ' + currentValue.toFixed(1) + '. Нажмите «Запустить».';
}
function setFeedback(type) {
feedbackType = type;
document.getElementById('sysFeedbackNeg').style.background = type === 'negative' ? 'var(--accent)' : '';
document.getElementById('sysFeedbackNeg').style.color = type === 'negative' ? '#fff' : '';
document.getElementById('sysFeedbackPos').style.background = type === 'positive' ? 'var(--accent)' : '';
document.getElementById('sysFeedbackPos').style.color = type === 'positive' ? '#fff' : '';
statusEl.innerHTML = 'Тип обратной связи: ' + (type === 'negative' ? 'Отрицательная (стабилизация)' : 'Положительная (усиление)') + '.';
}
function switchScenario(name) {
currentScenario = name;
stopSim();
const scenario = SCENARIOS[name];
currentValue = scenario.initialValue;
graphData = [currentValue];
lastTime = 0;
feedbackType = scenario.feedbackType;
// Обновляем кнопки сценариев
document.querySelectorAll('.sys-scenario-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.scenario === name);
});
renderComponents();
renderGraph();
setFeedback(feedbackType);
statusEl.className = 'sys-status';
statusEl.innerHTML = 'Сценарий: ' + scenario.name + '. ' + scenario.description + ': ' + currentValue.toFixed(1) + '. Нажмите «Запустить».';
}
/* ═══════════════════════════════════════════════════════════
ИНИЦИАЛИЗАЦИЯ
═══════════════════════════════════════════════════════════ */
function init() {
document.getElementById('sysStart').addEventListener('click', startSim);
document.getElementById('sysStop').addEventListener('click', stopSim);
document.getElementById('sysReset').addEventListener('click', resetSim);
document.getElementById('sysFeedbackNeg').addEventListener('click', () => setFeedback('negative'));
document.getElementById('sysFeedbackPos').addEventListener('click', () => setFeedback('positive'));
document.querySelectorAll('.sys-scenario-btn').forEach(btn => {
btn.addEventListener('click', () => switchScenario(btn.dataset.scenario));
});
// Начальное состояние
switchScenario('thermostat');
setFeedback('negative');
}
// Ждём полной загрузки DOM + небольшой запас, чтобы header.js успел отрендерить хедер
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
setTimeout(init, 50);
});
} else {
setTimeout(init, 50);
}