

这是您要的“建立城池打仗”游戏HTML代码,它是一个用Canvas绘制的即时战略小游戏,您可以在其中建造城池、招募士兵并攻击敌方。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">建城·打仗 | 城池争霸</title>
<style>
* {
box-sizing: border-box;
user-select: none;
}
body {
margin: 0;
min-height: 100vh;
background: linear-gradient(145deg, #1a2f1f 0%, #2d4a2e 100%);
display: flex;
align-items: center;
justify-content: center;
font-family: 'Segoe UI', Roboto, system-ui, sans-serif;
padding: 16px;
}
.game-container {
background: #4a6b3f;
padding: 24px 24px 30px;
border-radius: 60px 60px 40px 40px;
box-shadow: 0 20px 30px rgba(0, 0, 0, 0.6), inset 0 0 15px #b9a87c;
border: 6px solid #7a5a3a;
border-top-color: #9b7e5a;
border-left-color: #8b6e4a;
}
canvas {
display: block;
margin: 0 auto;
border-radius: 28px;
box-shadow: 0 0 0 8px #3a2e1e, 0 20px 30px black;
background: #aacf9a;
cursor: crosshair;
width: 900px;
height: 600px;
}
.ui-panel {
display: flex;
justify-content: space-between;
align-items: center;
margin: 12px 16px 0;
color: #f6eed9;
text-shadow: 3px 3px 0 #2b3a1f;
font-weight: bold;
letter-spacing: 1px;
}
.resources {
display: flex;
gap: 32px;
background: #2e3d1fcc;
padding: 8px 28px;
border-radius: 40px;
border: 2px solid #ab8e5a;
backdrop-filter: blur(2px);
font-size: 1.4rem;
}
.resources span {
display: flex;
align-items: center;
gap: 8px;
}
.resources i {
font-size: 1.8rem;
filter: drop-shadow(0 4px 2px #00000060);
}
.actions {
display: flex;
gap: 12px;
}
.btn {
background: #c9aa6b;
border: none;
border-bottom: 6px solid #6b4e2a;
padding: 10px 24px;
border-radius: 40px;
font-weight: bold;
font-size: 1.2rem;
color: #1d2b0e;
text-shadow: 1px 1px 0 #e9d6a8;
cursor: pointer;
transition: 0.08s linear;
box-shadow: 0 6px 0 #3a2e1e50;
letter-spacing: 1px;
display: flex;
align-items: center;
gap: 8px;
}
.btn:active {
border-bottom-width: 2px;
transform: translateY(4px);
box-shadow: 0 2px 0 #3a2e1e50;
}
.btn:disabled {
opacity: 0.5;
transform: translateY(4px);
border-bottom-width: 2px;
pointer-events: none;
}
.status {
font-size: 1.2rem;
background: #1e2b14b3;
padding: 6px 24px;
border-radius: 40px;
border: 2px solid #ab8e5a;
}
.hint {
position: relative;
top: 8px;
text-align: center;
color: #d9d0b0;
font-size: 0.95rem;
letter-spacing: 1px;
text-shadow: 2px 2px 0 #1e2b14;
}
</style>
</head>
<body>
<div class="game-container">
<canvas id="gameCanvas" width="900" height="600"></canvas>
<div class="ui-panel">
<div class="resources">
<span>🪙 <span id="goldDisplay">300</span></span>
<span>👨🌾 <span id="soldierDisplay">0</span></span>
</div>
<div class="actions">
<button class="btn" id="buildButton" title="快速建城: 消耗100金">🏗️ 建城</button>
<button class="btn" id="attackButton" title="进攻敌方城池!">⚔️ 进攻</button>
</div>
</div>
<div class="hint">点击自己的城池招募士兵 (30金) · 点击敌方城池进攻</div>
</div>
<script>
(function(){
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const goldSpan = document.getElementById('goldDisplay');
const soldierSpan = document.getElementById('soldierDisplay');
const buildBtn = document.getElementById('buildButton');
const attackBtn = document.getElementById('attackButton');
// ---------- 游戏配置 ----------
const CONFIG = {
goldPerSecond: 8, // 每秒自动黄金
soldierCost: 30, // 招募一个士兵花费
buildCost: 100, // 建城花费
maxSoldiersPerCity: 40,
playerStartGold: 300,
enemyStartGold: 200,
aiSoldierCost: 20, // 敌人招募更便宜(但数量上限低一些)
aiMaxSoldiers: 35,
aiBuildDelay: 9, // 敌人每9秒尝试建新城(如果黄金够且城池<3)
};
// ---------- 游戏状态 ----------
let playerGold = CONFIG.playerStartGold;
let playerCities = []; // 每个城池 { x, y, soldiers }
let enemyCities = [];
let enemyGold = CONFIG.enemyStartGold;
let gameOver = false;
let win = false;
// 计时器累计
let lastTime = 0;
let goldTimer = 0;
let aiBuildTimer = 0;
// 选中状态 (用于点击canvas时判断)
const CITY_RADIUS = 32;
const PLAYER_COLOR = '#3a7b4b';
const ENEMY_COLOR = '#a13d3d';
// ---------- 初始化 ----------
function initGame() {
// 玩家初始一座城 (偏左下)
playerCities = [
{ x: 220, y: 420, soldiers: 5 }
];
// 敌人两座城 (右上和右中)
enemyCities = [
{ x: 680, y: 180, soldiers: 8 },
{ x: 750, y: 360, soldiers: 6 }
];
playerGold = CONFIG.playerStartGold;
enemyGold = CONFIG.enemyStartGold;
gameOver = false;
win = false;
goldTimer = 0;
aiBuildTimer = 0;
updateUI();
}
// ---------- 辅助函数 ----------
function updateUI() {
goldSpan.textContent = Math.floor(playerGold);
let totalSoldiers = playerCities.reduce((sum, city) => sum + city.soldiers, 0);
soldierSpan.textContent = totalSoldiers;
}
// 获取玩家总士兵
function playerTotalSoldiers() {
return playerCities.reduce((sum, c) => sum + c.soldiers, 0);
}
// 获取敌人总士兵
function enemyTotalSoldiers() {
return enemyCities.reduce((sum, c) => sum + c.soldiers, 0);
}
// ---------- 游戏逻辑更新 ----------
function updateGame(deltaTime) {
if (gameOver) return;
// 1. 黄金自动增长 (玩家)
playerGold += CONFIG.goldPerSecond * deltaTime;
// 敌人黄金增长(略慢)
enemyGold += (CONFIG.goldPerSecond * 0.8) * deltaTime;
// 2. 敌人AI: 招募士兵 & 建城
// 每2秒敌人尝试招募士兵(基于黄金)
aiBuildTimer += deltaTime;
// AI 招募士兵 (每个城池独立尝试,我们简单按全局概率)
// 避免过于频繁,每1秒执行一次
if (aiBuildTimer >= 1.0) {
aiBuildTimer = 0;
// AI 招募: 如果有城池士兵少于上限, 并且金币够
for (let city of enemyCities) {
if (city.soldiers < CONFIG.aiMaxSoldiers && enemyGold >= CONFIG.aiSoldierCost) {
// 每个城池最多招募1个每次tick
city.soldiers += 1;
enemyGold -= CONFIG.aiSoldierCost;
}
}
// AI 建城: 如果黄金>150, 且城池数小于3, 新建一座城 (位置随机在右上区域)
if (enemyCities.length < 3 && enemyGold >= 180) {
// 找合适位置 (不与其他城池太近)
let attempts = 0;
let newX, newY, valid = false;
while (!valid && attempts < 50) {
newX = 550 + Math.random() * 280;
newY = 80 + Math.random() * 400;
valid = true;
for (let c of enemyCities) {
const dx = c.x - newX;
const dy = c.y - newY;
if (Math.hypot(dx, dy) < 70) {
valid = false;
break;
}
}
// 也别离玩家太近
for (let c of playerCities) {
if (Math.hypot(c.x - newX, c.y - newY) < 150) valid = false;
}
attempts++;
}
if (valid) {
enemyCities.push({ x: newX, y: newY, soldiers: 4 });
enemyGold -= 170; // 建城花费
}
}
}
// 玩家黄金显示更新
updateUI();
}
// ---------- 绘制 ----------
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制草地纹理
drawTerrain();
// 绘制所有城池
// 玩家城池 (绿色)
playerCities.forEach(city => drawCity(city, PLAYER_COLOR, 'player'));
// 敌人城池 (红色)
enemyCities.forEach(city => drawCity(city, ENEMY_COLOR, 'enemy'));
// 绘制连接线/装饰
// 游戏结束覆盖层
if (gameOver) {
ctx.fillStyle = 'rgba(0,0,0,0.7)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.font = 'bold 52px "Segoe UI", Roboto, sans-serif';
ctx.fillStyle = win ? '#e6d9a2' : '#c77b6b';
ctx.shadowColor = '#000000';
ctx.shadowBlur = 20;
ctx.textAlign = 'center';
ctx.fillText(win ? '🏆 你征服了敌人!' : '💀 城池被攻陷...', canvas.width/2, canvas.height/2 - 20);
ctx.font = '28px sans-serif';
ctx.fillStyle = '#ffffff';
ctx.fillText('点击"建城"重新开始', canvas.width/2, canvas.height/2 + 70);
ctx.shadowBlur = 0;
ctx.shadowColor = 'transparent';
// 禁用按钮状态取消, 但我们通过逻辑判断点击时重建
return;
}
// 绘制一些指引提示
ctx.font = 'bold 18px "Segoe UI"';
ctx.fillStyle = '#2f2f1f';
ctx.shadowBlur = 0;
ctx.fillText('🏰 你的城池', 30, 50);
ctx.fillStyle = '#5e2a2a';
ctx.fillText('⚔️ 敌方城池', 750, 50);
}
function drawTerrain() {
// 草地渐变
const grad = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
grad.addColorStop(0, '#b5d6a0');
grad.addColorStop(0.6, '#9bbf85');
grad.addColorStop(1, '#7fa86a');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 简单的道路/路径纹理
ctx.fillStyle = '#bfb37b20';
for (let i = 0; i < 200; i++) {
ctx.beginPath();
ctx.arc(Math.random() * 900, Math.random() * 600, Math.random() * 40 + 5, 0, Math.PI * 2);
ctx.fill();
}
// 画点小草丛
ctx.shadowBlur = 6;
ctx.shadowColor = '#567a4a';
for (let i = 0; i < 60; i++) {
ctx.fillStyle = '#588c4e30';
ctx.beginPath();
ctx.ellipse(Math.random() * 900, Math.random() * 600, 12, 6, 0, 0, Math.PI * 2);
ctx.fill();
}
ctx.shadowBlur = 0;
}
// 绘制单个城池
function drawCity(city, baseColor, type) {
const x = city.x;
const y = city.y;
const soldiers = city.soldiers;
// 阴影
ctx.shadowColor = '#2d2d1d';
ctx.shadowBlur = 14;
ctx.shadowOffsetY = 4;
// 主体城堡
ctx.beginPath();
ctx.arc(x, y, CITY_RADIUS, 0, Math.PI * 2);
ctx.fillStyle = baseColor;
ctx.fill();
ctx.strokeStyle = '#f3e6c9';
ctx.lineWidth = 4;
ctx.stroke();
// 城墙/塔楼装饰
ctx.shadowBlur = 6;
ctx.fillStyle = '#eeddb0';
ctx.beginPath();
ctx.arc(x - 8, y - 12, 10, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(x + 12, y - 16, 9, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(x, y - 22, 8, 0, Math.PI * 2);
ctx.fill();
// 城门
ctx.fillStyle = '#2a1e0e';
ctx.beginPath();
ctx.ellipse(x, y + 10, 12, 8, 0, 0, Math.PI * 2);
ctx.fill();
// 士兵数量显示
ctx.shadowBlur = 0;
ctx.shadowOffsetY = 0;
ctx.font = 'bold 22px "Segoe UI", Roboto, sans-serif';
ctx.fillStyle = '#ffffff';
ctx.strokeStyle = '#1d2b0e';
ctx.lineWidth = 4;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.strokeText(soldiers, x, y + 42);
ctx.fillText(soldiers, x, y + 42);
// 名称标识
ctx.font = 'bold 16px "Segoe UI"';
ctx.fillStyle = type === 'player' ? '#d4f0c0' : '#ffcfb0';
ctx.strokeStyle = '#0e1a0a';
ctx.lineWidth = 3;
ctx.strokeText(type === 'player' ? '我方' : '敌方', x, y - 45);
ctx.fillText(type === 'player' ? '我方' : '敌方', x, y - 45);
}
// ---------- 交互 (点击canvas) ----------
function handleCanvasClick(e) {
if (gameOver) {
// 游戏结束状态下, 点击canvas也可以重启(方便)
initGame();
draw();
return;
}
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / rect.width;
const scaleY = canvas.height / rect.height;
const mouseX = (e.clientX - rect.left) * scaleX;
const mouseY = (e.clientY - rect.top) * scaleY;
// 1. 检查是否点击了玩家城池 -> 招募士兵
for (let city of playerCities) {
const dx = mouseX - city.x;
const dy = mouseY - city.y;
if (Math.hypot(dx, dy) <= CITY_RADIUS + 10) {
// 招募士兵
if (playerGold >= CONFIG.soldierCost) {
if (city.soldiers < CONFIG.maxSoldiersPerCity) {
city.soldiers += 1;
playerGold -= CONFIG.soldierCost;
} else {
alert('该城池士兵已满 (' + CONFIG.maxSoldiersPerCity + ')');
}
} else {
alert('金币不足!需要 ' + CONFIG.soldierCost + ' 金币');
}
updateUI();
draw();
return;
}
}
// 2. 检查是否点击了敌方城池 -> 进攻
for (let city of enemyCities) {
const dx = mouseX - city.x;
const dy = mouseY - city.y;
if (Math.hypot(dx, dy) <= CITY_RADIUS + 10) {
attackEnemyCity(city);
draw();
return;
}
}
}
// 进攻逻辑 (简化但有趣)
function attackEnemyCity(targetCity) {
// 玩家总共士兵
const totalPlayerSoldiers = playerTotalSoldiers();
if (totalPlayerSoldiers <= 0) {
alert('你没有士兵可以进攻!点击自己的城池招募。');
return;
}
// 找到最近且士兵最多的玩家城池作为进攻主力 (为了游戏性,我们随机选择一座城,但优先最近)
let sourceCity = null;
let minDist = Infinity;
for (let pc of playerCities) {
if (pc.soldiers === 0) continue;
const dist = Math.hypot(pc.x - targetCity.x, pc.y - targetCity.y);
if (dist < minDist) {
minDist = dist;
sourceCity = pc;
}
}
if (!sourceCity || sourceCity.soldiers === 0) {
// 如果有士兵但没选到, 找任意
sourceCity = playerCities.find(c => c.soldiers > 0);
}
if (!sourceCity) {
alert('没有可用的士兵');
return;
}
// 进攻方派出该城所有士兵 (或者保留最低1个?更好玩: 派出80%士兵)
let attackForce = Math.floor(sourceCity.soldiers * 0.8);
if (attackForce < 1) attackForce = sourceCity.soldiers; // 至少派1个
if (attackForce < 1) {
alert('士兵不足');
return;
}
// 防守方士兵
const defenderForce = targetCity.soldiers;
// 战斗模拟: 简单对比,但有随机性
// 基础攻击力 = attackForce + 随机(0~5)
// 基础防御 = defenderForce + 随机(0~5) + 城池防御加成 (固定3)
const attackRoll = attackForce + Math.floor(Math.random() * 6);
const defendRoll = defenderForce + 3 + Math.floor(Math.random() * 7);
// 扣减士兵
if (attackRoll > defendRoll) {
// 进攻胜利, 攻方损失约30% 的进攻兵力
const losses = Math.floor(attackForce * (0.25 + Math.random() * 0.2));
const survivingAttackers = Math.max(0, attackForce - losses);
// 防守方全灭
targetCity.soldiers = 0;
// 从原城池扣除进攻的士兵
sourceCity.soldiers -= attackForce;
// 胜利后, 如果城池还有防守方? 已经0, 我们移除此城池 (并奖励金币)
// 移除敌方城池
const index = enemyCities.indexOf(targetCity);
if (index !== -1) {
enemyCities.splice(index, 1);
// 玩家获得战利品
playerGold += 120;
// 如果敌方没有城池了,游戏胜利
if (enemyCities.length === 0) {
gameOver = true;
win = true;
updateUI();
draw();
return;
}
}
// 如果有幸存者而且玩家城池还有空间,可以把幸存者归队(简化: 加到sourceCity,不超过上限)
if (survivingAttackers > 0) {
sourceCity.soldiers = Math.min(CONFIG.maxSoldiersPerCity, sourceCity.soldiers + survivingAttackers);
}
// 提示
alert(`⚔️ 进攻胜利!损失 ${losses} 名士兵,获得 120 金币。`);
} else {
// 进攻失败
// 进攻方全灭 (减去所有进攻兵力)
sourceCity.soldiers = Math.max(0, sourceCity.soldiers - attackForce);
// 防守方损失一部分 (进攻方造成的伤害)
const defenderLoss = Math.min(defenderForce, Math.floor(attackForce * (0.4 + Math.random() * 0.4)));
targetCity.soldiers = Math.max(0, defenderForce - defenderLoss);
// 如果防守方士兵降为0,城池保留但士兵0,仍然存在
if (targetCity.soldiers === 0) {
// 城池已被攻陷? 逻辑上应该移除,但为了游戏可继续,如果为0则移除
const index = enemyCities.indexOf(targetCity);
if (index !== -1 && targetCity.soldiers === 0) {
enemyCities.splice(index, 1);
playerGold += 80;
if (enemyCities.length === 0) {
gameOver = true;
win = true;
}
}
}
alert(`⚔️ 进攻失败…… 损失 ${attackForce} 名士兵,敌方损失 ${defenderLoss} 人。`);
}
updateUI();
// 检查玩家是否还有士兵,如果没有且城池数大于0,没事
}
// 建造新玩家城池 (消耗金币)
function buildCity() {
if (gameOver) {
// 重新开始
initGame();
draw();
return;
}
if (playerGold < CONFIG.buildCost) {
alert('金币不足,需要 ' + CONFIG.buildCost + ' 金币');
return;
}
if (playerCities.length >= 3) {
alert('最多拥有三座城池');
return;
}
// 寻找合适位置 (在玩家区域,避开已有玩家和敌人)
let attempts = 0;
let newX, newY, valid = false;
while (!valid && attempts < 100) {
newX = 120 + Math.random() * 340; // 左下区域
newY = 300 + Math.random() * 250;
valid = true;
// 与现有玩家城池距离>100
for (let c of playerCities) {
if (Math.hypot(c.x - newX, c.y - newY) < 100) {
valid = false;
break;
}
}
// 与敌人城池距离>150
for (let c of enemyCities) {
if (Math.hypot(c.x - newX, c.y - newY) < 160) {
valid = false;
break;
}
}
attempts++;
}
if (valid) {
playerCities.push({ x: newX, y: newY, soldiers: 3 }); // 新建城送3个兵
playerGold -= CONFIG.buildCost;
updateUI();
draw();
} else {
alert('没有合适的位置建城,请再试一次');
}
}
// ---------- 游戏主循环 (基于时间增量) ----------
function gameLoop(now) {
if (!lastTime) lastTime = now;
const deltaTime = Math.min(0.1, (now - lastTime) / 1000); // 限制最大步长
lastTime = now;
if (!gameOver) {
updateGame(deltaTime);
}
draw();
requestAnimationFrame(gameLoop);
}
// ---------- 事件绑定 ----------
canvas.addEventListener('click', handleCanvasClick);
buildBtn.addEventListener('click', () => {
buildCity();
});
attackBtn.addEventListener('click', () => {
if (gameOver) {
initGame();
draw();
return;
}
// 进攻按钮:提示玩家点击敌方城池(降低操作门槛)
alert('🔍 点击任意敌方城池发起进攻!');
});
// 重新开始快捷键 (R键, 但无伤大雅)
window.addEventListener('keydown', (e) => {
if (e.key.toLowerCase() === 'r' && gameOver) {
initGame();
draw();
}
});
// ---------- 启动 ----------
initGame();
draw();
requestAnimationFrame(gameLoop);
})();
</script>
</body>
</html>
玩法与操作说明
游戏围绕资源管理与战术决策展开,您需要积累金币,招募士兵并扩张城池,最终消灭所有敌方城池。
- 资源与招募:屏幕顶部的面板会显示您的金币和士兵总数,金币会随时间自动增长。点击您自己的绿色城池,可以花费30金币招募一名士兵,每个城池最多容纳40名士兵。
- 建造与扩张:点击“建城”按钮可以花费100金币建造一座新城池,最多可拥有三座,新建的城池会自带3名士兵。
- 进攻与战斗:点击任意红色敌方城池即可发起进攻,系统会自动从距离最近且士兵最多的我方城池中派出80%的兵力,战斗结果由双方兵力加随机值决定,胜利会获得金币奖励并可能占领敌方城池。
- 游戏目标:当所有敌方城池被消灭时,您将获得胜利,如果您的所有士兵耗尽且无法招募,则可能面临失败。
优化建议: 您可以在代码开头的 CONFIG 对象中调整游戏参数,例如修改 goldPerSecond(金币增速)或 soldierCost(士兵成本)来改变游戏节奏。

