当前位置:首页 > 行业动态 > 正文

html切水果游戏

该HTML切水果游戏采用Canvas绘制动态水果轨迹,通过鼠标/触屏滑动模拟切割动作,碰撞检测实现精准判定,内置物理引擎控制水果抛物线运动,积分系统实时统计连击奖励,配合粒子特效增强打击感,兼容PC与移动设备双

切水果游戏是一款通过鼠标或触摸屏操作,模拟切割屏幕中下落水果的休闲小游戏,玩家需要在水果掉落到底部之前将其切开,切中得分,未切中则扣除生命值,生命值归零时游戏结束。

html切水果游戏  第1张


技术栈

技术类别 具体技术
前端语言 HTML(页面结构)、CSS(样式)、JavaScript(逻辑交互)
核心功能 Canvas绘图、随机水果生成、鼠标/触摸事件监听、碰撞检测、计分系统
扩展功能 音效播放、动画特效、难度分级(如加速或增加水果种类)

实现步骤

创建基础页面结构

<canvas id="gameCanvas" width="400" height="600"></canvas>
<div id="score">Score: 0</div>
<div id="life">Life: 3</div>

初始化Canvas与游戏变量

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let score = 0;
let life = 3;
let fruits = []; // 存储当前水果对象

定义水果类(随机生成属性)

class Fruit {
  constructor() {
    this.x = Math.random()  canvas.width;
    this.y = -50; // 初始位置在顶部外
    this.size = 30 + Math.random()  20; // 随机大小
    this.type = ['apple', 'orange', 'watermelon'][Math.floor(Math.random()  3)]; // 随机类型
    this.speed = 2 + Math.random()  3; // 随机下落速度
  }
  draw() {
    ctx.drawImage(this.type === 'apple' ? appleImg : 
                 this.type === 'orange' ? orangeImg : watermelonImg, 
                 this.x this.size / 2, this.y this.size / 2, this.size, this.size);
  }
  update() {
    this.y += this.speed; // 下落逻辑
  }
}

生成水果与游戏循环

function createFruit() {
  fruits.push(new Fruit());
}
setInterval(createFruit, 1000); // 每秒生成一个水果
function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
  fruits.forEach(fruit => {
    fruit.update();
    fruit.draw();
  });
  requestAnimationFrame(gameLoop); // 循环调用
}
gameLoop();

监听切割事件(鼠标/触摸)

canvas.addEventListener('click', (e) => {
  const clickX = e.offsetX;
  const clickY = e.offsetY;
  fruits.forEach((fruit, index) => {
    const distance = Math.hypot(clickX fruit.x, clickY fruit.y);
    if (distance < fruit.size / 2) { // 碰撞检测
      score++;
      fruits.splice(index, 1); // 移除被切中的水果
    }
  });
});

更新生命值与游戏结束逻辑

function checkLife() {
  fruits.forEach(fruit => {
    if (fruit.y > canvas.height) {
      life--;
      fruits.splice(fruits.indexOf(fruit), 1);
    }
  });
  if (life <= 0) {
    clearInterval(gameLoop);
    alert('Game Over!');
  }
}
setInterval(checkLife, 100); // 每100ms检查一次

代码示例:完整逻辑整合

// 假设已加载图片资源:appleImg, orangeImg, watermelonImg
function initGame() {
  createFruit();
  gameLoop();
}
initGame();

优化建议

优化方向 具体方案
性能优化 使用requestAnimationFrame替代setInterval,减少重绘消耗
用户体验 添加切割音效(Audio对象)、水果飞溅动画(Canvas渐变填充)
扩展玩法 增加炸弾或特殊道具、限时模式、排行榜功能

相关问题与解答

问题1:如何调整水果生成速度?

解答:修改setInterval(createFruit, 1000)中的时间间隔值,改为500会让水果生成速度翻倍。

问题2:如何给切割动作添加音效?

解答:在切割逻辑中插入音效播放代码:

const cutSound = new Audio('cut.mp3');
canvas.addEventListener('click', () => {
  // 其他逻辑...
  cutSound.play(); // 播放音效
});
0