<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>彈球遊戲</title>
<script src="https://unpkg.com/vue@3"></script>
<style>
body {
margin: 0;
padding: 0;
}
.container {
position: relative;
margin: 0 auto;
width: 440px;
height: 440px;
background-color: blanchedalmond;
}
.ball {
position: absolute;
width: 30px;
height: 30px;
left: 0px;
top: 0px;
background-color: orange;
border-radius: 30px;
}
.board {
position: absolute;
left: 0;
bottom: 0;
height: 10px;
width: 80px;
border-radius: 5px;
background-color: red;
}
</style>
</head>
<body>
<div id="Application">
<!-- 遊戲區域 -->
<div class="container">
<!-- 底部擋板 -->
<div class="board" :style="{left: boardX + 'px'}"></div>
<!-- 彈球 -->
<div class="ball" :style="{left: ballX+'px', top: ballY+'px'}"></div>
<!-- 遊戲結束提示 -->
<h1 v-if="fail" style="text-align: center;">遊戲失敗</h1>
</div>
</div>
<script>
const App = {
data() {
return {
boardX: 0, // 控制擋板位置
ballX: 0, // 控制彈球位置
ballY: 0,
rateX: 0.5, // 控制彈球移動速度
rateY: 0.5,
fail: false // 控制結束遊戲顯示的顯示
}
},
mounted() { // 元件生命週期函數,元件載入時會呼叫
this.enterKeyup(); // 新增鍵盤事件
this.rateX = (Math.random() + 0.3); // 隨機彈球的運動速度和方向
this.rateY = (Math.random() + 0.3);
this.timer = setInterval(() => { // 開啟計數器,控制彈球移動
if (this.ballX + this.rateX >= 440 - 30) {
this.rateX *= -1; // 到達右側邊緣進行反彈
}
if (this.ballX + this.rateX <= 0) {
this.rateX *= -1; // 到達左側邊緣進行反彈
}
if (this.ballY + this.rateY <= 0) {
this.rateY *= -1; // 到達上側邊緣進行反彈
}
// 修改小球的位置:當前位置加上單位時間的速度
this.ballX += this.rateX;
this.ballY += this.rateY;
// 失敗判定
if (this.ballY >= 440 - 30 - 10) {
if (this.boardX <= this.ballX + 30 && this.boardX + 80 >= this.ballX) {
this.rateY *= -1; // 擋板接住了彈球,進行反彈
} else {
clearInterval(this.timer);
this.fail = true; // 沒有接住彈球,遊戲結束
}
}
}, 2); //每隔2毫秒執行一次函數
},
methods: {
// 控制擋板移動
keydown(event) {
if (event.key == "ArrowLeft") {
if (this.boardX > 10) {
this.boardX -= 30;
}
} else if (event.key == "ArrowRight") {
if (this.boardX < 440 - 80) {
this.boardX += 30;
}
}
},
enterKeyup() {
document.addEventListener("keydown", this.keydown);
}
}
}
Vue.createApp(App).mount("#Application");
</script>
</body>
</html>
今天的內容就先到這邊,放鬆一下,明天再繼續學習吧!