You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.1 KiB
85 lines
2.1 KiB
<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);
|
|
const container = document.getElementById("gameContainer");
|
|
const canvas = this.gameInstance.canvas;
|
|
if (canvas.parentNode === container) container.removeChild(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>
|