index.vue
<template>
<div class="game-scene" tabindex="0" @keydown="onKeyDown">
<!-- 游戏元素组件 -->
<Plane :x="planeX" :y="planeY" />
<Enemy :x="enemyX" :y="enemyY" />
<Bullet :x="bulletX" :y="bulletY" />
</div>
</template>
<script>
import Plane from "./Plane.vue";
import Enemy from "./Enemy.vue";
import Bullet from "./Bullet.vue";
export default {
components: {
Plane,
Enemy,
Bullet,
},
data() {
return {
planeX: 0, // 飞机X坐标
planeY: 0, // 飞机Y坐标
enemyX: 0, // 敌人X坐标
enemyY: 0, // 敌人Y坐标
bulletX: 0, // 子弹X坐标
bulletY: 0, // 子弹Y坐标
};
},
methods: {
onKeyDown(e) {
switch (e.key) {
case "ArrowLeft":
this.planeX -= 10;
break;
case "ArrowRight":
this.planeX += 10;
break;
case "ArrowUp":
this.planeY -= 10;
break;
case "ArrowDown":
this.planeY += 10;
break;
case " ":
this.bulletX = this.planeX + 50; // 子弹从飞机中央射出
this.bulletY = this.planeY - 10; // 子弹在飞机上方
break;
}
},
},
watch: {
bulletY(newY) {
// 子弹与敌人相撞
if (
newY < this.enemyY + 50 &&
newY > this.enemyY &&
this.bulletX > this.enemyX &&
this.bulletX < this.enemyX + 50
) {
this.enemyX = Math.random() * 450; // 敌人重新出现在随机位置
this.enemyY = 0;
this.bulletX = -100; // 子弹回到屏幕外
this.bulletY = -100;
}
},
enemyY(newY) {
// 敌人飞出屏幕外
if (newY > 500) {
this.enemyX = Math.random() * 450; // 敌人重新出现在随机位置
this.enemyY = 0;
}
},
},
mounted() {
// 敌人和子弹移动
setInterval(() => {
this.enemyY += 10;
this.bulletY -= 20;
}, 100);
},
};
</script>
<style>
.game-scene {
position: relative;
width: 500px;
height: 500px;
background-color: #333;
margin: 0 auto;
}
/* 飞机 */
.plane {
position: absolute;
left: 200px;
top: 400px;
width: 100px;
height: 100px;
/* background-image: url(./plane.png); */
background-repeat: no-repeat;
background-size: contain;
background-color: aqua;
}
/* 敌人 */
.enemy {
position: absolute;
width: 50px;
height: 50px;
/* background-image: url(./enemy.png); */
background-repeat: no-repeat;
background-size: contain;
background-color: beige;
}
/* 子弹 */
.bullet {
position: absolute;
width: 10px;
height: 30px;
background-color: #fff;
}
</style>
<!-- Plane.vue -->
<template>
<div class="plane" :style="{ left: x + 'px', top: y + 'px' }"></div>
</template>
<script>
export default {
props: {
x: Number,
y: Number,
},
};
</script>
<template>
<div class="enemy" :style="{ left: x + 'px', top: y + 'px' }"></div>
</template>
<script>
export default {
props: {
x: Number,
y: Number,
},
};
</script>
<!-- Bullet.vue -->
<template>
<div class="bullet" :style="{ left: x + 'px', top: y + 'px' }"></div>
</template>
<script>
export default {
props: {
x: Number,
y: Number,
},
};
</script>