<template>
  <div id="gameContainer" :style="containerStyle"></div>
</template>
<script>
import ballMove from "./games/game-ballmove/game";
import flappyBird from "./games/game-flipbird/game";
import game2048 from "./games/game2048/game";
const games = { ballMove, flappyBird, game2048 };
const STATE_RUNNING = 0;
const STATE_LOSE = 1;
const STATE_WIN = 2;
const STATE_PAUSED = 3;
export default {
  props: ["name", "containerStyle"],
  data() {
    return {
      state: STATE_RUNNING,
      gameInstance: null,
      containerId: "gameContainer",
    };
  },
  watch: {
    name(val, oldVal) {
      if (oldVal) {
        this.dispose();
        this.reload(val);
      }
    },
  },
  methods: {
    pause() {
      this.gameInstance.scene.scenes.forEach((scene) => {
        scene.scene.pause();
      });
      this.state = STATE_PAUSED;
      this.$emit("paused");
    },
    resume() {
      if (this.state === STATE_PAUSED) {
        this.gameInstance.scene.scenes.forEach((scene) => {
          scene.scene.resume();
        });
        this.state = STATE_RUNNING;
        this.$emit("resumed");
      }
    },
    restart() {
      this.gameInstance.restart();
      this.state = STATE_RUNNING;
    },
    dispose() {
      for (const key in this.gameInstance.scene.keys) {
        if (this.gameInstance.scene.keys.hasOwnProperty(key)) {
          this.gameInstance.scene.stop(key); //停止渲染
          this.gameInstance.scene.keys[key] = undefined;
        }
      }
      this.gameInstance.destroy(false);
      document
        .getElementById("gameContainer")
        .removeChild(this.gameInstance.canvas);
    },
    reload(name) {
      this.gameInstance = games[name]({
        containerId: this.containerId,
        onLose: () => {
          if (this.state !== STATE_LOSE) this.$emit("lost");
          this.state = STATE_LOSE;
        },
      });
    },
  },
  async mounted() {
    console.log("a");
    this.reload(this.name);
  },

  destroyed() {
    this.dispose();
  },
};
</script>

<style>
</style>