Skip to content
TheChatArchiveThe Chat Archive
Googlegemma-3-27b-it· GoogleHugging Face LMArena Human Preference 140K

改进代码: [code]

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with DeepSeekdeepseek-v3-0324’s answer.
  1. User

    改进代码:

    <!DOCTYPE html>
    <html lang="zh">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>六边形文明扩张与生产</title>
    <style>
    	:root {
    		--bg:#fff; --border:#333; --center:#f00; --connect:#00f;
    		--player:#4285f4; --ai:#ea4335; --neutral:#9e9e9e; --selection:#FFD700;
    	}
    	body {
    		margin:0; font-family:sans-serif; 
    		display:flex; flex-direction:row; 
    		padding:0; background:#f5f5f5;
    		height:100vh;
    		overflow:hidden;
    	}
    	#ui { 
    		display:flex; 
    		height:100vh;
    		overflow-y:auto;
    		width:300px;
    		background:#fff;
    		box-shadow:2px 0 5px rgba(0,0,0,0.1);
    	}
    	#panel {
    		width:100%; display:flex; flex-direction:column; gap:.5rem;
    		padding:.75rem;
    		section {
    		background:#fff; border-radius:8px; box-shadow:0 0 5px #0001; padding:.75rem;
    		h3 { margin:.2rem 0; font-size:1rem }
    		}
    	}
    	#game-container {
    		flex:1;
    		display:flex;
    		flex-direction:column;
    		align-items:center;
    		padding:1rem;
    		overflow:auto;
    	}
    	label { font-size:.8rem }
    	input[type=range] { width:100% }
    	button {
    		padding:.4rem .6rem; border:0; border-radius:4px; 
    		background:#4caf50; color:#fff; cursor:pointer;
    		&:disabled { opacity:0.6 }
    	}
    	.stat {
    		display:inline-block; padding:.2rem .5rem; border-radius:4px; 
    		color:#fff; font-weight:700; font-size:.8rem;
    		&#pStat { background:var(--player) }
    		&#aStat { background:var(--ai) }
    		&#nStat { background:var(--neutral); color:#000 }
    	}
    	.res-line { font-size:.9rem }
    	#msg { min-height:1.5em; font-weight:700; margin-top:.5rem }
    	#actionPanel { min-height:2.5em; display:flex; flex-wrap:wrap; gap:.3rem }
    	.territory-percentage {
    		margin-top: 0.5rem;
    		font-size: 0.9rem;
    		.progress-bar {
    			height: 10px;
    			background: #ddd;
    			border-radius: 5px;
    			margin-top: 0.2rem;
    			overflow: hidden;
    			.progress {
    				height: 100%;
    				background: var(--player);
    				width: 0%;
    				transition: width 0.3s;
    			}
    		}
    	}
    	.action-points {
    		margin-top: 0.5rem;
    		font-size: 0.9rem;
    		font-weight: bold;
    		.player-ap { color: var(--player) }
    		.ai-ap { color: var(--ai) }
    	}
    
    	@keyframes pulse {
    		0% { transform:scale(1); opacity:0.7 }
    		50% { transform:scale(1.05); opacity:1 }
    		100% { transform:scale(1); opacity:0.7 }
    	}
    </style>
    </head>
    
    <body>
    <div id="ui">
    	<div id="panel">
    		<section>
    			<span class="stat" id="pStat">玩家 0</span>
    			<span class="stat" id="aStat">AI 0</span>
    			<span class="stat" id="nStat">中立 0</span>
    			<div class="territory-percentage">
    				领土占比: <span id="pPercentage">0%</span>
    				<div class="progress-bar"><div class="progress" id="pProgress"></div></div>
    			</div>
    			<div class="action-points">
    				<span class="player-ap">行动点: <span id="playerAP">1.0</span></span>
    				<span class="ai-ap"> | AI行动点: <span id="aiAP">1.0</span></span>
    			</div>
    			<div id="msg">点击任一六边形开始游戏</div>
    		</section>
    
    		<section>
    			<h3>资源统计 (回合: <span id="turnCount">1</span>)</h3>
    			<div id="playerResStats">
    				<strong style="color:var(--player)">玩家:</strong><br>
    				<span class="res-line">土地: <span id="pLand">0</span></span><br>
    				<span class="res-line">金钱: <span id="pGold">0</span> (收入: <span id="pGoldIncome">0</span>)</span><br>
    				<span class="res-line">产能: <span id="pProd">0</span> (收入: <span id="pProdIncome">0</span>)</span>
    			</div>
    			<hr>
    			<div id="aiResStats">
    				<strong style="color:var(--ai)">AI:</strong><br>
    				<span class="res-line">土地: <span id="aiLand">0</span></span><br>
    				<span class="res-line">金钱: <span id="aiGold">0</span> (收入: <span id="aiGoldIncome">0</span>)</span><br>
    				<span class="res-line">产能: <span id="aiProd">0</span> (收入: <span id="aiProdIncome">0</span>)</span>
    			</div>
    		</section>
    
    		<section>
    			<h3>操作</h3>
    			<div id="actionPanel"></div>
    			<div style="display:flex; gap:.5rem; margin-top:.5rem">
    				<button id="new">新游戏</button>
    				<button id="skip">跳过</button>
    			</div>
    		</section>
    
    		<section>
    			<h3>设置</h3>
    			<label>AI难度
    				<select id="difficulty">
    					<option value="easy">简单</option>
    					<option value="medium" selected>中等</option>
    					<option value="hard">困难</option>
    				</select>
    			</label>
    		</section>
    
    		<section>
    			<h3>显示</h3>
    			<label><input type="checkbox" id="showCenters">圆心</label>
    			<label><input type="checkbox" id="showConnections">连接</label>
    			<label><input type="checkbox" id="showBorders" checked>边框</label>
    		    <label><input type="checkbox" id="showResources" checked>资源</label>
    		    <label><input type="checkbox" id="showBuildings" checked>建筑</label>
    		    <label><input type="checkbox" id="showLevels" checked>等级</label>
    		    <label><input type="checkbox" id="showCapitals" checked>首都标记</label>
    		</section>
    
    		<section>
    			<h3>网格</h3>
    			<label>半径 <span id="rV">30</span></label>
    			<input data-bind="radius" type="range" min="5" max="90" value="30">
    			<label>旋转 <span id="rotV">0</span>°</label>
    			<input data-bind="rotation" , type="range" min="0" max="60" value="0">
    			<label>水平 <span id="oxV">0</span></label>
    			<input data-bind="offsetX" , type="range" min="-200" , max="200" , value="0">
    			<label>垂直 <span id="oyV">0</span></label>
    			<input data-bind="offsetY" , type="range" min="-200" , max="200" , value="0">
    		</section>
    
    		<section>
    			<h3>画布</h3>
    			<label>宽度 <span id="wV">800</span></label>
    			<input data-bind="canvasWidth" , type="range" min="300" , max="1000" , value="800">
    			<label>高度 <span id="hV">600</span></label>
    			<input data-bind="canvasHeight" , type="range" min="300" , max="1000" , value="600">
    			<label>背景<input type="color" id="bgColor" value="#ffffff"></label>
    		</section>
    
    		<section>
    			<h3>颜色</h3>
    			<label>玩家<input type="color" id="playerColor" value="#4285f4"></label>
    			<label>AI<input type="color" id="aiColor" value="#ea4335"></label>
    			<label>中立<input type="color" id="neutralColor" value="#9e9e9e"></label>
    			<label>边框<input type="color" id="borderColor" value="#333333"></label>
    			<label>圆心<input type="color" id="centerColor" value="#ff0000"></label>
    			<label>连线<input type="color" id="connectColor" value="#0000ff"></label>
    		</section>
    	</div>
    </div>
    <div id="game-container">
    	<h1>六边形文明扩张与生产</h1>
    	<canvas id="cv" width="800" height="600"></canvas>
    </div>
    <script>
    	(() => {
    		// 辅助函数
    		const $ = sel => document.querySelector(sel);
    		const $$ = sel => document.querySelectorAll(sel);
    		const createButton = (text, onClick, disabled = false) => {
    			const btn = document.createElement('button');
    			btn.textContent = text;
    			btn.onclick = onClick;
    			btn.disabled = disabled;
    			return btn;
    		};
    
    		// 配置和状态
    		const config = {
    			offsetX: 0, offsetY: 0, radius: 30, rotation: 0,
    			canvasWidth: 800, canvasHeight: 600,
    			get hexHeight() { return Math.sqrt(3) * this.radius },
    			get hexStepX() { return this.radius * 2 * 0.75 }, // 3/4 width for hex grid
    			colors: {
    				background: '#ffffff', border: '#333', center: '#f00', 
    				connect: '#00f', player: '#4285f4', ai: '#ea4335', 
    				neutral: '#9e9e9e', selection: '#FFD700'
    			},
    			show:{centers:false,connections:false,borders:true,resources:true,buildings:true,levels:true,capitals:true},
    			animation: { pulseSpeed: 1.5, pulseWidth: 3 }
    		};
    
    		const state = {
    			player: new Set(), ai: new Set(), turn: 'player',
    			started: false, over: false, diff: 'medium',
    			turnCount: 1, selectedHex: null, animationFrame: 0,
    			resources: {
    				player: { gold: 10, prod: 0, goldInc: 0, prodInc: 0 },
    				ai: { gold: 10, prod: 0, goldInc: 0, prodInc: 0 }
    			},
    			actionPoints: {
    				player: 1.0,
    				ai: 1.0
    			},
    			capitals: { player: null, ai: null },
    			capitalUnderSiege: { player: 0, ai: 0 },
    			BUILDINGS: {
    				factory: { name: '工厂', cost: 10, prod: 2, desc: '产能+2' },
    				bank: { name: '银行', cost: 12, gold: 2, desc: '金钱+2' }
    			},
    			UPGRADE_COST: level => 8 + level * 4,
    			ACTION_COSTS: {
    				capture: 1.0,
    				upgrade: 0.5,
    				build: 0.5,
    				endTurn: 0
    			}
    		};
    
    		let grid = [], hexResMap = {};
    
    		// 游戏逻辑函数
    		const game = {
    			genHexRes: () => ({
    				gold: 1 + (Math.random() < 0.5 ? 1 : 0),
    				prod: Math.random() < 0.5 ? 1 : 0,
    				level: 1, building: null
    			}),
    
    			hexAt: (col, row) => grid.find(h => h.col === col && h.row === row),
    
    			neighbors: hex => {
    				const isEvenCol = hex.col % 2 === 0;
    				const offsets = [
    					[0,-1],[0,1],                          // 上下
    					[-1, isEvenCol ? -1 : 0],[-1, isEvenCol ? 0 : 1],  // 左
    					[1, isEvenCol ? -1 : 0],[1, isEvenCol ? 0 : 1]     // 右
    				];
    				return offsets.map(([dc, dr]) => game.hexAt(hex.col + dc, hex.row + dr)).filter(Boolean);
    			},
    
    			canCapture: (hex, side) => hex.owner === 'neutral' && 
    				game.neighbors(hex).some(neighbor => state[side].has(neighbor.id)),
    
    			captureHex: (hex, side) => {
    				if (!game.canCapture(hex, side)) return false;
    
    				// 消耗行动点
    				if (state.actionPoints[side] < state.ACTION_COSTS.capture) return false;
    				state.actionPoints[side] -= state.ACTION_COSTS.capture;
    				ui.updateActionPoints();
    
    				const opponent = side === 'player' ? 'ai' : 'player';
    
    				// 检查是否占领了对方首都
    				if (hex.id === state.capitals[opponent]) {
    					state.capitalUnderSiege[opponent]++;
        
    				    // 如果是重新夺回自己的首都,重置围攻计数
    				    if (hex.owner === opponent) {
    				        state.capitalUnderSiege[side] = 0;
    				    }
        
    					if (state.capitalUnderSiege[opponent] >= 3) {
    						// 连锁占领所有领土
    						grid.forEach(h => {
    							if (h.owner === opponent) {
    								h.owner = side;
    								state[side].add(h.id);
    								state[opponent].delete(h.id);
    							}
    						});
    						state.over = true;
    						ui.msg(`游戏结束!${side === 'player' ? '玩家' : 'AI'}占领了所有领土`);
    						ui.showActionPanel();
    						return true;
    					}
    				} else {
    					state.capitalUnderSiege[opponent] = 0;
    				}
    
    				state[side].add(hex.id);
    				hex.owner = side;
    
    				// 检查领土占比是否达到80%
    				game.checkTerritoryWinCondition(side);
    				return true;
    			},
    
    			checkTerritoryWinCondition: (side) => {
    				const totalHexes = grid.length;
    				const ownedHexes = state[side].size;
    				const percentage = (ownedHexes / totalHexes) * 100;
    
    				if (percentage >= 80) {
    					state.over = true;
    					ui.msg(`游戏结束!${side === 'player' ? '玩家' : 'AI'}占领了${percentage.toFixed(1)}%的领土`);
    					ui.showActionPanel();
    					return true;
    				}
    				return false;
    			},
    
    			processResources: (side) => {
    				const res = state.resources[side];
    				res.goldInc = res.prodInc = 0;
    
    				grid.filter(hex => hex.owner === side).forEach(hex => {
    					const building = hex.res.building ? state.BUILDINGS[hex.res.building] : null;
    					res.goldInc += hex.res.gold + (building?.gold || 0);
    					res.prodInc += hex.res.prod + (building?.prod || 0);
    
    					if (hex.res.level > 1) {
    						res.goldInc += (hex.res.level - 1);
    						res.prodInc += Math.floor((hex.res.level - 1) / 2);
    					}
    				});
    
    				// 计算行动点 (基础1点 + 每0.1产能增加0.1行动点)
    				const baseAP = 1.0;
    				const prodBonus = res.prodInc * 0.1;
    				state.actionPoints[side] = baseAP + prodBonus;
    				ui.updateActionPoints();
    			},
    
    			nextTurn: () => {
    				['player', 'ai'].forEach(side => {
    					game.processResources(side);
    					const capitalId = state.capitals[side];
    					const capitalHex = grid.find(h => h.id === capitalId);
    					if (capitalHex && capitalHex.owner === side) {
    						state.capitalUnderSiege[side] = 0;
    					}
    					state.resources[side].gold += state.resources[side].goldInc;
    				});
    
    				state.turnCount++;
    				ui.updateAllStats();
    			},
    
    			checkGameOver: () => {
    			    // 检查是否有一方被完全消灭
    			    if (state.player.size === 0 || state.ai.size === 0) {
    			        state.over = true;
    			        const winner = state.player.size > 0 ? '玩家' : 'AI';
    			        ui.msg(`游戏结束!${winner}消灭了对手`);
    			        ui.showActionPanel();
    			        return true;
    			    }
        
    				const neutralHexes = grid.filter(hex => hex.owner === 'neutral');
    				const playerCanCapture = neutralHexes.some(hex => game.canCapture(hex, 'player'));
    				const aiCanCapture = neutralHexes.some(hex => game.canCapture(hex, 'ai'));
    
    				if (!playerCanCapture && !aiCanCapture) {
    					state.over = true;
    					const winner = state.player.size > state.ai.size ? '玩家' : 
    									state.player.size < state.ai.size ? 'AI' : '平局';
    					ui.msg(`游戏结束!${winner}胜`);
    					ui.showActionPanel();
    				}
    
    				return state.over;
    			},
    
    			autoExpand: (side) => {
    				if (state.actionPoints[side] < state.ACTION_COSTS.capture) {
    					state.turn = side === 'player' ? 'ai' : 'player';
    					if (side === 'player') {
    						ui.msg('行动点不足,自动结束回合');
    						game.nextTurn();
    						if (state.turn === 'ai') game.aiTurn();
    					}
    					return;
    				}
    
    				const hexes = Array.from(side === 'player' ? state.player : state.ai).map(id => 
    					grid.find(h => h.id === id));
    
    				// 找到所有可以扩张的边界
    				const borders = [];
    				hexes.forEach(hex => {
    					game.neighbors(hex).forEach(neighbor => {
    						if (neighbor.owner === 'neutral' && game.canCapture(neighbor, side)) {
    							borders.push({ source: hex, target: neighbor });
    						}
    					});
    				});
    
    				if (borders.length === 0) {
    					state.turn = side === 'player' ? 'ai' : 'player';
    					if (side === 'player') {
    						ui.msg('没有可扩张的领土,自动结束回合');
    						game.nextTurn();
    						if (state.turn === 'ai') game.aiTurn();
    					}
    					return;
    				}
    
    				// 选择扩张目标
    				let target;
    				if (side === 'player') {
    					// 玩家自动扩张 - 选择最近的边界
    					if (state.selectedHex) {
    						target = borders.reduce((best, current) => 
    							Math.hypot(current.target.x - state.selectedHex.x, current.target.y - state.selectedHex.y) < 
    							Math.hypot(best.target.x - state.selectedHex.x, best.target.y - state.selectedHex.y) ? 
    							current : best, borders[0]);
    					} else {
    						target = borders[0];
    					}
    				} else {
    					// AI扩张逻辑
    					if (state.diff === 'easy') {
    						target = borders[Math.random() * borders.length | 0];
    					} else {
    						const potential = hex => game.neighbors(hex).filter(n => n.owner === 'neutral').length;
    						target = borders.reduce((best, current) => 
    							potential(current.target) > potential(best.target) ? current : best, borders[0]);
    						if (state.diff === 'medium' && Math.random() > .7) {
    							target = borders[Math.random() * borders.length | 0];
    						}
    					}
    				}
    
    				// 执行扩张
    				if (game.captureHex(target.target, side)) {
    					if (side === 'player') {
    						state.selectedHex = target.target;
    						ui.msg('自动扩张领土');
    						render.draw();
    						ui.updateAllStats();
    						ui.showActionPanel();
    					}
    
    					// 继续扩张直到行动点不足
    					setTimeout(() => game.autoExpand(side), side === 'player' ? 300 : { easy: 500, medium: 300, hard: 200 }[state.diff]);
    				} else {
    					state.turn = side === 'player' ? 'ai' : 'player';
    					if (side === 'player') {
    						ui.msg('扩张失败,自动结束回合');
    						game.nextTurn();
    						if (state.turn === 'ai') game.aiTurn();
    					}
    				}
    			},
    
    			aiTurn: () => {
    				if (state.over) return;
    
    				setTimeout(() => {
    					// 1. 扩张优先
    					if (state.actionPoints.ai >= state.ACTION_COSTS.capture) {
    						const captureOptions = grid.filter(hex => game.canCapture(hex, 'ai'));
    						if (captureOptions.length) {
    							game.autoExpand('ai');
    					        game.checkGameOver(); // 添加检查
    							return;
    						}
    					}
    
    					// 2. 建造/升级
    					const aiHexes = grid.filter(hex => hex.owner === 'ai');
    					const aiRes = state.resources.ai;
    
    					// 优先升级低级地块
    					if (state.actionPoints.ai >= state.ACTION_COSTS.upgrade) {
    						const upgradableHex = aiHexes.find(hex => 
    							aiRes.gold >= state.UPGRADE_COST(hex.res.level) && hex.res.level < 3);
    						if (upgradableHex) {
    							aiRes.gold -= state.UPGRADE_COST(upgradableHex.res.level);
    							upgradableHex.res.level++;
    							state.actionPoints.ai -= state.ACTION_COSTS.upgrade;
    							ui.updateActionPoints();
    							ui.msg('AI升级地块');
    							render.draw();
    					        game.checkGameOver(); // 添加检查
    							setTimeout(() => game.aiTurn(), { easy: 500, medium: 300, hard: 200 }[state.diff]);
    							return;
    						}
    					}
    
    					// 建造工厂/银行
    					if (state.actionPoints.ai >= state.ACTION_COSTS.build) {
    					    const aiHexes = grid.filter(hex => hex.owner === 'ai');
    					    const buildableHex = aiHexes.find(hex => !hex.res.building && aiRes.gold >= 
    					        Math.min(state.BUILDINGS.factory.cost, state.BUILDINGS.bank.cost));
        
    					    if (buildableHex) {
    					        // 根据AI难度和当前经济情况选择建筑
    					        let building = 'factory';
    					        if (aiRes.goldInc < aiRes.prodInc || 
    					            (state.diff === 'hard' && Math.random() > 0.5)) {
    					            building = 'bank';
    					        }
            
    					        aiRes.gold -= state.BUILDINGS[building].cost;
    					        buildableHex.res.building = building;
    					        state.actionPoints.ai -= state.ACTION_COSTS.build;
    					        ui.updateActionPoints();
    					        ui.msg(`AI建造${state.BUILDINGS[building].name}`);
    					        render.draw();
    							setTimeout(() => game.aiTurn(), { easy: 500, medium: 300, hard: 200 }[state.diff]);
    							return;
    						}
    					}
    
    					// 跳过
    					ui.msg('AI跳过');
    				    game.checkGameOver(); // 添加检查
    					state.turn = 'player';
    					game.nextTurn();
    					game.checkGameOver();
    				}, { easy: 1000, medium: 500, hard: 300 }[state.diff]);
    			},
    
    			initGameState: () => {
    				Object.assign(state, {
    					player: new Set(), ai: new Set(), turn: 'player', started: false, over: false,
    					turnCount: 1, selectedHex: null,
    					resources: {
    						player: { gold: 10, prod: 0, goldInc: 0, prodInc: 0 },
    						ai: { gold: 10, prod: 0, goldInc: 0, prodInc: 0 }
    					},
    					actionPoints: {
    						player: 1.0,
    						ai: 1.0
    					},
    					capitals: { player: null, ai: null },
    					capitalUnderSiege: { player: 0, ai: 0 }
    				});
    				hexResMap = {};
    				state.diff = $('#difficulty').value;
    				ui.updateActionPoints();
    			    render.draw(); // 添加渲染调用
    			}
    		};
    
    		// 渲染函数
    		const render = {
    			canvas: null,
    			ctx: null,
    
    			initCanvas() {
    				this.canvas = $('#cv');
    				this.ctx = this.canvas.getContext('2d');
    			},
    
    			hexPath(x, y, radius) {
    				this.ctx.beginPath();
    				for (let i = 0; i < 6; i++) {
    					const angle = Math.PI / 3 * i + config.rotation * Math.PI / 180;
    					this.ctx[i ? 'lineTo' : 'moveTo'](x + radius * Math.cos(angle), y + radius * Math.sin(angle));
    				}
    				this.ctx.closePath();
    			},
    
    			drawSelectedHex(hex) {
    				if (!hex) return;
    
    				this.ctx.save();
    				this.ctx.translate(hex.x, hex.y);
    
    				const progress = (state.animationFrame / 30) % 1;
    				const scale = 1 + 0.05 * Math.sin(progress * Math.PI * 2);
    
    				this.hexPath(0, 0, config.radius * scale);
    				this.ctx.lineWidth = config.animation.pulseWidth;
    				this.ctx.strokeStyle = config.colors.selection;
    				this.ctx.globalAlpha = 0.7 + 0.3 * Math.sin(progress * Math.PI * 2);
    				this.ctx.stroke();
    
    				this.ctx.restore();
    			},
    
    			drawStar(x, y, radius, color) {
    				this.ctx.save();
    				this.ctx.fillStyle = color;
    				this.ctx.translate(x, y);
    				this.ctx.beginPath();
    				for (let i = 0; i < 5; i++) {
    					const angle = (i * 2 * Math.PI / 5) - Math.PI/2;
    					this.ctx.lineTo(
    						radius * Math.cos(angle), 
    						radius * Math.sin(angle)
    					);
    					this.ctx.lineTo(
    						0.4 * radius * Math.cos(angle + Math.PI/5), 
    						0.4 * radius * Math.sin(angle + Math.PI/5)
    					);
    				}
    				this.ctx.closePath();
    				this.ctx.fill();
    				this.ctx.restore();
    			},
    
    			draw() {
    				this.initCanvas();
    				state.animationFrame = (state.animationFrame + 1) % 60;
    
    				const canvas = this.canvas;
    				this.ctx.fillStyle = config.colors.background;
    				this.ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    				const hexHeight = config.hexHeight;
    				const hexStepX = config.hexStepX;
    				const colCount = Math.ceil(canvas.width / hexStepX) + 2;
    				const rowCount = Math.ceil(canvas.height / hexHeight) + 2;
    				grid = [];
    
    				// 生成网格
    				for (let col = 0; col < colCount; col++) {
    					for (let row = 0; row < rowCount; row++) {
    						const x = col * hexStepX + config.offsetX;
    						const y = row * hexHeight + (col % 2 ? hexHeight / 2 : 0) + config.offsetY;
    						if (x < -config.radius || x > canvas.width + config.radius || 
    							y < -config.radius || y > canvas.height + config.radius) continue;
    
    						const id = `${col},${row}`;
    						let owner = 'neutral';
    						if (state.player.has(id)) owner = 'player';
    						else if (state.ai.has(id)) owner = 'ai';
    
    						let res = hexResMap[id];
    						if (!res) { res = game.genHexRes(); hexResMap[id] = res; }
    
    						const hex = { x, y, col, row, id, owner, res };
    						grid.push(hex);
    
    						// 绘制六边形
    						this.ctx.save();
    						this.ctx.translate(x, y);
    						this.hexPath(0, 0, config.radius);
    						this.ctx.fillStyle = config.colors[owner];
    						this.ctx.fill();
    						if (config.show.borders) {
    							this.ctx.strokeStyle = config.colors.border;
    							this.ctx.stroke();
    						}
    						this.ctx.restore();
    					}
    				}
    
    				// 绘制选中地块动画
    				if (state.selectedHex) this.drawSelectedHex(state.selectedHex);
    
    				// 绘制资源和建筑信息
    				grid.forEach(hex => {
    					this.ctx.save();
    					this.ctx.font = "bold 12px sans-serif";
    					this.ctx.textAlign = "center";
    					this.ctx.textBaseline = "middle";
    					this.ctx.fillStyle = "#222";
        
    				    // 只显示资源如果配置允许
    				    if (config.show.resources) {
    				        this.ctx.fillText(`$${hex.res.gold}⚙${hex.res.prod}`, hex.x, hex.y + config.radius / 2 - 8);
    				    }
        
    				    // 只显示建筑如果配置允许
    				    if (hex.res.building && config.show.buildings) {
    				        this.ctx.fillStyle = config.colors[hex.owner];
    				        this.ctx.fillText(state.BUILDINGS[hex.res.building].name, hex.x, hex.y + config.radius / 2 + 8);
    				    }
        
    				    // 只显示等级如果配置允许
    				    if (hex.res.level > 1 && config.show.levels) {
    				        this.ctx.fillStyle = "#FFD700";
    				        this.ctx.fillText("Lv" + hex.res.level, hex.x, hex.y - config.radius / 2 + 8);
    				    }
        
    				    // 只显示首都标记如果配置允许
    				    if (config.show.capitals && (hex.id === state.capitals.player || hex.id === state.capitals.ai)) {
    				        const color = hex.owner === 'player' ? '#FFD700' : '#FFFFFF';
    				        this.drawStar(hex.x, hex.y - config.radius * 0.3, config.radius * 0.2, color);
    				    }
    				    this.ctx.restore();
    				});
    
    				// 绘制连接和圆心
    				grid.forEach(hex => {
    					if (config.show.connections) {
    						game.neighbors(hex).forEach(neighbor => {
    							this.ctx.beginPath();
    							this.ctx.moveTo(hex.x, hex.y);
    							this.ctx.lineTo(neighbor.x, neighbor.y);
    							this.ctx.strokeStyle = config.colors.connect;
    							this.ctx.stroke();
    						});
    					}
    					if (config.show.centers) {
    						this.ctx.beginPath();
    						this.ctx.arc(hex.x, hex.y, 2, 0, 2 * Math.PI);
    						this.ctx.fillStyle = config.colors.center;
    						this.ctx.fill();
    					}
    				});
    
    				if (state.started && !state.over) requestAnimationFrame(() => render.draw());
    			}
    		};
    
    		// UI函数
    		const ui = {
    			valueTextElements: {
    				offsetX: $('#oxV'), offsetY: $('#oyV'), radius: $('#rV'), rotation: $('#rotV'),
    				canvasWidth: $('#wV'), canvasHeight: $('#hV')
    			},
    
    			msg: text => $('#msg').textContent = text,
    
    			updateActionPoints: () => {
    				$('#playerAP').textContent = state.actionPoints.player.toFixed(1);
    				$('#aiAP').textContent = state.actionPoints.ai.toFixed(1);
    			},
    
    			updateAllStats: () => {
    				// 更新领地统计
    				$('#pStat').textContent = `玩家 ${state.player.size}`;
    				$('#aStat').textContent = `AI ${state.ai.size}`;
    				$('#nStat').textContent = `中立 ${grid.length - state.player.size - state.ai.size}`;
    
    				// 更新领土占比
    				const totalHexes = grid.length;
    				const playerPercentage = (state.player.size / totalHexes) * 100;
    				$('#pPercentage').textContent = playerPercentage.toFixed(1) + '%';
    				$('#pProgress').style.width = playerPercentage + '%';
    
    				// 更新回合数和资源统计
    				$('#turnCount').textContent = state.turnCount;
    				['player', 'ai'].forEach(side => {
    					const res = state.resources[side];
    					const prefix = side === 'player' ? 'p' : 'ai';
    					$(`#${prefix}Land`).textContent = side === 'player' ? state.player.size : state.ai.size;
    					$(`#${prefix}Gold`).textContent = res.gold;
    					$(`#${prefix}GoldIncome`).textContent = res.goldInc;
    					$(`#${prefix}Prod`).textContent = res.prod;
    					$(`#${prefix}ProdIncome`).textContent = res.prodInc;
    				});
    
    				// 更新行动点
    				this.updateActionPoints();
    			},
    
    			updateValueTexts: () => {
    				Object.keys(ui.valueTextElements).forEach(key => {
    					ui.valueTextElements[key].textContent = config[key];
    				});
    			},
    
    			showActionPanel: () => {
    				const actionPanel = $('#actionPanel');
    				actionPanel.innerHTML = '';
    
    				if (!state.started || state.over) return;
    				if (state.turn !== 'player') { actionPanel.textContent = '等待行动...'; return; }
    				if (!state.selectedHex) { actionPanel.textContent = '点击己方领土可进行操作'; return; }
    
    				const hex = state.selectedHex;
    				if (hex.owner !== 'player') { actionPanel.textContent = '只能操作己方领土'; return; }
    				const playerRes = state.resources.player;
    
    				// 升级按钮
    				if (hex.res.level < 3) {
    					const cost = state.UPGRADE_COST(hex.res.level);
    					actionPanel.appendChild(createButton(
    						`升级(Lv${hex.res.level + 1}) $${cost} (0.5AP)`,
    						() => {
    							if (state.actionPoints.player < state.ACTION_COSTS.upgrade) {
    								ui.msg('行动点不足!');
    								return;
    							}
    							playerRes.gold -= cost;
    							hex.res.level++;
    							state.actionPoints.player -= state.ACTION_COSTS.upgrade;
    							ui.msg('升级成功');
    							render.draw();
    							ui.updateAllStats();
    							ui.showActionPanel();
    						},
    						playerRes.gold < cost || state.actionPoints.player < state.ACTION_COSTS.upgrade
    					));
    				}
    
    				// 建造按钮
    				if (!hex.res.building) {
    					Object.keys(state.BUILDINGS).forEach(buildingKey => {
    						const building = state.BUILDINGS[buildingKey];
    						actionPanel.appendChild(createButton(
    							`建造${building.name} $${building.cost} (0.5AP)`,
    							() => {
    								if (state.actionPoints.player < state.ACTION_COSTS.build) {
    									ui.msg('行动点不足!');
    									return;
    								}
    								playerRes.gold -= building.cost;
    								hex.res.building = buildingKey;
    								state.actionPoints.player -= state.ACTION_COSTS.build;
    								ui.msg('建造成功');
    								render.draw();
    								ui.updateAllStats();
    								ui.showActionPanel();
    							},
    							playerRes.gold < building.cost || state.actionPoints.player < state.ACTION_COSTS.build
    						));
    					});
    				}
    
    				// 扩张按钮
    				if (game.neighbors(hex).some(neighbor => neighbor.owner === 'neutral')) {
    					actionPanel.appendChild(createButton('扩张领土 (1AP)', () => {
    						if (state.actionPoints.player < state.ACTION_COSTS.capture) {
    							ui.msg('行动点不足!');
    							return;
    						}
    						game.autoExpand('player');
    					}, state.actionPoints.player < state.ACTION_COSTS.capture));
    				}
    
    				// 结束回合按钮
    				actionPanel.appendChild(createButton('结束回合', () => {
    					game.nextTurn();
    					state.turn = 'ai';
    					state.selectedHex = null;
    					render.draw();
    					ui.updateAllStats();
    					ui.showActionPanel();
    					game.aiTurn();
    				}));
    			},
    
    			initUIEvents: () => {
    				// 游戏画布点击事件
    				const canvas = $('#cv');
    				canvas.addEventListener('click', evt => {
    					const rect = canvas.getBoundingClientRect();
    					const clickX = evt.clientX - rect.left, clickY = evt.clientY - rect.top;
    					const hex = grid.find(h => Math.hypot(h.x - clickX, h.y - clickY) < config.radius * 0.9);
    					if (!hex) return;
    
    					if (!state.started) {
    						game.initGameState();
    						hexResMap = {};
    
    						// 设置玩家起始位置
    						state.player.add(hex.id);
    						hex.owner = 'player';
    						state.capitals.player = hex.id;
    
    						// 为AI随机选择起始位置
    						const potentialAiStarts = grid.filter(h => 
    							h.owner === 'neutral' && 
    							Math.abs(h.col - hex.col) > 3 &&  // 与玩家保持至少3列距离
    							Math.abs(h.row - hex.row) > 3     // 与玩家保持至少3行距离
    						);
    
    						if (potentialAiStarts.length) {
    							const aiStart = potentialAiStarts[Math.floor(Math.random() * potentialAiStarts.length)];
    							state.ai.add(aiStart.id);
    							aiStart.owner = 'ai';
    							state.capitals.ai = aiStart.id;
    						} else {
    							// 如果找不到足够远的位置,选择任意中立地块
    							const neutralHexes = grid.filter(h => h.owner === 'neutral');
    							if (neutralHexes.length) {
    								const aiStart = neutralHexes[Math.floor(Math.random() * neutralHexes.length)];
    								state.ai.add(aiStart.id);
    								aiStart.owner = 'ai';
    								state.capitals.ai = aiStart.id;
    							}
    						}
    
    						state.started = true;
    						ui.msg('玩家先手,点击己方领土进行操作');
    						render.draw();
    						ui.updateAllStats();
    						ui.showActionPanel();
    						return;
    					}
    
    					if (state.over) return;
    					if (hex.owner === 'player') {
    						state.selectedHex = hex;
    						ui.showActionPanel();
    						render.draw();
    						return;
    					}
    
    					if (state.turn === 'player' && game.canCapture(hex, 'player')) {
    						if (state.actionPoints.player < state.ACTION_COSTS.capture) {
    							ui.msg('行动点不足!');
    							return;
    						}
    						game.captureHex(hex, 'player');
    						state.selectedHex = hex;
    						ui.msg('扩张成功');
    						render.draw();
    						ui.updateAllStats();
    						ui.showActionPanel();
    						game.checkGameOver();
    					}
    				});
    
    				// 按钮事件
    				$('#new').onclick = () => {
    					game.initGameState();
    					hexResMap = {};
    					ui.msg('点击六边形开始游戏');
    					ui.updateAllStats();
    					render.draw();
    					ui.showActionPanel();
    				};
    
    				$('#skip').onclick = () => {
    					if (state.turn === 'player' && !state.over) {
    						game.nextTurn();
    						state.turn = 'ai';
    						state.selectedHex = null;
    						render.draw();
    						ui.updateAllStats();
    						ui.showActionPanel();
    						game.aiTurn();
    					}
    				};
    
    				// 绑定UI控件
    				$('#difficulty').onchange = evt => state.diff = evt.target.value;
    
    				// 绑定滑块控件
    				$$('input[data-bind]').forEach(el => {
    					const key = el.dataset.bind;
    					el.oninput = evt => { 
    						config[key] = +evt.target.value; 
    						ui.updateValueTexts(); 
    						render.draw(); 
    					};
    				});
    
    				// 绑定颜色选择器
    				const colorMap = {
    					bgColor: 'background', playerColor: 'player', aiColor: 'ai', 
    					neutralColor: 'neutral', borderColor: 'border', 
    					centerColor: 'center', connectColor: 'connect'
    				};
    
    				Object.keys(colorMap).forEach(id => {
    					$(`#${id}`).oninput = evt => {
    						config.colors[colorMap[id]] = evt.target.value;
    						render.draw();
    					};
    				});
    
    				// 绑定复选框
    				['Centers', 'Connections', 'Borders', 'Resources', 'Buildings', 'Levels', 'Capitals'].forEach(name => {
    					$(`#show${name}`).onchange = evt => {
    						config.show[name.toLowerCase()] = evt.target.checked;
    						render.draw();
    					};
    				});
    			},
    
    			init: () => {
    				ui.initUIEvents();
    				ui.updateValueTexts();
    				ui.updateAllStats();
    				render.initCanvas();
    				render.draw();
    				ui.showActionPanel();
    			}
    		};
    
    		ui.init();
    	})();
    </script>
    </body>
    </html>
    
  2. Google Assistant

    This is a substantial piece of code! Here's a breakdown of improvements, categorized for clarity, along with explanations. I'll focus on readability, maintainability, performance, and best practices. I'll also point out potential areas for further development.

    1. Code Structure & Organization

    • Modularization: The code is already reasonably well-structured with game, render, and ui objects. However, consider breaking down game further. For example, AI logic could be in a separate ai object. This improves testability and reduces the size of individual functions.
    • Configuration: The config object is good. Consider using a separate configuration file (e.g., JSON) for more complex settings. This allows for easier modification without code changes.
    • State Management: The state object is central. Consider using a more robust state management library (like Redux or Vuex, if you're moving towards a framework) for larger applications. For this size, it's acceptable, but be mindful of potential complexity as the game grows.
    • Comments: Add more comments, especially explaining complex logic or algorithms. The existing comments are good, but more detail is always helpful.

    2. Readability & Style

    • Consistent Indentation: Ensure consistent indentation throughout the code. Your code is mostly good, but a linter can help enforce this.
    • Whitespace: Use whitespace effectively to separate logical blocks of code.
    • Naming Conventions: Your naming is generally good. Be consistent. For example, use camelCase for variables and functions (hexStepX instead of hexStepX).
    • String Literals: Use template literals (backticks) for string concatenation, especially when embedding variables. This improves readability. Example: ui.msg(AI 建造 ${state.BUILDINGS[building].name});
    • CSS: The CSS is well-organized. Consider using a CSS preprocessor (Sass or Less) for more advanced features like variables, nesting, and mixins.

    3. Performance

    • Canvas Redraws: The render.draw() function is called frequently. Optimize it to minimize unnecessary redraws. Only redraw parts of the canvas that have changed. This is crucial for performance, especially on lower-end devices. Consider using a double-buffering technique.
    • Grid Traversal: The code iterates through the grid array multiple times. If performance becomes an issue, consider using spatial data structures (like a quadtree or octree) to speed up neighbor searches and other grid-based operations.
    • DOM Manipulation: Minimize direct DOM manipulation. Use techniques like document fragments to batch updates. Your code is already relatively good in this regard, but be mindful of it.
    • Event Listeners: Avoid attaching event listeners to individual elements if possible. Use event delegation (attaching a single listener to a parent element) to improve performance. You're already doing this with the canvas click event.
    • requestAnimationFrame: You're using requestAnimationFrame correctly, which is excellent for smooth animations.

    4. Code Improvements & Bug Fixes

    • game.neighbors: The game.neighbors function could be simplified using a more concise array of offsets.
    • game.canCapture: This function is good.
    • game.captureHex: This function is the core of the game logic. It's well-structured.
    • game.processResources: This function is good.
    • game.nextTurn: This function is good.
    • game.aiTurn: This function is complex. Break it down into smaller, more manageable functions. Consider using a state machine to manage the AI's decision-making process. The AI logic is currently hardcoded. Make it more configurable and extensible.
    • render.draw: This function is the most performance-critical. Optimize it as described above.
    • ui.updateAllStats: This function is good.
    • ui.initUIEvents: This function is good.
    • Error Handling: Add error handling to prevent the game from crashing due to unexpected input or conditions.
    • Input Validation: Validate user input (e.g., difficulty level) to prevent invalid values.
    • Accessibility: Consider accessibility when designing the UI. Use appropriate ARIA attributes and ensure that the game is usable by people with disabilities.

    5. Specific Code Snippets & Suggestions

    • game.hexAt:

      game.hexAt = (col, row) => grid.find(h => h.col === col && h.row === row);
      

      This is fine, but for a large grid, a hash map (object) keyed by the hex ID (${col},${row}) would be much faster for lookups.

    • game.neighbors:

      const offsets = [
          [0,-1],[0,1],                          // 上下
          [-1, isEvenCol ? -1 : 0],[-1, isEvenCol ? 0 : 1],  // 左
          [1, isEvenCol ? -1 : 0],[1, isEvenCol ? 0 : 1]     // 右
      ];
      

      Could be slightly more concise:

      const offsets = [[0, -1], [0, 1], [-1, -1], [-1, 1], [1, -1], [1, 1]];
      
    • AI Logic: The AI logic in game.aiTurn is very basic. Consider implementing more sophisticated AI algorithms, such as:

      • Minimax: A classic game AI algorithm.
      • Monte Carlo Tree Search (MCTS): A more advanced algorithm that is often used in complex games.
      • Behavior Trees: A flexible and modular way to define AI behavior.
    • Action Panel: The action panel is dynamically generated. Consider using a template engine or a component-based approach to make it more maintainable.

    6. Further Development

    • Multiplayer: Add multiplayer support.
    • More Resources: Add more resources (e.g., minerals, energy).
    • More Buildings: Add more buildings with different effects.
    • Technology Tree: Implement a technology tree that allows players to unlock new units and abilities.
    • Units: Add units that can move around the map and attack other players.
    • Diplomacy: Add diplomacy options that allow players to negotiate with each other.
    • Map Generation: Implement more sophisticated map generation algorithms.
    • Sound Effects and Music: Add sound effects and music to enhance the gaming experience.
    • User Interface: Improve the user interface to make it more intuitive and user-friendly.

    Example of Refactoring game.aiTurn (Partial):

    const ai = {
        evaluateHex(hex) {
            // Logic to evaluate the value of a hex for the AI
            // Consider resources, neighbors, level, etc.
            return 0; // Placeholder
        },
    
        findBestCaptureTarget(hexes) {
            // Find the best hex to capture based on evaluation
            return null; // Placeholder
        },
    
        buildOrUpgrade(hexes) {
            // Logic to determine whether to build or upgrade
            // and which building/level to choose
        },
    
        turn(state) {
            if (state.over) return;
    
            // 1. Capture
            const captureOptions = grid.filter(hex => game.canCapture(hex, 'ai'));
            if (captureOptions.length && state.actionPoints.ai >= state.ACTION_COSTS.capture) {
                const target = this.findBestCaptureTarget(captureOptions);
                if (target) {
                    game.captureHex(target, 'ai');
                    return; // End turn after capturing
                }
            }
    
            // 2. Build/Upgrade
            this.buildOrUpgrade(grid.filter(hex => hex.owner === 'ai'));
    
            // 3. Skip
            game.nextTurn();
            state.turn = 'player';
        }
    };
    
    // In game.aiTurn:
    game.aiTurn = () => {
        setTimeout(() => {
            ai.turn(state);
        }, { easy: 1000, medium: 500, hard: 300 }[state.diff]);
    };
    

    Tools to Help:

    • ESLint: A JavaScript linter that helps enforce coding style and identify potential errors.
    • Prettier: An opinionated code formatter that automatically formats your code.
    • Chrome DevTools: Use the Chrome DevTools to profile your code and identify performance bottlenecks.

    This is a comprehensive review. Start with the most important improvements (performance optimization, code structure, and error handling) and then gradually work your way through the other suggestions. Good luck! Let me know if you'd like me to elaborate on any specific point.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.