用HTML做
- User
用HTML做
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
用HTML做
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
好的,我们来用 HTML、CSS 和 JavaScript 实现一个可视化页面,展示蚂蚁找食物的算法。
这个实现将包括:
index.html): 页面结构,包含一个 canvas 元素用于绘图,以及一些控制按钮和信息显示。style.css): 样式,让页面看起来更美观。script.js): 核心算法逻辑(蚁群优化)、绘制逻辑和用户交互。index.html (主页面结构)<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>蚂蚁寻食模拟 - 蚁群优化</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>蚂蚁寻食模拟</h1>
<div class="container">
<div class="controls">
<div class="param-group">
<label for="gridSize">网格大小:</label>
<input type="number" id="gridSize" value="30" min="10" max="100">
</div>
<div class="param-group">
<label for="numAnts">蚂蚁数量:</label>
<input type="number" id="numAnts" value="50" min="1" max="200">
</div>
<div class="param-group">
<label for="maxStepsPerAnt">蚂蚁最大步数:</label>
<input type="number" id="maxStepsPerAnt" value="150" min="20" max="500">
</div>
<div class="param-group">
<label for="numIterations">总迭代次数:</label>
<input type="number" id="numIterations" value="200" min="10" max="1000">
</div>
<div class="param-group">
<label for="pheromoneDecay">信息素挥发率 (0-1):</label>
<input type="range" id="pheromoneDecay" min="0.01" max="0.2" step="0.01" value="0.05">
<span id="pheromoneDecayValue">0.05</span>
</div>
<div class="param-group">
<label for="pheromoneDeposit">信息素沉积量:</label>
<input type="number" id="pheromoneDeposit" value="50" min="1" max="200">
</div>
<div class="param-group">
<label for="alpha">信息素权重 (α):</label>
<input type="range" id="alpha" min="0" max="5" step="0.1" value="1.0">
<span id="alphaValue">1.0</span>
</div>
<div class="param-group">
<label for="beta">启发信息权重 (β):</label>
<input type="range" id="beta" min="0" max="5" step="0.1" value="2.0">
<span id="betaValue">2.0</span>
</div>
<div class="param-group">
<label for="randomExploreFactor">随机探索因子:</label>
<input type="range" id="randomExploreFactor" min="0" max="0.5" step="0.01" value="0.1">
<span id="randomExploreFactorValue">0.1</span>
</div>
<div class="param-group">
<label for="animationSpeed">动画速度 (ms/帧):</label>
<input type="range" id="animationSpeed" min="10" max="200" step="10" value="50">
<span id="animationSpeedValue">50</span>
</div>
<button id="startBtn">开始模拟</button>
<button id="stopBtn">停止模拟</button>
<button id="resetBtn">重置并生成新地图</button>
<div class="info">
<p>当前迭代: <span id="currentIteration">0</span> / <span id="totalIterations">0</span></p>
<p>最佳路径长度: <span id="bestPathLength">∞</span></p>
<p>找到食物的蚂蚁: <span id="antsFoundFood">0</span> / <span id="totalAnts">0</span></p>
</div>
<p class="legend">图例:</p>
<div class="legend-item">
<div class="color-box" style="background-color: rgb(51, 51, 204);"></div> 蚁巢 (Nest)
</div>
<div class="legend-item">
<div class="color-box" style="background-color: rgb(51, 204, 51);"></div> 食物 (Food)
</div>
<div class="legend-item">
<div class="color-box" style="background-color: rgb(25, 25, 25);"></div> 障碍物 (Obstacle)
</div>
<div class="legend-item">
<div class="color-box" style="background-color: rgb(200, 200, 200);"></div> 空白区域 (Pheromone)
</div>
<div class="legend-item">
<div class="color-box" style="background-color: purple;"></div> 蚂蚁 (Ant)
</div>
<div class="legend-item">
<div class="color-box" style="background-color: red; border: 1px dashed black;"></div> 最佳路径
</div>
</div>
<canvas id="acoCanvas"></canvas>
</div>
<script src="script.js"></script>
</body>
</html>
style.css (样式表)body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
background-color: #f0f0f0;
margin: 0;
padding: 20px;
}
h1 {
color: #333;
margin-bottom: 20px;
}
.container {
display: flex;
gap: 30px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.controls {
display: flex;
flex-direction: column;
gap: 15px;
width: 280px; /* 固定控制面板宽度 */
padding-right: 20px;
border-right: 1px solid #eee;
}
.param-group {
display: flex;
flex-direction: column;
gap: 5px;
}
.param-group label {
font-weight: bold;
color: #555;
}
.param-group input[type="number"],
.param-group input[type="range"] {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
.param-group input[type="range"] + span {
font-size: 0.9em;
color: #777;
text-align: right;
}
button {
padding: 10px 15px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1em;
transition: background-color 0.2s ease;
}
button:hover {
background-color: #0056b3;
}
button:active {
background-color: #00408f;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.info {
margin-top: 15px;
padding: 10px;
background-color: #e9f7ff;
border: 1px solid #cceeff;
border-radius: 4px;
}
.info p {
margin: 5px 0;
font-size: 0.95em;
color: #333;
}
#acoCanvas {
background-color: #eee;
border: 1px solid #ccc;
display: block;
box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.1);
}
.legend {
margin-top: 15px;
font-weight: bold;
color: #555;
margin-bottom: 5px;
}
.legend-item {
display: flex;
align-items: center;
margin-bottom: 5px;
font-size: 0.9em;
color: #666;
}
.color-box {
width: 15px;
height: 15px;
border: 1px solid #aaa;
margin-right: 8px;
border-radius: 3px;
}
script.js (JavaScript 逻辑)// --- 常量定义 ---
const CELL_EMPTY = 0;
const CELL_NEST = 1;
const CELL_FOOD = 2;
const CELL_OBSTACLE = 3;
const CELL_COLORS = {
[CELL_EMPTY]: 'rgb(245, 245, 245)', // Light Gray (background for pheromones)
[CELL_NEST]: 'rgb(51, 51, 204)', // Blue
[CELL_FOOD]: 'rgb(51, 204, 51)', // Green
[CELL_OBSTACLE]: 'rgb(25, 25, 25)' // Black
};
const ANT_COLOR = 'purple';
const BEST_PATH_COLOR = 'red';
// --- DOM 元素获取 ---
const canvas = document.getElementById('acoCanvas');
const ctx = canvas.getContext('2d');
const gridSizeInput = document.getElementById('gridSize');
const numAntsInput = document.getElementById('numAnts');
const maxStepsPerAntInput = document.getElementById('maxStepsPerAnt');
const numIterationsInput = document.getElementById('numIterations');
const pheromoneDecayInput = document.getElementById('pheromoneDecay');
const pheromoneDecayValueSpan = document.getElementById('pheromoneDecayValue');
const pheromoneDepositInput = document.getElementById('pheromoneDeposit');
const alphaInput = document.getElementById('alpha');
const alphaValueSpan = document.getElementById('alphaValue');
const betaInput = document.getElementById('beta');
const betaValueSpan = document.getElementById('betaValue');
const randomExploreFactorInput = document.getElementById('randomExploreFactor');
const randomExploreFactorValueSpan = document.getElementById('randomExploreFactorValue');
const animationSpeedInput = document.getElementById('animationSpeed');
const animationSpeedValueSpan = document.getElementById('animationSpeedValue');
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');
const currentIterationSpan = document.getElementById('currentIteration');
const totalIterationsSpan = document.getElementById('totalIterations');
const bestPathLengthSpan = document.getElementById('bestPathLength');
const antsFoundFoodSpan = document.getElementById('antsFoundFood');
const totalAntsSpan = document.getElementById('totalAnts');
// --- 全局变量 ---
let CELL_SIZE = 0; // 每个单元格的像素大小
let simulationInterval = null; // 用于控制动画循环的 interval ID
let simulator = null; // ACOSimulator 实例
// --- Ant 类 ---
class Ant {
constructor(startPos, maxSteps) {
this.startPos = startPos;
this.currentPos = { r: startPos.r, c: startPos.c };
this.path = [{ r: startPos.r, c: startPos.c }]; // 记录走过的路径
this.foundFood = false; // 是否找到食物
this.steps = 0;
this.maxSteps = maxSteps;
this.visited = new Set(); // 用于当前蚂蚁避免立即回头或原地打转
this.visited.add(`${startPos.r},${startPos.c}`);
}
reset() {
this.currentPos = { r: this.startPos.r, c: this.startPos.c };
this.path = [{ r: this.startPos.r, c: this.startPos.c }];
this.foundFood = false;
this.steps = 0;
this.visited.clear();
this.visited.add(`${this.startPos.r},${this.startPos.c}`);
}
move(grid, pheromoneMap, foodPos, params) {
if (this.foundFood || this.steps >= this.maxSteps) {
return false; // 蚂蚁已经完成任务或达到最大步数
}
const { r, c } = this.currentPos;
const height = grid.length;
const width = grid[0].length;
const neighbors = [];
// 尝试上下左右四个方向
const directions = [{ dr: 0, dc: 1 }, { dr: 0, dc: -1 }, { dr: 1, dc: 0 }, { dr: -1, dc: 0 }];
for (const dir of directions) {
const nr = r + dir.dr;
const nc = c + dir.dc;
// 检查边界和障碍物
if (nr >= 0 && nr < height && nc >= 0 && nc < width && grid[nr][nc] !== CELL_OBSTACLE) {
// 避免立即回头 (除非没有其他选择)
if (this.path.length > 1 && this.path[this.path.length - 2].r === nr && this.path[this.path.length - 2].c === nc) {
continue;
}
// 避免走已经走过的格子,除非是食物点
if (this.visited.has(`${nr},${nc}`) && grid[nr][nc] !== CELL_FOOD) {
continue;
}
neighbors.push({ r: nr, c: nc });
}
}
if (neighbors.length === 0) {
// 蚂蚁被困住,重置(本次寻路失败)
this.foundFood = false;
return false;
}
// 计算选择每个邻居的概率
let probabilities = [];
let totalAttractiveness = 0;
for (const neighbor of neighbors) {
const pheromoneStrength = Math.pow(pheromoneMap[neighbor.r][neighbor.c], params.alpha);
// 启发信息 (距离食物的倒数)
let heuristic = 1.0;
const distToFood = Math.sqrt(Math.pow(neighbor.r - foodPos.r, 2) + Math.pow(neighbor.c - foodPos.c, 2));
if (distToFood === 0) { // 到达食物点
heuristic = 100.0; // 给予非常高的启发信息
} else {
heuristic = 1.0 / distToFood; // 距离越近,启发信息越高
}
const heuristicStrength = Math.pow(heuristic, params.beta);
const attractiveness = pheromoneStrength * heuristicStrength;
probabilities.push(attractiveness);
totalAttractiveness += attractiveness;
}
// 概率归一化
if (totalAttractiveness === 0) {
// 如果所有路径吸引力都为0,随机选择
probabilities = Array(neighbors.length).fill(1.0 / neighbors.length);
} else {
probabilities = probabilities.map(p => p / totalAttractiveness);
}
// 引入随机探索因子
let chosenIdx;
if (Math.random() < params.randomExploreFactor) {
chosenIdx = Math.floor(Math.random() * neighbors.length);
} else {
// 根据概率选择下一个位置
const rand = Math.random();
let cumulativeProbability = 0;
for (let i = 0; i < probabilities.length; i++) {
cumulativeProbability += probabilities[i];
if (rand <= cumulativeProbability) {
chosenIdx = i;
break;
}
}
}
const nextPos = neighbors[chosenIdx];
this.currentPos = nextPos;
this.path.push(nextPos);
this.steps++;
this.visited.add(`${nextPos.r},${nextPos.c}`);
// 检查是否找到食物
if (grid[nextPos.r][nextPos.c] === CELL_FOOD) {
this.foundFood = true;
return true;
}
return false;
}
}
// --- ACOSimulator 类 ---
class ACOSimulator {
constructor(height, width, numAnts, maxStepsPerAnt, params) {
this.height = height;
this.width = width;
this.numAnts = numAnts;
this.maxStepsPerAnt = maxStepsPerAnt;
this.params = params; // alpha, beta, pheromoneDecay, pheromoneDeposit, randomExploreFactor
this.grid = [];
this.pheromoneMap = [];
this.nestPos = { r: 1, c: 1 };
this.foodPos = { r: height - 2, c: width - 2 };
this.ants = [];
this.bestPath = null;
this.bestPathLength = Infinity;
this.currentIteration = 0;
this.maxIterations = params.numIterations;
this.activeAnts = []; // 追踪当前迭代中仍在移动的蚂蚁
this.antsFinishedThisIteration = 0; // 统计当前迭代中已完成的蚂蚁数量
this.frameCounter = 0; // 动画帧计数器
this.interval = null; // 用于 requestAnimationFrame 的 ID
this.initGrid();
this.initAnts();
}
initGrid() {
this.grid = Array(this.height).fill(0).map(() => Array(this.width).fill(CELL_EMPTY));
this.pheromoneMap = Array(this.height).fill(0).map(() => Array(this.width).fill(0.1)); // 初始信息素浓度
this.grid[this.nestPos.r][this.nestPos.c] = CELL_NEST;
this.grid[this.foodPos.r][this.foodPos.c] = CELL_FOOD;
this.addObstacles();
}
initAnts() {
this.ants = [];
for (let i = 0; i < this.numAnts; i++) {
this.ants.push(new Ant(this.nestPos, this.maxStepsPerAnt));
}
this.activeAnts = [...this.ants]; // 所有蚂蚁都是活跃的
this.antsFinishedThisIteration = 0;
}
addObstacles() {
// 边界障碍
for (let i = 0; i < this.height; i++) {
this.grid[i][0] = CELL_OBSTACLE;
this.grid[i][this.width - 1] = CELL_OBSTACLE;
}
for (let j = 0; j < this.width; j++) {
this.grid[0][j] = CELL_OBSTACLE;
this.grid[this.height - 1][j] = CELL_OBSTACLE;
}
// 随机生成一些障碍物(避免覆盖巢穴和食物)
const numObstacles = Math.floor(this.height * this.width * 0.15); // 约15%的格子是障碍
for (let i = 0; i < numObstacles; i++) {
let r, c;
do {
r = Math.floor(Math.random() * this.height);
c = Math.floor(Math.random() * this.width);
} while (this.grid[r][c] !== CELL_EMPTY ||
(r === this.nestPos.r && c === this.nestPos.c) ||
(r === this.foodPos.r && c === this.foodPos.c) ||
// 确保巢穴和食物周围有通路
(Math.abs(r - this.nestPos.r) < 3 && Math.abs(c - this.nestPos.c) < 3) ||
(Math.abs(r - this.foodPos.r) < 3 && Math.abs(c - this.foodPos.c) < 3));
this.grid[r][c] = CELL_OBSTACLE;
}
// 确保巢穴和食物点是可达的
// (更高级的迷宫生成算法可以保证连通性,这里简单地随机生成,可能出现不可达情况)
}
_depositPheromone(path, pathLength) {
if (pathLength === 0) return;
// 路径越短,沉积的信息素越多
const depositAmount = this.params.pheromoneDeposit / pathLength;
for (const pos of path) {
if (this.grid[pos.r][pos.c] !== CELL_OBSTACLE) {
this.pheromoneMap[pos.r][pos.c] += depositAmount;
// 限制信息素上限,防止数值过大
this.pheromoneMap[pos.r][pos.c] = Math.min(this.pheromoneMap[pos.r][pos.c], 100.0);
}
}
}
_evaporatePheromone() {
for (let r = 0; r < this.height; r++) {
for (let c = 0; c < this.width; c++) {
this.pheromoneMap[r][c] *= (1 - this.params.pheromoneDecay);
// 确保信息素有一个最小基础值,避免完全消失
this.pheromoneMap[r][c] = Math.max(this.pheromoneMap[r][c], 0.01);
}
}
}
start() {
if (this.interval) return; // 防止重复启动
startBtn.disabled = true;
resetBtn.disabled = true;
stopBtn.disabled = false;
this.setParamInputsDisabled(true);
this.animationLoop();
}
stop() {
if (this.interval) {
cancelAnimationFrame(this.interval);
this.interval = null;
}
startBtn.disabled = false;
resetBtn.disabled = false;
stopBtn.disabled = true;
this.setParamInputsDisabled(false);
}
setParamInputsDisabled(disabled) {
gridSizeInput.disabled = disabled;
numAntsInput.disabled = disabled;
maxStepsPerAntInput.disabled = disabled;
numIterationsInput.disabled = disabled;
pheromoneDecayInput.disabled = disabled;
pheromoneDepositInput.disabled = disabled;
alphaInput.disabled = disabled;
betaInput.disabled = disabled;
randomExploreFactorInput.disabled = disabled;
// animationSpeedInput.disabled = disabled; // 动画速度可以随时调整
}
animationLoop() {
this.frameCounter++;
// 每隔 animationSpeed 毫秒执行一次逻辑更新和绘制
if (this.frameCounter * this.params.animationSpeed < (this.params.animationSpeed === 0 ? 0 : 1000/60)) { // 确保每帧至少执行一次,或按设置的速度执行
this.interval = requestAnimationFrame(() => this.animationLoop());
return;
}
this.frameCounter = 0;
// 如果所有蚂蚁都已完成本轮移动,则进入下一迭代
if (this.antsFinishedThisIteration >= this.numAnts || this.currentIteration >= this.maxIterations) {
// 所有蚂蚁都在本轮完成了任务或达到最大步数
this.currentIteration++;
// 信息素挥发
this._evaporatePheromone();
// 重置所有蚂蚁为下一轮做准备
for (const ant of this.ants) {
ant.reset();
}
this.activeAnts = [...this.ants]; // 重新激活所有蚂蚁
this.antsFinishedThisIteration = 0;
if (this.currentIteration > this.maxIterations) {
this.stop();
console.log("Simulation finished.");
this.draw(); // 最终绘制
this.updateStatus();
return;
}
}
// 让蚂蚁移动一步
for (let i = this.activeAnts.length - 1; i >= 0; i--) {
const ant = this.activeAnts[i];
if (!ant.foundFood && ant.steps < ant.maxSteps) {
const foundFood = ant.move(this.grid, this.pheromoneMap, this.foodPos, this.params);
if (foundFood) {
const pathLength = ant.path.length - 1; // 路径长度是步数
this._depositPheromone(ant.path, pathLength);
if (pathLength < this.bestPathLength) {
this.bestPathLength = pathLength;
this.bestPath = ant.path.slice(); // 复制一份路径
}
this.antsFinishedThisIteration++;
// 从活跃蚂蚁列表中移除已找到食物的蚂蚁,以提高性能
this.activeAnts.splice(i, 1);
} else if (ant.steps >= ant.maxSteps) {
// 达到最大步数但未找到食物,也视为本轮完成
this.antsFinishedThisIteration++;
this.activeAnts.splice(i, 1); // 移除
}
} else if (ant.foundFood) {
// 已经找到食物的蚂蚁,并且已经处理过信息素沉积
// 但可能还在activeAnts中,确保被移除
this.activeAnts.splice(i, 1);
}
}
this.draw();
this.updateStatus();
this.interval = requestAnimationFrame(() => setTimeout(() => this.animationLoop(), this.params.animationSpeed));
}
draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制网格和信息素
let maxPheromone = 0.1;
for (let r = 0; r < this.height; r++) {
for (let c = 0; c < this.width; c++) {
maxPheromone = Math.max(maxPheromone, this.pheromoneMap[r][c]);
}
}
for (let r = 0; r < this.height; r++) {
for (let c = 0; c < this.width; c++) {
const cellType = this.grid[r][c];
let color = CELL_COLORS[cellType];
if (cellType === CELL_EMPTY) {
// 根据信息素浓度调整颜色
const pheromone = this.pheromoneMap[r][c];
const normalizedPheromone = pheromone / maxPheromone; // 归一化到 0-1
// 越高的信息素,颜色越接近黄色/红色
const rComp = 255;
const gComp = Math.floor(255 * (1 - normalizedPheromone * 0.8)); // 红色越多,绿色越少
const bComp = Math.floor(255 * (1 - normalizedPheromone * 0.8)); // 红色越多,蓝色越少
color = `rgb(${rComp}, ${gComp}, ${bComp})`;
}
ctx.fillStyle = color;
ctx.fillRect(c * CELL_SIZE, r * CELL_SIZE, CELL_SIZE, CELL_SIZE);
// 绘制网格线
ctx.strokeStyle = '#ccc';
ctx.lineWidth = 0.5;
ctx.strokeRect(c * CELL_SIZE, r * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
// 绘制蚁巢和食物(确保它们在信息素之上可见)
ctx.fillStyle = CELL_COLORS[CELL_NEST];
ctx.fillRect(this.nestPos.c * CELL_SIZE, this.nestPos.r * CELL_SIZE, CELL_SIZE, CELL_SIZE);
ctx.fillStyle = CELL_COLORS[CELL_FOOD];
ctx.fillRect(this.foodPos.c * CELL_SIZE, this.foodPos.r * CELL_SIZE, CELL_SIZE, CELL_SIZE);
// 绘制蚂蚁
ctx.fillStyle = ANT_COLOR;
for (const ant of this.ants) {
if (!ant.foundFood && ant.steps < ant.maxSteps) { // 只绘制仍在移动的蚂蚁
const centerX = ant.currentPos.c * CELL_SIZE + CELL_SIZE / 2;
const centerY = ant.currentPos.r * CELL_SIZE + CELL_SIZE / 2;
ctx.beginPath();
ctx.arc(centerX, centerY, CELL_SIZE * 0.3, 0, Math.PI * 2); // 蚂蚁画成小圆
ctx.fill();
}
}
// 绘制最佳路径
if (this.bestPath) {
ctx.strokeStyle = BEST_PATH_COLOR;
ctx.lineWidth = 2;
ctx.setLineDash([5, 5]); // 虚线
ctx.beginPath();
ctx.moveTo(this.bestPath[0].c * CELL_SIZE + CELL_SIZE / 2, this.bestPath[0].r * CELL_SIZE + CELL_SIZE / 2);
for (let i = 1; i < this.bestPath.length; i++) {
ctx.lineTo(this.bestPath[i].c * CELL_SIZE + CELL_SIZE / 2, this.bestPath[i].r * CELL_SIZE + CELL_SIZE / 2);
}
ctx.stroke();
ctx.setLineDash([]); // 恢复实线
}
}
updateStatus() {
currentIterationSpan.textContent = this.currentIteration;
totalIterationsSpan.textContent = this.maxIterations;
bestPathLengthSpan.textContent = this.bestPathLength === Infinity ? '∞' : this.bestPathLength;
antsFoundFoodSpan.textContent = this.ants.filter(ant => ant.foundFood).length;
totalAntsSpan.textContent = this.numAnts;
}
}
// --- 初始化和事件监听 ---
function initializeSimulator() {
const params = {
gridSize: parseInt(gridSizeInput.value),
numAnts: parseInt(numAntsInput.value),
maxStepsPerAnt: parseInt(maxStepsPerAntInput.value),
numIterations: parseInt(numIterationsInput.value),
pheromoneDecay: parseFloat(pheromoneDecayInput.value),
pheromoneDeposit: parseFloat(pheromoneDepositInput.value),
alpha: parseFloat(alphaInput.value),
beta: parseFloat(betaInput.value),
randomExploreFactor: parseFloat(randomExploreFactorInput.value),
animationSpeed: parseInt(animationSpeedInput.value)
};
CELL_SIZE = Math.floor(500 / params.gridSize); // Canvas width/height is 500px, so calculate cell size
canvas.width = params.gridSize * CELL_SIZE;
canvas.height = params.gridSize * CELL_SIZE;
simulator = new ACOSimulator(params.gridSize, params.gridSize, params.numAnts, params.maxStepsPerAnt, params);
simulator.draw();
simulator.updateStatus();
console.log("Simulator initialized.");
}
// 绑定事件监听器
startBtn.addEventListener('click', () => simulator.start());
stopBtn.addEventListener('click', () => simulator.stop());
resetBtn.addEventListener('click', () => {
simulator.stop(); // 停止当前模拟(如果有)
initializeSimulator(); // 重新初始化
});
// 参数变化时更新显示值
pheromoneDecayInput.addEventListener('input', (e) => {
pheromoneDecayValueSpan.textContent = parseFloat(e.target.value).toFixed(2);
if (simulator) simulator.params.pheromoneDecay = parseFloat(e.target.value);
});
alphaInput.addEventListener('input', (e) => {
alphaValueSpan.textContent = parseFloat(e.target.value).toFixed(1);
if (simulator) simulator.params.alpha = parseFloat(e.target.value);
});
betaInput.addEventListener('input', (e) => {
betaValueSpan.textContent = parseFloat(e.target.value).toFixed(1);
if (simulator) simulator.params.beta = parseFloat(e.target.value);
});
randomExploreFactorInput.addEventListener('input', (e) => {
randomExploreFactorValueSpan.textContent = parseFloat(e.target.value).toFixed(2);
if (simulator) simulator.params.randomExploreFactor = parseFloat(e.target.value);
});
animationSpeedInput.addEventListener('input', (e) => {
animationSpeedValueSpan.textContent = parseInt(e.target.value);
if (simulator) simulator.params.animationSpeed = parseInt(e.target.value);
});
// 页面加载完成后初始化模拟器
document.addEventListener('DOMContentLoaded', initializeSimulator);
ant_simulation)。index.html、style.css、script.js。index.html 文件。<canvas>):
开始模拟: 启动模拟。停止模拟: 暂停模拟。重置并生成新地图: 停止当前模拟,清除所有数据,并生成一个新的随机地图和蚂蚁。setTimeout 配合 requestAnimationFrame 来控制每一步的视觉刷新速度,确保流畅性。pheromoneDecay (信息素挥发率): 越高,旧路径的信息素消失越快,利于探索新路径,但可能忘记好路径。pheromoneDeposit (信息素沉积量): 越高,找到食物的路径信息素积累越快,引导性越强。alpha (信息素权重): 越高,蚂蚁越倾向于选择信息素浓度高的路径(利用)。beta (启发信息权重): 越高,蚂蚁越倾向于选择看起来更接近食物的路径(探索)。randomExploreFactor (随机探索因子): 越高,蚂蚁越可能随机选择路径,有助于跳出局部最优。这个可视化版本应该能很好地帮助你理解蚁群优化算法的原理。