可以建立城池打仗的游戏,攻城略地,建造你的专属城池,征战四方


这是您需要的“建城打仗”游戏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, #1a2a1f 0%, #2d3e2a 100%);
display: flex;
align-items: center;
justify-content: center;
font-family: 'Segoe UI', Roboto, system-ui, sans-serif;
}
.game-container {
background: #3b4f38;
padding: 20px 25px 25px 25px;
border-radius: 40px 40px 30px 30px;
box-shadow: 0 20px 30px rgba(0,0,0,0.6), inset 0 2px 5px #7e9b72;
border: 1px solid #7b9a6e;
}
canvas {
display: block;
margin: 0 auto;
border-radius: 24px;
box-shadow: inset 0 0 0 2px #2a3527, 0 10px 15px #0f130e;
background: #4f6748;
cursor: crosshair;
}
.hud {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 12px;
color: #f0e9d0;
text-shadow: 2px 2px 0 #1f2a1a;
font-weight: bold;
padding: 0 10px;
}
.stats {
display: flex;
gap: 28px;
background: #2d3e28;
padding: 8px 25px;
border-radius: 50px;
border: 1px solid #8baa7c;
box-shadow: inset 0 0 8px #1a2315;
}
.stat-item {
display: flex;
align-items: center;
gap: 8px;
font-size: 18px;
}
.gold-icon, .soldier-icon, .city-icon {
font-size: 22px;
filter: drop-shadow(0 2px 2px black);
}
.buttons {
display: flex;
gap: 15px;
}
button {
background: #6a8a5f;
border: none;
border-radius: 40px;
padding: 8px 24px;
font-weight: bold;
font-size: 16px;
color: #f5f2e3;
text-shadow: 1px 1px 0 #2b3a24;
box-shadow: 0 6px 0 #2b3a24, 0 8px 10px #0e120c;
cursor: pointer;
transition: all 0.08s ease;
letter-spacing: 0.5px;
border: 1px solid #a7c59a;
}
button:active {
transform: translateY(5px);
box-shadow: 0 1px 0 #2b3a24, 0 5px 8px #0e120c;
}
button:disabled {
opacity: 0.5;
transform: translateY(5px);
box-shadow: 0 1px 0 #2b3a24, 0 5px 8px #0e120c;
pointer-events: none;
}
.message {
font-size: 16px;
font-style: italic;
color: #e9e1b0;
background: #2d3e28b3;
padding: 6px 18px;
border-radius: 30px;
border: 1px solid #b1c7a3;
backdrop-filter: blur(2px);
white-space: nowrap;
}
</style>
</head>
<body>
<div class="game-container">
<canvas id="gameCanvas" width="900" height="600"></canvas>
<div class="hud">
<div class="stats">
<div class="stat-item"><span class="gold-icon">🪙</span> <span id="goldDisplay">300</span></div>
<div class="stat-item"><span class="soldier-icon">⚔️</span> <span id="armyDisplay">0</span></div>
<div class="stat-item"><span class="city-icon">🏰</span> <span id="cityDisplay">0</span></div>
</div>
<div class="message" id="messageBox">点击绿色草地建城,再选兵营招兵</div>
<div class="buttons">
<button id="resetBtn">新游戏</button>
</div>
</div>
</div>
<script>
(function() {
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 显示元素
const goldSpan = document.getElementById('goldDisplay');
const armySpan = document.getElementById('armyDisplay');
const citySpan = document.getElementById('cityDisplay');
const messageBox = document.getElementById('messageBox');
// 游戏配置
const CONFIG = {
cityCost: 200, // 建城花费
soldierCost: 50, // 招兵花费
cityIncome: 30, // 每座城每回合收入
startGold: 300,
startCityCount: 0,
startArmy: 0,
maxCities: 4, // 最多4座城,防止太乱
};
// 游戏状态
let gold = CONFIG.startGold;
let army = CONFIG.startArmy;
let cities = []; // 每个城: { x, y, id }
let selectedCityId = null; // 当前选中的城市ID(用于招兵)
let income = 0; // 每回合收入显示用
// 用于提示信息的计时器
let messageTimer = null;
// 初始化
function initGame() {
gold = CONFIG.startGold;
army = CONFIG.startArmy;
cities = [];
selectedCityId = null;
updateUI();
setMessage('点击绿色草地建立第一座城池 (花费200金)');
draw();
}
// 更新UI文本
function updateUI() {
goldSpan.textContent = Math.floor(gold);
armySpan.textContent = army;
citySpan.textContent = cities.length;
// 计算收入预览
income = cities.length * CONFIG.cityIncome;
// 如果收入>0,修改消息框提示? 但消息是动态的,不覆盖
}
// 设置消息(自动清除之前的定时器)
function setMessage(text, isTemporary = false) {
if (messageTimer) {
clearTimeout(messageTimer);
messageTimer = null;
}
messageBox.textContent = text;
if (isTemporary) {
messageTimer = setTimeout(() => {
if (cities.length === 0) {
messageBox.textContent = '点击绿色草地建城 (200金)';
} else {
messageBox.textContent = `已建城 ${cities.length} 座 · 点击兵营招兵 (50金)`;
}
messageTimer = null;
}, 2000);
}
}
// 永久消息 (不自动消失)
function setDefaultMessage() {
if (cities.length === 0) {
messageBox.textContent = '点击绿色草地建城 (200金)';
} else if (selectedCityId !== null) {
messageBox.textContent = `已选中城池 #${selectedCityId} · 点击兵营(城下)招兵 (50金)`;
} else {
messageBox.textContent = `已建城 ${cities.length} 座 · 点击兵营招兵 (50金)`;
}
}
// 绘制游戏
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 1. 绘制草地(带纹理感)
ctx.fillStyle = '#7aa06b';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 草地纹理网格
ctx.strokeStyle = '#6a8f5c';
ctx.lineWidth = 1.5;
for (let i = 0; i < canvas.width; i += 40) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i, canvas.height);
ctx.strokeStyle = '#6a8f5c30';
ctx.stroke();
}
for (let i = 0; i < canvas.height; i += 40) {
ctx.beginPath();
ctx.moveTo(0, i);
ctx.lineTo(canvas.width, i);
ctx.strokeStyle = '#6a8f5c30';
ctx.stroke();
}
// 2. 绘制所有城池
cities.forEach(city => {
drawCity(city);
});
// 3. 绘制选中高亮
if (selectedCityId !== null) {
const city = cities.find(c => c.id === selectedCityId);
if (city) {
ctx.beginPath();
ctx.arc(city.x, city.y, 32, 0, Math.PI * 2);
ctx.strokeStyle = '#ffd966';
ctx.lineWidth = 5;
ctx.setLineDash([8, 8]);
ctx.stroke();
ctx.setLineDash([]); // 重置
}
}
// 4. 绘制收入浮标 (每座城一个金币图标)
cities.forEach(city => {
ctx.font = 'bold 18px "Segoe UI", sans-serif';
ctx.fillStyle = '#ffd966';
ctx.shadowColor = '#4d3b00';
ctx.shadowBlur = 8;
ctx.fillText(`+${CONFIG.cityIncome}`, city.x + 20, city.y - 30);
ctx.shadowBlur = 0;
});
// 5. 绘制提示:没有城市时加一些标记
if (cities.length === 0) {
ctx.font = 'italic 28px "Segoe UI", sans-serif';
ctx.fillStyle = '#2d3e28b3';
ctx.shadowBlur = 0;
ctx.fillText('点击草地建城', 320, 300);
}
}
// 绘制单个城市
function drawCity(city) {
const { x, y, id } = city;
// 城池地基(石砖)
ctx.beginPath();
ctx.ellipse(x, y + 10, 36, 16, 0, 0, Math.PI * 2);
ctx.fillStyle = '#5f6b55';
ctx.shadowColor = '#1f2a1a';
ctx.shadowBlur = 12;
ctx.fill();
ctx.shadowBlur = 0;
// 城墙主体
ctx.fillStyle = '#b8a78b';
ctx.shadowColor = '#2b2b1a';
ctx.shadowBlur = 8;
ctx.beginPath();
ctx.roundRect(x - 28, y - 25, 56, 45, 8);
ctx.fill();
// 城垛 (顶部)
ctx.fillStyle = '#9e8d72';
ctx.shadowBlur = 4;
for (let i = -22; i <= 22; i += 12) {
ctx.beginPath();
ctx.roundRect(x + i - 5, y - 36, 10, 14, 4);
ctx.fill();
}
// 城门
ctx.fillStyle = '#4d3e2b';
ctx.shadowBlur = 0;
ctx.beginPath();
ctx.roundRect(x - 10, y - 5, 20, 25, [8, 8, 0, 0]);
ctx.fill();
// 门把手
ctx.fillStyle = '#f0d98c';
ctx.beginPath();
ctx.arc(x - 5, y + 8, 2, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(x + 5, y + 8, 2, 0, Math.PI * 2);
ctx.fill();
// 窗户
ctx.fillStyle = '#f0e6c5';
ctx.beginPath();
ctx.roundRect(x - 20, y - 20, 10, 10, 3);
ctx.fill();
ctx.beginPath();
ctx.roundRect(x + 10, y - 20, 10, 10, 3);
ctx.fill();
// 兵营图标:在城下方画个小兵符号 (表示点击这里招兵)
ctx.font = '20px "Segoe UI", "Segoe UI Emoji"';
ctx.fillStyle = '#3d2b1a';
ctx.shadowBlur = 0;
ctx.fillText('⚔️', x - 8, y + 42); // 兵营标记
// 半透明圈表示可点击区域
ctx.beginPath();
ctx.arc(x, y + 30, 18, 0, Math.PI * 2);
ctx.fillStyle = '#d9b38240';
ctx.fill();
ctx.strokeStyle = '#a9774d';
ctx.lineWidth = 2;
ctx.stroke();
// 城市编号 (小ID)
ctx.font = 'bold 16px "Segoe UI"';
ctx.fillStyle = '#fff9e6';
ctx.shadowColor = '#3b2b1a';
ctx.shadowBlur = 6;
ctx.fillText(`#${id}`, x - 8, y - 48);
ctx.shadowBlur = 0;
}
// 工具:Canvas roundRect
CanvasRenderingContext2D.prototype.roundRect = function (x, y, w, h, r) {
if (w < 2 * r) r = w / 2;
if (h < 2 * r) r = h / 2;
this.moveTo(x + r, y);
this.lineTo(x + w - r, y);
this.quadraticCurveTo(x + w, y, x + w, y + r);
this.lineTo(x + w, y + h - r);
this.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
this.lineTo(x + r, y + h);
this.quadraticCurveTo(x, y + h, x, y + h - r);
this.lineTo(x, y + r);
this.quadraticCurveTo(x, y, x + r, y);
return this;
};
// 检查坐标是否在某个城池的“招兵”区域 (圆形)
function hitTestBarracks(clickX, clickY) {
for (let city of cities) {
const dx = clickX - city.x;
const dy = clickY - (city.y + 30);
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist <= 22) { // 点击兵营区域
return city;
}
}
return null;
}
// 检查点击区域是否可建城 (不可与已有城市重叠,至少60距离)
function canBuildCity(x, y) {
// 边界限制
if (x < 60 || x > canvas.width - 60 || y < 70 || y > canvas.height - 70) return false;
// 与现有城市距离检查
for (let city of cities) {
const dx = x - city.x;
const dy = y - city.y;
if (Math.sqrt(dx * dx + dy * dy) < 75) return false;
}
return true;
}
// 建城逻辑
function tryBuildCity(x, y) {
if (cities.length >= CONFIG.maxCities) {
setMessage('❌ 最多只能拥有4座城池!', true);
return false;
}
if (gold < CONFIG.cityCost) {
setMessage('💰 金币不足,无法建城!', true);
return false;
}
if (!canBuildCity(x, y)) {
setMessage('📍 此处无法建城:太靠近边界或其他城池', true);
return false;
}
// 扣钱,建城
gold -= CONFIG.cityCost;
const newId = cities.length + 1;
cities.push({ x, y, id: newId });
// 选中新建的城
selectedCityId = newId;
updateUI();
draw();
setMessage(`🏰 建城成功!城池 #${newId} 已建立`, true);
return true;
}
// 招兵
function tryRecruit(city) {
if (gold < CONFIG.soldierCost) {
setMessage('💰 金币不足,无法招募士兵!', true);
return;
}
// 增加士兵
gold -= CONFIG.soldierCost;
army += 1;
selectedCityId = city.id;
updateUI();
draw();
setMessage(`⚔️ 城池 #${city.id} 招募了1名士兵!`, true);
}
// 回合结束?我们采用“点击城池招兵”即时制,所以不需要传统回合。
// 但为了经济,我们可以在每次建城或者招兵时没有收入,改为按每座城自动产出?
// 更合理的即时收入:按时间?但策略游戏需要收入,我们采用手动收取收入的方式?
// 添加一个“征税”的逻辑吧,但更简单:每次招兵/建城时,不自动加钱,加一个“征收赋税”按钮?
// 或者每建一座城,定期加钱?可以用定时器:每3秒加一次收入?会让游戏更动态。
// 我们改用定时器: 每3秒根据城市数量加金币,并在消息栏提示。
// 为了让玩家有反馈,我们更新收入显示。
// 更新收入定时器
function startIncomeTimer() {
setInterval(() => {
if (cities.length > 0) {
const earned = cities.length * CONFIG.cityIncome;
gold += earned;
updateUI();
draw(); // 重绘可更新金币显示 (但金币显示在UI,canvas上无变化)
// 可选消息提示 (不覆盖重要消息),但可能会干扰,所以仅在控制台
// 但为了玩家感知,短暂显示
if (earned > 0) {
// 用轻提示,但不影响默认消息,我们使用临时消息但可覆盖
// 但如果玩家正在操作,消息被覆盖也没关系。
// 这里使用 setMessage 会覆盖消息并自动恢复,但可能频繁
// 减少干扰:仅在收入时闪烁一下,不改变消息
// 我们改一下:在消息框旁边显示?不好弄。
// 算了,就不显示了,玩家看金币数字跳动即可。
}
}
}, 3000);
}
// 点击Canvas事件
function handleCanvasClick(e) {
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. 优先检测是否点击了兵营(招兵)
const clickedCityForBarracks = hitTestBarracks(mouseX, mouseY);
if (clickedCityForBarracks) {
tryRecruit(clickedCityForBarracks);
return;
}
// 2. 检测是否点击了某个城池主体(选中该城,方便查看)
let clickedCity = null;
for (let city of cities) {
const dx = mouseX - city.x;
const dy = mouseY - (city.y - 5);
if (Math.abs(dx) < 40 && Math.abs(dy) < 45) {
clickedCity = city;
break;
}
}
if (clickedCity) {
selectedCityId = clickedCity.id;
draw();
setMessage(`🏰 已选中城池 #${clickedCity.id} · 点击下方兵营招兵`, true);
return;
}
// 3. 否则尝试建城
tryBuildCity(mouseX, mouseY);
}
// 重置游戏
function resetGame() {
// 清除收入定时器? 由于无法clearInterval,我们通过重启页面? 不,用标志。
// 简单起见,重新初始化状态,但保留定时器会累加,所以需要清除之前的定时器。
// 用一个全局变量保存定时器ID
if (window.incomeInterval) {
clearInterval(window.incomeInterval);
}
initGame();
// 重新启动收入定时器
window.incomeInterval = setInterval(() => {
if (cities.length > 0) {
const earned = cities.length * CONFIG.cityIncome;
gold += earned;
updateUI();
// 画布上的金币数字不需要重绘,但为了选中状态保留
draw();
}
}, 3000);
setMessage('新游戏开始!点击草地建城', true);
}
// 启动游戏
function startGame() {
initGame();
// 启动收入定时器
if (window.incomeInterval) clearInterval(window.incomeInterval);
window.incomeInterval = setInterval(() => {
if (cities.length > 0) {
const earned = cities.length * CONFIG.cityIncome;
gold += earned;
updateUI();
// 短暂视觉反馈? 仅仅重绘没啥变化, 但更新UI文本即可
// 可闪烁金币显示, 但略过
}
}, 3000);
// 事件绑定
canvas.addEventListener('click', handleCanvasClick);
document.getElementById('resetBtn').addEventListener('click', () => {
resetGame();
});
}
// 页面加载启动
window.addEventListener('load', startGame);
})();
</script>
</body>
</html>
玩法与操作说明
您可以先建立城池,再招募士兵来壮大军队,游戏的核心循环围绕着金币的获取与消耗展开。
- 建城与招兵:点击地图上的绿色草地即可花费200金币建立城池,城池下方有一个兵营图标区域,点击即可花费50金币招募一名士兵,每座城池每3秒会自动产出30金币。
- 状态与反馈:屏幕顶部的状态栏会实时显示您的金币、士兵和城池数量,当您进行建城、招兵或金币不足等操作时,中央的消息框会给出明确的文字提示。
- 策略与限制:您最多只能拥有4座城池,并且建城位置不能太靠近地图边界或其他城池,选中已有的城池(点击城池主体)可以高亮显示,方便您确认招兵的位置。
优化建议: 您可以根据需要调整代码开头的CONFIG对象中的数值,例如修改cityCost(建城费用)、soldierCost(招兵费用)或cityIncome(每座城每回合收入)来改变游戏难度和经济节奏。

发表评论