<template>
  <div ref="gameContainer" class="gameContainer"></div>
</template>

<script setup name="JumpRope">
import { onMounted, ref } from 'vue';
import Phaser from 'phaser';
const gameContainer = ref(null);
const game = ref(null);
const animatorProperty = ref(null);
const player = ref(null);
const frameRate = ref(null);

function preload() {
  this.load.spritesheet('character', 'static/images/animation/jumprope.png', {
    frameWidth: 240,
    frameHeight: 240
  });
}
function create() {
  // 创建动画
  animatorProperty.value = this.anims.create({
    key: 'sports',
    frames: this.anims.generateFrameNumbers('character', { start: 0, end: 6 }),
    frameRate: 15,
    repeat: 0 // -1表示无限循环
  });
  // 创建精灵并播放动画
  player.value = this.add.sprite(120, 120, 'character');
}

function update() {
  animatorProperty.value.frameRate = frameRate.value;
}

// 触发运动
const sports = (data) => {
  frameRate.value = data;
  player.value.play('sports');
};

onMounted(() => {
  // 创建 Phaser 游戏实例
  const config = {
    type: Phaser.AUTO,
    parent: gameContainer.value,
    width: 240,
    height: 240,
    transparent: true, // 设置为透明背景
    scene: {
      preload,
      create,
      update
    }
  };
  game.value = new Phaser.Game(config);
});

onBeforeUnmount(() => {
  if (game.value) {
    game.value.destroy(true);
  }
});

//暴露给父组件用
defineExpose({
  sports
});
</script>

<style scoped>
.gameContainer {
  width: 240px;
  height: 240px;
  position: fixed;
  z-index: 999;
  left: 10%;
  margin-left: -120px;
  bottom: 1.5vh;
}
</style>
