📜  JavaScript 代码打高尔夫球(1)

📅  最后修改于: 2023-12-03 15:01:41.375000             🧑  作者: Mango

JavaScript 代码打高尔夫球

在这篇文章中,我们将介绍如何使用 JavaScript 编写一个简单的高尔夫球游戏。

前置知识
  • HTML & CSS 基础知识
  • JavaScript 基础知识
  • canvas
游戏规则
  • 点击屏幕开始游戏
  • 球初始位置为左下角,点击屏幕后,球将开始运动
  • 球每次运动方向随机(上、左上、左、左下)
  • 球每次运动距离随机(20 到 50 像素)
  • 如果球触碰到边界,则游戏失败,弹出游戏结束提示
具体实现

首先,我们需要在 HTML 中创建一个 canvas 元素,用于绘制游戏画面。

<canvas id="gameCanvas"></canvas>

接下来,我们需要在 JavaScript 中获取该元素,并设置其宽高。

const canvas = document.getElementById('gameCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

然后,我们需要获取 canvas 的上下文,用于绘制图形。

const ctx = canvas.getContext('2d');

接下来,我们需要定义游戏中的球对象。

const ball = {
  x: 50,
  y: canvas.height - 50,
  r: 10,
  color: 'red',
  dx: getRandomDirection(),
  dy: getRandomDirection(),
  speed: getRandomSpeed(),
};

球的 x、y 坐标表示其初始位置,r 表示球的半径,color 表示球的颜色,dx、dy 表示球的横向和纵向速度,speed 表示球的速度。

接下来,我们需要定义一个函数来绘制球。

function drawBall() {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
  ctx.fillStyle = ball.color;
  ctx.fill();
  ctx.closePath();
}

该函数使用 canvas 的 arc 方法来绘制一个圆形,并使用球的颜色进行填充。

然后,我们需要定义一个定时器来控制球的运动。

setInterval(() => {
  moveBall();
  drawBall();
}, 50);

moveBall 函数用于控制球的运动,它实现了游戏规则中的随机运动方向和距离,同时还会判断球是否触碰到边界。

function moveBall() {
  ball.x += ball.dx * ball.speed;
  ball.y += ball.dy * ball.speed;

  if (ball.x - ball.r < 0 || ball.x + ball.r > canvas.width) {
    ball.dx = -ball.dx;
  }

  if (ball.y - ball.r < 0 || ball.y + ball.r > canvas.height) {
    ball.dy = -ball.dy;
  }
}

function getRandomDirection() {
  return Math.random() > 0.5 ? -1 : 1;
}

function getRandomSpeed() {
  return Math.floor(Math.random() * 30) + 20;
}

到这里,我们已经完成了 JavaScript 代码打高尔夫球游戏,你可以在浏览器中尝试运行该代码,并不断优化游戏体验。