高尔夫球进洞怎么出来
```html
/* 游戏界面风格设置 */
body {
fontfamily: Arial, sansserif;
backgroundcolor: f2f2f2;
textalign: center;
margin: 0;
}
.gamecontainer {
width: 100vw;
height: 100vh;
display: flex;
flexdirection: column;
justifycontent: center;
alignitems: center;
}
.gametitle {
fontsize: 24px;
marginbottom: 20px;
color: 333;
}
.gamecanvas {
border: 1px solid 000;
width: 400px;
height: 400px;
backgroundcolor: fff;
}
/* 控制面板风格设置 */
.controlscontainer {
margintop: 20px;
}
.controlscontainer button {
padding: 10px 20px;
margin: 5px;
backgroundcolor: 007BFF;
color: fff;
border: none;
borderradius: 5px;
cursor: pointer;
}
.controlscontainer button:hover {
backgroundcolor: 0056b3;
}
.instructions {
margintop: 20px;
fontsize: 16px;
color: 666;
}
使用鼠标单击调整球的方向和力度,使球尽可能快速地进洞。
// 初始化画布
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// 设置游戏变量
let ball = { x: 50, y: 50, radius: 10, vx: 0, vy: 0 };
let hole = { x: 350, y: 350, radius: 15 };
let isGameActive = true;
// 初始化游戏
function initGame() {
ball.x = 50;
ball.y = 50;
ball.vx = 0;
ball.vy = 0;
isGameActive = true;
drawGame();
}
// 绘制游戏元素
function drawGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制洞
ctx.beginPath();
ctx.arc(hole.x, hole.y, hole.radius, 0, 2 * Math.PI);
ctx.fillStyle = 'black';
ctx.fill();
// 绘制球
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.radius, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
if (isGameActive) {
updateGame();
requestAnimationFrame(drawGame);
}
}
// 更新游戏元素
function updateGame() {
// 更新球的坐标
ball.x = ball.vx;
ball.y = ball.vy;
// 计算摩擦力
ball.vx *= 0.99;
ball.vy *= 0.99;
// 检查球是否进洞
const dx = ball.x hole.x;
const dy = ball.y hole.y;
const distance = Math.sqrt(dx * dx dy * dy);
if (distance <= ball.radius hole.radius) {
isGameActive = false;
alert('恭喜你!球进洞了!');
}
// 限制球在画布内
if (ball.x < ball.radius || ball.x > canvas.width ball.radius) {
ball.vx = ball.vx;
}
if (ball.y < ball.radius || ball.y > canvas.height ball.radius) {
ball.vy = ball.vy;
}
}
// 监听画布点击事件
canvas.addEventListener('click', function (event) {
if (!isGameActive) return;
// 计算点击点相对于画布的坐标
const rect = canvas.getBoundingClientRect();
const clickX = event.clientX rect.left;
const clickY = event.clientY rect.top;
// 计算球和点击点之间的角度和距离
const dx = clickX ball.x;
const dy = clickY ball.y;
const angle = Math.atan2(dy, dx);
const distance = Math.sqrt(dx * dx dy * dy);
// 根据点击的距离和角度调整球的速度
const speed = Math.min(distance / 10, 10);
ball.vx = speed * Math.cos(angle);
ball.vy = speed * Math.sin(angle);
});
// 重新开始游戏
document.getElementById('restartButton').addEventListener('click', function () {
initGame();
});
// 启动游戏
initGame();