格斗对决v4.5

html 复制代码
<!DOCTYPE html>

<html lang="zh-CN">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>格斗对决 v4.4</title>

<style>

* { margin: 0; padding: 0; box-sizing: border-box; }

body {

  background: #0a0a0a;

  display: flex;

  flex-direction: column;

  align-items: center;

  justify-content: center;

  height: 100vh;

  font-family: 'Microsoft YaHei', sans-serif;

  overflow: hidden;

  user-select: none;

}

#gameContainer {

  position: relative;

  width: 900px;

  height: 560px;

  border: 2px solid #333;

  border-radius: 8px;

  overflow: hidden;

  box-shadow: 0 0 40px rgba(0,100,255,0.15), 0 0 80px rgba(255,50,50,0.1);

}

canvas { display: block; }

#ui-overlay {

  position: absolute;

  top: 0; left: 0; right: 0;

  padding: 12px 20px;

  display: flex;

  justify-content: space-between;

  align-items: flex-start;

  pointer-events: none;

  z-index: 10;

}

.player-info {

  display: flex;

  flex-direction: column;

  gap: 4px;

  width: 320px;

}

.player-info.right { align-items: flex-end; }

.player-name {

  font-size: 14px;

  font-weight: bold;

  text-shadow: 0 0 8px rgba(0,0,0,0.8);

}

.player-name.blue { color: #4fc3f7; }

.player-name.red { color: #ef5350; }

.hp-bar-bg {

  width: 100%;

  height: 18px;

  background: #1a1a2e;

  border: 1px solid #444;

  border-radius: 3px;

  overflow: hidden;

  position: relative;

}

.hp-bar {

  height: 100%;

  transition: width 0.2s ease;

  border-radius: 2px;

}

.hp-bar.blue { background: linear-gradient(180deg, #4fc3f7, #0288d1); }

.hp-bar.red { background: linear-gradient(180deg, #ef5350, #c62828); }

.hp-text {

  position: absolute;

  top: 0; left: 0; right: 0; bottom: 0;

  display: flex;

  align-items: center;

  justify-content: center;

  font-size: 11px;

  color: #fff;

  text-shadow: 0 1px 2px #000;

  font-weight: bold;

}

.energy-bar-bg {

  width: 100%;

  height: 8px;

  background: #1a1a2e;

  border: 1px solid #333;

  border-radius: 2px;

  overflow: hidden;

  position: relative;

}

.energy-bar {

  height: 100%;

  transition: width 0.15s ease;

  border-radius: 1px;

}

.energy-bar.blue { background: linear-gradient(180deg, #ffd54f, #ff8f00); }

.energy-bar.red { background: linear-gradient(180deg, #ce93d8, #7b1fa2); }

.energy-full {

  position: absolute;

  right: 4px;

  top: -1px;

  font-size: 8px;

  color: #ffd54f;

  font-weight: bold;

  text-shadow: 0 0 4px #ffd54f;

  opacity: 0;

  transition: opacity 0.3s;

}

.energy-full.show { opacity: 1; }

#timer-container {

  display: flex;

  flex-direction: column;

  align-items: center;

  min-width: 70px;

}

#timer {

  font-size: 36px;

  font-weight: bold;

  color: #ffd54f;

  text-shadow: 0 0 15px rgba(255,213,79,0.5), 0 2px 4px #000;

  line-height: 1;

}

#timer-label {

  font-size: 10px;

  color: #888;

  letter-spacing: 2px;

}

#startScreen, #endScreen {

  position: absolute;

  top: 0; left: 0; right: 0; bottom: 0;

  display: flex;

  flex-direction: column;

  align-items: center;

  justify-content: center;

  padding-top: 50px;

  background: rgba(0,0,0,0.85);

  z-index: 100;

  gap: 15px;

}

#startScreen h1 {

  font-size: 52px;

  background: linear-gradient(135deg, #4fc3f7, #ef5350);

  -webkit-background-clip: text;

  -webkit-text-fill-color: transparent;

  text-shadow: none;

  letter-spacing: 8px;

}

#endScreen h1 {

  font-size: 42px;

  color: #ffd54f;

  text-shadow: 0 0 20px rgba(255,213,79,0.4);

}

#endResult {

  font-size: 22px;

  color: #ccc;

}

.btn {

  padding: 12px 40px;

  font-size: 18px;

  border: 2px solid #ffd54f;

  background: transparent;

  color: #ffd54f;

  border-radius: 6px;

  cursor: pointer;

  pointer-events: all;

  transition: all 0.2s;

  font-family: inherit;

  letter-spacing: 2px;

}

.btn:hover {

  background: #ffd54f;

  color: #000;

  box-shadow: 0 0 20px rgba(255,213,79,0.3);

}

.map-select {

  display: flex;

  gap: 16px;

  margin-top: 6px;

}

.map-card {

  width: 160px;

  height: 100px;

  border: 2px solid #444;

  border-radius: 8px;

  cursor: pointer;

  pointer-events: all;

  overflow: hidden;

  position: relative;

  transition: all 0.2s;

  background: #111;

}

.map-card:hover {

  border-color: #ffd54f;

  box-shadow: 0 0 15px rgba(255,213,79,0.2);

}

.map-card.selected {

  border-color: #ffd54f;

  box-shadow: 0 0 20px rgba(255,213,79,0.4);

}

.map-card canvas {

  width: 100%;

  height: 100%;

}

.map-card-label {

  position: absolute;

  bottom: 0;

  left: 0;

  right: 0;

  padding: 4px 0;

  text-align: center;

  font-size: 12px;

  font-weight: bold;

  color: #ddd;

  background: rgba(0,0,0,0.7);

}

#ultSelectScreen {

  position: absolute;

  top: 0; left: 0; right: 0; bottom: 0;

  display: none;

  flex-direction: column;

  align-items: center;

  justify-content: center;

  background: rgba(0,0,0,0.88);

  z-index: 100;

  gap: 16px;

}

#ultSelectScreen h2 {

  font-size: 28px;

  color: #ffd54f;

  letter-spacing: 4px;

  text-shadow: 0 0 15px rgba(255,213,79,0.3);

}

.ult-cards {

  display: flex;

  gap: 18px;

  max-width: 800px;

  overflow-x: auto;

  padding: 10px;

  scroll-behavior: smooth;

}

.ult-cards::-webkit-scrollbar {

  height: 8px;

}

.ult-cards::-webkit-scrollbar-track {

  background: #1a1a1a;

  border-radius: 4px;

}

.ult-cards::-webkit-scrollbar-thumb {

  background: #ffd54f;

  border-radius: 4px;

}

.ult-card {

  width: 200px;

  padding: 18px 14px;

  border: 2px solid #444;

  border-radius: 10px;

  cursor: pointer;

  pointer-events: all;

  text-align: center;

  transition: all 0.2s;

  background: #111;

  display: flex;

  flex-direction: column;

  align-items: center;

  gap: 8px;

}

.ult-card:hover {

  border-color: #ffd54f;

  box-shadow: 0 0 20px rgba(255,213,79,0.2);

  transform: translateY(-3px);

}

.ult-card.selected {

  border-color: #ffd54f;

  box-shadow: 0 0 25px rgba(255,213,79,0.4);

  background: #1a1a0a;

}

.ult-icon {

  font-size: 36px;

  line-height: 1;

}

.ult-name {

  font-size: 18px;

  font-weight: bold;

  color: #ffd54f;

}

.ult-origin {

  font-size: 11px;

  color: #888;

}

.ult-desc {

  font-size: 12px;

  color: #bbb;

  line-height: 1.5;

}

#diffSelectScreen {

  position: absolute;

  top: 0; left: 0; right: 0; bottom: 0;

  display: none;

  flex-direction: column;

  align-items: center;

  justify-content: center;

  background: rgba(0,0,0,0.88);

  z-index: 100;

  gap: 20px;

}

#diffSelectScreen h2 {

  font-size: 28px;

  color: #ffd54f;

  letter-spacing: 4px;

  text-shadow: 0 0 15px rgba(255,213,79,0.3);

}

.diff-cards {

  display: flex;

  gap: 24px;

}

.diff-card {

  width: 180px;

  padding: 24px 16px;

  border: 2px solid #444;

  border-radius: 12px;

  cursor: pointer;

  pointer-events: all;

  text-align: center;

  transition: all 0.2s;

  background: #111;

  display: flex;

  flex-direction: column;

  align-items: center;

  gap: 10px;

}

.diff-card:hover {

  border-color: #ffd54f;

  box-shadow: 0 0 20px rgba(255,213,79,0.2);

  transform: translateY(-3px);

}

.diff-card.selected {

  border-color: #ffd54f;

  box-shadow: 0 0 25px rgba(255,213,79,0.4);

  background: #1a1a0a;

}

.diff-icon {

  font-size: 40px;

  line-height: 1;

}

.diff-name {

  font-size: 20px;

  font-weight: bold;

  color: #ffd54f;

}

.diff-desc {

  font-size: 12px;

  color: #bbb;

  line-height: 1.6;

}

.controls-hint {

  display: flex;

  gap: 30px;

  margin-top: 10px;

}

.control-group {

  display: flex;

  flex-direction: column;

  align-items: center;

  gap: 6px;

}

.control-group-title {

  font-size: 13px;

  color: #4fc3f7;

  font-weight: bold;

  margin-bottom: 4px;

}

.control-row {

  display: flex;

  gap: 8px;

  align-items: center;

}

.key {

  display: inline-flex;

  align-items: center;

  justify-content: center;

  min-width: 32px;

  height: 28px;

  padding: 0 6px;

  background: #222;

  border: 1px solid #555;

  border-radius: 4px;

  color: #ddd;

  font-size: 12px;

  font-weight: bold;

}

.key-label {

  font-size: 11px;

  color: #999;

}

.key-hint {

  font-size: 10px;

  color: #666;

  margin-top: 2px;

}

#comboDisplay {

  position: absolute;

  bottom: 80px;

  left: 50%;

  transform: translateX(-50%);

  font-size: 28px;

  font-weight: bold;

  color: #ffd54f;

  text-shadow: 0 0 15px rgba(255,213,79,0.6);

  pointer-events: none;

  z-index: 20;

  opacity: 0;

  transition: opacity 0.3s;

}

#roundAnnounce {

  position: absolute;

  top: 50%;

  left: 50%;

  transform: translate(-50%, -50%);

  font-size: 60px;

  font-weight: bold;

  color: #fff;

  text-shadow: 0 0 30px rgba(255,255,255,0.5);

  pointer-events: none;

  z-index: 50;

  opacity: 0;

}

</style>

</head>

<body>

<div id="gameContainer">

  <canvas id="gameCanvas" width="900" height="560"></canvas>



  <div id="ui-overlay">

    <div class="player-info">

      <span class="player-name blue">玩家 <span id="playerUltLabel" style="font-size:11px;color:#ffd54f;"></span></span>

      <div class="hp-bar-bg">

        <div class="hp-bar blue" id="playerHp" style="width:100%"></div>

        <div class="hp-text" id="playerHpText">1000 / 1000</div>

      </div>

      <div class="energy-bar-bg">

        <div class="energy-bar blue" id="playerEnergy" style="width:0%"></div>

        <span class="energy-full" id="playerEnergyFull">MAX</span>

      </div>

    </div>

    <div id="timer-container">

      <div id="timer">60</div>

      <div id="timer-label">TIME</div>

    </div>

    <div class="player-info right">

      <span class="player-name red"><span id="aiUltLabel" style="font-size:11px;color:#ffd54f;"></span> AI 对手</span>

      <!-- 主AI血条和能量条 -->

      <div class="hp-bar-bg">

        <div class="hp-bar red" id="aiHp" style="width:100%"></div>

        <div class="hp-text" id="aiHpText">1000 / 1000</div>

      </div>

      <div class="energy-bar-bg">

        <div class="energy-bar red" id="aiEnergy" style="width:0%"></div>

        <span class="energy-full" id="aiEnergyFull">MAX</span>

      </div>

      <!-- 额外敌人血条容器 -->

      <div id="extraEnemyBars" style="display:none;margin-top:8px;"></div>

    </div>

  </div>



  <div id="comboDisplay"></div>

  <div id="roundAnnounce"></div>



  <!-- 返回菜单按钮 -->

  <button id="backToMenuBtn" style="position:absolute;top:80px;left:10px;background:rgba(0,0,0,0.7);color:#fff;border:1px solid #666;padding:8px 16px;font-size:14px;cursor:pointer;border-radius:6px;z-index:50;display:none;">返回菜单</button>



  <div id="startScreen">

    <h1>格斗对决</h1>

    <div class="controls-hint">

      <div class="control-group">

        <div class="control-group-title">移动</div>

        <div class="control-row">

          <span class="key">A</span><span class="key">D</span>

          <span class="key-label">左右移动</span>

        </div>

        <div class="control-row">

          <span class="key">W</span>

          <span class="key-label">跳跃</span>

        </div>

        <div class="control-row">

          <span class="key">S</span>

          <span class="key-label">防御(消耗能量)</span>

        </div>

      </div>

      <div class="control-group">

        <div class="control-group-title">攻击</div>

        <div class="control-row">

          <span class="key">J</span>

          <span class="key-label">普攻(50伤害)</span>

        </div>

        <div class="control-row">

          <span class="key">K</span>

          <span class="key-label">发波(30伤害)</span>

        </div>

        <div class="control-row">

          <span class="key">L</span>

          <span class="key-label">大招(开局选择)</span>

        </div>

        <div class="key-hint">受击硬直中也可按L释放!</div>

        <div class="key-hint" style="color:#ffd54f;margin-top:4px;">伤害对比:普攻50 / 发波30 / 忍刀90 / 升龙60 / 超大波150 | 大招消耗:升龙30 / 虚化100 / 瞬移50 / 超大波80 / 斯安威斯坦20</div>

      </div>

    </div>

    <div style="display:flex;flex-direction:column;align-items:center;gap:8px;">

      <div style="font-size:14px;color:#aaa;letter-spacing:2px;">选择地图</div>

      <div class="map-select">

        <div class="map-card selected" id="mapCard0" onclick="selectMap(0)">

          <canvas id="mapPreview0" width="160" height="100"></canvas>

          <div class="map-card-label">默认竞技场</div>

        </div>

        <div class="map-card" id="mapCard1" onclick="selectMap(1)">

          <canvas id="mapPreview1" width="160" height="100"></canvas>

          <div class="map-card-label">平台高地</div>

        </div>

        <div class="map-card" id="mapCard2" onclick="selectMap(2)">

          <canvas id="mapPreview2" width="160" height="100"></canvas>

          <div class="map-card-label">三英战吕布</div>

        </div>

      </div>

    </div>

    <button class="btn" id="startBtn">开始对战</button>

  </div>



  <div id="endScreen" style="display:none">

    <h1 id="endTitle">对战结束</h1>

    <div id="endResult"></div>

    <button class="btn" id="restartBtn">再来一局</button>

  </div>



  <div id="ultSelectScreen">

    <h2>选择大招</h2>

    <div class="ult-cards">

      <div class="ult-card selected" id="ultCard0" onclick="selectUltimate(0)">

        <div class="ult-icon">🐉</div>

        <div class="ult-name">升龙拳</div>

        <div class="ult-origin">经典格斗</div>

        <div class="ult-desc">蓄力上勾拳<br>60伤害 / 击飞对手<br>带无敌帧,可打断攻击<br><span style="color:#ffd54f">消耗 30 能量</span></div>

      </div>

      <div class="ult-card" id="ultCard1" onclick="selectUltimate(1)">

        <div class="ult-icon">👁️</div>

        <div class="ult-name">虚化</div>

        <div class="ult-origin">神威 · 宇智波带土</div>

        <div class="ult-desc">身体虚化5秒<br>完全无敌,对手打不到你<br>攻击也无效,纯假动作<br><span style="color:#ffd54f">消耗 100 能量</span></div>

      </div>

      <div class="ult-card" id="ultCard2" onclick="selectUltimate(2)">

        <div class="ult-icon">⚡</div>

        <div class="ult-name">瞬移</div>

        <div class="ult-origin">飞雷神 · 波风水门</div>

        <div class="ult-desc">按L+方向键触发<br>A向左/D向右/W向上<br>瞬移5个身位<br><span style="color:#ffd54f">消耗 50 能量</span></div>

      </div>

      <div class="ult-card" id="ultCard3" onclick="selectUltimate(3)">

        <div class="ult-icon">💥</div>

        <div class="ult-name">超大波</div>

        <div class="ult-origin">尾兽玉 · 尾兽模式</div>

        <div class="ult-desc">巨型能量弹<br>150伤害 / 硬直35帧<br>范围大,命中必连招<br><span style="color:#ffd54f">消耗 80 能量</span></div>

      </div>

      <div class="ult-card" id="ultCard4" onclick="selectUltimate(4)">

        <div class="ult-icon">⏱️</div>

        <div class="ult-name">斯安威斯坦</div>

        <div class="ult-origin">赛博朋克 · 时间减缓</div>

        <div class="ult-desc">时间减缓0.5秒<br>敌人速度降至10%<br>玩家不受影响<br>长按L可连续使用<br>期间无法恢复能量<br><span style="color:#ffd54f">消耗 20 能量</span></div>

      </div>

    </div>

    <button class="btn" id="ultConfirmBtn" onclick="confirmUltimate()">确认出战</button>

  </div>



  <div id="diffSelectScreen">

    <h2>选择难度</h2>

    <div class="diff-cards">

      <div class="diff-card selected" id="diffCard0" onclick="selectDifficulty(0)">

        <div class="diff-icon">😊</div>

        <div class="diff-name">简单</div>

        <div class="diff-desc">AI反应慢<br>攻击频率低<br>适合新手练习</div>

      </div>

      <div class="diff-card" id="diffCard1" onclick="selectDifficulty(1)">

        <div class="diff-icon">😐</div>

        <div class="diff-name">普通</div>

        <div class="diff-desc">AI正常发挥<br>攻防平衡<br>标准对战体验</div>

      </div>

      <div class="diff-card" id="diffCard2" onclick="selectDifficulty(2)">

        <div class="diff-icon">😈</div>

        <div class="diff-name">困难</div>

        <div class="diff-desc">AI反应快<br>攻击凶猛<br>防御意识强</div>

      </div>

    </div>

    <button class="btn" onclick="confirmDifficulty()">开始对战</button>

  </div>

</div>



<script>

const canvas = document.getElementById('gameCanvas');

const ctx = canvas.getContext('2d');

const W = 900, H = 560;

const GROUND = H - 80;

const GRAVITY = 0.6;

const MAX_HP = 1000;

const MAX_ENERGY = 100;

const GAME_TIME = 60;

const BLOCK_ENERGY_COST = 0.4; // 防御每帧消耗能量

const BLOCK_MIN_ENERGY = 5; // 低于此值无法防御

// ============ 地图系统 ============

// 平台定义: { x, y, w, h }

// y 是平台顶面坐标(角色脚底站的位置)

const MAPS = [

  {

    name: '默认竞技场',

    platforms: [] // 纯平地,无额外平台

  },

  {

    name: '平台高地',

    platforms: [

      // 中间长平台(离地约100px,轻松跳上)

      { x: 300, y: 380, w: 300, h: 14 },

      // 左侧高处小平台(离地约135px,接近跳跃极限但能上)

      { x: 70, y: 345, w: 110, h: 14 },

      // 右侧高处小平台(对称)

      { x: 720, y: 345, w: 110, h: 14 }

    ]

  },

  {

    name: '三英战吕布',

    platforms: [

      // 第一层:中间长平台

      { x: 300, y: 380, w: 300, h: 14 },

      // 第一层:左侧小平台

      { x: 70, y: 345, w: 110, h: 14 },

      // 第一层:右侧小平台

      { x: 720, y: 345, w: 110, h: 14 },

      // 第二层:左侧小平台

      { x: 150, y: 280, w: 110, h: 14 },

      // 第二层:右侧小平台

      { x: 640, y: 280, w: 110, h: 14 },

      // 第三层:中央平台

      { x: 350, y: 210, w: 200, h: 14 }

    ],

    enemies: 3 // 1个主AI + 2个额外敌人

  }

];



let selectedMap = 0;

let currentPlatforms = []; // 当前地图的平台列表



// ============ 大招选择系统 ============

// 0=升龙拳, 1=虚化, 2=瞬移, 3=超大波, 4=斯安威斯坦

const ULTIMATES = [

  { name: '升龙拳', icon: '🐉' },

  { name: '虚化', icon: '👁️' },

  { name: '瞬移', icon: '⚡' },

  { name: '超大波', icon: '💥' },

  { name: '斯安威斯坦', icon: '⏱️' }

];

let selectedUltimate = 0;

let playerUltimate = 0;

let aiUltimate = 0;



function selectUltimate(idx) {

  selectedUltimate = idx;

  document.querySelectorAll('.ult-card').forEach((c, i) => {

    c.classList.toggle('selected', i === idx);

  });

}



// 鼠标滚轮滚动大招卡片

document.addEventListener('DOMContentLoaded', function() {

  const ultCards = document.querySelector('.ult-cards');

  if (ultCards) {

    ultCards.addEventListener('wheel', function(e) {

      e.preventDefault();

      ultCards.scrollLeft += e.deltaY;

    });

  }

});



function confirmUltimate() {

  playerUltimate = selectedUltimate;

  // AI随机选一个大招

  aiUltimate = Math.floor(Math.random() * 5);

  document.getElementById('ultSelectScreen').style.display = 'none';

  document.getElementById('diffSelectScreen').style.display = 'flex';

}

// ============ 难度选择系统 ============

// 0=简单, 1=普通, 2=困难

const DIFFICULTIES = [

  { name: '简单', icon: '😊' },

  { name: '普通', icon: '😐' },

  { name: '困难', icon: '😈' }

];

let selectedDifficulty = 0;



// AI难度参数(速度与玩家一致,差异在操作反应)

const AI_PARAMS = {

  0: { // 简单

    speed: 4, // 与玩家一致

    reactionTime: 45, // 反应慢

    attackFrequency: 0.2,

    blockProbability: 0.2,

    ultimateFrequency: 0.15

  },

  1: { // 普通

    speed: 4, // 与玩家一致

    reactionTime: 25, // 反应中等

    attackFrequency: 0.4,

    blockProbability: 0.45,

    ultimateFrequency: 0.3

  },

  2: { // 困难

    speed: 4, // 与玩家一致

    reactionTime: 10, // 反应极快

    attackFrequency: 0.6,

    blockProbability: 0.7,

    ultimateFrequency: 0.5

  }

};

let currentAIParams = AI_PARAMS[0];



function selectDifficulty(idx) {

  selectedDifficulty = idx;

  document.querySelectorAll('.diff-card').forEach((c, i) => {

    c.classList.toggle('selected', i === idx);

  });

}



function confirmDifficulty() {

  currentAIParams = AI_PARAMS[selectedDifficulty];

  document.getElementById('diffSelectScreen').style.display = 'none';

  startGame();

}



function selectMap(idx) {

  selectedMap = idx;

  document.querySelectorAll('.map-card').forEach((c, i) => {

    c.classList.toggle('selected', i === idx);

  });

}



// 绘制地图预览缩略图

function drawMapPreviews() {

  for (let i = 0; i < MAPS.length; i++) {

    const cvs = document.getElementById('mapPreview' + i);

    if (!cvs) continue;

    const c = cvs.getContext('2d');

    const pw = 160, ph = 100;

    // 背景

    const g = c.createLinearGradient(0, 0, 0, ph);

    g.addColorStop(0, '#0d1b2a');

    g.addColorStop(1, '#1a0e0a');

    c.fillStyle = g;

    c.fillRect(0, 0, pw, ph);

    // 地面

    const groundY = ph - 14;

    c.fillStyle = '#3e2723';

    c.fillRect(0, groundY, pw, 14);

    c.strokeStyle = '#5d4037';

    c.lineWidth = 1;

    c.beginPath();

    c.moveTo(0, groundY);

    c.lineTo(pw, groundY);

    c.stroke();

    // 平台(缩放比例)

    const sx = pw / W;

    const sy = ph / H;

    MAPS[i].platforms.forEach(p => {

      c.fillStyle = '#5d4037';

      c.fillRect(p.x * sx, p.y * sy, p.w * sx, p.h * sy + 2);

      c.fillStyle = '#8d6e63';

      c.fillRect(p.x * sx, p.y * sy, p.w * sx, 3);

    });

  }

}



// Game state

let gameRunning = false;

let gameTime = GAME_TIME;

let timerInterval = null;

let particles = [];

let projectiles = [];

let shakeTimer = 0;

let shakeIntensity = 0;

let comboCount = 0;

let comboTimer = 0;

let announceText = '';

let announceTimer = 0;



// 斯安威斯坦时间减缓效果

let sandevistanTimer = 0; // 剩余帧数(30帧=0.5秒)

const SANDEVISTAN_DURATION = 30; // 0.5秒

const SANDEVISTAN_TIME_SCALE = 0.1; // 敌人速度降至10%



// Keys

const keys = {};

const keyJustPressed = {};

document.addEventListener('keydown', e => {

  if (!keys[e.key]) {

    keyJustPressed[e.key] = true;

  }

  keys[e.key] = true;

  e.preventDefault();

});

document.addEventListener('keyup', e => {

  keys[e.key] = false;

  e.preventDefault();

});



function consumeKey(k) {

  if (keyJustPressed[k]) {

    keyJustPressed[k] = false;

    return true;

  }

  return false;

}



// ============ 道具系统 ============

let items = [];

let itemSpawnTimer = 0;

const ITEM_SPAWN_INTERVAL = 300; // 5秒刷新一次

const ITEM_TYPES = {

  ENERGY_BALL: 'energy_ball',

  NINJA_SWORD: 'ninja_sword'

};



class Item {

  constructor(x, y, type) {

    this.x = x;

    this.y = y;

    this.type = type;

    this.radius = type === ITEM_TYPES.ENERGY_BALL ? 15 : 20;

    this.alive = true;

    this.bobPhase = Math.random() * Math.PI * 2;

    this.lifetime = 600; // 10秒后消失

  }



  update() {

    this.bobPhase += 0.05;

    this.lifetime--;

    if (this.lifetime <= 0) {

      this.alive = false;

    }

  }



  draw() {

    ctx.save();

    const bobY = Math.sin(this.bobPhase) * 2; // 轻微浮动

    const alpha = this.lifetime < 120 ? (this.lifetime / 120) * (0.5 + Math.sin(this.lifetime * 0.2) * 0.5) : 1;

    ctx.globalAlpha = alpha;



    if (this.type === ITEM_TYPES.ENERGY_BALL) {

      // 能量球:金色发光球体,坐在地面上

      const ballY = this.y - this.radius + bobY; // 球心在地面以上

      const gradient = ctx.createRadialGradient(this.x, ballY, 0, this.x, ballY, this.radius * 1.5);

      gradient.addColorStop(0, '#fff');

      gradient.addColorStop(0.3, '#ffd54f');

      gradient.addColorStop(0.7, '#ff8f00');

      gradient.addColorStop(1, 'transparent');

      ctx.fillStyle = gradient;

      ctx.beginPath();

      ctx.arc(this.x, ballY, this.radius * 1.5, 0, Math.PI * 2);

      ctx.fill();



      // 内部核心

      ctx.fillStyle = '#fff';

      ctx.beginPath();

      ctx.arc(this.x, ballY, this.radius * 0.4, 0, Math.PI * 2);

      ctx.fill();



      // 文字提示(在道具上方)

      ctx.fillStyle = '#ffd54f';

      ctx.font = 'bold 11px Microsoft YaHei';

      ctx.textAlign = 'center';

      ctx.fillText('能量', this.x, ballY - this.radius - 8);

    } else if (this.type === ITEM_TYPES.NINJA_SWORD) {

      // 忍刀:紫色刀身,插在地面上

      const swordBaseY = this.y + bobY; // 刀底部在地面



      // 刀身光晕

      const swordGlow = ctx.createRadialGradient(this.x, swordBaseY - 20, 0, this.x, swordBaseY - 20, 30);

      swordGlow.addColorStop(0, 'rgba(156, 39, 176, 0.4)');

      swordGlow.addColorStop(1, 'transparent');

      ctx.fillStyle = swordGlow;

      ctx.beginPath();

      ctx.arc(this.x, swordBaseY - 20, 30, 0, Math.PI * 2);

      ctx.fill();



      // 刀身(从地面向上)

      ctx.fillStyle = '#9c27b0';

      ctx.fillRect(this.x - 3, swordBaseY - 45, 6, 40);



      // 刀刃高光

      ctx.fillStyle = '#e1bee7';

      ctx.fillRect(this.x - 1, swordBaseY - 45, 2, 40);



      // 刀柄(在地面处)

      ctx.fillStyle = '#4a148c';

      ctx.fillRect(this.x - 4, swordBaseY - 5, 8, 10);



      // 护手

      ctx.fillStyle = '#7b1fa2';

      ctx.fillRect(this.x - 8, swordBaseY - 7, 16, 3);



      // 文字提示(在道具上方)

      ctx.fillStyle = '#ce93d8';

      ctx.font = 'bold 11px Microsoft YaHei';

      ctx.textAlign = 'center';

      ctx.fillText('忍刀', this.x, swordBaseY - 52);

    }



    ctx.restore();

  }



    // 检测是否与角色碰撞

  collidesWith(fighter) {

    // 道具中心位置(考虑道具坐在地面上)

    let itemCenterY = this.y;

    if (this.type === ITEM_TYPES.ENERGY_BALL) {

      itemCenterY = this.y - this.radius; // 能量球心在地面以上

    } else if (this.type === ITEM_TYPES.NINJA_SWORD) {

      itemCenterY = this.y - 20; // 忍刀中心在刀身中部

    }



    const dx = this.x - fighter.cx;

    const dy = itemCenterY - (fighter.y - fighter.height / 2);

    const dist = Math.sqrt(dx * dx + dy * dy);

    return dist < this.radius + 35;

  }

}



// 在平台上随机生成道具

function spawnItems() {

  if (selectedMap === 0) return; // 默认竞技场不生成道具



  const spawnPoints = [];



  // 收集所有平台的表面点(道具坐在地面上)

  currentPlatforms.forEach(plat => {

    for (let x = plat.x + 30; x < plat.x + plat.w - 30; x += 60) {

      spawnPoints.push({ x, y: plat.y }); // 道具在地面上

    }

  });



  // 地面也可以生成

  for (let x = 100; x < W - 100; x += 100) {

    spawnPoints.push({ x, y: GROUND }); // 道具在地面上

  }



  // 随机选择位置生成

  if (spawnPoints.length > 0 && items.length < 3) {

    const pos = spawnPoints[Math.floor(Math.random() * spawnPoints.length)];

    const type = Math.random() < 0.6 ? ITEM_TYPES.ENERGY_BALL : ITEM_TYPES.NINJA_SWORD;

    items.push(new Item(pos.x, pos.y, type));

  }

}



// Fighter class

class Fighter {

  constructor(x, facingRight, isPlayer, color) {

    this.x = x;

    this.y = GROUND;

    this.vx = 0;

    this.vy = 0;

    this.width = 50;

    this.height = 90;

    this.facingRight = facingRight;

    this.isPlayer = isPlayer;

    this.color = color;

    this.hp = MAX_HP;

    this.maxHp = MAX_HP;

    this.energy = 0;

    this.speed = 4;

    this.jumpForce = -13;

    this.onGround = true;

    this.blocking = false;

    this.attacking = false;

    this.attackType = null;

    this.attackTimer = 0;

    this.attackCooldown = 0;

    this.hitStun = 0;

    this.invincible = 0;

    this.animFrame = 0;

    this.animTimer = 0;

    this.walkCycle = 0;

    this.attackHit = false;

    // Ultimate (升龙拳) state

    this.ultimateActive = false;

    this.ultimateTimer = 0;

    this.uppercutPhase = 0; // 0=none, 1=crouch, 2=rising, 3=peak, 4=landing

    this.uppercutY = 0;

    // Interrupt state (被打断)

    this.interrupted = false;

    this.interruptTimer = 0;

    // 虚化状态

    this.intangible = false;

    this.intangibleTimer = 0;

    // 瞬移状态

    this.teleporting = false;

    this.teleportTimer = 0;

    this.afterimageX = 0;

    this.afterimageY = 0;

    this.afterimageVisible = false;

    this.afterimageTimer = 0;

    this.ultType = 0; // 0=升龙拳, 1=虚化, 2=瞬移

    // 忍刀状态

    this.hasSword = false;

    this.swordAttackTimer = 0; // 忍刀攻击前摇

  }



  get cx() { return this.x + this.width / 2; }

  get cy() { return this.y - this.height / 2; }

  get left() { return this.x; }

  get right() { return this.x + this.width; }

  get top() { return this.y - this.height; }

  get bottom() { return this.y; }



  takeDamage(amount, knockbackX, attacker) {

    if (this.invincible > 0) return false;

    if (this.intangible) return false; // 虚化状态完全无敌

    let blocked = false;

    if (this.blocking && this.energy >= BLOCK_MIN_ENERGY) {

      amount = Math.floor(amount * 0.15);

      knockbackX *= 0.3;

      this.energy = Math.max(0, this.energy - amount * 0.3); // 防御也消耗能量

      spawnParticles(this.cx, this.cy, '#4fc3f7', 5, 2);

      blocked = true;

    } else {

      spawnParticles(this.cx, this.cy, '#ff5252', 12, 4);

      shakeTimer = 8;

      shakeIntensity = 4;

      // 受击硬直(默认值,发波命中会覆盖为更高)

      this.hitStun = 10;

      // 打断当前动作

      if (this.attacking && !this.ultimateActive) {

        this.interrupted = true;

        this.interruptTimer = 10;

        this.attacking = false;

        this.attackType = null;

        this.attackHit = false;

      }

    }

    this.hp = Math.max(0, this.hp - amount);

    this.vx = knockbackX;

    // 受击恢复能量:受伤越多恢复越多,单次不超过30(斯安威斯坦期间无法恢复)

    if (!(this.isPlayer && sandevistanTimer > 0)) {

      const energyGain = Math.min(30, amount * 0.2);

      this.energy = Math.min(MAX_ENERGY, this.energy + energyGain);

    }

    return !blocked;

  }



update(opponent) {

    // 斯安威斯坦时间减缓效果(仅对敌人生效)

    const timeScale = (!this.isPlayer && sandevistanTimer > 0) ? SANDEVISTAN_TIME_SCALE : 1.0;



    // 硬直倒计时

    if (this.hitStun > 0) {

      this.hitStun -= timeScale;

      this.vx *= 0.88;

    }

    // 打断恢复

    if (this.interruptTimer > 0) {

      this.interruptTimer -= timeScale;

      if (this.interruptTimer <= 0) {

        this.interrupted = false;

      }

    }

    if (this.invincible > 0) this.invincible -= timeScale;

    if (this.attackCooldown > 0) this.attackCooldown -= timeScale;



    // 虚化计时

    if (this.intangible) {

      this.intangibleTimer -= timeScale;

      if (this.intangibleTimer <= 0) {

        this.intangible = false;

      }

    }

    // 瞬移计时

    if (this.teleporting) {

      this.teleportTimer -= timeScale;

      this.invincible = 3; // 瞬移中持续短暂无敌

      if (this.teleportTimer <= 0) {

        this.teleporting = false;

      }

    }

    // 残影消失计时

    if (this.afterimageVisible) {

      this.afterimageTimer -= timeScale;

      if (this.afterimageTimer <= 0) {

        this.afterimageVisible = false;

      }

    }



    // Attack timer

    if (this.attacking && !this.ultimateActive) {

      this.attackTimer -= timeScale;

      if (this.attackTimer <= 0) {

        this.attacking = false;

        this.attackType = null;

        this.attackHit = false;

      }

    }



    // Ultimate (升龙拳) phases

    if (this.ultimateActive) {

      this.ultimateTimer -= timeScale;

      this.uppercutPhase += timeScale;



      if (this.uppercutPhase <= 8) {

        // Phase 1: crouch down (蓄力下蹲)

        this.vy = 0;

        this.invincible = 3;

      } else if (this.uppercutPhase <= 20) {

        // Phase 2: rising uppercut (升龙上升)

        this.vy = -14;

        this.invincible = 5;

        // Trail particles

        const c = this.isPlayer ? '#4fc3f7' : '#ef5350';

        spawnParticles(this.cx, this.y, c, 3, 3);

      } else if (this.uppercutPhase <= 28) {

        // Phase 3: peak (最高点悬停)

        this.vy *= 0.7;

        this.invincible = 3;

      } else {

        // Phase 4: falling

        this.invincible = 0;

      }



      if (this.ultimateTimer <= 0) {

        this.ultimateActive = false;

        this.uppercutPhase = 0;

        this.attacking = false;

        this.attackType = null;

        this.attackHit = false;

      }

    }



    // Physics

    if (!this.onGround) {

      this.vy += GRAVITY * timeScale;

    }

    this.x += this.vx * timeScale;

    this.y += this.vy * timeScale;



    // Ground

    if (this.y >= GROUND) {

      this.y = GROUND;

      this.vy = 0;

      this.onGround = true;

    } else {

      this.onGround = false;

    }



// Platform collision (one-way: land on top only when falling)

    if (!this.onGround && this.vy >= 0) {

      for (const plat of currentPlatforms) {

        // Check if feet crossed platform top this frame

        const prevBottom = this.y - this.vy; // approximate previous bottom

        if (prevBottom <= plat.y && this.y >= plat.y) {

          // Check x overlap

          if (this.x + this.width > plat.x && this.x < plat.x + plat.w) {

            this.y = plat.y;

            this.vy = 0;

            this.onGround = true;

            break;

          }

        }

      }

    }



    // Walls

    if (this.x < 10) this.x = 10;

    if (this.x + this.width > W - 10) this.x = W - this.width - 10;



    // Friction

    if (this.onGround && this.hitStun <= 0) {

      this.vx *= 0.8;

    }



    // Face opponent (AI only, player uses direction keys)

    if (!this.isPlayer && this.hitStun <= 0 && !this.attacking) {

      this.facingRight = opponent.cx > this.cx;

    }



    // Animation

    this.animTimer++;

    if (this.animTimer > 8) {

      this.animTimer = 0;

      this.animFrame = (this.animFrame + 1) % 4;

    }

    if (Math.abs(this.vx) > 0.5 && this.onGround) {

      this.walkCycle += 0.15;

    }



    // Passive energy regen (very slow, 斯安威斯坦期间无法恢复)

    if (!(this.isPlayer && sandevistanTimer > 0)) {

      this.energy = Math.min(MAX_ENERGY, this.energy + 0.02);

    }

  }



  draw() {

    ctx.save();

    const dir = this.facingRight ? 1 : -1;

    const cx = this.cx;

    const baseY = this.y;



    // Shadow - project onto ground or platform below

    let shadowY = GROUND + 2;

    // Check if standing on a platform

    for (const plat of currentPlatforms) {

      if (this.y === plat.y && this.x + this.width > plat.x && this.x < plat.x + plat.w) {

        shadowY = plat.y + 2;

        break;

      }

    }

    const shadowScale = 1 - (shadowY - this.y) * 0.002;

    ctx.fillStyle = 'rgba(0,0,0,0.3)';

    ctx.beginPath();

    ctx.ellipse(cx, shadowY, 28 * Math.max(0.5, shadowScale), 6 * Math.max(0.5, shadowScale), 0, 0, Math.PI * 2);

    ctx.fill();



    // Flash on hit

    let bodyColor = this.color;

    if (this.hitStun > 0 && this.hitStun % 3 === 0) {

      bodyColor = '#fff';

    }

    if (this.invincible > 0 && this.invincible % 4 < 2) {

      ctx.globalAlpha = 0.5;

    }



    // 虚化效果:半透明闪烁

    if (this.intangible) {

      ctx.globalAlpha = 0.2 + Math.sin(Date.now() * 0.02) * 0.15;

      bodyColor = this.isPlayer ? '#4fc3f7' : '#ef5350';

    }



    // 残影绘制(瞬移后留在原地)

    if (this.afterimageVisible) {

      const alpha = this.afterimageTimer / 30;

      ctx.globalAlpha = alpha * 0.5;

      ctx.fillStyle = this.isPlayer ? '#4fc3f7' : '#ef5350';

      ctx.fillRect(this.afterimageX - 20, this.afterimageY - 85, 40, 55);

      ctx.beginPath();

      ctx.arc(this.afterimageX, this.afterimageY - 95, 16, 0, Math.PI * 2);

      ctx.fill();

      ctx.fillRect(this.afterimageX - 28, this.afterimageY - 78, 10, 30);

      ctx.fillRect(this.afterimageX + 18, this.afterimageY - 78, 10, 30);

      ctx.fillRect(this.afterimageX - 15, this.afterimageY - 30, 12, 30);

      ctx.fillRect(this.afterimageX + 3, this.afterimageY - 30, 12, 30);

      ctx.globalAlpha = (this.invincible > 0 && this.invincible % 4 < 2) ? 0.5 : (this.intangible ? 0.2 + Math.sin(Date.now() * 0.02) * 0.15 : 1);

    }



    // Hitstun visual (身体后仰)

    if (this.hitStun > 0 && !this.ultimateActive) {

      ctx.fillStyle = bodyColor;

      // Body tilted back

      ctx.save();

      ctx.translate(cx, baseY - 45);

      ctx.rotate(-dir * 0.2);

      ctx.fillRect(-20, -40, 40, 55);

      ctx.beginPath();

      ctx.arc(0, -50, 16, 0, Math.PI * 2);

      ctx.fill();

      // Pain expression

      ctx.fillStyle = '#fff';

      ctx.fillRect(-8, -54, 4, 2);

      ctx.fillRect(4, -54, 4, 2);

      ctx.restore();

      // Legs

      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 15, baseY - 30, 12, 30);

      ctx.fillRect(cx + 3, baseY - 30, 12, 30);

      // Energy full indicator during hitstun (凹大招提示)

      if (this.energy >= MAX_ENERGY && this.isPlayer) {

        ctx.fillStyle = '#ffd54f';

        ctx.font = 'bold 14px Microsoft YaHei';

        ctx.textAlign = 'center';

        ctx.globalAlpha = 0.5 + Math.sin(Date.now() * 0.015) * 0.5;

        ctx.fillText('按L反击!', cx, baseY - 110);

        ctx.globalAlpha = 1;

      }

    }

    // Blocking stance

    else if (this.blocking) {

      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 22, baseY - 65, 44, 65);

      // Shield effect - color changes based on energy

      const shieldColor = this.energy > 30 ? '#4fc3f7' : '#ff8a65';

      ctx.strokeStyle = shieldColor;

      ctx.lineWidth = 3;

      ctx.beginPath();

      ctx.arc(cx + dir * 15, baseY - 40, 30, -Math.PI * 0.6 * dir, Math.PI * 0.6 * dir);

      ctx.stroke();

      ctx.strokeStyle = shieldColor + '40';

      ctx.lineWidth = 6;

      ctx.beginPath();

      ctx.arc(cx + dir * 15, baseY - 40, 34, -Math.PI * 0.5 * dir, Math.PI * 0.5 * dir);

      ctx.stroke();

    }



// 升龙拳 animation

    else if (this.ultimateActive) {

      const phase = this.uppercutPhase;

      const auraColor = this.isPlayer ? '#4fc3f7' : '#ef5350';



      // Aura

      const pulse = Math.sin(Date.now() * 0.03) * 0.3 + 0.7;

      ctx.fillStyle = auraColor;

      ctx.globalAlpha = pulse * 0.25;

      ctx.beginPath();

      ctx.arc(cx, baseY - 50, 55 + phase * 0.5, 0, Math.PI * 2);

      ctx.fill();

      ctx.globalAlpha = (this.invincible > 0 && this.invincible % 4 < 2) ? 0.5 : 1;



      if (phase <= 8) {

        // Crouch / charge

        ctx.fillStyle = bodyColor;

        ctx.fillRect(cx - 22, baseY - 55, 44, 55);

        ctx.beginPath();

        ctx.arc(cx, baseY - 65, 16, 0, Math.PI * 2);

        ctx.fill();

        // Charging fist

        ctx.fillStyle = auraColor;

        ctx.beginPath();

        ctx.arc(cx + dir * 20, baseY - 45, 8 + phase * 0.5, 0, Math.PI * 2);

        ctx.fill();

        // Legs bent

        ctx.fillStyle = bodyColor;

        ctx.fillRect(cx - 18, baseY - 20, 14, 20);

        ctx.fillRect(cx + 4, baseY - 20, 14, 20);

      } else if (phase <= 20) {

        // Rising uppercut

        const riseProgress = (phase - 8) / 12;

        ctx.fillStyle = bodyColor;

        ctx.fillRect(cx - 20, baseY - 85, 40, 55);

        ctx.beginPath();

        ctx.arc(cx, baseY - 95, 16, 0, Math.PI * 2);

        ctx.fill();

        // Uppercut arm - extending upward

        const armY = -95 - riseProgress * 30;

        ctx.fillStyle = bodyColor;

        ctx.save();

        ctx.translate(cx + dir * 10, baseY + armY);

        ctx.rotate(-dir * 0.3);

        ctx.fillRect(-6, 0, 12, -35);

        ctx.restore();

        // Glowing fist

        ctx.fillStyle = '#fff';

        ctx.beginPath();

        ctx.arc(cx + dir * 15, baseY + armY - 35, 10, 0, Math.PI * 2);

        ctx.fill();

        ctx.fillStyle = auraColor;

        ctx.beginPath();

        ctx.arc(cx + dir * 15, baseY + armY - 35, 14, 0, Math.PI * 2);

        ctx.fill();

        // Legs

        ctx.fillStyle = bodyColor;

        ctx.fillRect(cx - 12, baseY - 30, 10, 30);

        ctx.fillRect(cx + 2, baseY - 30, 10, 30);

      } else {

        // Peak / landing

        ctx.fillStyle = bodyColor;

        ctx.fillRect(cx - 20, baseY - 85, 40, 55);

        ctx.beginPath();

        ctx.arc(cx, baseY - 95, 16, 0, Math.PI * 2);

        ctx.fill();

        // Arms up victory pose

        ctx.fillRect(cx - 28, baseY - 120, 10, 30);

        ctx.fillRect(cx + 18, baseY - 120, 10, 30);

        // Fists glow

        ctx.fillStyle = auraColor;

        ctx.beginPath();

        ctx.arc(cx - 23, baseY - 125, 8, 0, Math.PI * 2);

        ctx.fill();

        ctx.beginPath();

        ctx.arc(cx + 23, baseY - 125, 8, 0, Math.PI * 2);

        ctx.fill();

        // Legs

        ctx.fillStyle = bodyColor;

        ctx.fillRect(cx - 15, baseY - 30, 12, 30);

        ctx.fillRect(cx + 3, baseY - 30, 12, 30);

      }

    }

    else if (this.attacking && this.attackType === 'normal') {

      const progress = 1 - (this.attackTimer / (this.hasSword ? 20 : 12));

      const armExtend = Math.sin(progress * Math.PI) * (this.hasSword ? 55 : 40);



      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 20, baseY - 85, 40, 55);

      ctx.beginPath();

      ctx.arc(cx, baseY - 95, 16, 0, Math.PI * 2);

      ctx.fill();

      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx + dir * 15, baseY - 75, dir * armExtend, 12);



// 忍刀攻击:画刀

      if (this.hasSword && armExtend > 15) {

        ctx.save();

        ctx.translate(cx + dir * (15 + armExtend), baseY - 72);

        ctx.rotate(dir * (progress < 0.5 ? -0.5 : 0.3));

        // 刀身

        ctx.fillStyle = '#9c27b0';

        ctx.fillRect(0, -3, dir * 45, 6);

        // 刀刃高光

        ctx.fillStyle = '#e1bee7';

        ctx.fillRect(0, -1, dir * 45, 2);

        // 刀柄

        ctx.fillStyle = '#4a148c';

        ctx.fillRect(-dir * 2, -4, dir * 10, 8);

        // 护手

        ctx.fillStyle = '#7b1fa2';

        ctx.fillRect(-dir * 1, -6, dir * 3, 12);

        // 斩击特效

        if (progress > 0.3 && progress < 0.7) {

          ctx.strokeStyle = 'rgba(206, 147, 216, 0.6)';

          ctx.lineWidth = 3;

          ctx.beginPath();

          ctx.arc(dir * 20, 0, 35, -0.8, 0.8);

          ctx.stroke();

        }

        ctx.restore();

      } else if (armExtend > 20) {

        // 普通拳头

        ctx.fillStyle = '#ffd54f';

        ctx.fillRect(cx + dir * (15 + armExtend - 5), baseY - 78, 14, 18);

      }

      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 15, baseY - 30, 12, 30);

      ctx.fillRect(cx + 3, baseY - 30, 12, 30);

    } else if (this.attacking && this.attackType === 'wave') {

      const progress = 1 - (this.attackTimer / 18);



      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 20, baseY - 85, 40, 55);

      ctx.beginPath();

      ctx.arc(cx, baseY - 95, 16, 0, Math.PI * 2);

      ctx.fill();

      const armLen = Math.sin(progress * Math.PI) * 30;

      ctx.fillRect(cx + dir * 15, baseY - 72, dir * armLen, 10);

      ctx.fillRect(cx + dir * 15, baseY - 60, dir * armLen, 10);

      if (progress > 0.3 && progress < 0.7) {

        ctx.fillStyle = this.isPlayer ? 'rgba(79,195,247,0.4)' : 'rgba(239,83,80,0.4)';

        ctx.beginPath();

        ctx.arc(cx + dir * 45, baseY - 65, 15, 0, Math.PI * 2);

        ctx.fill();

      }

      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 15, baseY - 30, 12, 30);

      ctx.fillRect(cx + 3, baseY - 30, 12, 30);

    } else {

      // Idle / walking

      const bobY = this.onGround ? Math.sin(this.walkCycle) * 3 : 0;

      const legOffset = this.onGround ? Math.sin(this.walkCycle) * 8 : 5;



      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 20, baseY - 85 + bobY, 40, 55);

      ctx.beginPath();

      ctx.arc(cx, baseY - 95 + bobY, 16, 0, Math.PI * 2);

      ctx.fill();

      ctx.fillStyle = '#fff';

      ctx.fillRect(cx + dir * 5 - 3, baseY - 98 + bobY, 6, 4);

      ctx.fillStyle = '#000';

      ctx.fillRect(cx + dir * 7 - 2, baseY - 97 + bobY, 3, 3);

      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 28, baseY - 78 + bobY, 10, 30);

      ctx.fillRect(cx + 18, baseY - 78 + bobY, 10, 30);



      // 持刀状态:背后背刀

      if (this.hasSword) {

        ctx.save();

        ctx.translate(cx - dir * 15, baseY - 75 + bobY);

        ctx.rotate(-dir * 0.3);

        // 刀身

        ctx.fillStyle = '#9c27b0';

        ctx.fillRect(-2, -30, 4, 50);

        // 刀刃高光

        ctx.fillStyle = '#e1bee7';

        ctx.fillRect(-1, -30, 2, 50);

        // 刀柄

        ctx.fillStyle = '#4a148c';

        ctx.fillRect(-3, 20, 6, 10);

        // 护手

        ctx.fillStyle = '#7b1fa2';

        ctx.fillRect(-5, 18, 10, 3);

        ctx.restore();

      }



      ctx.fillStyle = bodyColor;

      ctx.fillRect(cx - 15, baseY - 30, 12, 30 + legOffset * 0.3);

      ctx.fillRect(cx + 3, baseY - 30, 12, 30 - legOffset * 0.3);

      ctx.fillStyle = this.isPlayer ? '#0288d1' : '#c62828';

      ctx.fillRect(cx - 20, baseY - 35 + bobY, 40, 5);

    }



    ctx.restore();

  }



  getAttackBox() {

    if (!this.attacking || this.attackHit) return null;

    if (this.intangible) return null; // 虚化时攻击无判定,打不到人

    if (this.attackType === 'normal') {

      // 忍刀攻击:范围更长、伤害更高

      if (this.hasSword) {

        return {

          x: this.facingRight ? this.cx + 5 : this.cx - 85,

          y: this.y - 85,

          w: 80,

          h: 40,

          damage: 90,

          knockback: this.facingRight ? 8 : -8,

          type: 'sword'

        };

      }



// 普通普攻:伤害高、击退适中

      const dir = this.facingRight ? 1 : -1;

      return {

        x: this.facingRight ? this.cx + 10 : this.cx - 55,

        y: this.y - 75,

        w: 45,

        h: 25,

        damage: 50,

        knockback: this.facingRight ? 5 : -5,

        type: 'normal'

      };

    }

    if (this.attackType === 'uppercut' && this.uppercutPhase >= 8 && this.uppercutPhase <= 22) {

      // 升龙拳判定框 - 大范围上方

      return {

        x: this.cx - 30,

        y: this.y - 130,

        w: 60,

        h: 100,

        damage: 60,

        knockback: this.facingRight ? 12 : -12,

        type: 'uppercut'

      };

    }

    return null;

  }

}



// Projectile class

class Projectile {

  constructor(x, y, dir, owner) {

    this.x = x;

    this.y = y;

    this.dir = dir;

    this.owner = owner;

    // 发波:速度慢、伤害低

    this.speed = 5;

    this.radius = 14;

    this.damage = 30;

    this.alive = true;

    this.life = 100;

    this.color = owner.isPlayer ? '#4fc3f7' : '#ef5350';

  }



  update() {

    // 斯安威斯坦时间减缓效果(仅对敌人发射的飞行道具生效)

    const timeScale = (this.owner && !this.owner.isPlayer && sandevistanTimer > 0) ? SANDEVISTAN_TIME_SCALE : 1.0;



    this.x += this.dir * this.speed * timeScale;

    this.life -= timeScale;

    if (this.life <= 0 || this.x < -30 || this.x > W + 30) {

      this.alive = false;

    }

    if (Math.random() < 0.6) {

      spawnParticles(this.x, this.y, this.color, 1, 1.5);

    }

  }



  draw() {

    ctx.save();

    const gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.radius * 2);

    gradient.addColorStop(0, this.color);

    gradient.addColorStop(0.5, this.color + '80');

    gradient.addColorStop(1, 'transparent');

    ctx.fillStyle = gradient;

    ctx.beginPath();

    ctx.arc(this.x, this.y, this.radius * 2, 0, Math.PI * 2);

    ctx.fill();

    ctx.fillStyle = '#fff';

    ctx.beginPath();

    ctx.arc(this.x, this.y, this.radius * 0.5, 0, Math.PI * 2);

    ctx.fill();

    ctx.fillStyle = this.color;

    ctx.beginPath();

    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);

    ctx.fill();

    ctx.restore();

  }

}



// MegaProjectile - 超大波

class MegaProjectile {

  constructor(x, y, dir, owner) {

    this.x = x;

    this.y = y;

    this.dir = dir;

    this.owner = owner;

    this.speed = 4;

    this.radius = 50; // 增大碰撞范围

    this.damage = 150;

    this.alive = true;

    this.life = 120;

    this.color = owner.isPlayer ? '#4fc3f7' : '#ef5350';

    this.pulsePhase = 0;

  }



  update() {

    // 斯安威斯坦时间减缓效果(仅对敌人发射的飞行道具生效)

    const timeScale = (this.owner && !this.owner.isPlayer && sandevistanTimer > 0) ? SANDEVISTAN_TIME_SCALE : 1.0;



    this.x += this.dir * this.speed * timeScale;

    this.pulsePhase += 0.15 * timeScale;

    this.life -= timeScale;

    if (this.life <= 0 || this.x < -50 || this.x > W + 50) {

      this.alive = false;

    }

    // 更多拖尾粒子

    if (Math.random() < 0.9 * timeScale) {

      spawnParticles(this.x, this.y, this.color, 2, 3);

    }

  }



  draw() {

    ctx.save();

    const pulse = 1 + Math.sin(this.pulsePhase) * 0.15;

    const r = this.radius * pulse;

    // 外层光晕

    const gradient = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, r * 2.5);

    gradient.addColorStop(0, this.color);

    gradient.addColorStop(0.3, this.color + 'AA');

    gradient.addColorStop(0.6, this.color + '44');

    gradient.addColorStop(1, 'transparent');

    ctx.fillStyle = gradient;

    ctx.beginPath();

    ctx.arc(this.x, this.y, r * 2.5, 0, Math.PI * 2);

    ctx.fill();

    // 中间白色核心

    ctx.fillStyle = '#fff';

    ctx.beginPath();

    ctx.arc(this.x, this.y, r * 0.4, 0, Math.PI * 2);

    ctx.fill();

    // 主体

    ctx.fillStyle = this.color;

    ctx.globalAlpha = 0.8;

    ctx.beginPath();

    ctx.arc(this.x, this.y, r, 0, Math.PI * 2);

    ctx.fill();

    ctx.globalAlpha = 1;

    // 内部纹理

    ctx.strokeStyle = '#fff';

    ctx.lineWidth = 2;

    ctx.globalAlpha = 0.4;

    ctx.beginPath();

    ctx.arc(this.x, this.y, r * 0.7, 0, Math.PI * 2);

    ctx.stroke();

    ctx.restore();

  }

}



// SwordProjectile - 投掷忍刀

class SwordProjectile {

  constructor(x, y, dir, owner) {

    this.x = x;

    this.y = y;

    this.dir = dir;

    this.owner = owner;

    this.speed = 9;

    this.damage = 70;

    this.alive = true;

    this.life = 80;

    this.rotation = 0;

    this.width = 45;

    this.height = 6;

    this.radius = 25; // 碰撞检测用,扩大判定范围

  }



  update() {

    // 斯安威斯坦时间减缓效果(仅对敌人发射的飞行道具生效)

    const timeScale = (this.owner && !this.owner.isPlayer && sandevistanTimer > 0) ? SANDEVISTAN_TIME_SCALE : 1.0;



    this.x += this.dir * this.speed * timeScale;

    this.rotation += 0.3 * timeScale;

    this.life -= timeScale;

    if (this.life <= 0 || this.x < -50 || this.x > W + 50) {

      this.alive = false;

    }

    // 拖尾粒子

    if (Math.random() < 0.5 * timeScale) {

      spawnParticles(this.x, this.y, '#ce93d8', 1, 2);

    }

  }



  draw() {

    ctx.save();

    ctx.translate(this.x, this.y);

    ctx.rotate(this.rotation);



    // 刀身光晕

    const glow = ctx.createRadialGradient(0, 0, 0, 0, 0, 25);

    glow.addColorStop(0, 'rgba(156, 39, 176, 0.5)');

    glow.addColorStop(1, 'transparent');

    ctx.fillStyle = glow;

    ctx.beginPath();

    ctx.arc(0, 0, 25, 0, Math.PI * 2);

    ctx.fill();



    // 刀身

    ctx.fillStyle = '#9c27b0';

    ctx.fillRect(-this.width / 2, -this.height / 2, this.width, this.height);

    // 刀刃高光

    ctx.fillStyle = '#e1bee7';

    ctx.fillRect(-this.width / 2, -1, this.width, 2);

    // 刀柄

    ctx.fillStyle = '#4a148c';

    ctx.fillRect(-this.width / 2 - 8, -3, 10, 6);

    // 护手

    ctx.fillStyle = '#7b1fa2';

    ctx.fillRect(-this.width / 2 - 2, -5, 4, 10);



    ctx.restore();

  }



  // 碰撞检测用矩形

  getBounds() {

    return {

      x: this.x - this.width / 2,

      y: this.y - this.height / 2 - 5,

      w: this.width,

      h: this.height + 10

    };

  }

}



// Particles

function spawnParticles(x, y, color, count, size) {

  for (let i = 0; i < count; i++) {

    particles.push({

      x, y,

      vx: (Math.random() - 0.5) * 8,

      vy: (Math.random() - 0.5) * 8 - 2,

      life: 20 + Math.random() * 15,

      maxLife: 35,

      size: size + Math.random() * 3,

      color

    });

  }

}



function updateParticles() {

  for (let i = particles.length - 1; i >= 0; i--) {

    const p = particles[i];

    p.x += p.vx;

    p.y += p.vy;

    p.vy += 0.15;

    p.vx *= 0.96;

    p.life--;

    if (p.life <= 0) particles.splice(i, 1);

  }

}



function drawParticles() {

  particles.forEach(p => {

    const alpha = p.life / p.maxLife;

    ctx.globalAlpha = alpha;

    ctx.fillStyle = p.color;

    ctx.fillRect(p.x - p.size / 2, p.y - p.size / 2, p.size, p.size);

  });

  ctx.globalAlpha = 1;

}



// Collision

function boxOverlap(a, b) {

  return a.x < b.x + a.w && a.x + a.w > b.x && a.y < b.y + a.h && a.y + a.h > b.y;

}



function circleBoxOverlap(cx, cy, cr, bx, by, bw, bh) {

  const closestX = Math.max(bx, Math.min(cx, bx + bw));

  const closestY = Math.max(by, Math.min(cy, by + bh));

  const dx = cx - closestX;

  const dy = cy - closestY;

  return dx * dx + dy * dy < cr * cr;

}



// Player & AI

let player, ai;

let extraEnemies = [];



function initGame() {

  player = new Fighter(150, true, true, '#1565c0');

  ai = new Fighter(650, false, false, '#b71c1c');

  projectiles = [];

  particles = [];

  items = [];

  itemSpawnTimer = 0;

  gameTime = GAME_TIME;

  comboCount = 0;

  comboTimer = 0;

  aiActionTimer = 0;

  aiState = 'approach';

  sandevistanTimer = 0; // 重置时间减缓效果

  currentPlatforms = MAPS[selectedMap].platforms;



  // 初始化额外敌人

  extraEnemies = [];

  if (MAPS[selectedMap].enemies > 1) {

    const enemyColors = ['#ff6b6b', '#4ecdc4', '#ffe66d']; // 红、绿、黄

    for (let i = 1; i < MAPS[selectedMap].enemies; i++) {

      const enemy = new Fighter(400 + i * 100, false, false, enemyColors[i-1] || '#ff6b6b');

      extraEnemies.push(enemy);

    }

  }



  // 设置大招标签

  document.getElementById('playerUltLabel').textContent = ULTIMATES[playerUltimate].icon + ' ' + ULTIMATES[playerUltimate].name;

  document.getElementById('aiUltLabel').textContent = ULTIMATES[aiUltimate].icon + ' ' + ULTIMATES[aiUltimate].name;

  updateUI();

}



function updateUI() {

  document.getElementById('playerHp').style.width = (player.hp / MAX_HP * 100) + '%';

  document.getElementById('playerHpText').textContent = `${Math.ceil(player.hp)} / ${MAX_HP}`;

  document.getElementById('playerEnergy').style.width = (player.energy / MAX_ENERGY * 100) + '%';



  // 主AI血条:hp<=0时隐藏

  const aiHpContainer = document.getElementById('aiHp').parentElement;

  if (ai.hp <= 0) {

    aiHpContainer.style.display = 'none';

  } else {

    aiHpContainer.style.display = 'block';

    document.getElementById('aiHp').style.width = (ai.hp / MAX_HP * 100) + '%';

    document.getElementById('aiHpText').textContent = `${Math.ceil(ai.hp)} / ${MAX_HP}`;

    document.getElementById('aiEnergy').style.width = (ai.energy / MAX_ENERGY * 100) + '%';

  }



  document.getElementById('timer').textContent = (selectedMap === 2) ? '∞' : Math.ceil(gameTime);



  // Energy full indicators

  document.getElementById('playerEnergyFull').className = 'energy-full' + (player.energy >= MAX_ENERGY ? ' show' : '');

  if (ai.hp > 0) {

    document.getElementById('aiEnergyFull').className = 'energy-full' + (ai.energy >= MAX_ENERGY ? ' show' : '');

  }



  // 更新额外敌人血条

  const extraBarsContainer = document.getElementById('extraEnemyBars');

  if (extraEnemies.length > 0) {

    extraBarsContainer.style.display = 'block';



    // 动态创建血条元素(如果不存在)

    if (extraBarsContainer.children.length !== extraEnemies.length) {

      extraBarsContainer.innerHTML = '';

      extraEnemies.forEach((enemy, idx) => {

        if (enemy) {

          const barHtml = `

            <div style="margin-bottom:4px;">

              <div style="font-size:10px;color:#ff8a80;margin-bottom:2px;">敌人 ${idx + 2}</div>

              <div class="hp-bar-bg" style="height:12px;">

                <div class="hp-bar red" id="extraHp${idx}" style="width:100%"></div>

                <div class="hp-text" id="extraHpText${idx}" style="font-size:10px;">1000 / 1000</div>

              </div>

              <div class="energy-bar-bg" style="height:6px;margin-top:2px;">

                <div class="energy-bar red" id="extraEnergy${idx}" style="width:0%"></div>

              </div>

            </div>

          `;

          extraBarsContainer.innerHTML += barHtml;

        }

      });

    }



    // 更新血条数值

    extraEnemies.forEach((enemy, idx) => {

      if (enemy) {

        const hpBar = document.getElementById(`extraHp${idx}`);

        const hpText = document.getElementById(`extraHpText${idx}`);

        const energyBar = document.getElementById(`extraEnergy${idx}`);



        if (hpBar) hpBar.style.width = (enemy.hp / MAX_HP * 100) + '%';

        if (hpText) hpText.textContent = `${Math.ceil(enemy.hp)} / ${MAX_HP}`;

        if (energyBar) energyBar.style.width = (enemy.energy / MAX_ENERGY * 100) + '%';

      }

    });

  } else {

    extraBarsContainer.style.display = 'none';

  }

}



// ============ Player Input ============

function handlePlayerInput() {

  // === 受击硬直中:所有按键无效,但可以凹大招 ===

  if (player.hitStun > 0) {

    // 凹大招:硬直中能量足够,按L触发

    const ultReq = [30, 100, 50, 80, 20]; // 升龙30, 虚化100, 瞬移50, 超大波80, 斯安威斯坦20

    if (player.energy >= ultReq[playerUltimate] && (consumeKey('l') || consumeKey('L'))) {

      triggerUltimate(player, playerUltimate);

      player.hitStun = 0; // 清除硬直

      const ultName = ULTIMATES[playerUltimate].name;

      announce(ultName + '!');

    }

    return;

  }



  // 被打断后短暂无法操作

  if (player.interrupted) return;



  // 虚化状态:可以移动和攻击,但对手打不到你

  if (player.intangible) {

    if (keys['a'] || keys['A']) {

      player.vx = -player.speed * 0.7;

      player.facingRight = false;

    }

    if (keys['d'] || keys['D']) {

      player.vx = player.speed * 0.7;

      player.facingRight = true;

    }

    if ((keys['w'] || keys['W']) && player.onGround) {

      player.vy = player.jumpForce;

      player.onGround = false;

    }

    // 虚化中可以攻击

    if (player.attackCooldown <= 0) {

      if (consumeKey('j') || consumeKey('J')) {

        player.attacking = true;

        player.attackType = 'normal';

        player.attackTimer = 8;

        player.attackCooldown = 12;

        player.attackHit = false;

      }

      if (consumeKey('k') || consumeKey('K')) {

        player.attacking = true;

        player.attackType = 'wave';

        player.attackTimer = 25;

        player.attackCooldown = 55;

        player.attackHit = false;

        const dir = player.facingRight ? 1 : -1;

        projectiles.push(new Projectile(player.cx + dir * 35, player.y - 60, dir, player));

      }

    }

    return;

  }



  player.blocking = false;



  if (player.attacking) return;



  // Movement

  if (keys['a'] || keys['A']) {

    player.vx = -player.speed;

    player.facingRight = false;

  }

  if (keys['d'] || keys['D']) {

    player.vx = player.speed;

    player.facingRight = true;

  }

  // Jump

  if ((keys['w'] || keys['W']) && player.onGround) {

    player.vy = player.jumpForce;

    player.onGround = false;

  }

  // Block (消耗能量,能量不足无法防御)

  if (keys['s'] || keys['S']) {

    if (player.energy >= BLOCK_MIN_ENERGY) {

      player.blocking = true;

      player.vx *= 0.3;

    }

  }



  // Attacks

  if (player.attackCooldown <= 0) {

    // 检查L键是否刚按下(不消耗,先判断)

    const lJustPressed = keyJustPressed['l'] || keyJustPressed['L'];



    // 斯安威斯坦长按连续使用逻辑

    if (playerUltimate === 4 && (keys['l'] || keys['L']) && player.energy >= 20) {

      // 长按L键持续刷新斯安威斯坦效果

      sandevistanTimer = SANDEVISTAN_DURATION;

      player.energy = Math.max(0, player.energy - 0.5); // 每帧消耗0.5能量,约30帧消耗15能量

      // 持续产生粒子效果

      if (Math.random() < 0.3) {

        spawnParticles(player.cx, player.y - 50, '#00e5ff', 2, 2);

      }

    }



    if (lJustPressed) {

      if (playerUltimate === 2) {

        // 飞雷神:需要同时按方向键才触发

        const hasDirKey = keys['a'] || keys['A'] || keys['d'] || keys['D'] || keys['w'] || keys['W'];

        if (hasDirKey && player.energy >= 50) {

          // 消耗L键

          consumeKey('l'); consumeKey('L');

          const keyDist = 250; // 5个身位



          if (keys['a'] || keys['A']) {

            player.afterimageX = player.cx;

            player.afterimageY = player.y;

            player.afterimageVisible = true;

            player.afterimageTimer = 40;

            player.invincible = 5;

            player.x = Math.max(10, player.x - keyDist);

            spawnParticles(player.cx, player.y - 40, '#ffd54f', 10, 3);

            player.energy = Math.max(0, player.energy - 50);

            player.attackCooldown = 15;

            announce('飞雷神!');

          } else if (keys['d'] || keys['D']) {

            player.afterimageX = player.cx;

            player.afterimageY = player.y;

            player.afterimageVisible = true;

            player.afterimageTimer = 40;

            player.invincible = 5;

            player.x = Math.min(W - player.width - 10, player.x + keyDist);

            spawnParticles(player.cx, player.y - 40, '#ffd54f', 10, 3);

            player.energy = Math.max(0, player.energy - 50);

            player.attackCooldown = 15;

            announce('飞雷神!');

          } else if (keys['w'] || keys['W']) {

            player.afterimageX = player.cx;

            player.afterimageY = player.y;

            player.afterimageVisible = true;

            player.afterimageTimer = 40;

            player.invincible = 5;

            // 向上瞬移5个身位

            player.y = Math.max(50, player.y - keyDist);

            player.onGround = false;

            spawnParticles(player.cx, player.y - 40, '#ffd54f', 10, 3);

            player.energy = Math.max(0, player.energy - 50);

            player.attackCooldown = 15;

            announce('飞雷神!');

          }

        }

        // 没有方向键:不消耗L键,不触发,不return(允许其他操作)

      } else if (playerUltimate === 4) {

        // 斯安威斯坦:首次按下触发,后续长按由上面的逻辑处理

        consumeKey('l'); consumeKey('L');

        if (player.energy >= 20) {

          triggerUltimate(player, playerUltimate);

        }

      } else {

        // 其他大招:按L直接触发,无需方向键

        consumeKey('l'); consumeKey('L');

        const ultReq = [30, 100, 50, 80, 20]; // 升龙30, 虚化100, 瞬移50, 超大波80, 斯安威斯坦20

        if (player.energy >= ultReq[playerUltimate]) {

          triggerUltimate(player, playerUltimate);

        }

      }

      return;

    }

    if (consumeKey('j') || consumeKey('J')) {

      // 检查附近是否有忍刀可以拾取

      let pickedUpSword = false;

      if (!player.hasSword) {

        for (let i = items.length - 1; i >= 0; i--) {

          const item = items[i];

          if (item.type === ITEM_TYPES.NINJA_SWORD && item.collidesWith(player)) {

            player.hasSword = true;

            item.alive = false;

            spawnParticles(item.x, item.y, '#ce93d8', 15, 3);

            announce('拾取忍刀!');

            pickedUpSword = true;

            break;

          }

        }

      }

      if (!pickedUpSword) {

        // 普攻:攻速快、硬直低、伤害高(忍刀时更慢更强)

        player.attacking = true;

        player.attackType = 'normal';

        player.attackTimer = player.hasSword ? 20 : 8;

        player.attackCooldown = player.hasSword ? 28 : 12;

        player.attackHit = false;

      }

    }

    if (consumeKey('k') || consumeKey('K')) {

      // 持有忍刀时:丢弃忍刀并发射

      if (player.hasSword) {

        player.hasSword = false;

        const dir = player.facingRight ? 1 : -1;

        // 发射忍刀作为飞行道具

        projectiles.push(new SwordProjectile(player.cx + dir * 30, player.y - 60, dir, player));

        player.attackCooldown = 30;

        announce('投掷忍刀!');

      } else {

        // 发波:攻速慢、硬直高、伤害低

        player.attacking = true;

        player.attackType = 'wave';

        player.attackTimer = 25;

        player.attackCooldown = 55;

        player.attackHit = false;

        player.energy = Math.max(0, player.energy - 10);

        const dir = player.facingRight ? 1 : -1;

        projectiles.push(new Projectile(player.cx + dir * 35, player.y - 60, dir, player));

      }

    }

  }

}



// 大招触发(根据类型分发)

function triggerUltimate(fighter, ultType) {

  fighter.ultType = ultType;



  if (ultType === 0) {

    // 升龙拳 - 消耗30能量

    fighter.energy = Math.max(0, fighter.energy - 30);

    fighter.ultimateActive = true;

    fighter.ultimateTimer = 35;

    fighter.uppercutPhase = 0;

    fighter.attacking = true;

    fighter.attackType = 'uppercut';

    fighter.attackCooldown = 55;

    fighter.attackHit = false;

    fighter.invincible = 8;



    const color = fighter.isPlayer ? '#4fc3f7' : '#ef5350';

    spawnParticles(fighter.cx, fighter.y - 40, color, 30, 4);

    shakeTimer = 15;

    shakeIntensity = 8;



    if (fighter.isPlayer) {

      announce('升龙拳!');

    } else {

      announce('AI 升龙拳!');

    }

  } else if (ultType === 1) {

    // 虚化 - 消耗100能量(满能量)

    fighter.energy = Math.max(0, fighter.energy - 100);

    fighter.intangible = true;

    fighter.intangibleTimer = 300; // 5秒

    fighter.attackCooldown = 20;



    const color = fighter.isPlayer ? '#4fc3f7' : '#ef5350';

    spawnParticles(fighter.cx, fighter.y - 50, color, 20, 3);



    if (fighter.isPlayer) {

      announce('虚化!');

    } else {

      announce('AI 虚化!');

    }

  } else if (ultType === 2) {

    // 瞬移 - 消耗50能量

    fighter.energy = Math.max(0, fighter.energy - 50);

    fighter.attackCooldown = 15;



    // 记录残影位置

    fighter.afterimageX = fighter.cx;

    fighter.afterimageY = fighter.y;

    fighter.afterimageVisible = true;

    fighter.afterimageTimer = 40;

    fighter.invincible = 5;



    const keyDist = 250; // 5个身位



    if (fighter.isPlayer) {

      // 玩家瞬移已经在handlePlayerInput中处理了,这里只是消耗能量

      // 不应该到达这里

    } else {

      // AI瞬移:根据情况选择方向

      const dirToPlayer = player.cx > fighter.cx ? 1 : -1;



      if (fighter.hp < 300 && Math.random() < 0.5) {

        // 低血量时往后跳

        fighter.x = Math.max(10, Math.min(W - fighter.width - 10, fighter.x - dirToPlayer * keyDist));

      } else {

        // 通常向玩家方向瞬移

        fighter.x = Math.max(10, Math.min(W - fighter.width - 10, fighter.x + dirToPlayer * keyDist));

      }



      spawnParticles(fighter.cx, fighter.y - 40, '#ffd54f', 10, 3);

      announce('AI 飞雷神!');

    }

  } else if (ultType === 3) {

    // 超大波 - 消耗80能量

    fighter.energy = Math.max(0, fighter.energy - 80);

    fighter.attacking = true;

    fighter.attackType = 'megawave';

    fighter.attackTimer = 30;

    fighter.attackCooldown = 60;

    fighter.attackHit = false;

    fighter.invincible = 5;



    const dir = fighter.facingRight ? 1 : -1;

    projectiles.push(new MegaProjectile(fighter.cx + dir * 40, fighter.y - 55, dir, fighter));



    const color = fighter.isPlayer ? '#4fc3f7' : '#ef5350';

    spawnParticles(fighter.cx, fighter.y - 50, color, 25, 5);

    shakeTimer = 10;

    shakeIntensity = 6;



    if (fighter.isPlayer) {

      announce('超大波!');

    } else {

      announce('AI 超大波!');

    }

  } else if (ultType === 4) {

    // 斯安威斯坦 - 消耗20能量

    fighter.energy = Math.max(0, fighter.energy - 20);

    fighter.attackCooldown = 10;

    fighter.invincible = 5;



    // 激活时间减缓效果

    sandevistanTimer = SANDEVISTAN_DURATION;



    const color = fighter.isPlayer ? '#00e5ff' : '#ff4081';

    spawnParticles(fighter.cx, fighter.y - 50, color, 40, 6);

    shakeTimer = 8;

    shakeIntensity = 4;



    if (fighter.isPlayer) {

      announce('斯安威斯坦!');

    } else {

      announce('AI 斯安威斯坦!');

    }

  }

}



// ============ AI Logic ============

let aiActionTimer = 0;

let aiState = 'approach';

let aiStrafeDir = 1; // 左右移动方向

let aiStrafeTimer = 0;



function updateAI() {

  if (ai.hitStun > 0) {

    // AI 也可以凹大招(根据难度调整概率)

    if (ai.energy >= MAX_ENERGY && Math.random() < 0.02 + currentAIParams.ultimateFrequency * 0.1) {

      triggerUltimate(ai, aiUltimate);

      ai.hitStun = 0;

    }

    return;

  }



  if (ai.interrupted) return;



  // 虚化状态:AI只需要等待,不做其他操作

  if (ai.intangible) {

    ai.vx *= 0.5;

    return;

  }



  ai.blocking = false;

  if (ai.attacking) return;



  const dist = Math.abs(ai.cx - player.cx);

  const dirToPlayer = player.cx > ai.cx ? 1 : -1;

  const hpRatio = ai.hp / ai.maxHp;

  const playerHpRatio = player.hp / player.maxHp;



  // 左右移动计时

  aiStrafeTimer--;

  if (aiStrafeTimer <= 0) {

    aiStrafeDir = Math.random() < 0.5 ? 1 : -1;

    aiStrafeTimer = 30 + Math.random() * 60;

  }



  // 检查附近是否有道具

  let nearestItem = null;

  let nearestItemDist = 999;

  for (const item of items) {

    if (!item.alive) continue;

    const itemDist = Math.abs(ai.cx - item.x);

    if (itemDist < 200 && itemDist < nearestItemDist) {

      nearestItem = item;

      nearestItemDist = itemDist;

    }

  }



  // 检查是否有敌方飞行道具飞来

  let incomingProjectile = null;

  for (const proj of projectiles) {

    if (!proj.alive || proj.owner === ai) continue;

    const projDir = proj.dir || (proj.vx > 0 ? 1 : -1);

    const projDist = proj.x - ai.cx;

    // 道具朝AI飞来且在一定距离内

    if ((projDir < 0 && projDist > 0 && projDist < 250) || 

        (projDir > 0 && projDist < 0 && projDist > -250)) {

      incomingProjectile = proj;

      break;

    }

  }



  aiActionTimer--;

  if (aiActionTimer <= 0) {

    const rand = Math.random();



    // === 优先级1: 躲避飞行道具 ===

    if (incomingProjectile && ai.onGround && Math.random() < 0.6 + currentAIParams.blockProbability * 0.3) {

      aiState = 'dodge';

      aiActionTimer = 20;

    }

    // === 优先级2: 拾取道具 ===

    else if (nearestItem && dist > 150 && Math.random() < 0.7) {

      aiState = 'pickup';

      aiActionTimer = 30;

    }

    // === 优先级3: 低血量策略 ===

    else if (hpRatio < 0.3 && Math.random() < 0.5) {

      if (ai.energy >= 100 && aiUltimate === 1) {

        // 低血量满能量:虚化

        aiState = 'ultimate';

        aiActionTimer = 10;

      } else if (dist < 150) {

        // 低血量近距离:后退或防御

        aiState = Math.random() < 0.5 ? 'retreat' : 'block';

        aiActionTimer = 25;

      } else {

        // 低血量远距离:发波消耗

        aiState = 'wave';

        aiActionTimer = 20;

      }

    }

    // === 优先级4: 大招决策 ===

    else {

      const ultEnergyReq = [30, 100, 50, 80];

      if (ai.energy >= ultEnergyReq[aiUltimate]) {

        if (aiUltimate === 0 && dist < 150 && rand < currentAIParams.ultimateFrequency) {

          aiState = 'ultimate';

          aiActionTimer = currentAIParams.reactionTime + 10;

        } else if (aiUltimate === 1 && player.attacking && dist < 150 && rand < currentAIParams.ultimateFrequency + 0.1) {

          aiState = 'ultimate';

          aiActionTimer = currentAIParams.reactionTime + 5;

        } else if (aiUltimate === 2 && (dist > 200 || dist < 80) && rand < currentAIParams.ultimateFrequency - 0.05) {

          aiState = 'ultimate';

          aiActionTimer = currentAIParams.reactionTime;

        } else if (aiUltimate === 3 && dist > 150 && dist < 500 && rand < currentAIParams.ultimateFrequency + 0.05) {

          aiState = 'ultimate';

          aiActionTimer = currentAIParams.reactionTime + 15;

        }

      }

      // === 优先级5: 防御 ===

      else if (player.attacking && dist < 130 && rand < currentAIParams.blockProbability && ai.energy > 20) {

        aiState = 'block';

        aiActionTimer = currentAIParams.reactionTime;

      }

      // === 优先级6: 风筝战术(中距离发波) ===

      else if (dist > 200 && dist < 400 && ai.energy > 15 && Math.random() < 0.4 + currentAIParams.attackFrequency * 0.3) {

        aiState = 'wave';

        aiActionTimer = currentAIParams.reactionTime + 10;

      }

      // === 优先级7: 远距离接近 ===

      else if (dist > 350) {

        aiState = 'approach';

        aiActionTimer = currentAIParams.reactionTime + Math.random() * 15;

      }

      // === 优先级8: 近距离攻击 ===

      else if (dist < 100 && rand < currentAIParams.attackFrequency + 0.2) {

        aiState = 'attack';

        aiActionTimer = currentAIParams.reactionTime;

      }

      // === 优先级9: 中距离游走 ===

      else if (dist > 150 && dist < 300 && Math.random() < 0.4) {

        aiState = 'strafe';

        aiActionTimer = 40 + Math.random() * 40;

      }

      // === 优先级10: 近距离后退 ===

      else if (dist < 80 && Math.random() < 0.4) {

        aiState = 'retreat';

        aiActionTimer = 20 + Math.random() * 20;

      }

      // === 默认: 接近 ===

      else {

        aiState = 'approach';

        aiActionTimer = currentAIParams.reactionTime;

      }

    }

  }



switch (aiState) {

    case 'approach':

      ai.vx = dirToPlayer * currentAIParams.speed;

      // 随机跳跃增加变化

      if (Math.random() < 0.03 && ai.onGround) {

        ai.vy = ai.jumpForce;

        ai.onGround = false;

      }

      break;

    case 'retreat':

      ai.vx = -dirToPlayer * currentAIParams.speed * 0.9;

      // 后退时也可能跳跃

      if (Math.random() < 0.04 && ai.onGround) {

        ai.vy = ai.jumpForce * 0.8;

        ai.onGround = false;

      }

      break;

    case 'strafe':

      // 左右移动保持距离

      ai.vx = aiStrafeDir * currentAIParams.speed * 0.7;

      // 保持与玩家的距离

      if (dist < 180) {

        ai.vx += -dirToPlayer * currentAIParams.speed * 0.3;

      } else if (dist > 280) {

        ai.vx += dirToPlayer * currentAIParams.speed * 0.3;

      }

      // 随机跳跃

      if (Math.random() < 0.025 && ai.onGround) {

        ai.vy = ai.jumpForce * 0.7;

        ai.onGround = false;

      }

      break;

    case 'dodge':

      // 躲避飞行道具:跳跃或后退

      if (ai.onGround) {

        ai.vy = ai.jumpForce;

        ai.onGround = false;

        ai.vx = -dirToPlayer * currentAIParams.speed;

      }

      break;

    case 'pickup':

      // 去拾取道具

      if (nearestItem) {

        const dirToItem = nearestItem.x > ai.cx ? 1 : -1;

        ai.vx = dirToItem * currentAIParams.speed;

        if (Math.abs(ai.cx - nearestItem.x) < 40 && nearestItemDist < 60) {

          // 到达道具位置,尝试拾取

          if (ai.attackCooldown <= 0) {

            ai.attacking = true;

            ai.attackType = 'normal';

            ai.attackTimer = 8;

            ai.attackCooldown = 14;

            ai.attackHit = false;

          }

          aiState = 'approach';

        }

      } else {

        aiState = 'approach';

      }

      break;

    case 'attack':

      if (dist < 100 && ai.attackCooldown <= 0) {

        // AI普攻也改为快速高伤

        ai.attacking = true;

        ai.attackType = 'normal';

        ai.attackTimer = 8;

        ai.attackCooldown = 14;

        ai.attackHit = false;

        aiState = 'approach';

      } else {

        ai.vx = dirToPlayer * currentAIParams.speed;

      }

      break;

    case 'block':

      if (ai.energy >= BLOCK_MIN_ENERGY) {

        ai.blocking = true;

        ai.vx *= 0.3;

      } else {

        aiState = 'retreat';

      }

      break;

    case 'wave':

      if (ai.attackCooldown <= 0 && ai.energy > 15) {

        // AI发波也改为慢速低伤高硬直

        ai.attacking = true;

        ai.attackType = 'wave';

        ai.attackTimer = 25;

        ai.attackCooldown = 55;

        ai.attackHit = false;

        ai.energy = Math.max(0, ai.energy - 10);

        const d = ai.facingRight ? 1 : -1;

        projectiles.push(new Projectile(ai.cx + d * 35, ai.y - 60, d, ai));

        aiState = 'approach';

      }

      break;

    case 'ultimate':

      const ultReq = [30, 100, 50, 80, 20]; // 升龙30, 虚化100, 瞬移50, 超大波80, 斯安威斯坦20

      if (ai.energy >= ultReq[aiUltimate] && ai.attackCooldown <= 0) {

        // 根据AI大招类型决定触发条件

        const canTrigger = (aiUltimate === 0 && dist < 180) || // 升龙拳需要近身

                           (aiUltimate === 1) || // 虚化随时可放

                           (aiUltimate === 2) || // 瞬移随时可放

                           (aiUltimate === 3 && dist > 100 && dist < 550) || // 超大波中远距离

                           (aiUltimate === 4 && dist < 300); // 斯安威斯坦中近距离

        if (canTrigger) {

          triggerUltimate(ai, aiUltimate);

          aiState = 'approach';

        } else {

          ai.vx = dirToPlayer * currentAIParams.speed;

        }

      } else if (dist >= 180) {

        ai.vx = dirToPlayer * currentAIParams.speed;

      }

      break;

  }

}



// ============ Extra Enemy AI ============

function updateExtraEnemyAI(enemy) {

  if (enemy.hitStun > 0) {

    // 额外敌人也可以凹大招

    if (enemy.energy >= MAX_ENERGY && Math.random() < 0.03) {

      triggerUltimate(enemy, Math.floor(Math.random() * 4));

      enemy.hitStun = 0;

    }

    return;

  }



  if (enemy.interrupted) return;



  // 虚化状态

  if (enemy.intangible) {

    enemy.vx *= 0.5;

    return;

  }



  enemy.blocking = false;

  if (enemy.attacking) return;



  const dist = Math.abs(enemy.cx - player.cx);

  const dirToPlayer = player.cx > enemy.cx ? 1 : -1;



  // === 角色分配:根据距离和队友位置决定前压/后援 ===

  // 计算所有额外敌人与玩家的距离

  let myRank = 0; // 0=最近(前锋), 1=次近, 2=最远(后援)

  const myDist = dist;

  extraEnemies.forEach(other => {

    if (other !== enemy && other.hp > 0) {

      const otherDist = Math.abs(other.cx - player.cx);

      if (otherDist < myDist) myRank++;

    }

  });



  // 根据角色分配行为倾向

  const isAggressor = myRank === 0; // 最近的敌人负责前压

  const isSupport = myRank >= 1; // 较远的敌人负责后援



  // 检查攻击是否会伤害队友

  function willHitAlly(attackRange) {

    const attackDir = enemy.facingRight ? 1 : -1;

    const attackStartX = enemy.cx;

    const attackEndX = enemy.cx + attackDir * attackRange;



    for (const ally of extraEnemies) {

      if (ally === enemy || ally.hp <= 0) continue;



      // 检查队友是否在攻击路径上

      const allyInPath = (attackDir > 0 && ally.cx > attackStartX && ally.cx < attackEndX) ||

                         (attackDir < 0 && ally.cx < attackStartX && ally.cx > attackEndX);



      // 检查队友是否在攻击范围内(垂直方向)

      const verticalDist = Math.abs(ally.y - enemy.y);



      if (allyInPath && verticalDist < 80) {

        return true;

      }

    }

    return false;

  }



  // 检查发波是否会伤害队友

  function willWaveHitAlly() {

    const waveDir = enemy.facingRight ? 1 : -1;



    for (const ally of extraEnemies) {

      if (ally === enemy || ally.hp <= 0) continue;



      // 检查队友是否在波的飞行路径上

      const allyInPath = (waveDir > 0 && ally.cx > enemy.cx) ||

                         (waveDir < 0 && ally.cx < enemy.cx);



      // 检查队友是否在波的飞行高度

      const verticalDist = Math.abs((ally.y - 60) - (enemy.y - 60));

      const horizontalDist = Math.abs(ally.cx - enemy.cx);



      if (allyInPath && verticalDist < 50 && horizontalDist < 400) {

        return true;

      }

    }

    return false;

  }



  // 简单的AI状态机

  if (!enemy.aiState) enemy.aiState = 'approach';

  if (!enemy.aiTimer) enemy.aiTimer = 0;



  enemy.aiTimer--;

  if (enemy.aiTimer <= 0) {

    const rand = Math.random();



    // === 前锋策略:主动前压近战 ===

    if (isAggressor) {

      if (dist < 120) {

        // 近距离:攻击为主,但会考虑友军伤害

        const hitsAlly = willHitAlly(120);



        // 如果会伤害队友,有50%概率犹豫

        if (hitsAlly && Math.random() < 0.5) {

          enemy.aiState = 'strafe';

          enemy.aiTimer = 15;

        } else if (rand < 0.6) {

          enemy.aiState = 'attack';

          enemy.aiTimer = 15 + Math.random() * 10;

        } else if (rand < 0.8) {

          enemy.aiState = 'retreat';

          enemy.aiTimer = 15;

        } else {

          enemy.aiState = 'strafe';

          enemy.aiTimer = 20;

        }

      } else if (dist < 250) {

        // 中距离:接近玩家

        enemy.aiState = 'approach';

        enemy.aiTimer = 20 + Math.random() * 15;

      } else {

        // 远距离:快速接近

        enemy.aiState = 'approach';

        enemy.aiTimer = 25;

      }

    }

    // === 后援策略:保持距离发波 ===

    else if (isSupport) {

      if (dist < 150) {

        // 太近了:后退或防御

        if (player.attacking && rand < 0.5) {

          enemy.aiState = 'block';

          enemy.aiTimer = 20;

        } else {

          enemy.aiState = 'retreat';

          enemy.aiTimer = 20;

        }

      } else if (dist > 200 && dist < 450 && enemy.energy > 15) {

        // 理想距离:发波输出,但会考虑友军伤害

        const hitsAlly = willWaveHitAlly();



        // 如果会伤害队友,有40%概率犹豫

        if (hitsAlly && Math.random() < 0.4) {

          enemy.aiState = 'strafe';

          enemy.aiTimer = 25;

        } else if (rand < 0.5) {

          enemy.aiState = 'wave';

          enemy.aiTimer = 25 + Math.random() * 15;

        } else if (rand < 0.7) {

          enemy.aiState = 'strafe';

          enemy.aiTimer = 30;

        } else {

          enemy.aiState = 'approach';

          enemy.aiTimer = 15;

        }

      } else if (dist >= 450) {

        // 太远:稍微接近

        enemy.aiState = 'approach';

        enemy.aiTimer = 20;

      } else {

        // 中近距离:游走找机会

        enemy.aiState = 'strafe';

        enemy.aiTimer = 25;

      }

    }

  }



// 执行状态

  switch (enemy.aiState) {

    case 'approach':

      enemy.vx = dirToPlayer * currentAIParams.speed * 0.9;

      if (Math.random() < 0.02 && enemy.onGround) {

        enemy.vy = enemy.jumpForce;

        enemy.onGround = false;

      }

      break;

    case 'retreat':

      enemy.vx = -dirToPlayer * currentAIParams.speed * 0.8;

      if (Math.random() < 0.03 && enemy.onGround) {

        enemy.vy = enemy.jumpForce * 0.7;

        enemy.onGround = false;

      }

      break;

    case 'strafe':

      // 左右游走,保持距离

      if (!enemy.strafeDir) enemy.strafeDir = Math.random() < 0.5 ? 1 : -1;

      if (Math.random() < 0.02) enemy.strafeDir *= -1; // 偶尔换方向

      enemy.vx = enemy.strafeDir * currentAIParams.speed * 0.6;

      // 根据距离微调

      if (dist < 180) {

        enemy.vx += -dirToPlayer * currentAIParams.speed * 0.3;

      } else if (dist > 350) {

        enemy.vx += dirToPlayer * currentAIParams.speed * 0.3;

      }

      if (Math.random() < 0.02 && enemy.onGround) {

        enemy.vy = enemy.jumpForce * 0.6;

        enemy.onGround = false;

      }

      break;

    case 'attack':

      if (dist < 120 && enemy.attackCooldown <= 0) {

        enemy.attacking = true;

        enemy.attackType = 'normal';

        enemy.attackTimer = 8;

        enemy.attackCooldown = 14;

        enemy.attackHit = false;

        enemy.aiState = 'strafe';

        enemy.aiTimer = 15;

      } else {

        enemy.vx = dirToPlayer * currentAIParams.speed;

      }

      break;

    case 'wave':

      if (enemy.attackCooldown <= 0 && enemy.energy > 15) {

        enemy.attacking = true;

        enemy.attackType = 'wave';

        enemy.attackTimer = 25;

        enemy.attackCooldown = 50;

        enemy.attackHit = false;

        enemy.energy = Math.max(0, enemy.energy - 10);

        const d = enemy.facingRight ? 1 : -1;

        projectiles.push(new Projectile(enemy.cx + d * 35, enemy.y - 60, d, enemy));

        enemy.aiState = 'strafe';

        enemy.aiTimer = 20;

      } else {

        enemy.vx = dirToPlayer * currentAIParams.speed * 0.5;

      }

      break;

    case 'block':

      if (enemy.energy >= BLOCK_MIN_ENERGY) {

        enemy.blocking = true;

        enemy.vx *= 0.3;

      } else {

        enemy.aiState = 'retreat';

        enemy.aiTimer = 15;

      }

      break;

  }

}



// ============ Collision Resolution ============

function resolveCollision(a, b) {

  // 获取两者的边界框

  const aBox = { x: a.x, y: a.y - a.height, w: a.width, h: a.height };

  const bBox = { x: b.x, y: b.y - b.height, w: b.width, h: b.height };



  // 检测是否重叠

  if (!boxOverlap(aBox, bBox)) return;



  // 计算重叠区域

  const overlapX = Math.min(aBox.x + aBox.w, bBox.x + bBox.w) - Math.max(aBox.x, bBox.x);



  // 根据位置关系推开

  if (a.cx < b.cx) {

    // a在左边,b在右边

    a.x -= overlapX / 2;

    b.x += overlapX / 2;

  } else {

    // a在右边,b在左边

    a.x += overlapX / 2;

    b.x -= overlapX / 2;

  }



  // 确保不超出边界

  a.x = Math.max(0, Math.min(W - a.width, a.x));

  b.x = Math.max(0, Math.min(W - b.width, b.x));

}



// ============ Combat Resolution ============

function resolveCombat() {

  // Player attack hits AI

  const pBox = player.getAttackBox();

  if (pBox) {

    const aiBox = { x: ai.x, y: ai.y - ai.height, w: ai.width, h: ai.height };

    if (boxOverlap(pBox, aiBox)) {

      const hit = ai.takeDamage(pBox.damage, pBox.knockback, player);

      player.attackHit = true;

      // 攻击命中涨能量(只有真正命中才涨,虚化不涨)

      if (hit) {

        const energyGain = pBox.type === 'uppercut' ? 0 : 15;

        // 斯安威斯坦期间玩家无法恢复能量

        if (!(player.isPlayer && sandevistanTimer > 0)) {

          player.energy = Math.min(MAX_ENERGY, player.energy + energyGain);

        }

        comboCount++;

        comboTimer = 60;

      }

      // 普攻命中:对手硬直低(快速连招)

      if (pBox.type === 'normal' && hit) {

        ai.hitStun = 10;

      }

      // 忍刀攻击命中:硬直高

      if (pBox.type === 'sword' && hit) {

        ai.hitStun = 25;

        spawnParticles(ai.cx, ai.y - 50, '#ce93d8', 15, 4);

      }

      // 升龙拳命中额外效果

      if (pBox.type === 'uppercut') {

        ai.vy = -10; // 击飞

        spawnParticles(ai.cx, ai.y - 60, '#ffd54f', 20, 5);

        shakeTimer = 15;

        shakeIntensity = 10;

      }

    }

  }



  // AI attack hits player

  const aBox = ai.getAttackBox();

  if (aBox) {

    const pBox2 = { x: player.x, y: player.y - player.height, w: player.width, h: player.height };

    if (boxOverlap(aBox, pBox2)) {

      const hit = player.takeDamage(aBox.damage, aBox.knockback, ai);

      ai.attackHit = true;

      // 攻击命中涨能量(只有真正命中才涨,虚化不涨)

      if (hit) {

        const energyGain = aBox.type === 'uppercut' ? 0 : 15;

        ai.energy = Math.min(MAX_ENERGY, ai.energy + energyGain);

        comboCount = 0;

      }

      // AI普攻命中:玩家硬直低

      if (aBox.type === 'normal' && hit) {

        player.hitStun = 10;

      }

      // AI忍刀攻击命中:玩家硬直高

      if (aBox.type === 'sword' && hit) {

        player.hitStun = 25;

        spawnParticles(player.cx, player.y - 50, '#ce93d8', 15, 4);

      }

      if (aBox.type === 'uppercut') {

        player.vy = -10;

        spawnParticles(player.cx, player.y - 60, '#ffd54f', 20, 5);

        shakeTimer = 15;

        shakeIntensity = 10;

      }

    }

  }



// Projectiles

  for (let i = projectiles.length - 1; i >= 0; i--) {

    const proj = projectiles[i];

    if (!proj.alive) {

      projectiles.splice(i, 1);

      continue;

    }



    if (proj.owner === player) {

      // 玩家飞行道具命中主AI

      const aiBox = { x: ai.x, y: ai.y - ai.height, w: ai.width, h: ai.height };

      const hitProj = !ai.intangible && !player.intangible && circleBoxOverlap(proj.x, proj.y, proj.radius, aiBox.x, aiBox.y, aiBox.w, aiBox.h);

      if (hitProj) {

        const hit = ai.takeDamage(proj.damage, proj.dir * 8, player);

        // 只有真正命中才涨能量,斯安威斯坦期间玩家无法恢复能量

        if (hit && !(player.isPlayer && sandevistanTimer > 0)) {

          player.energy = Math.min(MAX_ENERGY, player.energy + 15);

        }

        if (hit) {

          if (proj instanceof SwordProjectile) {

            ai.hitStun = 25;

            spawnParticles(proj.x, proj.y, '#ce93d8', 15, 4);

          } else {

            ai.hitStun = (proj instanceof MegaProjectile) ? 35 : 28;

            spawnParticles(proj.x, proj.y, proj.color, 15, 3);

          }

          comboCount++;

          comboTimer = 60;

        }

        proj.alive = false;

        continue;

      }



      // 玩家飞行道具命中额外敌人

      let hitExtra = false;

      extraEnemies.forEach(enemy => {

        if (!enemy || enemy.hp <= 0 || hitExtra) return;

        const enemyBox = { x: enemy.x, y: enemy.y - enemy.height, w: enemy.width, h: enemy.height };

        const hitEnemy = !enemy.intangible && circleBoxOverlap(proj.x, proj.y, proj.radius, enemyBox.x, enemyBox.y, enemyBox.w, enemyBox.h);

        if (hitEnemy) {

          const hit = enemy.takeDamage(proj.damage, proj.dir * 8, player);

          // 只有真正命中才涨能量,斯安威斯坦期间玩家无法恢复能量

          if (hit && !(player.isPlayer && sandevistanTimer > 0)) {

            player.energy = Math.min(MAX_ENERGY, player.energy + 15);

          }

          if (hit) {

            if (proj instanceof SwordProjectile) {

              enemy.hitStun = 25;

              spawnParticles(proj.x, proj.y, '#ce93d8', 15, 4);

            } else {

              enemy.hitStun = (proj instanceof MegaProjectile) ? 35 : 28;

              spawnParticles(proj.x, proj.y, proj.color, 15, 3);

            }

            comboCount++;

            comboTimer = 60;

          }

          proj.alive = false;

          hitExtra = true;

        }

      });

      if (hitExtra) continue;

    } else {

      // 敌人飞行道具命中玩家

      const pBox = { x: player.x, y: player.y - player.height, w: player.width, h: player.height };

      const hitProj = !player.intangible && circleBoxOverlap(proj.x, proj.y, proj.radius, pBox.x, pBox.y, pBox.w, pBox.h);

      if (hitProj) {

        const attacker = proj.owner;

        const hit = player.takeDamage(proj.damage, proj.dir * 8, attacker);

        // 只有真正命中才涨能量

        if (hit && attacker) {

          attacker.energy = Math.min(MAX_ENERGY, attacker.energy + 15);

        }

        if (hit) {

          if (proj instanceof SwordProjectile) {

            player.hitStun = 25;

            spawnParticles(proj.x, proj.y, '#ce93d8', 15, 4);

          } else {

            player.hitStun = (proj instanceof MegaProjectile) ? 35 : 28;

            spawnParticles(proj.x, proj.y, proj.color, 15, 3);

          }

          comboCount = 0;

        }

        proj.alive = false;

      }

    }

  }



  // 额外敌人与玩家的碰撞检测

  extraEnemies.forEach(enemy => {

    if (!enemy || enemy.hp <= 0) return;



    // 玩家攻击命中额外敌人

    const pBox = player.getAttackBox();

    if (pBox && !player.attackHit) {

      const enemyBox = { x: enemy.x, y: enemy.y - enemy.height, w: enemy.width, h: enemy.height };

      if (boxOverlap(pBox, enemyBox)) {

        const hit = enemy.takeDamage(pBox.damage, pBox.knockback, player);

        player.attackHit = true;

        // 只有真正命中才涨能量,斯安威斯坦期间玩家无法恢复能量

        if (hit) {

          const energyGain = pBox.type === 'uppercut' ? 0 : 15;

          if (!(player.isPlayer && sandevistanTimer > 0)) {

            player.energy = Math.min(MAX_ENERGY, player.energy + energyGain);

          }

          comboCount++;

          comboTimer = 60;

        }

        if (pBox.type === 'normal' && hit) {

          enemy.hitStun = 10;

        }

        if (pBox.type === 'sword' && hit) {

          enemy.hitStun = 25;

          spawnParticles(enemy.cx, enemy.y - 50, '#ce93d8', 15, 4);

        }

        if (pBox.type === 'uppercut') {

          enemy.vy = -10;

          spawnParticles(enemy.cx, enemy.y - 60, '#ffd54f', 20, 5);

          shakeTimer = 15;

          shakeIntensity = 10;

        }

      }

    }



    // 额外敌人攻击命中玩家

    const eBox = enemy.getAttackBox();

    if (eBox) {

      const pBox2 = { x: player.x, y: player.y - player.height, w: player.width, h: player.height };

      if (boxOverlap(eBox, pBox2)) {

        const hit = player.takeDamage(eBox.damage, eBox.knockback, enemy);

        enemy.attackHit = true;

        // 只有真正命中才涨能量

        if (hit) {

          const energyGain = eBox.type === 'uppercut' ? 0 : 15;

          enemy.energy = Math.min(MAX_ENERGY, enemy.energy + energyGain);

          comboCount = 0;

        }

        if (eBox.type === 'normal' && hit) {

          player.hitStun = 10;

        }

        if (eBox.type === 'sword' && hit) {

          player.hitStun = 25;

          spawnParticles(player.cx, player.y - 50, '#ce93d8', 15, 4);

        }

        if (eBox.type === 'uppercut') {

          player.vy = -10;

          spawnParticles(player.cx, player.y - 60, '#ffd54f', 20, 5);

          shakeTimer = 15;

          shakeIntensity = 10;

        }

      }

    }

  });



  // 主AI攻击命中额外敌人(友军伤害)

  const aiAttackBox = ai.getAttackBox();

  if (aiAttackBox) {

    extraEnemies.forEach(enemy => {

      if (!enemy || enemy.hp <= 0) return;



      const enemyBox = { x: enemy.x, y: enemy.y - enemy.height, w: enemy.width, h: enemy.height };

      if (boxOverlap(aiAttackBox, enemyBox)) {

        const hit = enemy.takeDamage(aiAttackBox.damage, aiAttackBox.knockback, ai);

        ai.attackHit = true;

        // 只有真正命中才涨能量

        if (hit) {

          const energyGain = aiAttackBox.type === 'uppercut' ? 0 : 10;

          ai.energy = Math.min(MAX_ENERGY, ai.energy + energyGain);

        }



        if (aiAttackBox.type === 'normal' && hit) {

          enemy.hitStun = 10;

        }

        if (aiAttackBox.type === 'sword' && hit) {

          enemy.hitStun = 25;

          spawnParticles(enemy.cx, enemy.y - 50, '#ce93d8', 15, 4);

        }

        if (aiAttackBox.type === 'uppercut') {

          enemy.vy = -10;

          spawnParticles(enemy.cx, enemy.y - 60, '#ffd54f', 20, 5);

          shakeTimer = 15;

          shakeIntensity = 10;

        }

      }

    });

  }



  // 友军伤害检测:额外敌人之间的攻击

  for (let i = 0; i < extraEnemies.length; i++) {

    const attacker = extraEnemies[i];

    if (!attacker || attacker.hp <= 0) continue;



    const aBox = attacker.getAttackBox();

    if (!aBox) continue;

// 检查是否命中其他额外敌人

    for (let j = 0; j < extraEnemies.length; j++) {

      if (i === j) continue;

      const target = extraEnemies[j];

      if (!target || target.hp <= 0) continue;



      const tBox = { x: target.x, y: target.y - target.height, w: target.width, h: target.height };

      if (boxOverlap(aBox, tBox)) {

        const hit = target.takeDamage(aBox.damage, aBox.knockback, attacker);

        attacker.attackHit = true;

        // 只有真正命中才涨能量

        if (hit) {

          const energyGain = aBox.type === 'uppercut' ? 0 : 10;

          attacker.energy = Math.min(MAX_ENERGY, attacker.energy + energyGain);

        }



        if (aBox.type === 'normal' && hit) {

          target.hitStun = 10;

        }

        if (aBox.type === 'sword' && hit) {

          target.hitStun = 25;

          spawnParticles(target.cx, target.y - 50, '#ce93d8', 15, 4);

        }

        if (aBox.type === 'uppercut') {

          target.vy = -10;

          spawnParticles(target.cx, target.y - 60, '#ffd54f', 20, 5);

          shakeTimer = 15;

          shakeIntensity = 10;

        }

      }

    }



// 额外敌人攻击命中主AI(友军伤害)

    const aiBox = { x: ai.x, y: ai.y - ai.height, w: ai.width, h: ai.height };

    if (boxOverlap(aBox, aiBox)) {

      const hit = ai.takeDamage(aBox.damage, aBox.knockback, attacker);

      attacker.attackHit = true;

      // 只有真正命中才涨能量

      if (hit) {

        const energyGain = aBox.type === 'uppercut' ? 0 : 10;

        attacker.energy = Math.min(MAX_ENERGY, attacker.energy + energyGain);

      }



      if (aBox.type === 'normal' && hit) {

        ai.hitStun = 10;

      }

      if (aBox.type === 'sword' && hit) {

        ai.hitStun = 25;

        spawnParticles(ai.cx, ai.y - 50, '#ce93d8', 15, 4);

      }

      if (aBox.type === 'uppercut') {

        ai.vy = -10;

        spawnParticles(ai.cx, ai.y - 60, '#ffd54f', 20, 5);

        shakeTimer = 15;

        shakeIntensity = 10;

      }

    }

  }



  // 友军飞行道具伤害检测

  for (let i = projectiles.length - 1; i >= 0; i--) {

    const proj = projectiles[i];

    if (!proj.alive) continue;



    // 主AI的飞行道具命中额外敌人(友军伤害)

    if (proj.owner === ai) {

      extraEnemies.forEach(enemy => {

        if (!enemy || enemy.hp <= 0 || !proj.alive) return;



        const enemyBox = { x: enemy.x, y: enemy.y - enemy.height, w: enemy.width, h: enemy.height };

        const hitEnemy = !enemy.intangible && circleBoxOverlap(proj.x, proj.y, proj.radius, enemyBox.x, enemyBox.y, enemyBox.w, enemyBox.h);



        if (hitEnemy) {

          const hit = enemy.takeDamage(proj.damage, proj.dir * 8, ai);

          // 只有真正命中才涨能量

          if (hit) {

            ai.energy = Math.min(MAX_ENERGY, ai.energy + 10);

          }



          if (hit) {

            if (proj instanceof SwordProjectile) {

              enemy.hitStun = 25;

              spawnParticles(proj.x, proj.y, '#ce93d8', 15, 4);

            } else {

              enemy.hitStun = (proj instanceof MegaProjectile) ? 35 : 28;

              spawnParticles(proj.x, proj.y, proj.color, 15, 3);

            }

          }

          proj.alive = false;

        }

      });

      continue;

    }



    // 额外敌人的飞行道具命中主AI或其他额外敌人(友军伤害)

    const ownerIdx = extraEnemies.indexOf(proj.owner);

    if (ownerIdx !== -1) {

      // 检查是否命中主AI

      const aiBox = { x: ai.x, y: ai.y - ai.height, w: ai.width, h: ai.height };

      const hitAi = !ai.intangible && circleBoxOverlap(proj.x, proj.y, proj.radius, aiBox.x, aiBox.y, aiBox.w, aiBox.h);



      if (hitAi) {

        const hit = ai.takeDamage(proj.damage, proj.dir * 8, proj.owner);

        // 只有真正命中才涨能量

        if (hit && proj.owner) {

          proj.owner.energy = Math.min(MAX_ENERGY, proj.owner.energy + 10);

        }



        if (hit) {

          if (proj instanceof SwordProjectile) {

            ai.hitStun = 25;

            spawnParticles(proj.x, proj.y, '#ce93d8', 15, 4);

          } else {

            ai.hitStun = (proj instanceof MegaProjectile) ? 35 : 28;

            spawnParticles(proj.x, proj.y, proj.color, 15, 3);

          }

        }

        proj.alive = false;

        continue;

      }



      // 检查是否命中其他额外敌人

      for (let j = 0; j < extraEnemies.length; j++) {

        if (j === ownerIdx) continue;

        const target = extraEnemies[j];

        if (!target || target.hp <= 0) continue;



        const tBox = { x: target.x, y: target.y - target.height, w: target.width, h: target.height };

        const hitTarget = !target.intangible && circleBoxOverlap(proj.x, proj.y, proj.radius, tBox.x, tBox.y, tBox.w, tBox.h);



        if (hitTarget) {

          const hit = target.takeDamage(proj.damage, proj.dir * 8, proj.owner);

          // 只有真正命中才涨能量

          if (hit && proj.owner) {

            proj.owner.energy = Math.min(MAX_ENERGY, proj.owner.energy + 10);

          }



          if (hit) {

            if (proj instanceof SwordProjectile) {

              target.hitStun = 25;

              spawnParticles(proj.x, proj.y, '#ce93d8', 15, 4);

            } else {

              target.hitStun = (proj instanceof MegaProjectile) ? 35 : 28;

              spawnParticles(proj.x, proj.y, proj.color, 15, 3);

            }

          }

          proj.alive = false;

          break;

        }

      }

    }

  }

}



// 防御持续消耗能量

function updateBlockDrain() {

  if (player.blocking) {

    player.energy = Math.max(0, player.energy - BLOCK_ENERGY_COST);

    if (player.energy < BLOCK_MIN_ENERGY) {

      player.blocking = false;

    }

  }

  if (ai.blocking) {

    ai.energy = Math.max(0, ai.energy - BLOCK_ENERGY_COST);

    if (ai.energy < BLOCK_MIN_ENERGY) {

      ai.blocking = false;

    }

  }

}



function announce(text) {

  const el = document.getElementById('roundAnnounce');

  el.textContent = text;

  el.style.opacity = '1';

  el.style.transform = 'translate(-50%, -50%) scale(1.2)';

  el.style.transition = 'none';

  setTimeout(() => {

    el.style.transition = 'opacity 0.5s, transform 0.5s';

    el.style.opacity = '0';

    el.style.transform = 'translate(-50%, -50%) scale(0.8)';

  }, 800);

}



// Draw background

function drawBackground() {

  const skyGrad = ctx.createLinearGradient(0, 0, 0, H);

  skyGrad.addColorStop(0, '#0d1b2a');

  skyGrad.addColorStop(0.6, '#1b2838');

  skyGrad.addColorStop(1, '#2a1a1a');

  ctx.fillStyle = skyGrad;

  ctx.fillRect(0, 0, W, H);



  ctx.fillStyle = '#ffffff';

  for (let i = 0; i < 30; i++) {

    const sx = (i * 137.5 + 50) % W;

    const sy = (i * 73.1 + 20) % (H * 0.5);

    const ss = 0.5 + (i % 3) * 0.5;

    ctx.globalAlpha = 0.3 + Math.sin(Date.now() * 0.001 + i) * 0.2;

    ctx.fillRect(sx, sy, ss, ss);

  }

  ctx.globalAlpha = 1;



  ctx.fillStyle = '#e0e0e0';

  ctx.beginPath();

  ctx.arc(750, 80, 35, 0, Math.PI * 2);

  ctx.fill();

  ctx.fillStyle = '#0d1b2a';

  ctx.beginPath();

  ctx.arc(740, 75, 30, 0, Math.PI * 2);

  ctx.fill();



  ctx.fillStyle = '#1a1a2e';

  ctx.beginPath();

  ctx.moveTo(0, GROUND + 10);

  ctx.lineTo(100, GROUND - 80);

  ctx.lineTo(200, GROUND - 30);

  ctx.lineTo(350, GROUND - 120);

  ctx.lineTo(500, GROUND - 50);

  ctx.lineTo(600, GROUND - 100);

  ctx.lineTo(750, GROUND - 60);

  ctx.lineTo(900, GROUND - 90);

  ctx.lineTo(W, GROUND + 10);

  ctx.fill();



  const groundGrad = ctx.createLinearGradient(0, GROUND, 0, H);

  groundGrad.addColorStop(0, '#3e2723');

  groundGrad.addColorStop(0.3, '#2c1e17');

  groundGrad.addColorStop(1, '#1a0e0a');

  ctx.fillStyle = groundGrad;

  ctx.fillRect(0, GROUND, W, H - GROUND);



  ctx.strokeStyle = '#5d4037';

  ctx.lineWidth = 2;

  ctx.beginPath();

  ctx.moveTo(0, GROUND + 1);

  ctx.lineTo(W, GROUND + 1);

  ctx.stroke();



  ctx.strokeStyle = '#4e342e';

  ctx.lineWidth = 1;

  for (let i = 0; i < W; i += 40) {

    ctx.beginPath();

    ctx.moveTo(i, GROUND + 5);

    ctx.lineTo(i + 20, GROUND + 5);

    ctx.stroke();

  }



  // Draw platforms

  currentPlatforms.forEach(plat => {

    // Platform body

    const pg = ctx.createLinearGradient(0, plat.y, 0, plat.y + plat.h + 20);

    pg.addColorStop(0, '#5d4037');

    pg.addColorStop(0.3, '#4e342e');

    pg.addColorStop(1, '#3e2723');

    ctx.fillStyle = pg;

    ctx.fillRect(plat.x, plat.y, plat.w, plat.h);

    // Top edge highlight

    ctx.fillStyle = '#8d6e63';

    ctx.fillRect(plat.x, plat.y, plat.w, 3);

    // Edge marks

    ctx.fillStyle = '#6d4c41';

    ctx.fillRect(plat.x, plat.y, 3, plat.h);

    ctx.fillRect(plat.x + plat.w - 3, plat.y, 3, plat.h);

    // Support pillars

    ctx.fillStyle = '#3e2723';

    const pillarW = 8;

    const pillarTop = plat.y + plat.h;

    const pillarH = GROUND - pillarTop;

    if (pillarH > 10) {

      ctx.fillRect(plat.x + 15, pillarTop, pillarW, pillarH);

      ctx.fillRect(plat.x + plat.w - 15 - pillarW, pillarTop, pillarW, pillarH);

    }

    // Surface texture

    ctx.strokeStyle = '#4e342e';

    ctx.lineWidth = 1;

    for (let i = plat.x + 20; i < plat.x + plat.w - 10; i += 25) {

      ctx.beginPath();

      ctx.moveTo(i, plat.y + 4);

      ctx.lineTo(i + 12, plat.y + 4);

      ctx.stroke();

    }

  });

}



// Game loop

function getNearestEnemy(target) {

  let nearest = ai;

  let minDist = Math.abs(ai.cx - target.cx);



  extraEnemies.forEach(enemy => {

    if (enemy && enemy.hp > 0) {

      const dist = Math.abs(enemy.cx - target.cx);

      if (dist < minDist) {

        minDist = dist;

        nearest = enemy;

      }

    }

  });



  return nearest;

}


function gameLoop() {

  if (!gameRunning) return;



  // 斯安威斯坦时间减缓计时

  if (sandevistanTimer > 0) {

    sandevistanTimer--;

  }



  // Clear just-pressed keys at end of frame

  handlePlayerInput();



  // AI更新(时间减缓在Fighter.update()内部处理)

  if (ai.hp > 0) {

    updateAI();

    ai.update(player);

  }



  // 更新额外敌人AI(时间减缓在Fighter.update()内部处理)

  extraEnemies.forEach(enemy => {

    if (enemy && enemy.hp > 0) {

      updateExtraEnemyAI(enemy);

      enemy.update(player);

    }

  });



  updateBlockDrain();

  player.update(getNearestEnemy(player)); // 玩家不受时间减缓影响



  // 找到最近的敌人(用于玩家朝向)




// 所有角色之间的碰撞检测

  resolveCollision(player, ai);

  extraEnemies.forEach(enemy => {

    if (enemy && enemy.hp > 0) {

      resolveCollision(player, enemy);

      resolveCollision(ai, enemy);

    }

  });

  // 额外敌人之间的碰撞

  for (let i = 0; i < extraEnemies.length; i++) {

    for (let j = i + 1; j < extraEnemies.length; j++) {

      if (extraEnemies[i] && extraEnemies[j] && extraEnemies[i].hp > 0 && extraEnemies[j].hp > 0) {

        resolveCollision(extraEnemies[i], extraEnemies[j]);

      }

    }

  }



  resolveCombat();



  // 道具系统(受时间减缓影响)

  itemSpawnTimer++;

  if (itemSpawnTimer >= ITEM_SPAWN_INTERVAL) {

    itemSpawnTimer = 0;

    spawnItems();

  }

  // 道具更新应用时间减缓

  const timeScale = sandevistanTimer > 0 ? SANDEVISTAN_TIME_SCALE : 1.0;

  if (timeScale < 1.0) {

    items.forEach(item => {

      const savedBobPhase = item.bobPhase;

      const savedLifetime = item.lifetime;

      item.bobPhase += (0.05 * timeScale - 0.05); // 减缓浮动速度

      item.lifetime += (1 - timeScale); // 减缓消失速度

      item.update();

      item.bobPhase = savedBobPhase + 0.05 * timeScale;

      item.lifetime = savedLifetime - timeScale;

    });

  } else {

    items.forEach(item => item.update());

  }

  items = items.filter(item => item.alive);



  // 能量球自动拾取

  for (let i = items.length - 1; i >= 0; i--) {

    const item = items[i];

    if (item.type === ITEM_TYPES.ENERGY_BALL) {

      if (item.collidesWith(player)) {

        player.energy = Math.min(MAX_ENERGY, player.energy + 30);

        item.alive = false;

        spawnParticles(item.x, item.y, '#ffd54f', 12, 3);

        announce('+30 能量!');

      } else if (item.collidesWith(ai)) {

        ai.energy = Math.min(MAX_ENERGY, ai.energy + 30);

        item.alive = false;

        spawnParticles(item.x, item.y, '#ffd54f', 12, 3);

      }

    }

  }



  // 飞行道具更新(受时间减缓影响)

  if (timeScale < 1.0) {

    projectiles.forEach(p => {

      // 保存原始速度

      const savedSpeed = p.speed;

      // 应用时间减缓

      p.speed *= timeScale;

      p.update();

      // 恢复原始速度

      p.speed = savedSpeed;

    });

  } else {

    projectiles.forEach(p => p.update());

  }

  projectiles = projectiles.filter(p => p.alive);



  updateParticles();



  // Combo display

  if (comboTimer > 0) {

    comboTimer--;

    const comboEl = document.getElementById('comboDisplay');

    if (comboCount >= 2) {

      comboEl.textContent = `${comboCount} COMBO!`;

      comboEl.style.opacity = '1';

    } else {

      comboEl.style.opacity = '0';

    }

  } else {

    comboCount = 0;

    document.getElementById('comboDisplay').style.opacity = '0';

  }



  // Screen shake

  ctx.save();

  if (shakeTimer > 0) {

    shakeTimer--;

    const sx = (Math.random() - 0.5) * shakeIntensity;

    const sy = (Math.random() - 0.5) * shakeIntensity;

    ctx.translate(sx, sy);

  }



  drawBackground();

  items.forEach(item => item.draw());

  projectiles.forEach(p => p.draw());

  player.draw();

  if (ai.hp > 0) {

    ai.draw();

  }

  // 绘制额外敌人

  extraEnemies.forEach(enemy => {

    if (enemy && enemy.hp > 0) {

      enemy.draw();

    }

  });

  drawParticles();



  // 斯安威斯坦时间减缓屏幕特效

  if (sandevistanTimer > 0) {

    // 青蓝色半透明覆盖层

    const alpha = 0.15 + Math.sin(sandevistanTimer * 0.3) * 0.05;

    ctx.fillStyle = `rgba(0, 229, 255, ${alpha})`;

    ctx.fillRect(0, 0, W, H);



    // 边缘光晕效果

    const gradient = ctx.createRadialGradient(W/2, H/2, W*0.3, W/2, H/2, W*0.7);

    gradient.addColorStop(0, 'transparent');

    gradient.addColorStop(1, `rgba(0, 229, 255, ${alpha * 0.5})`);

    ctx.fillStyle = gradient;

    ctx.fillRect(0, 0, W, H);



    // 时间减缓文字提示

    ctx.save();

    ctx.fillStyle = '#00e5ff';

    ctx.font = 'bold 24px Microsoft YaHei';

    ctx.textAlign = 'center';

    ctx.shadowColor = '#00e5ff';

    ctx.shadowBlur = 20;

    ctx.fillText(`⏱️ 时间减缓 ${Math.ceil(sandevistanTimer / 60 * 10) / 10}s`, W/2, 60);

    ctx.restore();

  }



  ctx.restore();



  updateUI();



  // Clear just-pressed keys

  for (const k in keyJustPressed) {

    keyJustPressed[k] = false;

  }



  // 检查游戏结束条件

  const allEnemiesDead = ai.hp <= 0 && extraEnemies.every(e => !e || e.hp <= 0);

  // 三英战吕布模式时间无限,不检查gameTime

  const timeUp = (selectedMap !== 2) && gameTime <= 0;

  if (player.hp <= 0 || allEnemiesDead || timeUp) {

    endGame();

    return;

  }



  requestAnimationFrame(gameLoop);

}



function startGame() {

  document.getElementById('startScreen').style.display = 'none';

  document.getElementById('ultSelectScreen').style.display = 'none';

  document.getElementById('endScreen').style.display = 'none';

  document.getElementById('backToMenuBtn').style.display = 'block';

  initGame();

  gameRunning = true;



  announce('FIGHT!');



  if (timerInterval) clearInterval(timerInterval);



// 三英战吕布模式时间无限,不启动倒计时

  if (selectedMap !== 2) {

    timerInterval = setInterval(() => {

      if (!gameRunning) return;

      gameTime -= 0.1;

      if (gameTime <= 0) gameTime = 0;

    }, 100);

  }



  gameLoop();

}



function endGame() {

  gameRunning = false;

  if (timerInterval) clearInterval(timerInterval);

  document.getElementById('backToMenuBtn').style.display = 'none';



  let title, result;



  // 计算所有敌人的总血量

  let totalEnemyHp = ai.hp;

  extraEnemies.forEach(e => {

    if (e) totalEnemyHp += e.hp;

  });



  if (player.hp <= 0) {

    title = 'K.O.!';

    result = 'AI 对手获胜!';

  } else if (ai.hp <= 0 && extraEnemies.every(e => !e || e.hp <= 0)) {

    title = 'K.O.!';

    result = '玩家获胜!';

  } else {

    title = 'TIME UP!';

    if (player.hp > totalEnemyHp) {

      result = `玩家获胜!(${Math.ceil(player.hp)} vs ${Math.ceil(totalEnemyHp)})`;

    } else if (totalEnemyHp > player.hp) {

      result = `AI 对手获胜!(${Math.ceil(totalEnemyHp)} vs ${Math.ceil(player.hp)})`;

    } else {

      result = '平局!';

    }

  }



  announce(title);



  setTimeout(() => {

    document.getElementById('endTitle').textContent = title;

    document.getElementById('endResult').textContent = result;

    document.getElementById('endScreen').style.display = 'flex';

  }, 1500);

}



document.getElementById('startBtn').addEventListener('click', () => {

  document.getElementById('startScreen').style.display = 'none';

  document.getElementById('ultSelectScreen').style.display = 'flex';

});

document.getElementById('restartBtn').addEventListener('click', () => {

  document.getElementById('endScreen').style.display = 'none';

  document.getElementById('ultSelectScreen').style.display = 'flex';

});



// 返回菜单按钮

document.getElementById('backToMenuBtn').addEventListener('click', () => {

  gameRunning = false;

  if (timerInterval) clearInterval(timerInterval);

  document.getElementById('backToMenuBtn').style.display = 'none';

  document.getElementById('endScreen').style.display = 'none';

  document.getElementById('startScreen').style.display = 'flex';

  // 重置地图选择

  selectedMap = 0;

  document.querySelectorAll('.map-card').forEach((c, i) => {

    c.classList.toggle('selected', i === 0);

  });

});



// Initialize

currentPlatforms = MAPS[selectedMap].platforms;

drawMapPreviews();

drawBackground();

</script>

</body>

</html>
相关推荐
狮子座的男孩15 分钟前
javascript 基础 es6:3、参数默认值,reset参数,spread扩展运算符,扩展运算符应用
前端·javascript·经验分享·es6·参数默认值·reset参数·spread扩展运算符
CodeSheep26 分钟前
华为园区,为啥碰到的高颜值妹子总是外包牌,华为工牌的基本都是资深大姐...
前端·后端·程序员
map_3d_vis30 分钟前
JSAPI 4.0 的命名空间:BMap 和 BMapGL 为什么都能用
前端·javascript·typescript·百度地图
恋猫de小郭34 分钟前
Flutter HC 旋转 ANR,而且还和之前的 HCPP 问题类似
android·前端·flutter
code2cat1 小时前
Vue项目实战之任务保存:编辑失败后,怎样保留输入再重试
前端·javascript·vue.js
1-1=01 小时前
Vue TodoList
前端·javascript·vue.js
feixing_fx12 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
qyr678913 小时前
全球汽车和航空航天用磁铁材料市场竞争格局变化趋势
大数据·人工智能·物联网·自动化·汽车和航空航天用磁铁材料
前端架构师-老李14 小时前
html教程:header、nav、main、footer 四个标签各管哪一块?
前端·html