// 在HTML中,建立一個畫布
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
document.body.appendChild(canvas);
// 設定彈珠台的位置和尺寸
const boardWidth = 200;
const boardHeight = 10;
let boardX = canvas.width / 2 - boardWidth / 2;
const boardY = canvas.height - boardHeight - 10;
// 建立一顆彈珠
const ballRadius = 10;
let ballX = canvas.width / 2;
let ballY = canvas.height - boardHeight - ballRadius - 10;
let ballDX = 2;
let ballDY = -2;
// 監聽滑鼠移動事件,移動彈珠台
canvas.addEventListener('mousemove', moveBoard);
// 移動彈珠台函數
function moveBoard(e) {
const relativeX = e.clientX - canvas.offsetLeft;
if (relativeX - boardWidth / 2 > 0 && relativeX + boardWidth / 2 < canvas.width) {
boardX = relativeX - boardWidth / 2;
}
}
// 繪製彈珠台函數
function drawBoard() {
ctx.beginPath();
ctx.rect(boardX, boardY, boardWidth, boardHeight);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// 繪製彈珠函數
function drawBall() {
ctx.beginPath();
ctx.arc(ballX, ballY, ballRadius, 0, Math.PI*2);
ctx.fillStyle = '#0095DD';
ctx.fill();
ctx.closePath();
}
// 碰撞偵測函數
function collisionDetection() {
if (
ballX > boardX &&
ballX < boardX + boardWidth &&
ballY > boardY &&
ballY < boardY + boardHeight
) {
ballDY = -ballDY;
}
}
// 更新畫面函數
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBoard();
drawBall();
collisionDetection();
// 當彈珠碰到牆壁時,改變方向
if (ballX + ballDX > canvas.width - ballRadius || ballX + ballDX < ballRadius) {
ballDX = -ballDX;
}
if (ballY + ballDY < ballRadius) {
ballDY = -ballDY;
} else if (ballY + ballDY > canvas.height - ballRadius) {
// 當彈珠碰到底部時,判定遊戲結束
// 在這裡你可以自行添加遊戲結束的相關邏輯。
alert('遊戲結束!');
document.location.reload();
}
ballX += ballDX;
ballY += ballDY;
requestAnimationFrame(update);
}
// 開始遊戲
update();