简介
游戏由HTML制作而成,玩家将在海域场景中操控战舰,通过合理规划航线、躲避障碍、攻击敌方船只来赢得胜利。玩家可以逐步解锁更强的舰船,在一次次海上对战中积累优势.
(请使用UTF-8格式保存)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2D海战游戏 - 增强版</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Font Awesome -->
<link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#3b82f6',
secondary: '#ef4444',
ocean: '#93c5fd',
land: '#84cc16',
'land-occupied': '#f97316',
gold: '#f59e0b',
silver: '#94a3b8'
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif']
},
animation: {
'pulse-glow': 'pulse-glow 2s ease-in-out infinite',
'float': 'float 3s ease-in-out infinite',
'shake': 'shake 0.5s ease-in-out',
'fade-in': 'fade-in 0.3s ease-out'
},
keyframes: {
'pulse-glow': {
'0%, 100%': { opacity: 0.7, boxShadow: '0 0 5px rgba(59, 130, 246, 0.5)' },
'50%': { opacity: 1, boxShadow: '0 0 20px rgba(59, 130, 246, 0.8)' }
},
'float': {
'0%, 100%': { transform: 'translateY(0px)' },
'50%': { transform: 'translateY(-5px)' }
},
'shake': {
'0%, 100%': { transform: 'translateX(0)' },
'25%': { transform: 'translateX(-5px)' },
'75%': { transform: 'translateX(5px)' }
},
'fade-in': {
'0%': { opacity: 0, transform: 'translateY(10px)' },
'100%': { opacity: 1, transform: 'translateY(0)' }
}
}
}
}
}
</script>
<style type="text/tailwindcss">
@layer utilities {
.pixel-art {
image-rendering: pixelated;
image-rendering: crisp-edges;
}
.game-container {
position: relative;
overflow: hidden;
background: linear-gradient(180deg, #1e40af 0%, #3b82f6 50%, #60a5fa 100%);
cursor: crosshair;
box-shadow: inset 0 0 50px rgba(0, 0, 0, 0.3);
}
.unit {
position: absolute;
width: 40px;
height: 40px;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 10;
cursor: pointer;
animation: float 3s ease-in-out infinite;
}
.unit img {
width: 100%;
height: 100%;
object-fit: contain;
filter: drop-shadow(2px 2px 3px rgba(0, 0, 0, 0.3));
}
.unit.selected {
outline: 3px solid #fbbf24;
outline-offset: 3px;
animation: pulse-glow 1s ease-in-out infinite;
z-index: 15;
}
.unit.enemy {
animation: float 2.5s ease-in-out infinite;
}
.island {
position: absolute;
z-index: 5;
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 50%;
box-shadow:
inset 0 0 20px rgba(0, 0, 0, 0.2),
0 5px 15px rgba(0, 0, 0, 0.3);
overflow: hidden;
}
.island::before {
content: '';
position: absolute;
top: -10%;
left: -10%;
right: -10%;
bottom: -10%;
background: linear-gradient(45deg,
rgba(255,255,255,0.1) 0%,
rgba(255,255,255,0.05) 25%,
rgba(0,0,0,0.1) 50%,
rgba(255,255,255,0.05) 75%,
rgba(255,255,255,0.1) 100%);
border-radius: inherit;
}
.island.state-0 { filter: brightness(1) saturate(1.2); }
.island.state-1 { filter: brightness(0.9) saturate(1.1); }
.island.state-2 { filter: brightness(0.8) saturate(1); }
.island.state-3 { filter: brightness(0.7) saturate(0.9); }
.island.state-4 { filter: brightness(0.6) saturate(0.8); }
.territory {
position: absolute;
z-index: 4;
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 50%;
pointer-events: none;
}
.territory.player {
background: radial-gradient(circle, rgba(59, 130, 246, 0.2) 0%, rgba(59, 130, 246, 0.05) 70%, transparent 100%);
box-shadow: 0 0 30px rgba(59, 130, 246, 0.3);
}
.territory.enemy {
background: radial-gradient(circle, rgba(239, 68, 68, 0.2) 0%, rgba(239, 68, 68, 0.05) 70%, transparent 100%);
box-shadow: 0 0 30px rgba(239, 68, 68, 0.3);
}
.territory.neutral {
background: radial-gradient(circle, rgba(148, 163, 184, 0.2) 0%, rgba(148, 163, 184, 0.05) 70%, transparent 100%);
box-shadow: 0 0 30px rgba(148, 163, 184, 0.2);
}
.territory.contested {
background: radial-gradient(circle, rgba(245, 158, 11, 0.3) 0%, rgba(245, 158, 11, 0.1) 70%, transparent 100%);
box-shadow: 0 0 40px rgba(245, 158, 11, 0.4);
animation: pulse-glow 2s ease-in-out infinite;
}
.control-panel {
background: linear-gradient(180deg, rgba(255, 255, 255, 0.95) 0%, rgba(248, 250, 252, 0.95) 100%);
backdrop-filter: blur(10px);
border-radius: 16px;
box-shadow:
0 10px 25px -5px rgba(0, 0, 0, 0.1),
0 10px 10px -5px rgba(0, 0, 0, 0.04),
inset 0 1px 0 rgba(255, 255, 255, 0.5);
border: 1px solid rgba(255, 255, 255, 0.3);
}
.btn {
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
position: relative;
overflow: hidden;
font-weight: 600;
letter-spacing: 0.025em;
}
.btn::after {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: left 0.5s;
}
.btn:hover::after {
left: 100%;
}
.btn:hover {
transform: translateY(-3px);
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}
.btn:active {
transform: translateY(-1px);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
box-shadow: none;
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
display: inline-block;
margin-right: 8px;
position: relative;
}
.status-indicator::after {
content: '';
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
border-radius: 50%;
animation: pulse-glow 2s infinite;
}
.status-indicator.player {
background-color: #3b82f6;
}
.status-indicator.player::after {
background: rgba(59, 130, 246, 0.3);
}
.status-indicator.enemy {
background-color: #ef4444;
}
.status-indicator.enemy::after {
background: rgba(239, 68, 68, 0.3);
}
.status-indicator.neutral {
background-color: #94a3b8;
}
.status-indicator.contested {
background-color: #f59e0b;
animation: pulse-glow 1.5s infinite;
}
.tooltip {
position: absolute;
background: linear-gradient(135deg, rgba(30, 41, 59, 0.95) 0%, rgba(15, 23, 42, 0.95) 100%);
color: white;
padding: 8px 12px;
border-radius: 8px;
font-size: 12px;
z-index: 1000;
pointer-events: none;
opacity: 0;
transition: opacity 0.2s ease;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.3);
max-width: 250px;
animation: fade-in 0.2s ease-out;
}
.explosion {
position: absolute;
width: 80px;
height: 80px;
z-index: 20;
pointer-events: none;
animation: fade-in 0.1s ease-out;
}
.path-line {
position: absolute;
height: 2px;
transform-origin: 0 50%;
z-index: 3;
pointer-events: none;
border-radius: 1px;
}
.path-line.player {
background: linear-gradient(90deg,
rgba(59, 130, 246, 0) 0%,
rgba(59, 130, 246, 0.8) 20%,
rgba(59, 130, 246, 0.8) 80%,
rgba(59, 130, 246, 0) 100%);
box-shadow: 0 0 10px rgba(59, 130, 246, 0.5);
}
.path-line.enemy {
background: linear-gradient(90deg,
rgba(239, 68, 68, 0) 0%,
rgba(239, 68, 68, 0.8) 20%,
rgba(239, 68, 68, 0.8) 80%,
rgba(239, 68, 68, 0) 100%);
box-shadow: 0 0 10px rgba(239, 68, 68, 0.5);
}
.island-label {
position: absolute;
bottom: -30px;
left: 50%;
transform: translateX(-50%);
background: linear-gradient(135deg, rgba(0, 0, 0, 0.85) 0%, rgba(30, 41, 59, 0.9) 100%);
color: white;
padding: 4px 12px;
border-radius: 15px;
font-size: 11px;
font-weight: 600;
white-space: nowrap;
z-index: 6;
backdrop-filter: blur(5px);
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3);
min-width: 80px;
text-align: center;
}
.wave {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(180deg,
transparent 0%,
rgba(255, 255, 255, 0.1) 50%,
transparent 100%);
animation: wave-animation 10s linear infinite;
pointer-events: none;
z-index: 1;
opacity: 0.3;
}
@keyframes wave-animation {
0% { transform: translateY(0) translateX(0); }
100% { transform: translateY(-100%) translateX(50px); }
}
.resource-gain {
position: absolute;
color: #10b981;
font-weight: bold;
font-size: 14px;
pointer-events: none;
z-index: 30;
animation: float-up 1s ease-out forwards;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}
@keyframes float-up {
0% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(-30px); }
}
.health-bar {
position: absolute;
top: -8px;
left: 5px;
right: 5px;
height: 4px;
background: rgba(0, 0, 0, 0.3);
border-radius: 2px;
overflow: hidden;
z-index: 11;
}
.health-fill {
height: 100%;
background: linear-gradient(90deg, #10b981 0%, #22c55e 100%);
transition: width 0.3s ease;
border-radius: 2px;
}
.notification {
position: fixed;
top: 20px;
right: 20px;
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white;
padding: 12px 20px;
border-radius: 12px;
box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3);
z-index: 1000;
animation: fade-in 0.3s ease-out;
max-width: 300px;
transform: translateX(100%);
animation: slide-in 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55) forwards;
}
@keyframes slide-in {
0% { transform: translateX(100%); opacity: 0; }
100% { transform: translateX(0); opacity: 1; }
}
.progress-bar {
height: 6px;
border-radius: 3px;
overflow: hidden;
background: rgba(0, 0, 0, 0.1);
}
.progress-fill {
height: 100%;
transition: width 0.5s ease-out;
border-radius: 3px;
}
}
</style>
</head>
<body class="bg-gradient-to-br from-gray-900 to-gray-800 font-sans text-gray-100">
<div class="container mx-auto px-4 py-6">
<!-- Game Header -->
<div class="flex flex-col md:flex-row justify-between items-center mb-6">
<div class="mb-4 md:mb-0">
<h1 class="text-3xl font-bold bg-gradient-to-r from-primary via-blue-400 to-cyan-400 bg-clip-text text-transparent">
<i class="fa fa-ship mr-3"></i>海战战略游戏
</h1>
<p class="text-gray-400 mt-1">征服海洋,统治岛屿!</p>
</div>
<div class="flex items-center space-x-6">
<div class="flex items-center gap-4">
<div class="flex items-center">
<span class="status-indicator player"></span>
<span class="text-sm">我方领地</span>
</div>
<div class="flex items-center">
<span class="status-indicator enemy"></span>
<span class="text-sm">敌方领地</span>
</div>
<div class="flex items-center">
<span class="status-indicator neutral"></span>
<span class="text-sm">中立领地</span>
</div>
<div class="flex items-center">
<span class="status-indicator contested"></span>
<span class="text-sm">争夺中</span>
</div>
</div>
</div>
</div>
<div class="flex flex-col lg:flex-row gap-6">
<!-- Game Area -->
<div class="lg:w-3/4">
<div class="relative rounded-2xl overflow-hidden shadow-2xl">
<div class="absolute inset-0 wave"></div>
<div id="game-container" class="game-container w-full" style="height: 700px;">
<!-- Game elements will be rendered here -->
</div>
</div>
</div>
<!-- Control Panel -->
<div class="lg:w-1/4">
<!-- Resources Panel -->
<div class="control-panel p-6 mb-6">
<h2 class="text-xl font-bold mb-6 text-gray-800 flex items-center">
<i class="fa fa-diamond mr-2 text-primary"></i>资源管理
</h2>
<div class="space-y-4">
<div>
<div class="flex justify-between items-center mb-1">
<span class="text-gray-700 font-medium">金币</span>
<span id="money" class="font-bold text-2xl text-gold">1000</span>
</div>
<div class="progress-bar">
<div id="money-progress" class="progress-fill bg-gradient-to-r from-yellow-400 to-yellow-600" style="width: 50%"></div>
</div>
</div>
<div>
<div class="flex justify-between items-center mb-1">
<span class="text-gray-700 font-medium">领地控制</span>
<span id="territory" class="font-bold text-2xl text-primary">100%</span>
</div>
<div class="progress-bar">
<div id="territory-progress" class="progress-fill bg-gradient-to-r from-primary to-blue-600" style="width: 100%"></div>
</div>
<div class="text-xs text-gray-500 mt-1">敌方控制: <span id="enemy-territory">0%</span></div>
</div>
</div>
</div>
<!-- Unit Production -->
<div class="control-panel p-6 mb-6">
<h2 class="text-xl font-bold mb-6 text-gray-800 flex items-center">
<i class="fa fa-industry mr-2 text-primary"></i>军事生产
</h2>
<div class="space-y-4">
<!-- Soldier -->
<div class="bg-gradient-to-r from-gray-50 to-gray-100 p-4 rounded-xl border border-gray-200 hover:border-primary transition-all duration-300">
<div class="flex items-center justify-between mb-3">
<div>
<span class="font-bold text-gray-800">士兵</span>
<div class="text-xs text-gray-500 mt-1">陆地单位,平衡型</div>
</div>
<div class="text-right">
<div class="text-sm bg-gradient-to-r from-yellow-500 to-yellow-600 text-white px-3 py-1 rounded-full font-bold">50 金币</div>
</div>
</div>
<div class="flex items-center gap-3">
<div class="relative">
<img src="https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/05dc1e32ccdb45fc82b0c1155696dcbb~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762158&x-signature=TkOsDtCaeOJQP4gOXilrz59wjLI%3D"
alt="Soldier" class="w-12 h-12 pixel-art">
<div class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 rounded-full text-xs flex items-center justify-center text-white font-bold">ATK</div>
</div>
<div class="flex-1">
<div class="text-xs text-gray-600 space-y-1">
<div class="flex justify-between">
<span>攻击力: <span class="font-bold text-red-500">5</span></span>
<span>生命值: <span class="font-bold text-green-500">10</span></span>
</div>
<div class="flex justify-between">
<span>速度: <span class="font-bold text-blue-500">1</span></span>
<span>类型: 陆地</span>
</div>
</div>
</div>
<button id="produce-soldier" class="btn bg-gradient-to-r from-primary to-blue-600 text-white px-4 py-2 rounded-lg hover:from-blue-600 hover:to-blue-700">
<i class="fa fa-plus mr-1"></i>生产
</button>
</div>
</div>
<!-- Ship -->
<div class="bg-gradient-to-r from-gray-50 to-gray-100 p-4 rounded-xl border border-gray-200 hover:border-primary transition-all duration-300">
<div class="flex items-center justify-between mb-3">
<div>
<span class="font-bold text-gray-800">战舰</span>
<div class="text-xs text-gray-500 mt-1">海军单位,强火力</div>
</div>
<div class="text-right">
<div class="text-sm bg-gradient-to-r from-yellow-500 to-yellow-600 text-white px-3 py-1 rounded-full font-bold">150 金币</div>
</div>
</div>
<div class="flex items-center gap-3">
<div class="relative">
<img src="https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/2b92f5d5d637459296bd26e89c6edb60~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762158&x-signature=%2FeweQ0qIQ8mEU3%2BWw8JobH%2FNbKA%3D"
alt="Ship" class="w-12 h-12 pixel-art">
<div class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 rounded-full text-xs flex items-center justify-center text-white font-bold">ATK</div>
</div>
<div class="flex-1">
<div class="text-xs text-gray-600 space-y-1">
<div class="flex justify-between">
<span>攻击力: <span class="font-bold text-red-500">10</span></span>
<span>生命值: <span class="font-bold text-green-500">20</span></span>
</div>
<div class="flex justify-between">
<span>速度: <span class="font-bold text-blue-500">2</span></span>
<span>类型: 海军</span>
</div>
</div>
</div>
<button id="produce-ship" class="btn bg-gradient-to-r from-primary to-blue-600 text-white px-4 py-2 rounded-lg hover:from-blue-600 hover:to-blue-700">
<i class="fa fa-plus mr-1"></i>生产
</button>
</div>
</div>
<!-- Plane -->
<div class="bg-gradient-to-r from-gray-50 to-gray-100 p-4 rounded-xl border border-gray-200 hover:border-primary transition-all duration-300">
<div class="flex items-center justify-between mb-3">
<div>
<span class="font-bold text-gray-800">战斗机</span>
<div class="text-xs text-gray-500 mt-1">空军单位,高机动</div>
</div>
<div class="text-right">
<div class="text-sm bg-gradient-to-r from-yellow-500 to-yellow-600 text-white px-3 py-1 rounded-full font-bold">200 金币</div>
</div>
</div>
<div class="flex items-center gap-3">
<div class="relative">
<img src="https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/b2680644b8354f54b930e5c212a795b8~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762159&x-signature=X9pr2SIYSAb0rA8Y7d2PJQ96QYo%3D"
alt="Plane" class="w-12 h-12 pixel-art">
<div class="absolute -top-1 -right-1 w-5 h-5 bg-red-500 rounded-full text-xs flex items-center justify-center text-white font-bold">ATK</div>
</div>
<div class="flex-1">
<div class="text-xs text-gray-600 space-y-1">
<div class="flex justify-between">
<span>攻击力: <span class="font-bold text-red-500">7</span></span>
<span>生命值: <span class="font-bold text-green-500">15</span></span>
</div>
<div class="flex justify-between">
<span>速度: <span class="font-bold text-blue-500">4</span></span>
<span>类型: 空军</span>
</div>
</div>
</div>
<button id="produce-plane" class="btn bg-gradient-to-r from-primary to-blue-600 text-white px-4 py-2 rounded-lg hover:from-blue-600 hover:to-blue-700">
<i class="fa fa-plus mr-1"></i>生产
</button>
</div>
</div>
</div>
</div>
<!-- Game Controls -->
<div class="control-panel p-6">
<h2 class="text-xl font-bold mb-6 text-gray-800 flex items-center">
<i class="fa fa-gamepad mr-2 text-primary"></i>游戏控制
</h2>
<div class="grid grid-cols-2 gap-3 mb-4">
<button id="start-game" class="btn bg-gradient-to-r from-green-500 to-emerald-600 text-white px-4 py-3 rounded-lg hover:from-green-600 hover:to-emerald-700 flex items-center justify-center">
<i class="fa fa-play mr-2"></i>开始游戏
</button>
<button id="pause-game" class="btn bg-gradient-to-r from-yellow-500 to-amber-600 text-white px-4 py-3 rounded-lg hover:from-yellow-600 hover:to-amber-700 flex items-center justify-center" disabled>
<i class="fa fa-pause mr-2"></i>暂停游戏
</button>
<button id="reset-game" class="btn bg-gradient-to-r from-red-500 to-rose-600 text-white px-4 py-3 rounded-lg hover:from-red-600 hover:to-rose-700 flex items-center justify-center">
<i class="fa fa-refresh mr-2"></i>重置游戏
</button>
<button id="send-all" class="btn bg-gradient-to-r from-indigo-500 to-purple-600 text-white px-4 py-3 rounded-lg hover:from-indigo-600 hover:to-purple-700 flex items-center justify-center" disabled>
<i class="fa fa-send mr-2"></i>全部派遣
</button>
</div>
</div>
</div>
</div>
<!-- Game Log -->
<div class="mt-6 bg-gradient-to-r from-gray-800 to-gray-900 p-6 rounded-2xl shadow-xl border border-gray-700">
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-bold text-white flex items-center">
<i class="fa fa-history mr-2 text-primary"></i>游戏日志
</h2>
<button id="clear-log" class="text-sm text-gray-400 hover:text-white transition-colors">
<i class="fa fa-trash mr-1"></i>清空日志
</button>
</div>
<div id="game-log" class="h-48 overflow-y-auto space-y-2 text-sm text-gray-300 font-mono">
<div class="text-gray-500 italic">游戏准备中...</div>
</div>
</div>
</div>
<!-- Tooltip -->
<div id="tooltip" class="tooltip"></div>
<!-- Explosion Animation -->
<div id="explosion-template" class="explosion hidden">
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
<defs>
<radialGradient id="explosion-gradient">
<stop offset="0%" stop-color="#ff4500"/>
<stop offset="50%" stop-color="#ffcc00"/>
<stop offset="100%" stop-color="#ff4500" stop-opacity="0"/>
</radialGradient>
</defs>
<circle cx="50" cy="50" r="40" fill="url(#explosion-gradient)" opacity="0.8">
<animate attributeName="r" values="0;40;0" dur="0.6s" fill="freeze" />
<animate attributeName="opacity" values="0.8;0" dur="0.6s" fill="freeze" />
</circle>
<circle cx="50" cy="50" r="25" fill="#ffffff" opacity="0.9">
<animate attributeName="r" values="0;25;0" dur="0.4s" fill="freeze" />
<animate attributeName="opacity" values="0.9;0" dur="0.4s" fill="freeze" />
</circle>
</svg>
</div>
<!-- Notification -->
<div id="notification" class="notification hidden"></div>
<script>
// Game Configuration
const GAME_CONFIG = {
// Player configuration
player: {
color: 'blue',
money: 1000,
moneyIncrement: 10,
territoryPercentage: 100
},
// Enemy configuration
enemy: {
color: 'red',
money: 1000,
moneyIncrement: 10,
territoryPercentage: 0
},
// Islands configuration
islands: [
{
id: 1,
name: "主基地",
position: { x: 200, y: 650 },
shape: "polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%)",
size: 100,
owner: "player",
state: 0,
productionRate: 1.5
},
{
id: 7,
name: "补给岛",
position: { x: 150, y: 450 },
shape: "polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%)",
size: 60,
owner: "player",
state: 0,
productionRate: 1.0
},
{
id: 8,
name: "防御岛",
position: { x: 350, y: 600 },
shape: "polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%)",
size: 70,
owner: "player",
state: 0,
productionRate: 0.8
},
{
id: 2,
name: "敌方基地",
position: { x: 650, y: 150 },
shape: "polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%)",
size: 100,
owner: "enemy",
state: 0,
productionRate: 1.5
},
{
id: 3,
name: "资源岛",
position: { x: 400, y: 400 },
shape: "polygon(50% 0%, 90% 20%, 100% 60%, 75% 100%, 25% 100%, 0% 60%, 10% 20%)",
size: 80,
owner: "neutral",
state: 0,
productionRate: 2.0
},
{
id: 4,
name: "前哨岛",
position: { x: 300, y: 300 },
shape: "polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%)",
size: 60,
owner: "neutral",
state: 0,
productionRate: 1.0
},
{
id: 5,
name: "战略岛",
position: { x: 550, y: 450 },
shape: "polygon(30% 0%, 70% 0%, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0% 70%, 0% 30%)",
size: 70,
owner: "neutral",
state: 0,
productionRate: 1.2
},
{
id: 6,
name: "敌方核心基地",
position: { x: 750, y: 600 },
shape: "polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%)",
size: 120,
owner: "enemy",
state: 0,
productionRate: 3.0,
isBossIsland: true,
repairRate: 0.1,
maxDefenseUnits: {
soldier: 5,
ship: 3,
plane: 4
},
defenseUnits: {
soldier: 0,
ship: 0,
plane: 0
},
activationThreshold: 0,
isActive: false
}
],
// Unit types and their properties
units: {
soldier: {
cost: 50,
speed: 1,
strength: 5,
health: 10,
blueImage: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/05dc1e32ccdb45fc82b0c1155696dcbb~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762158&x-signature=TkOsDtCaeOJQP4gOXilrz59wjLI%3D',
redImage: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/1cec83002be742dcb420ed7c0b235d71~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762158&x-signature=fATOlYnn4iBWRZcfaZ3v%2FCjHkbM%3D'
},
ship: {
cost: 150,
speed: 2,
strength: 10,
health: 20,
blueImage: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/2b92f5d5d637459296bd26e89c6edb60~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762158&x-signature=%2FeweQ0qIQ8mEU3%2BWw8JobH%2FNbKA%3D',
redImage: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/9fae9aa452dc445cb59e7c54a0f78d5a~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762159&x-signature=lKuUAVrX5iampwnQv2ioSfENEhQ%3D'
},
plane: {
cost: 200,
speed: 4,
strength: 7,
health: 15,
blueImage: 'https://p3-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/b2680644b8354f54b930e5c212a795b8~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762159&x-signature=X9pr2SIYSAb0rA8Y7d2PJQ96QYo%3D',
redImage: 'https://p9-flow-imagex-sign.byteimg.com/tos-cn-i-a9rns2rl98/rc/pc/super_tool/4719b907fc864599b2f5f86c3ceb7e35~tplv-a9rns2rl98-image.image?lk3s=8e244e95&rcl=202602040955298F22FED3FC7A9303D5A7&rrcfp=f06b921b&x-expires=1772762159&x-signature=3xYMEpTRUERvVdwmTrHqhMAmfNI%3D'
}
},
// Battle mechanics
battle: {
winChances: {
'soldier': {
'soldier': 0.5,
'ship': 0.1,
'plane': 0.2
},
'ship': {
'soldier': 0.8,
'ship': 0.5,
'plane': 0.6
},
'plane': {
'soldier': 0.7,
'ship': 0.4,
'plane': 0.5
}
}
},
// Game state
gameState: {
isRunning: false,
isPaused: false,
gameLoopInterval: null,
moneyInterval: null,
enemyAttackInterval: null,
lastEnemyAttack: 0,
minEnemyAttackInterval: 2,
maxEnemyAttackInterval: 8,
bossIslandActivated: false,
bossRepairCooldown: 0
}
};
// Game State
let gameState = {
player: {
money: GAME_CONFIG.player.money,
territoryPercentage: GAME_CONFIG.player.territoryPercentage,
units: []
},
enemy: {
money: GAME_CONFIG.enemy.money,
territoryPercentage: GAME_CONFIG.enemy.territoryPercentage,
units: []
},
islands: JSON.parse(JSON.stringify(GAME_CONFIG.islands)),
isRunning: false,
isPaused: false,
selectedUnit: null,
pathLines: [],
isPathPlanning: false,
currentPathWaypoints: [],
ctrlKeyPressed: false,
nextUnitId: 1,
bossIsland: {
activated: false,
repairCooldown: 0,
lastRepairTime: 0,
repairInterval: 5,
defenseSpawnCooldown: 0,
lastDefenseSpawn: 0,
defenseSpawnInterval: 8
},
enemyAI: {
difficulty: "hard",
attackCooldown: 0,
lastAttackType: null,
strategy: "balanced",
resourceThreshold: 300,
targetPriority: {},
unitProductionRatio: {
soldier: 0.3,
ship: 0.4,
plane: 0.3
},
playerBehavior: {
unitProduction: {
soldier: 0,
ship: 0,
plane: 0
},
lastAttackTime: 0,
attackFrequency: 0,
defensivePlay: false
},
adaptationLevel: 0,
lastAdaptationTime: 0,
adaptationInterval: 30
}
};
// DOM Elements
const gameContainer = document.getElementById('game-container');
const moneyDisplay = document.getElementById('money');
const territoryDisplay = document.getElementById('territory');
const enemyTerritoryDisplay = document.getElementById('enemy-territory');
const startGameBtn = document.getElementById('start-game');
const pauseGameBtn = document.getElementById('pause-game');
const resetGameBtn = document.getElementById('reset-game');
const sendAllBtn = document.getElementById('send-all');
const produceSoldierBtn = document.getElementById('produce-soldier');
const produceShipBtn = document.getElementById('produce-ship');
const producePlaneBtn = document.getElementById('produce-plane');
const gameLog = document.getElementById('game-log');
const clearLogBtn = document.getElementById('clear-log');
const tooltip = document.getElementById('tooltip');
const explosionTemplate = document.getElementById('explosion-template');
const notification = document.getElementById('notification');
// Initialize the game
function initGame() {
createGameMap();
setupEventListeners();
updateUI();
addLogEntry('游戏已初始化,请点击"开始游戏"按钮开始');
}
// Create the game map with multiple islands
function createGameMap() {
gameContainer.innerHTML = '';
gameState.pathLines = [];
gameState.islands.forEach(island => {
const islandElement = document.createElement('div');
islandElement.className = `island state-${island.state}`;
islandElement.id = `island-${island.id}`;
islandElement.style.left = `${island.position.x - island.size/2}px`;
islandElement.style.top = `${island.position.y - island.size/2}px`;
islandElement.style.width = `${island.size}px`;
islandElement.style.height = `${island.size}px`;
islandElement.style.backgroundColor = getIslandColor(island.owner);
islandElement.style.clipPath = island.shape;
islandElement.dataset.owner = island.owner;
islandElement.dataset.islandId = island.id;
const labelElement = document.createElement('div');
labelElement.className = 'island-label';
labelElement.textContent = island.name;
islandElement.appendChild(labelElement);
islandElement.addEventListener('click', (e) => {
e.stopPropagation();
handleIslandClick(e, island);
});
islandElement.addEventListener('mouseenter', (e) => {
showTooltip(e, `${island.name}\n所有者: ${getOwnerName(island.owner)}\n状态: ${getIslandStateName(island.state)}`);
});
islandElement.addEventListener('mouseleave', hideTooltip);
gameContainer.appendChild(islandElement);
const territoryElement = document.createElement('div');
territoryElement.className = `territory ${island.owner}`;
if (island.owner === 'neutral') territoryElement.classList.add('neutral');
territoryElement.style.left = `${island.position.x - island.size}px`;
territoryElement.style.top = `${island.position.y - island.size}px`;
territoryElement.style.width = `${island.size * 2}px`;
territoryElement.style.height = `${island.size * 2}px`;
territoryElement.style.borderRadius = '50%';
territoryElement.dataset.owner = island.owner;
territoryElement.dataset.islandId = island.id;
gameContainer.appendChild(territoryElement);
island.element = islandElement;
island.territoryElement = territoryElement;
});
}
function getIslandColor(owner) {
switch (owner) {
case 'player': return '#3b82f6';
case 'enemy': return '#ef4444';
case 'neutral': return '#94a3b8';
case 'contested': return '#f59e0b';
default: return '#94a3b8';
}
}
function getOwnerName(owner) {
switch (owner) {
case 'player': return '我方';
case 'enemy': return '敌方';
case 'neutral': return '中立';
case 'contested': return '争夺中';
default: return '未知';
}
}
function getIslandStateName(state) {
switch (state) {
case 0: return '完全控制';
case 1: return '大部分控制 (75%)';
case 2: return '部分控制 (50%)';
case 3: return '少量控制 (25%)';
default: return '未知';
}
}
function handleIslandClick(event, island) {
if (!gameState.isRunning || gameState.isPaused) return;
if (gameState.selectedUnit) {
if (island.owner !== gameState.selectedUnit.owner) {
setUnitPath(gameState.selectedUnit, island);
deselectUnit();
recordPlayerAttack(island);
} else {
addLogEntry('不能向自己的岛屿派遣部队!');
}
}
}
function setupEventListeners() {
startGameBtn.addEventListener('click', startGame);
pauseGameBtn.addEventListener('click', pauseGame);
resetGameBtn.addEventListener('click', resetGame);
sendAllBtn.addEventListener('click', sendAllUnits);
produceSoldierBtn.addEventListener('click', () => {
produceUnit('soldier');
gameState.enemyAI.playerBehavior.unitProduction.soldier++;
});
produceShipBtn.addEventListener('click', () => {
produceUnit('ship');
gameState.enemyAI.playerBehavior.unitProduction.ship++;
});
producePlaneBtn.addEventListener('click', () => {
produceUnit('plane');
gameState.enemyAI.playerBehavior.unitProduction.plane++;
});
clearLogBtn.addEventListener('click', () => {
gameLog.innerHTML = '<div class="text-gray-500 italic">日志已清空</div>';
});
gameContainer.addEventListener('mousemove', handleMouseMove);
gameContainer.addEventListener('mouseleave', () => {
tooltip.style.opacity = '0';
});
gameContainer.addEventListener('click', (e) => {
if (e.target === gameContainer || e.target.classList.contains('territory')) {
deselectUnit();
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Control') {
gameState.ctrlKeyPressed = true;
}
if (e.key === 'Escape' && gameState.isPathPlanning) {
cancelPathPlanning();
}
});
document.addEventListener('keyup', (e) => {
if (e.key === 'Control') {
gameState.ctrlKeyPressed = false;
}
});
}
function startGame() {
if (gameState.isRunning) return;
gameState.isRunning = true;
gameState.isPaused = false;
initializeEnemyAI();
startGameBtn.disabled = true;
pauseGameBtn.disabled = false;
sendAllBtn.disabled = false;
GAME_CONFIG.gameState.moneyInterval = setInterval(() => {
if (!gameState.isPaused) {
gameState.player.money += GAME_CONFIG.player.moneyIncrement;
gameState.enemy.money += GAME_CONFIG.enemy.moneyIncrement;
adjustResourceGrowth();
updateUI();
}
}, 1000);
GAME_CONFIG.gameState.gameLoopInterval = setInterval(gameLoop, 50);
GAME_CONFIG.gameState.lastEnemyAttack = Date.now();
GAME_CONFIG.gameState.enemyAttackInterval = setInterval(() => {
if (!gameState.isPaused && gameState.isRunning) {
const now = Date.now();
const elapsed = (now - GAME_CONFIG.gameState.lastEnemyAttack) / 1000;
const attackInterval = calculateDynamicAttackInterval();
if (elapsed >= attackInterval) {
enemyAttack();
GAME_CONFIG.gameState.lastEnemyAttack = now;
}
updateEnemyStrategy();
}
}, 1000);
addLogEntry('游戏开始!生产单位并发兵攻击敌人的岛屿。');
}
function initializeEnemyAI() {
gameState.enemyAI.strategy = "balanced";
gameState.enemyAI.targetPriority = {
1: 0.7,
3: 0.5,
4: 0.3,
5: 0.4
};
gameState.enemyAI.adaptationLevel = 0;
gameState.enemyAI.lastAdaptationTime = Date.now();
gameState.enemyAI.playerBehavior = {
unitProduction: {
soldier: 0,
ship: 0,
plane: 0
},
lastAttackTime: 0,
attackFrequency: 0,
defensivePlay: false
};
}
function calculateDynamicAttackInterval() {
let baseInterval = getRandomInt(GAME_CONFIG.gameState.minEnemyAttackInterval,
GAME_CONFIG.gameState.maxEnemyAttackInterval);
const enemyMainIsland = gameState.islands.find(island => island.id === 2);
if (enemyMainIsland && enemyMainIsland.owner === 'player') {
baseInterval *= 0.5;
gameState.enemyAI.strategy = "aggressive";
addLogEntry(`⚡ 敌方进入紧急防御状态!攻击频率大幅提升!`);
}
switch (gameState.enemyAI.strategy) {
case "aggressive":
baseInterval *= 0.7;
break;
case "defensive":
baseInterval *= 1.3;
break;
default:
break;
}
if (gameState.enemy.money > gameState.enemyAI.resourceThreshold) {
baseInterval *= 0.8;
}
baseInterval *= (1 - gameState.enemyAI.adaptationLevel * 0.05);
return Math.max(2, Math.min(15, baseInterval));
}
function adjustResourceGrowth() {
let playerIslandValue = 0;
let enemyIslandValue = 0;
gameState.islands.forEach(island => {
const islandValue = island.size * (1 - island.state * 0.25);
if (island.owner === 'player') {
playerIslandValue += islandValue;
} else if (island.owner === 'enemy') {
enemyIslandValue += islandValue;
}
});
const totalValue = playerIslandValue + enemyIslandValue;
if (totalValue > 0) {
const playerRatio = playerIslandValue / totalValue;
const enemyRatio = enemyIslandValue / totalValue;
let playerGrowth = GAME_CONFIG.player.moneyIncrement;
let enemyGrowth = GAME_CONFIG.enemy.moneyIncrement;
playerGrowth += Math.floor(playerRatio * 5);
enemyGrowth += Math.floor(enemyRatio * 5);
const enemyMainIsland = gameState.islands.find(island => island.id === 2);
if (enemyMainIsland && enemyMainIsland.owner === 'player') {
enemyGrowth += 15;
addLogEntry(`💰 敌方获得紧急资源补给!资源增长速度提升!`);
}
if (enemyGrowth < playerGrowth * 0.8) {
enemyGrowth = Math.floor(playerGrowth * 0.8);
}
enemyGrowth = Math.max(enemyGrowth, 20);
GAME_CONFIG.player.moneyIncrement = playerGrowth;
GAME_CONFIG.enemy.moneyIncrement = enemyGrowth;
}
}
function updateEnemyStrategy() {
const now = Date.now();
if (now - gameState.enemyAI.lastAdaptationTime >= gameState.enemyAI.adaptationInterval * 1000) {
adaptToPlayerBehavior();
gameState.enemyAI.lastAdaptationTime = now;
gameState.enemyAI.adaptationLevel += 0.1;
}
const playerIslands = gameState.islands.filter(island => island.owner === 'player').length;
const enemyIslands = gameState.islands.filter(island => island.owner === 'enemy').length;
if (enemyIslands < playerIslands && gameState.enemy.money > 300) {
gameState.enemyAI.strategy = "aggressive";
} else if (enemyIslands > playerIslands + 1) {
gameState.enemyAI.strategy = "defensive";
} else {
gameState.enemyAI.strategy = "balanced";
}
if (gameState.enemyAI.playerBehavior.defensivePlay) {
gameState.enemyAI.strategy = "defensive";
}
}
function adaptToPlayerBehavior() {
const { unitProduction } = gameState.enemyAI.playerBehavior;
const totalProduction = unitProduction.soldier + unitProduction.ship + unitProduction.plane;
if (totalProduction > 0) {
const soldierRatio = unitProduction.soldier / totalProduction;
const shipRatio = unitProduction.ship / totalProduction;
const planeRatio = unitProduction.plane / totalProduction;
if (soldierRatio > 0.5) {
gameState.enemyAI.unitProductionRatio = {
soldier: 0.2,
ship: 0.5,
plane: 0.3
};
} else if (shipRatio > 0.5) {
gameState.enemyAI.unitProductionRatio = {
soldier: 0.2,
ship: 0.3,
plane: 0.5
};
} else if (planeRatio > 0.5) {
gameState.enemyAI.unitProductionRatio = {
soldier: 0.4,
ship: 0.5,
plane: 0.1
};
} else {
gameState.enemyAI.unitProductionRatio = {
soldier: 0.3,
ship: 0.4,
plane: 0.3
};
}
}
const { attackFrequency } = gameState.enemyAI.playerBehavior;
if (attackFrequency > 5) {
gameState.enemyAI.strategy = "defensive";
} else if (attackFrequency < 2) {
gameState.enemyAI.strategy = "aggressive";
}
gameState.enemyAI.playerBehavior.unitProduction = {
soldier: 0,
ship: 0,
plane: 0
};
gameState.enemyAI.playerBehavior.attackFrequency = 0;
}
function recordPlayerAttack(targetIsland) {
const now = Date.now();
gameState.enemyAI.playerBehavior.lastAttackTime = now;
gameState.enemyAI.playerBehavior.attackFrequency++;
if (targetIsland.id === 2) {
gameState.enemyAI.playerBehavior.defensivePlay = false;
} else {
const playerIslands = gameState.islands.filter(island => island.owner === 'player');
const isNearPlayerIsland = playerIslands.some(island => {
const dx = island.position.x - targetIsland.position.x;
const dy = island.position.y - targetIsland.position.y;
const distance = Math.sqrt(dx * dx + dy * dy);
return distance < 200;
});
gameState.enemyAI.playerBehavior.defensivePlay = isNearPlayerIsland;
}
if (gameState.enemyAI.targetPriority[targetIsland.id] !== undefined) {
gameState.enemyAI.targetPriority[targetIsland.id] *= 0.8;
}
gameState.enemyAI.targetPriority[1] *= 1.1;
normalizeTargetPriorities();
}
function normalizeTargetPriorities() {
const totalPriority = Object.values(gameState.enemyAI.targetPriority).reduce((sum, p) => sum + p, 0);
if (totalPriority > 0) {
Object.keys(gameState.enemyAI.targetPriority).forEach(id => {
gameState.enemyAI.targetPriority[id] /= totalPriority;
});
}
}
function pauseGame() {
if (!gameState.isRunning) return;
gameState.isPaused = !gameState.isPaused;
pauseGameBtn.textContent = gameState.isPaused ? '继续游戏' : '暂停游戏';
pauseGameBtn.classList.toggle('bg-gradient-to-r', true);
if (gameState.isPaused) {
pauseGameBtn.classList.remove('from-yellow-500', 'to-amber-600');
pauseGameBtn.classList.add('from-green-500', 'to-emerald-600');
} else {
pauseGameBtn.classList.remove('from-green-500', 'to-emerald-600');
pauseGameBtn.classList.add('from-yellow-500', 'to-amber-600');
}
addLogEntry(gameState.isPaused ? '游戏已暂停' : '游戏继续');
}
function resetGame() {
clearInterval(GAME_CONFIG.gameState.gameLoopInterval);
clearInterval(GAME_CONFIG.gameState.moneyInterval);
clearInterval(GAME_CONFIG.gameState.enemyAttackInterval);
gameState = {
player: {
money: GAME_CONFIG.player.money,
territoryPercentage: GAME_CONFIG.player.territoryPercentage,
units: []
},
enemy: {
money: GAME_CONFIG.enemy.money,
territoryPercentage: GAME_CONFIG.enemy.territoryPercentage,
units: []
},
islands: JSON.parse(JSON.stringify(GAME_CONFIG.islands)),
isRunning: false,
isPaused: false,
selectedUnit: null,
pathLines: [],
isPathPlanning: false,
currentPathWaypoints: [],
ctrlKeyPressed: false,
nextUnitId: 1,
bossIsland: {
activated: false,
repairCooldown: 0,
lastRepairTime: 0,
repairInterval: 5,
defenseSpawnCooldown: 0,
lastDefenseSpawn: 0,
defenseSpawnInterval: 8
},
enemyAI: {
difficulty: "hard",
attackCooldown: 0,
lastAttackType: null,
strategy: "balanced",
resourceThreshold: 300,
targetPriority: {},
unitProductionRatio: {
soldier: 0.3,
ship: 0.4,
plane: 0.3
},
playerBehavior: {
unitProduction: {
soldier: 0,
ship: 0,
plane: 0
},
lastAttackTime: 0,
attackFrequency: 0,
defensivePlay: false
},
adaptationLevel: 0,
lastAdaptationTime: 0,
adaptationInterval: 30
}
};
createGameMap();
updateUI();
startGameBtn.disabled = false;
pauseGameBtn.disabled = true;
pauseGameBtn.textContent = '暂停游戏';
sendAllBtn.disabled = true;
addLogEntry('游戏已重置');
}
function gameLoop() {
if (gameState.isPaused || !gameState.isRunning) return;
updateUnits('player');
updateUnits('enemy');
checkUnitCollisions();
checkTerritoryInvasions();
checkBossIslandActivation();
if (gameState.bossIsland.activated) {
handleBossIslandRepair();
handleBossIslandDefense();
}
}
function updateUnits(side) {
const units = gameState[side].units;
for (let i = units.length - 1; i >= 0; i--) {
const unit = units[i];
if (!unit.isMoving || !unit.path || unit.path.length <= unit.currentPathIndex + 1) continue;
const currentWaypoint = unit.path[unit.currentPathIndex];
const nextWaypoint = unit.path[unit.currentPathIndex + 1];
const dx = nextWaypoint.x - unit.x;
const dy = nextWaypoint.y - unit.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 5) {
unit.currentPathIndex++;
if (unit.currentPathIndex === unit.path.length - 1) {
const targetIsland = gameState.islands.find(island =>
Math.abs(island.position.x - nextWaypoint.x) < 10 &&
Math.abs(island.position.y - nextWaypoint.y) < 10
);
if (targetIsland) {
unit.isMoving = false;
invadeIsland(unit, targetIsland);
}
continue;
}
}
const nx = dx / distance;
const ny = dy / distance;
unit.x += nx * unit.speed;
unit.y += ny * unit.speed;
unit.element.style.left = `${unit.x - 20}px`;
unit.element.style.top = `${unit.y - 20}px`;
const angle = Math.atan2(dy, dx) * 180 / Math.PI;
unit.element.style.transform = `rotate(${angle}deg)`;
checkUnitCollisions(unit);
}
}
function checkUnitCollisions(unit) {
const enemySide = unit.owner === 'player' ? 'enemy' : 'player';
const enemyUnits = gameState[enemySide].units;
for (let i = enemyUnits.length - 1; i >= 0; i--) {
const enemyUnit = enemyUnits[i];
const dx = unit.x - enemyUnit.x;
const dy = unit.y - enemyUnit.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < 30) {
battleUnits(unit, enemyUnit);
break;
}
}
}
function invadeIsland(unit, island) {
addLogEntry(`${unit.owner === 'player' ? '我方' : '敌方'}${getUnitTypeName(unit.type)}入侵${island.name}!`);
if (island.owner === 'neutral') {
changeIslandOwnership(island, unit.owner, 0);
addLogEntry(`${unit.owner === 'player' ? '我方' : '敌方'}成功占领了${island.name}!`);
} else if (island.owner !== unit.owner) {
const baseSuccessChance = calculateInvasionSuccessChance(unit, island);
const success = Math.random() < baseSuccessChance;
if (success) {
const newState = Math.min(4, island.state + 1);
changeIslandOwnership(island, unit.owner, newState);
const enemyControlPercent = 100 - (newState * 25);
const playerControlPercent = newState * 25;
if (unit.owner === 'player') {
addLogEntry(`⚔️ 我方成功推进了对${island.name}的控制!`);
addLogEntry(`🏝️ ${island.name}现在:敌方控制${enemyControlPercent}%,我方控制${playerControlPercent}%`);
if (newState === 4) {
changeIslandOwnership(island, 'player', 0);
addLogEntry(`🎉 我方完全占领了${island.name}!`);
}
} else {
addLogEntry(`⚔️ 敌方成功推进了对${island.name}的控制!`);
addLogEntry(`🏝️ ${island.name}现在:我方控制${enemyControlPercent}%,敌方控制${playerControlPercent}%`);
if (newState === 4) {
changeIslandOwnership(island, 'enemy', 0);
addLogEntry(`💥 敌方完全占领了${island.name}!`);
}
}
} else {
addLogEntry(`${unit.owner === 'player' ? '我方' : '敌方'}对${island.name}的入侵失败!`);
}
}
removeUnit(unit);
updateUI();
checkGameOver();
}
function calculateInvasionSuccessChance(unit, island) {
let baseChance = 0.4;
const strengthFactor = unit.strength * 0.1;
const stateFactor = island.state * 0.15;
let defenseBonus = 0;
if (island.id === 1 || island.id === 2) {
defenseBonus = 0.2;
}
let unitTypeBonus = 0;
if (island.id === 1 || island.id === 2) {
if (unit.type === 'ship') unitTypeBonus = 0.1;
} else if (island.id === 3) {
if (unit.type === 'plane') unitTypeBonus = 0.1;
}
let finalChance = baseChance + strengthFactor + stateFactor - defenseBonus + unitTypeBonus;
return Math.max(0.1, Math.min(0.9, finalChance));
}
function changeIslandOwnership(island, newOwner, newState) {
const oldOwner = island.owner;
island.owner = newOwner;
island.state = newState;
if (island.element) {
island.element.dataset.owner = newOwner;
island.element.style.backgroundColor = getIslandColor(newOwner);
island.element.className = `island state-${newState}`;
}
if (island.territoryElement) {
island.territoryElement.dataset.owner = newOwner;
island.territoryElement.className = `territory ${newOwner}`;
if (newOwner === 'neutral') island.territoryElement.classList.add('neutral');
}
if (newOwner === 'enemy' && island.id !== 2) {
if (gameState.enemyAI.targetPriority[island.id] !== undefined) {
gameState.enemyAI.targetPriority[island.id] *= 0.5;
}
} else if (newOwner === 'player' && island.id !== 1) {
if (gameState.enemyAI.targetPriority[island.id] !== undefined) {
gameState.enemyAI.targetPriority[island.id] *= 1.5;
}
}
normalizeTargetPriorities();
updateTerritoryPercentages();
}
function updateTerritoryPercentages() {
let playerTerritory = 0;
let enemyTerritory = 0;
let totalValue = 0;
gameState.islands.forEach(island => {
const islandValue = island.size * (1 - island.state * 0.25);
totalValue += island.size;
if (island.owner === 'player') {
playerTerritory += islandValue;
} else if (island.owner === 'enemy') {
enemyTerritory += islandValue;
}
});
gameState.player.territoryPercentage = Math.round((playerTerritory / totalValue) * 100);
gameState.enemy.territoryPercentage = Math.round((enemyTerritory / totalValue) * 100);
}
function battleUnits(unit1, unit2) {
const baseWinChance = GAME_CONFIG.battle.winChances[unit1.type][unit2.type];
let adjustedWinChance = baseWinChance;
if (unit1.owner === 'enemy') {
if (gameState.enemyAI.strategy === "aggressive") {
adjustedWinChance += 0.1;
} else if (gameState.enemyAI.strategy === "defensive") {
adjustedWinChance += 0.05;
}
adjustedWinChance += gameState.enemyAI.adaptationLevel * 0.05;
}
const randomFactor = (Math.random() * 0.1) - 0.05;
const finalWinChance = Math.max(0.05, Math.min(0.95, adjustedWinChance + randomFactor));
const random = Math.random();
const unit1Wins = random < finalWinChance;
createExplosion((unit1.x + unit2.x) / 2, (unit1.y + unit2.y) / 2);
removeUnit(unit1);
removeUnit(unit2);
const winner = unit1Wins ? (unit1.owner === 'player' ? '我方' : '敌方') : (unit2.owner === 'player' ? '我方' : '敌方');
const loser = unit1Wins ? (unit2.owner === 'player' ? '我方' : '敌方') : (unit1.owner === 'player' ? '我方' : '敌方');
const winnerType = unit1Wins ? unit1.type : unit2.type;
const loserType = unit1Wins ? unit2.type : unit1.type;
addLogEntry(`${winner}${getUnitTypeName(winnerType)}击败了${loser}${getUnitTypeName(loserType)}!`);
if (unit1.owner === 'player' || unit2.owner === 'player') {
addLogEntry(`战斗胜率: ${Math.round(finalWinChance * 100)}%`);
}
}
function createExplosion(x, y) {
const explosion = explosionTemplate.cloneNode(true);
explosion.id = `explosion-${Date.now()}`;
explosion.classList.remove('hidden');
explosion.style.left = `${x - 40}px`;
explosion.style.top = `${y - 40}px`;
gameContainer.appendChild(explosion);
setTimeout(() => {
explosion.remove();
}, 600);
}
function checkGameOver() {
const playerIslands = gameState.islands.filter(island => island.owner === 'player');
if (playerIslands.length === 0) {
endGame(false);
return;
}
const enemyIslands = gameState.islands.filter(island => island.owner === 'enemy' && !island.isBossIsland);
const bossIsland = gameState.islands.find(island => island.isBossIsland);
if (gameState.bossIsland.activated && bossIsland && bossIsland.owner === 'player' && bossIsland.state === 0) {
endGame(true);
return;
}
if (!gameState.bossIsland.activated) {
const enemyMainIsland = gameState.islands.find(island => island.id === 2);
if (enemyMainIsland && enemyMainIsland.owner === 'player' && enemyMainIsland.state === 0) {
endGame(true);
return;
}
}
const playerMainIsland = gameState.islands.find(island => island.id === 1);
if (playerMainIsland && playerMainIsland.owner === 'enemy' && playerMainIsland.state === 0) {
endGame(false);
return;
}
}
function checkBossIslandActivation() {
const bossIsland = gameState.islands.find(island => island.isBossIsland);
if (!bossIsland || gameState.bossIsland.activated) return;
const enemyIslands = gameState.islands.filter(island =>
island.owner === 'enemy' && !island.isBossIsland
);
if (enemyIslands.length === 0) {
gameState.bossIsland.activated = true;
bossIsland.isActive = true;
bossIsland.state = 0;
bossIsland.defenseUnits = {
soldier: 0,
ship: 0,
plane: 0
};
spawnBossDefenseUnits(bossIsland);
addLogEntry('⚠️ 警告:敌方核心基地已激活!这是最后的决战!');
addLogEntry('💪 敌方核心基地拥有强大的防御系统和自我修复能力!');
addLogEntry('⚔️ 你必须摧毁所有防御单位并占领核心基地才能获胜!');
}
}
function handleMainBaseRepair() {
const mainBase = gameState.islands.find(island => island.id === 2);
if (!mainBase || mainBase.owner !== 'player') return;
const now = Date.now();
if (now - gameState.bossIsland.lastRepairTime >= 3000) {
if (mainBase.state < 4) {
const oldState = mainBase.state;
mainBase.state = Math.max(0, mainBase.state - 1);
if (mainBase.element) {
mainBase.element.className = `island state-${mainBase.state}`;
}
const enemyControlPercent = 100 - (mainBase.state * 25);
const playerControlPercent = mainBase.state * 25;
addLogEntry(`🔧 敌方主基地正在自我修复!控制权变化:我方${playerControlPercent}% → ${enemyControlPercent}%`);
}
gameState.bossIsland.lastRepairTime = now;
}
}
function handleBossIslandRepair() {
const bossIsland = gameState.islands.find(island => island.isBossIsland);
if (!bossIsland || bossIsland.owner !== 'enemy') return;
handleMainBaseRepair();
const now = Date.now();
if (now - gameState.bossIsland.lastRepairTime >= gameState.bossIsland.repairInterval * 1000) {
if (bossIsland.state > 0) {
const oldState = bossIsland.state;
bossIsland.state = Math.max(0, bossIsland.state - 1);
if (bossIsland.element) {
bossIsland.element.className = `island state-${bossIsland.state}`;
}
addLogEntry(`🚧 敌方核心基地自我修复!状态从 ${getIslandStateName(oldState)} 恢复到 ${getIslandStateName(bossIsland.state)}`);
}
gameState.bossIsland.lastRepairTime = now;
}
}
function handleBossIslandDefense() {
const bossIsland = gameState.islands.find(island => island.isBossIsland);
if (!bossIsland || bossIsland.owner !== 'enemy') return;
const now = Date.now();
if (now - gameState.bossIsland.lastDefenseSpawn >= gameState.bossIsland.defenseSpawnInterval * 1000) {
spawnBossDefenseUnits(bossIsland);
gameState.bossIsland.lastDefenseSpawn = now;
}
}
function spawnBossDefenseUnits(bossIsland) {
const unitTypes = ['soldier', 'ship', 'plane'];
let unitsSpawned = 0;
unitTypes.forEach(unitType => {
const maxUnits = bossIsland.maxDefenseUnits[unitType];
const currentUnits = bossIsland.defenseUnits[unitType];
for (let i = currentUnits; i < maxUnits; i++) {
if (unitsSpawned >= 3) break;
const unitConfig = GAME_CONFIG.units[unitType];
const unitId = gameState.nextUnitId++;
const unit = {
id: unitId,
type: unitType,
owner: 'enemy',
x: bossIsland.position.x + (Math.random() * bossIsland.size/2 - bossIsland.size/4),
y: bossIsland.position.y + (Math.random() * bossIsland.size/2 - bossIsland.size/4),
speed: unitConfig.speed,
strength: unitConfig.strength * 1.5,
health: unitConfig.health * 1.5,
maxHealth: unitConfig.health * 1.5,
isMoving: false,
path: null,
currentPathIndex: 0,
element: null,
isBossDefense: true
};
const unitElement = document.createElement('div');
unitElement.className = 'unit enemy';
unitElement.id = `unit-${unitId}`;
unitElement.style.left = `${unit.x - 20}px`;
unitElement.style.top = `${unit.y - 20}px`;
unitElement.style.filter = 'brightness(1.2) hue-rotate(30deg)';
const unitImage = document.createElement('img');
unitImage.src = unitConfig.redImage;
unitImage.alt = getUnitTypeName(unitType);
unitImage.className = 'pixel-art';
unitElement.appendChild(unitImage);
unit.element = unitElement;
gameContainer.appendChild(unitElement);
gameState.enemy.units.push(unit);
bossIsland.defenseUnits[unitType]++;
unitsSpawned++;
patrolAroundBossIsland(unit, bossIsland);
}
});
if (unitsSpawned > 0) {
addLogEntry(`🛡️ 敌方核心基地生成了 ${unitsSpawned} 个防御单位!`);
}
}
function patrolAroundBossIsland(unit, bossIsland) {
const patrolRadius = bossIsland.size * 0.8;
const numPoints = 8;
const patrolPath = [];
for (let i = 0; i < numPoints; i++) {
const angle = (i / numPoints) * Math.PI * 2;
const x = bossIsland.position.x + Math.cos(angle) * patrolRadius;
const y = bossIsland.position.y + Math.sin(angle) * patrolRadius;
patrolPath.push({ x, y });
}
patrolPath.unshift({ x: unit.x, y: unit.y });
unit.path = patrolPath;
unit.currentPathIndex = 0;
unit.isMoving = true;
unit.isPatrolling = true;
for (let i = 0; i < patrolPath.length - 1; i++) {
createPathLine(patrolPath[i].x, patrolPath[i].y, patrolPath[i+1].x, patrolPath[i+1].y, 'enemy');
}
}
function endGame(playerWon) {
clearInterval(GAME_CONFIG.gameState.gameLoopInterval);
clearInterval(GAME_CONFIG.gameState.moneyInterval);
clearInterval(GAME_CONFIG.gameState.enemyAttackInterval);
gameState.isRunning = false;
startGameBtn.disabled = false;
pauseGameBtn.disabled = true;
sendAllBtn.disabled = true;
if (playerWon) {
addLogEntry('🎉 恭喜!你成功击败了敌人,赢得了战争!');
} else {
addLogEntry('💥 很遗憾!敌人占领了你的所有领地,你输了!');
}
addLogEntry('点击"重置游戏"开始新的游戏');
}
function produceUnit(unitType) {
if (!gameState.isRunning || gameState.isPaused) return;
const unitConfig = GAME_CONFIG.units[unitType];
if (gameState.player.money < unitConfig.cost) {
addLogEntry(`金币不足!需要 ${unitConfig.cost} 金币来生产${getUnitTypeName(unitType)}`);
return;
}
const playerIslands = gameState.islands.filter(island => island.owner === 'player');
if (playerIslands.length === 0) {
addLogEntry('你没有可用于生产单位的岛屿!');
return;
}
const randomIsland = playerIslands[Math.floor(Math.random() * playerIslands.length)];
gameState.player.money -= unitConfig.cost;
const unitId = gameState.nextUnitId++;
const unit = {
id: unitId,
type: unitType,
owner: 'player',
x: randomIsland.position.x + (Math.random() * randomIsland.size/2 - randomIsland.size/4),
y: randomIsland.position.y + (Math.random() * randomIsland.size/2 - randomIsland.size/4),
speed: unitConfig.speed,
strength: unitConfig.strength,
health: unitConfig.health,
maxHealth: unitConfig.health,
isMoving: false,
path: null,
currentPathIndex: 0,
element: null,
productionIsland: randomIsland.id
};
const unitElement = document.createElement('div');
unitElement.className = 'unit';
unitElement.id = `unit-${unitId}`;
unitElement.style.left = `${unit.x - 20}px`;
unitElement.style.top = `${unit.y - 20}px`;
const unitImage = document.createElement('img');
unitImage.src = unitConfig.blueImage;
unitImage.alt = getUnitTypeName(unitType);
unitImage.className = 'pixel-art';
unitElement.appendChild(unitImage);
unitElement.addEventListener('click', (e) => {
e.stopPropagation();
selectUnit(unit);
});
unitElement.addEventListener('mouseenter', (e) => {
showTooltip(e, `${getUnitTypeName(unitType)}\n速度: ${unit.speed}\n战斗力: ${unit.strength}\n生命值: ${unit.health}\n生产岛屿: ${randomIsland.name}`);
});
unitElement.addEventListener('mouseleave', hideTooltip);
unit.element = unitElement;
gameContainer.appendChild(unitElement);
gameState.player.units.push(unit);
updateUI();
addLogEntry(`在${randomIsland.name}生产了一个${getUnitTypeName(unit.type)}`);
}
function selectUnit(unit) {
deselectUnit();
gameState.selectedUnit = unit;
unit.element.classList.add('selected');
addLogEntry(`选择了${getUnitTypeName(unit.type)}`);
addLogEntry('点击敌方岛屿或海面设置移动目标');
}
function deselectUnit() {
if (gameState.selectedUnit) {
gameState.selectedUnit.element.classList.remove('selected');
gameState.selectedUnit = null;
}
if (gameState.isPathPlanning) {
cancelPathPlanning();
}
}
function setUnitPath(unit, targetIsland) {
const path = calculateSmartPath(unit, targetIsland);
unit.path = path;
unit.currentPathIndex = 0;
unit.isMoving = true;
for (let i = 0; i < path.length - 1; i++) {
createPathLine(path[i].x, path[i].y, path[i+1].x, path[i+1].y, unit.owner);
}
addLogEntry(`${getUnitTypeName(unit.type)}正在前往${targetIsland.name}...`);
}
function calculateSmartPath(unit, targetIsland) {
const startPoint = { x: unit.x, y: unit.y };
const endPoint = { x: targetIsland.position.x, y: targetIsland.position.y };
const path = [startPoint, endPoint];
if (unit.owner === 'enemy') {
return path;
}
const enemyUnits = gameState.enemy.units;
let needAvoidance = false;
for (const enemyUnit of enemyUnits) {
const distance = distancePointToLine(
enemyUnit.x, enemyUnit.y,
startPoint.x, startPoint.y,
endPoint.x, endPoint.y
);
if (distance < 80) {
needAvoidance = true;
break;
}
}
if (needAvoidance) {
const midPoint = {
x: (startPoint.x + endPoint.x) / 2,
y: (startPoint.y + endPoint.y) / 2
};
const dx = endPoint.x - startPoint.x;
const dy = endPoint.y - startPoint.y;
const length = Math.sqrt(dx * dx + dy * dy);
const perpX = -dy / length;
const perpY = dx / length;
const offsetDistance = 50;
const avoidancePoint = {
x: midPoint.x + perpX * offsetDistance,
y: midPoint.y + perpY * offsetDistance
};
path.splice(1, 0, avoidancePoint);
}
return path;
}
function distancePointToLine(px, py, x1, y1, x2, y2) {
const A = px - x1;
const B = py - y1;
const C = x2 - x1;
const D = y2 - y1;
const dot = A * C + B * D;
const lenSq = C * C + D * D;
let param = -1;
if (lenSq !== 0) {
param = dot / lenSq;
}
let xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
} else if (param > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + param * C;
yy = y1 + param * D;
}
const dx = px - xx;
const dy = py - yy;
return Math.sqrt(dx * dx + dy * dy);
}
function createPathLine(x1, y1, x2, y2, owner) {
const line = document.createElement('div');
line.className = `path-line ${owner}`;
const dx = x2 - x1;
const dy = y2 - y1;
const length = Math.sqrt(dx * dx + dy * dy);
const angle = Math.atan2(dy, dx) * 180 / Math.PI;
line.style.width = `${length}px`;
line.style.left = `${x1}px`;
line.style.top = `${y1}px`;
line.style.transform = `rotate(${angle}deg)`;
gameContainer.appendChild(line);
gameState.pathLines.push(line);
}
function clearPathLines() {
gameState.pathLines.forEach(line => {
if (line.parentNode) {
line.parentNode.removeChild(line);
}
});
gameState.pathLines = [];
}
function cancelPathPlanning() {
if (!gameState.isPathPlanning) return;
clearPathLines();
gameState.isPathPlanning = false;
gameState.currentPathWaypoints = [];
addLogEntry('路径规划已取消');
}
function removeUnit(unit) {
const units = gameState[unit.owner].units;
const index = units.findIndex(u => u.id === unit.id);
if (index !== -1) {
if (unit.element && unit.element.parentNode) {
unit.element.parentNode.removeChild(unit.element);
}
units.splice(index, 1);
if (unit.isBossDefense && unit.owner === 'enemy') {
const bossIsland = gameState.islands.find(island => island.isBossIsland);
if (bossIsland && bossIsland.defenseUnits[unit.type] > 0) {
bossIsland.defenseUnits[unit.type]--;
addLogEntry(`💥 敌方核心基地的${getUnitTypeName(unit.type)}被摧毁!`);
}
}
}
}
function enemyAttack() {
if (!gameState.isRunning || gameState.isPaused) return;
const bossIsland = gameState.islands.find(island => island.isBossIsland);
if (bossIsland && bossIsland.isActive && bossIsland.owner === 'enemy') {
handleBossIslandDefense();
}
let enemyIsland = gameState.islands.find(island => island.owner === 'enemy' && island.id === 2);
if (!enemyIsland) {
enemyIsland = bossIsland && bossIsland.owner === 'enemy' ? bossIsland : null;
}
if (!enemyIsland) return;
const targetIsland = selectOptimalTarget();
if (!targetIsland) return;
let unitsToSpawn = 15;
const enemyMainIsland = gameState.islands.find(island => island.id === 2);
if (enemyMainIsland && enemyMainIsland.owner === 'player') {
unitsToSpawn = 20;
addLogEntry(`🚨 敌方基地受到威胁!发动更猛烈的反击,一次性派出 ${unitsToSpawn} 个战斗单位!`);
} else {
addLogEntry(`🚨 敌方发动大规模进攻!一次性派出 ${unitsToSpawn} 个战斗单位!`);
}
const unitTypes = ['soldier', 'ship', 'plane'];
let unitsSpawned = 0;
for (let i = 0; i < unitsToSpawn; i++) {
let randomType = unitTypes[Math.floor(Math.random() * unitTypes.length)];
let unitConfig = GAME_CONFIG.units[randomType];
if (gameState.enemy.money < unitConfig.cost) {
if (gameState.enemy.money >= GAME_CONFIG.units.soldier.cost) {
randomType = 'soldier';
unitConfig = GAME_CONFIG.units.soldier;
} else {
if (enemyMainIsland && enemyMainIsland.owner === 'player') {
addLogEntry(`💸 敌方资源耗尽,但在紧急情况下强行征召士兵!`);
} else {
continue;
}
}
}
const enemyMainIsland = gameState.islands.find(island => island.id === 2);
if (enemyMainIsland && enemyMainIsland.owner === 'player') {
if (Math.random() < 0.3) {
const extraUnitId = gameState.nextUnitId++;
const extraUnit = {
id: extraUnitId,
type: randomType,
owner: 'enemy',
x: enemyIsland.position.x + (Math.random() * enemyIsland.size/2 - enemyIsland.size/4),
y: enemyIsland.position.y + (Math.random() * enemyIsland.size/2 - enemyIsland.size/4),
speed: unitConfig.speed * 1.2,
strength: unitConfig.strength * 1.1,
health: unitConfig.health,
maxHealth: unitConfig.health,
isMoving: false,
path: null,
currentPathIndex: 0,
element: null,
isDesperateDefense: true
};
const extraUnitElement = document.createElement('div');
extraUnitElement.className = 'unit enemy';
extraUnitElement.id = `unit-${extraUnitId}`;
extraUnitElement.style.left = `${extraUnit.x - 20}px`;
extraUnitElement.style.top = `${extraUnit.y - 20}px`;
extraUnitElement.style.filter = 'brightness(1.3) saturate(1.5)';
const extraUnitImage = document.createElement('img');
extraUnitImage.src = unitConfig.redImage;
extraUnitImage.alt = getUnitTypeName(randomType);
extraUnitImage.className = 'pixel-art';
extraUnitElement.appendChild(extraUnitImage);
extraUnit.element = extraUnitElement;
gameContainer.appendChild(extraUnitElement);
gameState.enemy.units.push(extraUnit);
setUnitPath(extraUnit, targetIsland);
addLogEntry(`⚡ 敌方在基地受攻击时派出增援部队!`);
}
}
gameState.enemy.money -= unitConfig.cost;
const unitId = gameState.nextUnitId++;
const unit = {
id: unitId,
type: randomType,
owner: 'enemy',
x: enemyIsland.position.x + (Math.random() * enemyIsland.size/2 - enemyIsland.size/4),
y: enemyIsland.position.y + (Math.random() * enemyIsland.size/2 - enemyIsland.size/4),
speed: unitConfig.speed,
strength: unitConfig.strength,
health: unitConfig.health,
maxHealth: unitConfig.health,
isMoving: false,
path: null,
currentPathIndex: 0,
element: null
};
const unitElement = document.createElement('div');
unitElement.className = 'unit enemy';
unitElement.id = `unit-${unitId}`;
unitElement.style.left = `${unit.x - 20}px`;
unitElement.style.top = `${unit.y - 20}px`;
const unitImage = document.createElement('img');
unitImage.src = unitConfig.redImage;
unitImage.alt = getUnitTypeName(randomType);
unitImage.className = 'pixel-art';
unitElement.appendChild(unitImage);
unit.element = unitElement;
gameContainer.appendChild(unitElement);
gameState.enemy.units.push(unit);
setUnitPath(unit, targetIsland);
unitsSpawned++;
}
if (unitsSpawned > 0) {
addLogEntry(`⚔️ 敌方成功派出 ${unitsSpawned} 个单位进攻${targetIsland.name}!`);
} else {
addLogEntry('💰 敌方资金不足,无法发动进攻!');
}
}
function selectOptimalTarget() {
const targetIslands = gameState.islands.filter(island =>
island.owner === 'player' || island.owner === 'neutral'
);
if (targetIslands.length === 0) return null;
if (gameState.enemyAI.strategy === "aggressive") {
const playerMainIsland = targetIslands.find(island => island.id === 1);
if (playerMainIsland && Math.random() < 0.7) {
return playerMainIsland;
}
} else if (gameState.enemyAI.strategy === "defensive") {
const enemyIsland = gameState.islands.find(island => island.owner === 'enemy' && island.id === 2);
if (enemyIsland) {
targetIslands.sort((a, b) => {
const distA = Math.sqrt(
Math.pow(a.position.x - enemyIsland.position.x, 2) +
Math.pow(a.position.y - enemyIsland.position.y, 2)
);
const distB = Math.sqrt(
Math.pow(b.position.x - enemyIsland.position.x, 2) +
Math.pow(b.position.y - enemyIsland.position.y, 2)
);
return distA - distB;
});
if (Math.random() < 0.6) {
return targetIslands[0];
}
}
}
const weightedTargets = targetIslands.map(island => {
const priority = gameState.enemyAI.targetPriority[island.id] || 0.3;
return { island, priority };
});
const totalWeight = weightedTargets.reduce((sum, t) => sum + t.priority, 0);
const normalizedTargets = weightedTargets.map(t => ({
island: t.island,
weight: t.priority / totalWeight
}));
let random = Math.random();
for (const target of normalizedTargets) {
random -= target.weight;
if (random <= 0) {
return target.island;
}
}
return targetIslands[0];
}
function sendAllUnits() {
if (!gameState.isRunning || gameState.isPaused) return;
const stationaryUnits = gameState.player.units.filter(unit => !unit.isMoving);
if (stationaryUnits.length === 0) {
addLogEntry('没有可派遣的单位!');
return;
}
const enemyIslands = gameState.islands.filter(island => island.owner === 'enemy');
if (enemyIslands.length === 0) {
addLogEntry('没有敌方岛屿可攻击!');
return;
}
const primaryTarget = enemyIslands.find(island => island.id === 2) || enemyIslands[0];
stationaryUnits.forEach(unit => {
setUnitPath(unit, primaryTarget);
});
recordPlayerAttack(primaryTarget);
addLogEntry(`派遣了 ${stationaryUnits.length} 个单位攻击${primaryTarget.name}!`);
}
function updateUI() {
moneyDisplay.textContent = gameState.player.money;
territoryDisplay.textContent = `${gameState.player.territoryPercentage}%`;
enemyTerritoryDisplay.textContent = `${gameState.enemy.territoryPercentage}%`;
const moneyProgress = document.getElementById('money-progress');
if (moneyProgress) {
const progress = Math.min(100, (gameState.player.money / 2000) * 100);
moneyProgress.style.width = `${progress}%`;
}
const territoryProgress = document.getElementById('territory-progress');
if (territoryProgress) {
territoryProgress.style.width = `${gameState.player.territoryPercentage}%`;
}
produceSoldierBtn.disabled = gameState.player.money < GAME_CONFIG.units.soldier.cost || !gameState.isRunning || gameState.isPaused;
produceShipBtn.disabled = gameState.player.money < GAME_CONFIG.units.ship.cost || !gameState.isRunning || gameState.isPaused;
producePlaneBtn.disabled = gameState.player.money < GAME_CONFIG.units.plane.cost || !gameState.isRunning || gameState.isPaused;
const hasStationaryUnits = gameState.player.units.some(unit => !unit.isMoving);
sendAllBtn.disabled = !hasStationaryUnits || !gameState.isRunning || gameState.isPaused;
}
function addLogEntry(message) {
const timestamp = new Date().toLocaleTimeString();
const logEntry = document.createElement('div');
logEntry.className = 'mb-1';
logEntry.innerHTML = `<span class="text-gray-500">[${timestamp}]</span> ${message}`;
if (gameLog.children.length === 1 && gameLog.children[0].classList.contains('italic')) {
gameLog.innerHTML = '';
}
gameLog.appendChild(logEntry);
gameLog.scrollTop = gameLog.scrollHeight;
}
function showTooltip(event, text) {
tooltip.innerHTML = text.replace(/\n/g, '<br>');
tooltip.style.left = `${event.pageX + 10}px`;
tooltip.style.top = `${event.pageY + 10}px`;
tooltip.style.opacity = '1';
}
function hideTooltip() {
tooltip.style.opacity = '0';
}
function handleMouseMove(event) {
if (tooltip.style.opacity === '1') {
tooltip.style.left = `${event.pageX + 10}px`;
tooltip.style.top = `${event.pageY + 10}px`;
}
}
function getUnitTypeName(type) {
switch (type) {
case 'soldier': return '士兵';
case 'ship': return '战舰';
case 'plane': return '战斗机';
default: return '单位';
}
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Initialize the game when the page loads
window.addEventListener('load', initGame);
</script>
</body>
</html>