寻找带有年味的烟花&爆竹-经典【扫雷】游戏改版

PK创意闹新春,我正在参加「春节创意投稿大赛」,详情请看:春节创意投稿大赛

游戏体验

效果图

image.png

游戏规则

大家通过效果图也看出来了,这就是个扫雷的游戏。所以,这个游戏的规则也是沿用扫雷的那一套规则。点击复习扫雷规则

烟花&爆竹全部找出之后,会自动点燃,并且送上新年祝福彩蛋(每个人的都不一样哦,欢迎把收到的彩蛋打在评论区)

onkex-ezwej.gif

试玩地址

点击链接试玩:hxkj.vip/demo/firecr…

代码实现

接下来是代码实现环节,咱们分步骤,一步步慢慢来。

初始化阶段

  • 计算方格总数、打开状态、标记状态
  • 刷新爆竹位置
// 游戏初始化
init (width, height, mineCount) {
    this.isEnd = false;
    const total = width * height;
    const mines = new Array(total).fill(0);
    for (let i = 0; i < mineCount; i++) {
        mines[i] = 1;
    }
    shuffle(mines, mineCount);
    this.mines = mines;
    this.openStatus = new Array(total).fill(0);
    this.markStatus = new Array(total).fill(0);
    this.selectedMineCount = 0;
},
// 打乱顺序
shuffle (mines, start) {
    for (let i = start; i < mines.length; i++) {
        const randomIndex = Math.floor(Math.random() * (i + 1));
        const tmp = mines[randomIndex];
        mines[randomIndex] = mines[i];
        mines[i] = tmp;
    }
}
复制代码

点击事件

  • 计算点击方格周围爆竹数量(当数值等于 0 时,代表周围9个方格都不包含爆竹,此时直接翻开周围区域的方格)
// 计算周围爆竹数量
neighbourMineCount () {
    const result = new Array(this.width * this.height).fill(0);
    for (let i = 0; i < result.length; i++) {
        if (!this.mines[i]) {
            continue;
        }
        const y = i % this.width;
        const x = (i - y) / this.width;
        for (let j = -1; j < 2; j++) {
            const newX = x + j;
            if (newX < 0 || newX === this.height) {
                continue;
            }
            for (let k = -1; k < 2; k++) {
                const newY = y + k;
                if (newY < 0 || newY === this.width) {
                    continue;
                }
                result[newX * this.width + newY]++;
            }
        }
    }
    return result;
},
复制代码

鼠标右击事件

  • 根据操作标记方格
handleRightClick (x, y) {
    if (this.isEnd) {
        return;
    }
    const index = x * this.width + y;
    if (this.openStatus[index] === 1) {
        return;
    }
    this.markStatus.splice(index, 1, (this.markStatus[index] + 1) % 3);
    if (this.markStatus[index] === 1) {
        this.selectedMineCount++;
    } else if (this.markStatus[index] === 2) {
        this.selectedMineCount--;
    }
},
复制代码

总体来讲核心代码量还是挺少的,祝大家新年快乐!

项目地址

码云 gitee: gitee.com/HashTang/fi…

结语

作者:HashTang

个人空间:hxkj.vip

Guess you like

Origin juejin.im/post/7054819621521588255