<template>
  <div class="game-container">
    <div id="gameCanvas" class="game-canvas"></div>

    <!-- 游戏启动界面 -->
    <div v-if="currentScene === 'start'" class="gamestart">
      <img v-if="currentScene === 'start'" src="/static/images/football/game_start.jpg" class="start_bg" />
      <div class="btn rule" @click="showRules = true">查看规则</div>
      <div class="btn start" @click="startGame">开始游戏</div>

      <!-- 规则弹窗 -->
      <div v-if="showRules" class="ruleshadow">
        <div class="rulebox">
          <span class="x_rulebox" @click="showRules = false"></span>
          <h3>操作方法：</h3>
          <p>手指拖动控制人物带球奔跑的方向和速度。</p>
          <h3>道具说明：</h3>
          <div class="daoju">
            <div class="daoju_item">
              <span class="daoju_1"></span>
              <p>每收集一个，生命值+1；触碰障碍物，生命可再复活。</p>
            </div>
            <div class="daoju_item">
              <span class="daoju_2"></span>
              <p>每收集一个，能力值+1；扫除面前一切障碍，加速前进。</p>
            </div>
            <div class="daoju_item">
              <span class="daoju_3"></span>
              <p>触碰锥桶，生命值-1；成功绕过一次分数+1。</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 规则说明 -->
    <div v-if="currentScene === 'rule'" class="zhiyin">
      <div class="btn start" @click="continueGame">继续游戏</div>
    </div>

    <!-- 倒计时 -->
    <div v-if="currentScene === 'countdown'" class="daoju">
      <div class="daojishibox">
        <div class="daojishinum">{{ countdownNum }}</div>
      </div>
    </div>

    <!-- 游戏结束 -->
    <div v-if="currentScene === 'gameover'" class="gameend">
      <div v-if="currentScene === 'gameover'" class="game_fenshu">
        <span>{{ score }}</span>分
      </div>

      <div class="chenghao">恭喜你获得称号<p>{{ getTitle(score) }}</p>
      </div>
      <div class="game_ogain" @click="restartGame">再次游戏</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import Phaser from 'phaser';

// 游戏状态管理
const currentScene = ref('start');
const showRules = ref(false);
const countdownNum = ref(3);
const score = ref(0);
const game = ref(null);
const gameConfig = ref(null);
let scoreListener = null; // 存储事件监听器引用

// 游戏常量
const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
const GAME_WIDTH = width;
const GAME_HEIGHT = height;

// 游戏资源
const gameAssets = {
  images: [
    { key: 'gameStart', url: 'static/images/football/game_start.jpg' },
    { key: 'grass', url: 'static/images/football/Caopi.png' },
    { key: 'playerShoot', url: 'static/images/football/QiuyuanShooting.png' },
    { key: 'pile', url: 'static/images/football/Pile.png' },
    { key: 'jersey', url: 'static/images/football/Jersey.png' },
    { key: 'broom', url: 'static/images/football/Broom.png' },
    { key: 'goalkeeper', url: 'static/images/football/Goalkeeper.png' },
    { key: 'goal', url: 'static/images/football/Goal.png' },
    { key: 'ball', url: 'static/images/football/Ball.png' },
    { key: 'line', url: 'static/images/football/Line.png' },
    { key: 'line2', url: 'static/images/football/Line2.png' },
    { key: 'goalBackground', url: 'static/images/football/GoalBackGround.png' },
    { key: 'gameOver', url: 'static/images/football/gameover.png' }
  ],
  spritesheets: [
    {
      key: 'playerAnim',
      url: 'static/images/football/Qiuyuan.png',
      frameWidth: 92.5,
      frameHeight: 92.5
    },
    {
      key: 'ballAnim',
      url: 'static/images/football/Ball.png',
      frameWidth: 31,
      frameHeight: 31
    },
    {
      key: 'goalkeeperAnim',
      url: 'static/images/football/Goalkeeper.png',
      frameWidth: 55,
      frameHeight: 56
    },
    {
      key: 'playerCollision',
      url: 'static/images/football/QiuyuanCollision.png',
      frameWidth: 92.5,
      frameHeight: 92.5
    },
    {
      key: 'playerSuper',
      url: 'static/images/football/QiuyuanSuper.png',
      frameWidth: 92.5,
      frameHeight: 92.5
    },
  ]
};

// 初始化Phaser游戏
const initGame = () => {
  // 游戏配置
  gameConfig.value = {
    type: Phaser.AUTO,
    width: GAME_WIDTH,
    height: GAME_HEIGHT,
    parent: 'gameCanvas',
    physics: {
      default: 'arcade',
      arcade: {
        gravity: { y: 0 },
        debug: false
      }
    },
    scene: [
      PreloaderScene,
      GameScene
    ]
  };

  game.value = new Phaser.Game(gameConfig.value);

  // 关键：使用局部变量存储事件监听器，便于后续清理
  scoreListener = (newScore) => {
    score.value = newScore;
  };

  // 添加事件监听
  if (game.value && game.value.events) {
    game.value.events.on('scoreChanged', scoreListener);
  }

  game.value.events.on('gameOver', () => {
    currentScene.value = 'gameover';
  });
};

// 预加载场景
class PreloaderScene extends Phaser.Scene {
  constructor() {
    super('PreloaderScene');
  }

  preload() {
    // 加载图片资源
    gameAssets.images.forEach(asset => {
      this.load.image(asset.key, asset.url);
    });

    // 加载精灵表
    gameAssets.spritesheets.forEach(asset => {
      this.load.spritesheet(asset.key, asset.url, {
        frameWidth: asset.frameWidth,
        frameHeight: asset.frameHeight
      });
    });

    // 显示加载进度
    const progressBar = this.add.graphics();
    const progressBox = this.add.graphics();
    progressBox.fillStyle(0x222222, 0.8);
    progressBox.fillRect(GAME_WIDTH / 2 - 160, GAME_HEIGHT / 2 - 25, 320, 50);

    const loadingText = this.make.text({
      x: GAME_WIDTH / 2,
      y: GAME_HEIGHT / 2 - 50,
      text: 'Loading...',
      style: {
        font: '20px monospace',
        fill: '#ffffff'
      }
    }).setOrigin(0.5, 0.5);

    const percentText = this.make.text({
      x: GAME_WIDTH / 2,
      y: GAME_HEIGHT / 2,
      text: '0%',
      style: {
        font: '18px monospace',
        fill: '#ffffff'
      }
    }).setOrigin(0.5, 0.5);

    this.load.on('progress', (value) => {
      percentText.setText(`${Math.round(value * 100)}%`);
      progressBar.clear();
      progressBar.fillStyle(0xffffff, 1);
      progressBar.fillRect(GAME_WIDTH / 2 - 150, GAME_HEIGHT / 2 - 15, 300 * value, 30);
    });

    this.load.on('complete', () => {
      progressBar.destroy();
      progressBox.destroy();
      loadingText.destroy();
      percentText.destroy();
    });
  }

  create() {
    // 初始化动画
    this.initAnimations();
    // 切换到游戏场景
    this.scene.start('GameScene');
  }

  initAnimations() {
    // 球员动画
    this.anims.create({
      key: 'playerLeft',
      frames: [
        { key: 'playerAnim', frame: 0 },
        { key: 'playerAnim', frame: 2 },
        { key: 'playerAnim', frame: 4 },
        { key: 'playerAnim', frame: 6 }
      ],
      frameRate: 10,
      repeat: -1
    });

    this.anims.create({
      key: 'playerRight',
      frames: [
        { key: 'playerAnim', frame: 1 },
        { key: 'playerAnim', frame: 3 },
        { key: 'playerAnim', frame: 5 },
        { key: 'playerAnim', frame: 7 }
      ],
      frameRate: 10,
      repeat: -1
    });

    // 足球动画
    this.anims.create({
      key: 'ballAnim',
      frames: this.anims.generateFrameNumbers('ballAnim', { start: 0, end: 1 }),
      frameRate: 5,
      repeat: -1
    });

    // 守门员动画
    this.anims.create({
      key: 'goalkeeperAnim',
      frames: this.anims.generateFrameNumbers('goalkeeperAnim', { start: 0, end: 1 }),
      frameRate: 3,
      repeat: -1
    });
  }
}

// 游戏主场景
class GameScene extends Phaser.Scene {
  constructor() {
    super('GameScene');
    this.player = null;
    this.score = 0;
    this.lives = 3;
    this.maxLives = 5;
    this.speed = 6;
    this.acceleration = 1.9;
    this.level = 1;
    this.obstacles = [];
    this.powerUps = [];
    this.isSuper = false;
    this.gameActive = false;
    this.timer = null;
    this.isShooting = false; // 新增：初始化射门状态
    this.obstacleTimer = null; // 新增：初始化障碍物计时器
    this.obstacleEvent = null;
    this.jerseyEvent = null;
    this.broomEvent = null;
  }

  create() {
    // 创建背景
    this.createBackground();

    // 创建玩家
    this.createPlayer();

    // 创建计分板
    this.createHUD();

    // 输入控制
    this.initControls();

    // 游戏事件
    this.events.on('resume', () => {
      this.gameActive = true;
    });

    // 等待开始游戏信号
    this.gameActive = false;
  }

  createBackground() {
    // 创建滚动背景
    this.background = this.add.tileSprite(0, 0, GAME_WIDTH, GAME_HEIGHT, 'grass');
    this.background.setOrigin(0, 0);
  }

  createPlayer() {
    // 创建玩家
    this.player = this.physics.add.sprite(GAME_WIDTH / 2, GAME_HEIGHT - 100, 'playerAnim');
    this.player.setCollideWorldBounds(true);
    this.player.setScale(0.8);
    this.player.lives = this.lives;
    this.player.setDepth(9);
  }

  createHUD() {
    // 分数显示
    this.scoreText = this.add.text(10, 10, `分数: ${this.score}`, {
      fontSize: '16px',
      fill: '#ffffff',
      backgroundColor: 'rgba(0,0,0,0.5)',
      padding: { x: 5, y: 2 }
    });
    this.scoreText.setDepth(10);

    // 生命值显示
    this.livesText = this.add.text(GAME_WIDTH - 80, 10, `生命: ${this.lives}`, {
      fontSize: '16px',
      fill: '#ffffff',
      backgroundColor: 'rgba(0,0,0,0.5)',
      padding: { x: 5, y: 2 }
    });
    this.livesText.setDepth(10);
  }

  initControls() {
    // 键盘控制
    this.cursors = this.input.keyboard.createCursorKeys();

    // 触摸控制（添加垂直移动）
    this.input.on('pointermove', (pointer) => {
      if (this.gameActive && pointer.isDown && !this.isShooting) {
        // 水平移动
        this.player.x = Phaser.Math.Clamp(pointer.x, this.player.width / 2, GAME_WIDTH - this.player.width / 2);
        // 垂直移动（限制范围）
        this.player.y = Phaser.Math.Clamp(
          pointer.y,
          0, // 最小Y值
          GAME_HEIGHT// 最大Y值
        );
      }
    });
  }

  startGame() {
    // 重置核心状态
    this.gameActive = true;
    this.score = 0;
    this.lives = 3; // 重置生命值
    this.maxLives = 5;
    this.speed = 6; // 重置基础速度
    this.acceleration = 1.9; // 重置加速度
    this.level = 1; // 重置等级
    this.isSuper = false;
    this.isShooting = false;
    this.obstacles = [];
    this.powerUps = [];

    // 更新UI显示
    this.livesText.setText(`生命: ${this.lives}`);
    this.updateScore();

    // 清理旧定时器（双重保险）
    if (this.timer) this.timer.remove();
    if (this.obstacleEvent) this.obstacleEvent.remove();
    if (this.jerseyEvent) this.jerseyEvent.remove();
    if (this.broomEvent) this.broomEvent.remove();

    // 重新开始生成障碍物和计时
    this.startSpawning();
    this.timer = this.time.addEvent({
      delay: 200,
      callback: () => {
        this.score++;
        this.updateScore();
        if (this.score % 200 === 0) {
          this.levelUp();
        }
      },
      loop: true
    });
  }

  startSpawning() {
    // 先移除旧事件（强化清除逻辑）
    if (this.obstacleEvent) {
      this.obstacleEvent.remove();
      this.obstacleEvent = null; // 置空引用
    }
    if (this.jerseyEvent) {
      this.jerseyEvent.remove();
      this.jerseyEvent = null; // 置空引用
    }
    if (this.broomEvent) {
      this.broomEvent.remove();
      this.broomEvent = null; // 置空引用
    }

    // 重新创建事件（使用安全的场景上下文）
    this.obstacleEvent = this.time.addEvent({
      delay: 1000 / this.level,
      callback: () => { if (this.gameActive) this.spawnObstacle(); },
      loop: true
    });
    this.jerseyEvent = this.time.addEvent({
      delay: 5000,
      callback: () => { if (this.gameActive) this.spawnPowerUp('jersey'); },
      loop: true
    });
    this.broomEvent = this.time.addEvent({
      delay: 8000,
      callback: () => { if (this.gameActive) this.spawnPowerUp('broom'); },
      loop: true
    });

    // 新增：立即生成第一个障碍物，确保倒计时结束后立即出现
    this.spawnObstacle();
  }

  spawnObstacle() {
    const x = Phaser.Math.Between(30, GAME_WIDTH - 30);
    const obstacle = this.physics.add.sprite(x, -50, 'pile');
    obstacle.setScale(0.7);
    // 降低速度（从原来的this.speed * this.acceleration * 10调整为）
    obstacle.setVelocityY(this.speed * this.acceleration * 5); // 速度减半
    obstacle.setDepth(8);
    obstacle.type = 'pile';

    // 碰撞检测
    this.physics.add.overlap(this.player, obstacle, this.handleObstacleCollision, null, this);

    this.obstacles.push(obstacle);

    // 替换原计时器代码
    const event = this.time.addEvent({ // 用变量接收事件引用
      delay: 100,
      loop: true,
      callback: () => {
        if (obstacle.active) {
          if (obstacle.y > GAME_HEIGHT + obstacle.height) {
            obstacle.destroy();
            this.obstacles = this.obstacles.filter(o => o !== obstacle);
            this.score++;
            this.updateScore();
            this.time.removeEvent(event); // 移除当前事件
          }
        } else {
          this.time.removeEvent(event);
        }
      }
    });
  }

  spawnPowerUp(type) {
    const x = Phaser.Math.Between(30, GAME_WIDTH - 30);
    let powerUp;

    if (type === 'jersey') {
      powerUp = this.physics.add.sprite(x, -50, 'jersey');
      powerUp.type = 'jersey';
    } else if (type === 'broom') {
      powerUp = this.physics.add.sprite(x, -50, 'broom');
      powerUp.type = 'broom';
    }

    powerUp.setScale(0.7);
    // 降低道具速度（从原来的this.speed * this.acceleration * 8调整为）
    powerUp.setVelocityY(this.speed * this.acceleration * 4); // 速度降低
    powerUp.setDepth(8);

    // 碰撞检测
    this.physics.add.overlap(this.player, powerUp, this.handlePowerUpCollision, null, this);

    this.powerUps.push(powerUp);

    // 延长道具生命周期
    this.time.addEvent({
      delay: 15000,
      callback: () => {
        if (powerUp.active) {
          powerUp.destroy();
          this.powerUps = this.powerUps.filter(p => p !== powerUp);
        }
      }
    });
  }

  handleObstacleCollision(player, obstacle) {
    if (this.isSuper) {
      // 超级状态下直接摧毁障碍物
      obstacle.destroy();
      this.obstacles = this.obstacles.filter(o => o !== obstacle);
      return;
    }

    // 扣除生命值
    player.lives--;
    this.lives = player.lives;
    this.livesText.setText(`生命: ${this.lives}`);

    // 显示受伤效果
    player.setTexture('playerCollision');
    this.time.addEvent({
      delay: 618,
      callback: () => {
        player.setTexture('playerAnim');
      }
    });

    // 销毁障碍物
    obstacle.destroy();
    this.obstacles = this.obstacles.filter(o => o !== obstacle);

    // 检查游戏是否结束
    if (player.lives <= 0) {
      this.gameOver();
    }
  }

  handlePowerUpCollision(player, powerUp) {
    if (powerUp.type === 'jersey') {
      // 增加生命值
      if (player.lives < this.maxLives) {
        player.lives++;
        this.lives = player.lives;
        this.livesText.setText(`生命: ${this.lives}`);
      }
    } else if (powerUp.type === 'broom') {
      // 激活超级状态
      this.activateSuperMode();
    }

    // 销毁道具
    powerUp.destroy();
    this.powerUps = this.powerUps.filter(p => p !== powerUp);
  }

  activateSuperMode() {
    this.isSuper = true;
    this.player.setTexture('playerSuper');
    this.acceleration = 10;

    // 3秒后结束超级状态
    this.time.addEvent({
      delay: 3000,
      callback: () => {
        this.isSuper = false;
        this.player.setTexture('playerAnim');
        this.acceleration = 1.9 + (this.level - 1) * 0.5;
      }
    });
  }

  levelUp() {
    this.level++;
    this.acceleration += 0.5;

    // 显示升级提示
    const levelUpText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, `Level ${this.level}!`, {
      fontSize: '32px',
      fill: '#ffff00',
      stroke: '#000000',
      strokeThickness: 2
    }).setOrigin(0.5);
    levelUpText.setDepth(10);

    this.time.addEvent({
      delay: 1000,
      callback: () => {
        levelUpText.destroy();
      }
    });
  }

  updateScore() {

    try {
      // 关键：检查DOM元素和场景是否存在
      if (!this.scoreText || !this.scene) return;

      this.scoreText.setText(`分数: ${this.score}`);

      // 触发全局分数更新事件（添加安全检查）
      if (this.game && this.game.events) {
        this.game.events.emit('scoreChanged', this.score);
      }

      // 每200分触发一次射门环节
      if (this.score % 200 === 0 && this.score > 0 && !this.isShooting) {
        this.enterShootingMode();
      }
    } catch (error) {
      console.error('updateScore 错误:', error);

    }


  }
  enterShootingMode() {
    this.gameActive = false;
    this.isShooting = true;

    // 停止所有生成事件（使用保存的引用）
    if (this.obstacleEvent) this.obstacleEvent.remove();
    if (this.jerseyEvent) this.jerseyEvent.remove();
    if (this.broomEvent) this.broomEvent.remove();

    // 停止生成普通障碍物（添加存在性判断）
    if (this.obstacleEvent && this.obstacleEvent.active) {
      this.obstacleEvent.remove();
    }

    // 清除现有障碍物
    this.obstacles.forEach(obs => obs.destroy());
    this.obstacles = [];
    this.powerUps.forEach(p => p.destroy());
    this.powerUps = [];

    // 创建射门场景背景
    this.background.setTexture('goalBackground');

    // 创建球门
    this.goal = this.physics.add.sprite(GAME_WIDTH / 2, 100, 'goal');
    this.goal.setScale(0.8);
    this.goal.setImmovable(true);
    this.goal.setDepth(5);

    // 创建守门员
    this.goalkeeper = this.physics.add.sprite(GAME_WIDTH / 2, 150, 'goalkeeperAnim');
    this.goalkeeper.setScale(0.9);
    this.goalkeeper.setImmovable(true);
    this.goalkeeper.anims.play('goalkeeperAnim', true);
    this.goalkeeper.setDepth(7);

    // 让守门员左右移动
    this.tweens.add({
      targets: this.goalkeeper,
      x: [GAME_WIDTH / 2 - 50, GAME_WIDTH / 2 + 50],
      duration: 2000,
      ease: 'Sine.inOut',
      repeat: -1,
      yoyo: true
    });

    // 调整球员位置（准备射门）
    this.player.setPosition(GAME_WIDTH / 2, GAME_HEIGHT - 100);
    this.player.setTexture('playerShoot');

    // 创建足球
    this.ball = this.physics.add.sprite(GAME_WIDTH / 2, GAME_HEIGHT - 150, 'ballAnim');
    this.ball.setScale(0.8);
    this.ball.anims.play('ballAnim', true);
    this.ball.setDepth(8);

    // 显示射门提示
    this.shootHint = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT - 50, '点击或按空格键射门', {
      fontSize: '16px',
      fill: '#ffffff',
      backgroundColor: 'rgba(0,0,0,0.5)',
      padding: { x: 5, y: 2 }
    }).setOrigin(0.5);
    this.shootHint.setDepth(10);

    // 射门控制（空格键或触摸）
    this.input.keyboard.on('keydown-SPACE', this.shootBall, this);
    this.input.on('pointerdown', this.shootBall, this);
  }

  shootBall() {
    if (!this.isShooting) return;

    // 禁用输入
    this.input.keyboard.off('keydown-SPACE', this.shootBall, this);
    this.input.off('pointerdown', this.shootBall, this);

    if (this.shootHint) {
      this.shootHint.destroy();
      this.shootHint = null;
    }

    // 计算龙门网内的目标位置
    const goalNetY = this.goal.y + 30;
    const goalNetX = this.player.x;

    // 创建射门动画
    const ballTween = this.tweens.add({
      targets: this.ball,
      x: goalNetX,
      y: goalNetY,
      duration: 1000,
      ease: 'Power1',
      onComplete: () => {
        if (!this.ball || !this.ball.active) return;

        // 判断是否成功
        const isSuccess = Phaser.Math.Between(0, 1) === 1;
        if (isSuccess) {
          this.score += 3;
          this.updateScore();
          this.ball.setDepth(6.5); // 成功：足球在守门员后方（网内）
          this.successShoot();
        } else {
          this.ball.setDepth(7.5); // 失败：足球在守门员前方
          this.failShoot();
        }
        ballTween.remove();
      }
    });
  }
  // 射门成功处理
  successShoot() {
    this.isShooting = false;

    // 显示成功提示
    const successText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, '射门成功！+3分', {
      fontSize: '24px',
      fill: '#0f0',
      stroke: '#000000',
      strokeThickness: 2
    }).setOrigin(0.5);
    successText.setDepth(10);

    // 2秒后返回奔跑场景
    this.time.addEvent({
      delay: 2000,
      callback: () => {
        if (successText && successText.active) {
          successText.destroy();
        }
        this.ball.destroy();
        this.resetToRunningScene();
      },
      callbackScope: this
    });
  }

  // 射门失败处理
  failShoot() {
    this.isShooting = false;

    // 显示失败提示
    const failText = this.add.text(GAME_WIDTH / 2, GAME_HEIGHT / 2, '射门失败！', {
      fontSize: '24px',
      fill: '#f00',
      stroke: '#000000',
      strokeThickness: 2
    }).setOrigin(0.5);
    failText.setDepth(10);

    // 2秒后返回奔跑场景
    this.time.addEvent({
      delay: 2000,
      callback: () => {
        if (failText && failText.active) {
          failText.destroy();
        }
        this.ball.destroy();
        this.resetToRunningScene();
      },
      callbackScope: this
    });
  }

  // 重置为奔跑场景
  resetToRunningScene() {
    this.clearScene(); // 调用统一的清理方法

    // 重置玩家状态
    if (this.player) {
      this.player.setTexture('playerAnim');
      this.player.setPosition(GAME_WIDTH / 2, GAME_HEIGHT - 100);
    }

    // 恢复背景和游戏状态
    if (this.background) this.background.setTexture('grass');
    this.gameActive = true;
    this.isShooting = false;

    // 重新开始生成障碍物
    this.startSpawning();
  }

  gameOver() {
    this.gameActive = false;

    // 清理所有定时事件
    if (this.timer) this.timer.remove();
    if (this.obstacleEvent) this.obstacleEvent.remove();
    if (this.jerseyEvent) this.jerseyEvent.remove();
    if (this.broomEvent) this.broomEvent.remove();

    // 彻底清理计时相关资源
    if (this.timer) {
      this.timer.destroy(); // 销毁计时器（比remove()更彻底）
      this.timer = null; // 置空引用，防止残留
    }

    // 显示游戏结束画面
    this.add.image(GAME_WIDTH / 2, GAME_HEIGHT / 2, 'gameOver').setOrigin(0.5);

    // 触发游戏结束事件
    this.time.addEvent({
      delay: 2000,
      callback: () => {
        this.game.events.emit('gameOver');
      }
    });
  }

  update() {
    if (!this.gameActive) return;

    // 玩家移动逻辑
    if (this.player && this.player.active && !this.isShooting) {
      if (this.cursors.left.isDown) {
        this.player.setVelocityX(-200);
        // 播放左移动画（确保动画未暂停且当前动画正确）
        if (this.player.anims.currentAnim?.key !== 'playerLeft' && !this.player.anims.paused) {
          this.player.anims.play('playerLeft', true);
        }
      } else if (this.cursors.right.isDown) {
        this.player.setVelocityX(200);
        // 播放右移动画
        if (this.player.anims.currentAnim?.key !== 'playerRight' && !this.player.anims.paused) {
          this.player.anims.play('playerRight', true);
        }
      } else if (this.cursors.up.isDown) {
        this.player.setVelocityY(-200);
        // 上下移动时保持当前左右动画
        if (this.player.anims.currentAnim?.key === 'playerLeft' && !this.player.anims.paused) {
          this.player.anims.play('playerLeft', true);
        } else if (this.player.anims.currentAnim?.key === 'playerRight' && !this.player.anims.paused) {
          this.player.anims.play('playerRight', true);
        }else{
          this.player.anims.play('playerLeft', true);
        }
      } else if (this.cursors.down.isDown) {
        this.player.setVelocityY(200);
        // 上下移动时保持当前左右动画
        if (this.player.anims.currentAnim?.key === 'playerLeft' && !this.player.anims.paused) {
          this.player.anims.play('playerLeft', true);
        } else if (this.player.anims.currentAnim?.key === 'playerRight' && !this.player.anims.paused) {
          this.player.anims.play('playerRight', true);
        }else{
          this.player.anims.play('playerLeft', true);
        }
      } else {
        // 停止移动时停止动画
        this.player.setVelocityX(0);
        this.player.setVelocityY(0);
        this.player.anims.stop();
      }
    }
  }
  // 添加 clearScene 方法
  clearScene() {
    // 清理射门场景的元素
    if (this.goal) this.goal.destroy();
    if (this.goalkeeper) this.goalkeeper.destroy();
    if (this.ball) this.ball.destroy();
    if (this.shootHint) this.shootHint.destroy();

    // 清理所有障碍物和道具
    this.obstacles.forEach(obs => obs.destroy());
    this.powerUps.forEach(p => p.destroy());
    this.obstacles = [];
    this.powerUps = [];

    // 仅停止 tweens，保留动画状态
    this.tweens.killAll();
  }

  // 新增：场景销毁时清理资源
  destroy() {
    // 清理所有定时器
    if (this.timer) this.timer.remove();
    if (this.obstacleEvent) this.obstacleEvent.remove();
    if (this.jerseyEvent) this.jerseyEvent.remove();
    if (this.broomEvent) this.broomEvent.remove();

    // 移除输入监听
    this.input.keyboard.off('keydown-SPACE', this.shootBall, this);
    this.input.off('pointerdown', this.shootBall, this);

    // 清理所有游戏对象
    this.obstacles.forEach(obs => obs.destroy());
    this.powerUps.forEach(p => p.destroy());
    if (this.goal) this.goal.destroy();
    if (this.goalkeeper) this.goalkeeper.destroy();
    if (this.ball) this.ball.destroy();

    // 调用父类销毁方法
    super.destroy();
  }
}

// 游戏控制函数
const startGame = () => {
  currentScene.value = 'countdown';

  // 倒计时
  currentScene.value = 'countdown';
  let count = 3;
  const countdownInterval = setInterval(() => {
    count--;
    countdownNum.value = count;

    if (count <= 0) {
      clearInterval(countdownInterval);
      currentScene.value = 'game';
      // 通知游戏开始
      if (game.value) {
        const gameScene = game.value.scene.getScene('GameScene');
        if (gameScene) {
          gameScene.startGame();
        }
      }
    }
  }, 1000);
};

const continueGame = () => {
  startGame();
};

const restartGame = () => {
  // 1. 彻底销毁旧游戏实例（含场景和资源）
  if (game.value) {
    // 先停止游戏逻辑
    const gameScene = game.value.scene.getScene('GameScene');
    if (gameScene) {
      gameScene.gameActive = false;
    }
    // 销毁游戏实例（强制清理DOM）
    game.value.destroy(true);
    game.value = null; // 置空引用，避免残留
  }

  // 2. 重置全局状态
  score.value = 0;
  currentScene.value = 'start';
  countdownNum.value = 3;

  // 3. 延迟初始化新游戏（确保旧实例完全销毁）
  setTimeout(() => {
    initGame();
  }, 100); // 短暂延迟确保DOM清理完成
};
const getTitle = (score) => {
  if (score < 50) return '足球新手';
  if (score < 100) return '业余球员';
  if (score < 200) return '专业选手';
  if (score < 300) return '足球明星';
  return '足球传奇';
};

// 组件挂载时初始化游戏
onMounted(() => {
  initGame();
});

// 监听场景变化
watch(currentScene, (newVal) => {
  if (newVal === 'game' && game.value) {
    const gameScene = game.value.scene.getScene('GameScene');
    if (gameScene) {
      gameScene.scene.resume();
    }
  }
});

// 组件卸载时清理事件监听
onUnmounted(() => {
  if (game.value && game.value.events && scoreListener) {
    game.value.events.off('scoreChanged', scoreListener);
  }
});
</script>

<style scoped>
.game-container {
  position: relative;
  width: 100%;
  height: 100vh;
  margin: 0 auto;
  overflow: hidden;
}

.game-canvas {
  width: 100%;
  height: 100%;
  background-color: #000;
}

.gamestart {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
}

.start_bg {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.btn {
  width: 80%;
  height: 40px;
  border-radius: 5px;
  text-align: center;
  line-height: 40px;
  color: #333;
  box-shadow: 0 5px 0px #07942c;
  box-shadow: 0 5px 0px rgba(0, 0, 0, 0.17);
  position: absolute;
  left: 50%;
  margin: 0 0 0 -40%;
  font-size: 18px;
}

.rule {
  background: #fff;
  bottom: 100px;
}

.start {
  background: #ffff00;
  bottom: 40px;
}

.ruleshadow {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 102;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
}

.rulebox {
  width: 280px;
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  position: relative;
  opacity: 0;
  animation: fadeIn 0.5s forwards;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.x_rulebox {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 20px;
  height: 20px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23000'%3E%3Cpath d='M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z'/%3E%3C/svg%3E");
  cursor: pointer;
}

.daoju {
  margin-top: 15px;
}

.daoju_item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.daoju_1,
.daoju_2,
.daoju_3 {
  display: inline-block;
  width: 60px;
  height: 60px;
  margin-right: 10px;
  background-size: contain;
  background-repeat: no-repeat;
  flex-shrink: 0;
}

.daoju_1 {
  background-image: url("/static/images/football/Jersey.png");
}

.daoju_2 {
  background-image: url("/static/images/football/Broom.png");
}

.daoju_3 {
  background-image: url("/static/images/football/Pile.png");
}

.zhiyin {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 100;
  display: flex;
  justify-content: center;
  align-items: center;
}

.daojishi {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
  display: none;
  z-index: 11;
  background: url(daojishu_bg.png) repeat left top;
  background-size: 100%;
}

.daojishiline {
  width: 100%;
  height: 95px;
  position: absolute;
  top: 109px;
  left: 0;
  background: #ffe400;
  z-index: 1;
}

.daojishibox {
  width: 180px;
  height: 180px;
  position: absolute;
  left: 50%;
  top: 71px;
  margin: 0 0 0 -90px;
  background: url(daojishibox.png) no-repeat left top;
  background-size: 100%;
  z-index: 2;
}

.daojishipangzi {
  width: 111px;
  height: 102px;
  position: absolute;
  left: 50%;
  bottom: 50px;
  margin: 0 0 0 -55px;
  background: url(daojishipangzi.png) no-repeat left top;
  background-size: 100%;
  z-index: -1;
}

.daojishinum {
  width: 100%;
  text-align: center;
  font-size: 80px;
  color: #FFFFFF;
  padding: 70px 0 0 0;
  line-height: normal;
}

@keyframes countDown {
  0% {
    transform: scale(3);
    opacity: 0;
  }

  50% {
    transform: scale(1.2);
    opacity: 1;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}

.gameend {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 100;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
}

.game_fenshu {
  font-size: 36px;
  margin-bottom: 20px;
}

.chenghao {
  font-size: 24px;
  margin-bottom: 30px;
  text-align: center;
}

.game_ogain,
.game_chakan,
.game_share {
  width: 150px;
  height: 40px;
  line-height: 40px;
  text-align: center;
  background-color: #f00;
  border-radius: 20px;
  margin-bottom: 10px;
  cursor: pointer;
  font-size: 18px;
}

.game_chakan {
  background-color: #666;
}

.game_share {
  background-color: #008000;
}
</style>