康诺生命游戏
本代码由DeepSeek编写
复制进.txt并将后缀改为.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>
<style>
:root {
--bg: #0f0f1a;
--panel-bg: #1a1a2e;
--text: #e0e0e0;
--text-secondary: #a0a0b8;
--accent: #4cc9f0;
--accent2: #f72585;
--accent3: #06d6a0;
--btn-bg: #252540;
--btn-hover: #303058;
--border: rgba(255, 255, 255, 0.08);
--radius: 12px;
--radius-sm: 8px;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
background: var(--bg);
font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
user-select: none;
-webkit-user-select: none;
color: var(--text);
}
.toolbar {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 16px;
background: var(--panel-bg);
border-bottom: 1px solid var(--border);
flex-wrap: wrap;
z-index: 10;
min-height: 56px;
}
.brand { font-weight: 700; font-size: 1.1rem; color: var(--accent); }
.brand span { color: var(--accent2); }
.sep { width: 1px; height: 24px; background: var(--border); margin: 0 4px; }
.btn {
padding: 8px 14px;
border: 1px solid var(--border);
background: var(--btn-bg);
color: var(--text);
border-radius: var(--radius-sm);
cursor: pointer;
font-size: 0.9rem;
font-weight: 500;
transition: all 0.2s;
white-space: nowrap;
display: flex;
align-items: center;
gap: 5px;
font-family: inherit;
}
.btn:hover { background: var(--btn-hover); border-color: rgba(255,255,255,0.2); }
.btn.active {
background: var(--accent2);
border-color: var(--accent2);
color: #fff;
animation: pulse 1.8s infinite;
}
@keyframes pulse {
0%,100% { box-shadow: 0 0 0 0 rgba(247,37,133,0.5); }
50% { box-shadow: 0 0 0 10px rgba(247,37,133,0); }
}
.btn.accent { background: var(--accent); border-color: var(--accent); color: #000; font-weight: 600; }
.btn.accent:hover { background: #5dd5f5; }
.slider-group { display: flex; align-items: center; gap: 6px; font-size: 0.85rem; color: var(--text-secondary); }
.slider-group input[type="range"] { width: 80px; accent-color: var(--accent); height: 6px; }
.slider-group .val { color: var(--accent); font-weight: 600; min-width: 28px; text-align: center; font-size: 0.8rem; }
.info-badge { font-size: 0.8rem; color: var(--text-secondary); background: var(--btn-bg); padding: 5px 10px; border-radius: 20px; }
.info-badge strong { color: var(--accent3); }
.canvas-container {
flex: 1; position: relative; overflow: hidden; cursor: crosshair;
background: radial-gradient(ellipse at center, rgba(76,201,240,0.02) 0%, transparent 70%) var(--bg);
}
.canvas-container.grabbing { cursor: grabbing; }
canvas { display: block; position: absolute; top: 0; left: 0; }
.hint-bar {
position: absolute; bottom: 12px; left: 50%; transform: translateX(-50%);
font-size: 0.75rem; color: rgba(255,255,255,0.35); pointer-events: none;
text-align: center; letter-spacing: 0.03em; transition: opacity 0.5s;
}
.preset-panel { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
.preset-btn {
padding: 5px 10px; font-size: 0.75rem; border: 1px solid var(--border);
background: var(--btn-bg); color: var(--text-secondary); border-radius: 16px;
cursor: pointer; transition: all 0.2s; white-space: nowrap; font-family: inherit;
}
.preset-btn:hover { background: var(--btn-hover); color: #fff; }
@media (max-width: 768px) {
.toolbar { gap: 5px; padding: 8px 10px; }
.btn { padding: 6px 10px; font-size: 0.78rem; }
.slider-group input[type="range"] { width: 50px; }
}
</style>
</head>
<body>
<div class="toolbar">
<div class="brand">🔬 生命<span>游戏</span></div>
<div class="sep"></div>
<button class="btn accent" id="btnPlay">▶ 开始</button>
<button class="btn" id="btnStep">⏭ 步进</button>
<button class="btn" id="btnReset">🗑 清除</button>
<div class="sep"></div>
<div class="slider-group">
<label>⚡速度</label>
<input type="range" id="speedSlider" min="1" max="60" value="10">
<span class="val" id="speedVal">10</span>
</div>
<div class="sep"></div>
<div class="slider-group">
<label>🔍单元格</label>
<input type="range" id="cellSizeSlider" min="3" max="40" value="14">
<span class="val" id="cellSizeVal">14</span>px
</div>
<button class="btn small" id="btnGridToggle">📐 网格线</button>
<button class="btn small" id="btnFitView">🎯 居中</button>
<div class="sep"></div>
<span class="info-badge">代: <strong id="genCount">0</strong></span>
<span class="info-badge">细胞: <strong id="cellCount">0</strong></span>
</div>
<div style="display:flex;align-items:center;gap:6px;padding:6px 16px;background:var(--panel-bg);border-bottom:1px solid var(--border);flex-wrap:wrap;">
<span style="font-size:0.78rem;color:var(--text-secondary);">📦 预设:</span>
<button class="preset-btn" data-preset="glider">滑翔机</button>
<button class="preset-btn" data-preset="lwss">轻型飞船</button>
<button class="preset-btn" data-preset="pulsar">脉冲星</button>
<button class="preset-btn" data-preset="gosper">高斯机枪</button>
<button class="preset-btn" data-preset="rpent">R-五格</button>
<button class="preset-btn" data-preset="blinker">振荡器</button>
<button class="preset-btn" data-preset="block">方块</button>
<button class="preset-btn" data-preset="random" style="color:var(--accent2);">🎲 随机填充</button>
</div>
<div class="canvas-container" id="canvasContainer">
<canvas id="lifeCanvas"></canvas>
<div class="hint-bar" id="hintBar">🖱 点击放置/移除 | 按住拖拽平移 | 滚轮缩放 | 空格键 开始/暂停</div>
</div>
<script>
(function() {
const canvas = document.getElementById('lifeCanvas');
const ctx = canvas.getContext('2d');
const container = document.getElementById('canvasContainer');
const hintBar = document.getElementById('hintBar');
const btnPlay = document.getElementById('btnPlay');
const btnStep = document.getElementById('btnStep');
const btnReset = document.getElementById('btnReset');
const btnGridToggle = document.getElementById('btnGridToggle');
const btnFitView = document.getElementById('btnFitView');
const speedSlider = document.getElementById('speedSlider');
const speedVal = document.getElementById('speedVal');
const cellSizeSlider = document.getElementById('cellSizeSlider');
const cellSizeVal = document.getElementById('cellSizeVal');
const genCountEl = document.getElementById('genCount');
const cellCountEl = document.getElementById('cellCount');
let livingCells = new Set();
let generation = 0;
let isRunning = false;
let cellSize = 14;
let offsetX = 0, offsetY = 0;
let showGrid = true;
let speed = 10;
let lastStepTime = 0;
let animationId = null;
let needsRedraw = true;
let isDragging = false;
let dragStartX = 0, dragStartY = 0;
let dragStartOffsetX = 0, dragStartOffsetY = 0;
const DRAG_THRESHOLD = 5;
let boundMouseMove = null, boundMouseUp = null;
let boundTouchMove = null, boundTouchEnd = null;
const presets = {
glider: [[0,1],[1,2],[2,0],[2,1],[2,2]],
lwss: [[0,1],[0,4],[1,0],[2,0],[2,4],[3,0],[3,1],[3,2],[3,3]],
pulsar: [[2,4],[2,5],[2,6],[2,10],[2,11],[2,12],[4,2],[4,7],[4,9],[4,14],[5,2],[5,7],[5,9],[5,14],[6,2],[6,7],[6,9],[6,14],[7,4],[7,5],[7,6],[7,10],[7,11],[7,12],[9,4],[9,5],[9,6],[9,10],[9,11],[9,12],[10,2],[10,7],[10,9],[10,14],[11,2],[11,7],[11,9],[11,14],[12,2],[12,7],[12,9],[12,14],[14,4],[14,5],[14,6],[14,10],[14,11],[14,12]],
gosper: [[0,24],[1,22],[1,24],[2,12],[2,13],[2,20],[2,21],[2,34],[2,35],[3,11],[3,15],[3,20],[3,21],[3,34],[3,35],[4,0],[4,1],[4,10],[4,16],[4,20],[4,21],[5,0],[5,1],[5,10],[5,14],[5,16],[5,17],[5,22],[5,24],[6,10],[6,16],[6,24],[7,11],[7,15],[8,12],[8,13]],
rpent: [[0,1],[0,2],[1,0],[1,1],[2,1]],
blinker: [[0,0],[0,1],[0,2]],
block: [[0,0],[0,1],[1,0],[1,1]]
};
function cellKey(x,y) { return `${x},${y}`; }
function parseKey(k) { const [x,y]=k.split(',').map(Number); return {x,y}; }
function toggleCell(x,y) {
const key = cellKey(x,y);
if (livingCells.has(key)) { livingCells.delete(key); return false; }
else { livingCells.add(key); return true; }
}
function stepSimulation() {
const neighbor = new Map();
const cur = new Set(livingCells);
for (const key of cur) {
const {x,y} = parseKey(key);
for (let dx=-1; dx<=1; dx++) for (let dy=-1; dy<=1; dy++) {
if (dx===0 && dy===0) continue;
const nk = cellKey(x+dx, y+dy);
neighbor.set(nk, (neighbor.get(nk)||0)+1);
}
if (!neighbor.has(key)) neighbor.set(key,0);
}
const next = new Set();
for (const [k, n] of neighbor) {
const wasAlive = cur.has(k);
if ((wasAlive && (n===2||n===3)) || (!wasAlive && n===3)) next.add(k);
}
livingCells = next;
generation++;
needsRedraw = true;
}
function resizeCanvas() {
const rect = container.getBoundingClientRect();
const dpr = window.devicePixelRatio || 1;
const w = rect.width, h = rect.height;
if (canvas.width !== w*dpr || canvas.height !== h*dpr) {
canvas.width = w*dpr; canvas.height = h*dpr;
canvas.style.width = w+'px'; canvas.style.height = h+'px';
ctx.setTransform(1,0,0,1,0,0); ctx.scale(dpr,dpr);
needsRedraw = true;
}
return { width:w, height:h };
}
function screenToWorld(sx, sy, w, h) {
return {
x: Math.floor((sx - w/2)/cellSize + offsetX),
y: Math.floor((sy - h/2)/cellSize + offsetY)
};
}
function render() {
const {width, height} = resizeCanvas();
ctx.clearRect(0,0,width,height);
ctx.fillStyle = '#0f0f1a'; ctx.fillRect(0,0,width,height);
const visCols = Math.ceil(width/cellSize)+2;
const visRows = Math.ceil(height/cellSize)+2;
const sx = Math.floor(offsetX - visCols/2)-1;
const sy = Math.floor(offsetY - visRows/2)-1;
const ex = sx+visCols+2, ey = sy+visRows+2;
if (showGrid && cellSize>=5) {
ctx.strokeStyle = 'rgba(255,255,255,0.035)'; ctx.lineWidth = 0.5; ctx.beginPath();
for (let wx=Math.floor(sx); wx<=ex; wx++) {
const screenX = (wx-offsetX)*cellSize + width/2;
if (screenX>=-cellSize && screenX<=width+cellSize) { ctx.moveTo(screenX,0); ctx.lineTo(screenX,height); }
}
for (let wy=Math.floor(sy); wy<=ey; wy++) {
const screenY = (wy-offsetY)*cellSize + height/2;
if (screenY>=-cellSize && screenY<=height+cellSize) { ctx.moveTo(0,screenY); ctx.lineTo(width,screenY); }
}
ctx.stroke();
}
const drawSize = Math.max(cellSize-1,1);
const radius = cellSize>8 ? Math.min(cellSize*0.28,6) : (cellSize>5?1.5:0);
const visible = [];
for (const key of livingCells) {
const {x,y} = parseKey(key);
if (x>=sx && x<=ex && y>=sy && y<=ey) {
const screenX = (x-offsetX)*cellSize + width/2;
const screenY = (y-offsetY)*cellSize + height/2;
if (screenX>-cellSize*2 && screenX<width+cellSize*2 && screenY>-cellSize*2 && screenY<height+cellSize*2) {
visible.push({sx:screenX, sy:screenY});
}
}
}
if (visible.length) {
if (cellSize<=4 || radius===0) {
ctx.fillStyle = '#4cc9f0';
for (const {sx,sy} of visible) ctx.fillRect(Math.floor(sx)+0.5, Math.floor(sy)+0.5, Math.max(drawSize,2), Math.max(drawSize,2));
} else if (cellSize<=7) {
ctx.fillStyle = '#4cc9f0';
for (const {sx,sy} of visible) {
const x=Math.floor(sx)+0.5, y=Math.floor(sy)+0.5, s=drawSize, r=radius;
ctx.beginPath(); ctx.moveTo(x+r,y); ctx.lineTo(x+s-r,y); ctx.arcTo(x+s,y,x+s,y+r,r); ctx.lineTo(x+s,y+s-r); ctx.arcTo(x+s,y+s,x+s-r,y+s,r); ctx.lineTo(x+r,y+s); ctx.arcTo(x,y+s,x,y+s-r,r); ctx.lineTo(x,y+r); ctx.arcTo(x,y,x+r,y,r); ctx.closePath(); ctx.fill();
}
} else {
ctx.shadowColor = 'rgba(76,201,240,0.6)'; ctx.shadowBlur = cellSize*0.45;
ctx.fillStyle = '#4cc9f0';
for (const {sx,sy} of visible) {
const x=Math.floor(sx)+0.5, y=Math.floor(sy)+0.5, s=drawSize, r=radius;
ctx.beginPath(); ctx.moveTo(x+r,y); ctx.lineTo(x+s-r,y); ctx.arcTo(x+s,y,x+s,y+r,r); ctx.lineTo(x+s,y+s-r); ctx.arcTo(x+s,y+s,x+s-r,y+s,r); ctx.lineTo(x+r,y+s); ctx.arcTo(x,y+s,x,y+s-r,r); ctx.lineTo(x,y+r); ctx.arcTo(x,y,x+r,y,r); ctx.closePath(); ctx.fill();
}
ctx.shadowColor = 'transparent'; ctx.shadowBlur = 0;
if (cellSize>=14) {
ctx.fillStyle = 'rgba(180,235,255,0.7)';
for (const {sx,sy} of visible) {
ctx.beginPath(); ctx.arc(Math.floor(sx)+cellSize/2, Math.floor(sy)+cellSize/2, cellSize*0.22, 0, Math.PI*2); ctx.fill();
}
}
}
}
genCountEl.textContent = generation;
cellCountEl.textContent = livingCells.size;
needsRedraw = false;
}
function gameLoop(ts) {
if (!ts) ts = performance.now();
if (isRunning) {
const interval = 1000/speed;
if (ts - lastStepTime >= interval) {
let steps = 0;
while (ts - lastStepTime >= interval && steps < 5) {
stepSimulation(); lastStepTime += interval; steps++;
}
if (steps>=5) lastStepTime = ts;
}
}
if (needsRedraw) render();
animationId = requestAnimationFrame(gameLoop);
}
function updatePlayButton() {
btnPlay.textContent = isRunning ? '⏸ 暂停' : '▶ 开始';
btnPlay.classList.toggle('active', isRunning);
}
function updateSliders() {
speedVal.textContent = speed; speedSlider.value = speed;
cellSizeVal.textContent = cellSize; cellSizeSlider.value = cellSize;
btnGridToggle.textContent = showGrid ? '📐 网格线' : '📐 网格线(关)';
btnGridToggle.style.opacity = showGrid ? '1' : '0.6';
needsRedraw = true;
}
function resetView() { offsetX = 0; offsetY = 0; needsRedraw = true; }
function clearAll() {
livingCells.clear(); generation = 0; lastStepTime = performance.now(); needsRedraw = true;
if (isRunning) { isRunning = false; updatePlayButton(); }
}
function placePreset(name) {
if (name === 'random') {
const {width, height} = resizeCanvas();
const cols = Math.ceil(width/cellSize)+2, rows = Math.ceil(height/cellSize)+2;
const sx = Math.floor(offsetX - cols/2), sy = Math.floor(offsetY - rows/2);
const candidates = [];
for (let x=sx; x<sx+cols; x++) for (let y=sy; y<sy+rows; y++) candidates.push([x,y]);
const target = Math.floor(candidates.length*0.3);
for (let i=0; i<target; i++) {
const j = i + Math.floor(Math.random()*(candidates.length-i));
[candidates[i], candidates[j]] = [candidates[j], candidates[i]];
}
livingCells.clear();
for (let i=0; i<target; i++) livingCells.add(cellKey(candidates[i][0], candidates[i][1]));
} else {
const p = presets[name];
if (!p) return;
let minX=Infinity, minY=Infinity, maxX=-Infinity, maxY=-Infinity;
for (const [x,y] of p) { minX=Math.min(minX,x); minY=Math.min(minY,y); maxX=Math.max(maxX,x); maxY=Math.max(maxY,y); }
const ox = Math.round(offsetX) - Math.floor((maxX-minX+1)/2) - minX;
const oy = Math.round(offsetY) - Math.floor((maxY-minY+1)/2) - minY;
livingCells.clear();
for (const [x,y] of p) livingCells.add(cellKey(ox+x, oy+y));
}
generation = 0; lastStepTime = performance.now(); needsRedraw = true;
}
function getCanvasPos(e) {
const rect = canvas.getBoundingClientRect();
return { x: e.clientX - rect.left, y: e.clientY - rect.top };
}
function startDrag(pos) {
isDragging = false;
dragStartX = pos.x; dragStartY = pos.y;
dragStartOffsetX = offsetX; dragStartOffsetY = offsetY;
container.classList.add('grabbing');
}
function moveDrag(pos) {
if (!container.classList.contains('grabbing')) return;
const dx = pos.x - dragStartX, dy = pos.y - dragStartY;
if (!isDragging && Math.hypot(dx, dy) > DRAG_THRESHOLD) isDragging = true;
if (isDragging) {
offsetX = dragStartOffsetX - dx/cellSize;
offsetY = dragStartOffsetY - dy/cellSize;
needsRedraw = true;
}
}
function endDrag(pos, isTouch = false) {
container.classList.remove('grabbing');
if (!isDragging) {
const {width, height} = resizeCanvas();
const w = screenToWorld(pos.x, pos.y, width, height);
toggleCell(w.x, w.y);
needsRedraw = true;
}
isDragging = false;
if (!isTouch) {
if (boundMouseMove) { document.removeEventListener('mousemove', boundMouseMove); boundMouseMove = null; }
if (boundMouseUp) { document.removeEventListener('mouseup', boundMouseUp); boundMouseUp = null; }
} else {
if (boundTouchMove) { window.removeEventListener('touchmove', boundTouchMove); boundTouchMove = null; }
if (boundTouchEnd) { window.removeEventListener('touchend', boundTouchEnd); boundTouchEnd = null; }
}
}
canvas.addEventListener('mousedown', e => {
if (e.button !== 0) return;
e.preventDefault();
const pos = getCanvasPos(e);
startDrag(pos);
boundMouseMove = ev => { ev.preventDefault(); moveDrag(getCanvasPos(ev)); };
boundMouseUp = ev => { ev.preventDefault(); endDrag(getCanvasPos(ev), false); };
document.addEventListener('mousemove', boundMouseMove);
document.addEventListener('mouseup', boundMouseUp);
});
canvas.addEventListener('touchstart', e => {
e.preventDefault();
if (e.touches.length === 1) {
const t = e.touches[0];
const pos = { x: t.clientX - canvas.getBoundingClientRect().left, y: t.clientY - canvas.getBoundingClientRect().top };
startDrag(pos);
boundTouchMove = ev => {
ev.preventDefault();
if (ev.touches.length === 1) {
const ct = ev.touches[0];
moveDrag({ x: ct.clientX - canvas.getBoundingClientRect().left, y: ct.clientY - canvas.getBoundingClientRect().top });
}
};
boundTouchEnd = ev => {
ev.preventDefault();
let lastPos;
if (ev.changedTouches.length) {
const ct = ev.changedTouches[0];
lastPos = { x: ct.clientX - canvas.getBoundingClientRect().left, y: ct.clientY - canvas.getBoundingClientRect().top };
} else lastPos = { x: dragStartX, y: dragStartY };
endDrag(lastPos, true);
};
window.addEventListener('touchmove', boundTouchMove, { passive: false });
window.addEventListener('touchend', boundTouchEnd);
}
}, { passive: false });
// --- 修复后的滚轮缩放 ---
canvas.addEventListener('wheel', e => {
e.preventDefault();
const pos = getCanvasPos(e);
const {width, height} = resizeCanvas();
const worldBefore = screenToWorld(pos.x, pos.y, width, height);
let newCellSize;
if (e.deltaY < 0) {
// 放大:确保至少 +1
newCellSize = Math.min(40, cellSize + 1);
// 也可以使用更平滑的缩放,但必须确保变化
// newCellSize = Math.min(40, Math.ceil(cellSize * 1.12));
} else {
// 缩小:确保至少 -1
newCellSize = Math.max(3, cellSize - 1);
// newCellSize = Math.max(3, Math.floor(cellSize / 1.12));
}
if (newCellSize !== cellSize) {
cellSize = newCellSize;
const worldAfter = screenToWorld(pos.x, pos.y, width, height);
offsetX += worldBefore.x - worldAfter.x;
offsetY += worldBefore.y - worldAfter.y;
updateSliders();
}
}, { passive: false });
document.addEventListener('keydown', e => {
if (e.code === 'Space') { e.preventDefault(); isRunning = !isRunning; if(isRunning) lastStepTime=performance.now(); updatePlayButton(); needsRedraw=true; }
else if (e.code === 'KeyS' && !e.ctrlKey) { if(!isRunning){ stepSimulation(); lastStepTime=performance.now(); } }
else if (e.code === 'KeyR') clearAll();
else if (e.code === 'KeyG') { showGrid = !showGrid; updateSliders(); }
else if (e.code === 'KeyF') resetView();
else if (e.code.startsWith('Arrow')) {
e.preventDefault();
const step = 5/cellSize;
if (e.code === 'ArrowUp') offsetY -= step;
else if (e.code === 'ArrowDown') offsetY += step;
else if (e.code === 'ArrowLeft') offsetX -= step;
else if (e.code === 'ArrowRight') offsetX += step;
needsRedraw = true;
}
});
btnPlay.addEventListener('click', () => { isRunning = !isRunning; if(isRunning) lastStepTime=performance.now(); updatePlayButton(); needsRedraw=true; });
btnStep.addEventListener('click', () => { if(!isRunning){ stepSimulation(); lastStepTime=performance.now(); } });
btnReset.addEventListener('click', clearAll);
btnGridToggle.addEventListener('click', () => { showGrid = !showGrid; updateSliders(); });
btnFitView.addEventListener('click', resetView);
speedSlider.addEventListener('input', () => { speed = +speedSlider.value; updateSliders(); if(isRunning) lastStepTime=performance.now(); });
cellSizeSlider.addEventListener('input', () => { cellSize = +cellSizeSlider.value; updateSliders(); });
document.querySelectorAll('.preset-btn').forEach(b => b.addEventListener('click', () => placePreset(b.dataset.preset)));
window.addEventListener('resize', () => { resizeCanvas(); needsRedraw=true; });
setTimeout(() => hintBar.style.opacity='0', 10000);
canvas.addEventListener('pointermove', () => { hintBar.style.opacity='0.7'; clearTimeout(canvas._ht); canvas._ht=setTimeout(()=>hintBar.style.opacity='0',3000); });
// 启动
resizeCanvas();
updateSliders();
updatePlayButton();
placePreset('glider');
generation = 0;
lastStepTime = performance.now();
animationId = requestAnimationFrame(gameLoop);
})();
</script>
</body>
</html>