实现“羊了个羊”玩法的消消乐(react)

实现“羊了个羊”消消乐(react)

体验地址:https://code.juejin.cn/pen/7143974476500172814?mode=light
和文章的代码写的有点不同。

1、前言

其实在羊了个羊出来的很久之前,我女朋友经常玩的一款游戏叫《方块物语》,就是一样的玩法,如下图。

在这里插入图片描述

当时看到的时候,就想着怎么去实现。也只是在脑海中构思了一下,没有动手行动起来。

然后看到了羊了个羊。诶,这不是和我女朋友之前玩的游戏一样吗?正好手头没什么事。就尝试了实现了一下。

2、实现
1、开始准备

由于懒得去搭项目,正好自己有个平时学习的react项目,就加个路由用react实现。

首先是布局,分为上中下三个部分,标题,游戏区域,操作区域。

就不说了。

2、游戏区域生成、是否被覆盖的判断。

初始数据,这里用的是12个文字,

name:文字

color:背景颜色

position:对应的位置分别是[第几层,第几行,第几个]

由于想偷懒,我直接每个同时放了三个。

const gameItemsArr = [
    {name: '马', color: '#5470c6', position: [null, null, null]},
    {name: '马', color: '#5470c6', position: [null, null, null]},
    {name: '马', color: '#5470c6', position: [null, null, null]},
    {name: '驰', color: '#fac858', position: [null, null, null]},
    {name: '驰', color: '#fac858', position: [null, null, null]},
    {name: '驰', color: '#fac858', position: [null, null, null]},
    {name: '朱', color: '#ee6666', position: [null, null, null]},
    {name: '朱', color: '#ee6666', position: [null, null, null]},
    {name: '朱', color: '#ee6666', position: [null, null, null]},
    {name: '振', color: '#73c0de', position: [null, null, null]},
    {name: '振', color: '#73c0de', position: [null, null, null]},
    {name: '振', color: '#73c0de', position: [null, null, null]},
    {name: '骚', color: '#3bd272', position: [null, null, null]},
    {name: '骚', color: '#3bd272', position: [null, null, null]},
    {name: '骚', color: '#3bd272', position: [null, null, null]},
    {name: '刘', color: '#9a60b4', position: [null, null, null]},
    {name: '刘', color: '#9a60b4', position: [null, null, null]},
    {name: '刘', color: '#9a60b4', position: [null, null, null]},
    {name: '胖', color: '#ea7ccc', position: [null, null, null]},
    {name: '胖', color: '#ea7ccc', position: [null, null, null]},
    {name: '胖', color: '#ea7ccc', position: [null, null, null]},
    {name: '邢', color: '#c14cac', position: [null, null, null]},
    {name: '邢', color: '#c14cac', position: [null, null, null]},
    {name: '邢', color: '#c14cac', position: [null, null, null]},
    {name: '吊', color: '#f08300', position: [null, null, null]},
    {name: '吊', color: '#f08300', position: [null, null, null]},
    {name: '吊', color: '#f08300', position: [null, null, null]},
    {name: '龙', color: '#004eff', position: [null, null, null]},
    {name: '龙', color: '#004eff', position: [null, null, null]},
    {name: '龙', color: '#004eff', position: [null, null, null]},
    {name: '楞', color: '#00e4ff', position: [null, null, null]},
    {name: '楞', color: '#00e4ff', position: [null, null, null]},
    {name: '楞', color: '#00e4ff', position: [null, null, null]},
    {name: '张', color: '#c0e8ff', position: [null, null, null]},
    {name: '张', color: '#c0e8ff', position: [null, null, null]},
    {name: '张', color: '#c0e8ff', position: [null, null, null]},
];

接下来是生成游戏区域的items

这边简单说一下level当前的关卡。一共设置了6个关卡。

floorItemsArr:每层有多少个,第一层9个,3的平方,第二层16个,4的平方依次类推,第一关有两层。

每层就是个正方形。

因为还要有空缺。这边也是偷懒,每个等级有多少空的。剩下的数组是三的倍数就可以了。

然后从上面的gameItemsArr取数据,看看不是空的item是不是36的倍数。

这边图省事也是写死的。

然后和空item数组拼接一下。

使用sort(()=>MathMath.random() - 0.5)打乱

然后依次从allItems取出每层的item

为了显示层级效果最上层的z-index值最大。这里也是偷懒写死的

最后判断每个元素的位置

每层的宽度和z-index

第一关最后就得到了一个这样的数组。

在这里插入图片描述

// 生成游戏items
export const itemsArr = (level) => {
    let arr = [...gameItemsArr];
    // 每层有多少item
    const floorItemsArr = [9, 16, 25, 36, 49, 64, 81];
    const floorNumsArr = [3, 4, 5, 6, 7, 8, 9];

    // 每个等级有多少空item数组
    const noItemsNum = [7, 14, 14, 24, 49, 40];
    // 每个等级有多少item数组
    const itemsNum = [18, 36, 72, 111, 150, 240];

    // 空item数组
    const noItemsArr = [];
    let i = noItemsNum[level - 1];
    while (i > 0) {
        noItemsArr.push({name: '', color: '', position: [null, null, null]});
        i--;
    }

    // 最后不完整的取几个
    const getArrItems = ((itemsNum[level - 1] / 3) % 12) * 3;
    const otherItemsArr = arr
        .map((i, index) => {
            if (index < getArrItems) {
                return i;
            }
            return null;
        })
        .filter((i) => i);
    let itemsNumsArr = [];
    if (level === 1) {
        itemsNumsArr = otherItemsArr;
    }
    if (level === 2) {
        itemsNumsArr = arr;
    }
    if (level === 3) {
        itemsNumsArr = arr.concat(arr);
    }
    if (level === 4) {
        arr = [...gameItemsArr];
        itemsNumsArr = arr.concat(arr, arr, otherItemsArr);
    }
    if (level === 5) {
        arr = [...gameItemsArr];
        itemsNumsArr = arr.concat(arr, arr, arr, otherItemsArr);
    }
    if (level === 6) {
        arr = [...gameItemsArr];
        itemsNumsArr = arr.concat(arr, arr, arr, arr, arr, otherItemsArr);
    }
   //打乱数组
    const allItems = itemsNumsArr.concat(noItemsArr).sort(() => Math.random() - 0.5);

    const resultArr = [];

    floorItemsArr.splice(0, level + 1).map((item, fIndex) => {
        resultArr.push(allItems.splice(0, item));
    });

    const zIndex = [6, 5, 4, 3, 2, 1];
    return resultArr.map((item, index) => {
        return {
            arr: [
                ...item.map((i, j) => {
                    i.position = [index + 1, parseInt(j / floorNumsArr[index]) + 1, (j + 1) % floorNumsArr[index] || floorNumsArr[index]];
                    return {...i};
                }),
            ],
            zIndex: zIndex[index],
            width: (index + 3) * 35,
        };
    });
};

得到了数组以后,就可以渲染页面了,但是还要解决覆盖的问题。

像上面那样,每一个上一层的元素覆盖了下一层的4个元素。

上面我们设置的position就排上了用场。

例如第一层的第一个位置是[1,1,1],那它所覆盖的元素就是[2,1,1],[2,1,2],[2,2,1],[2,2,2]

以此类推循环判断,就得到了一个都是position数组。

然后通过findIndex或者filter判断当前点击的item在不在这个数组当中。

在就不能点击,不在就可以点击。

为了能点击到下层,有个这个属性pointer-events:none设置给父元素,点击可以穿透,为了子元素可以点击。item设置pointer-events:auto

代码如下。

export const isItemCanClick = (item, allItems) => {
    const nowItem = {...item};
    const nowItemFloor = nowItem.position[0];
    const upFloor = allItems[nowItemFloor - 2]?.arr.filter((itemNow) => itemNow.name !== '') || [];
    // 最底下层不判断
    if (upFloor.length === 0) return true;
    let midArr = [];
    upFloor.map((itemNowM) => {
        const position = itemNowM.position;
        const a = [position[0] + 1, position[1], position[2]];
        const b = [position[0] + 1, position[1], position[2] + 1];
        const c = [position[0] + 1, position[1] + 1, position[2]];
        const d = [position[0] + 1, position[1] + 1, position[2] + 1];
        midArr.push(a);
        midArr.push(b);
        midArr.push(c);
        midArr.push(d);
    });

    const isCanClick =
        midArr.filter((mItem) => nowItem.position[0] === mItem[0] && nowItem.position[1] === mItem[1] && nowItem.position[2] === mItem[2])
            .length === 0;

    return isCanClick;
};

这样就可以完美生成我们的游戏区域了

 <div className="gameArea">
                {gameItemsArr.map((item, index) => {
                    return (
                        <div
                            className="gameAreaFloor"
                            key={item.zIndex}
                            style={
                                item.arr.filter((k) => k.name !== '').length !== 0
                                    ? {zIndex: item.zIndex, width: item.width, height: item.width}
                                    : {display: 'none'}
                            }>
                            {item.arr.map((gameItem, gameIndex) => {
                                return (
                                    <div
                                        onClick={() => {
                                            if (gameItem.name === '' || !isItemCanClick(gameItem, gameItemsArr)) return;

                                            moveItem(gameItem, gameIndex, index);
                                        }}
                                        key={gameIndex}
                                        style={
                                            gameItem.name === ''
                                                ? {opacity: 0, pointerEvents: 'none'}
                                                : isItemCanClick(gameItem, gameItemsArr)
                                                ? {background: gameItem.color}
                                                : {background: '#c2cbcbee'}
                                        }
                                        className="gameItem">
                                        {gameItem.name}
                                    </div>
                                );
                            })}
                        </div>
                    );
                })}
            </div>

3、操作判断

这里就比较简单,判断当前点击的层数,和点击的item

item push到操作的数组里面。

通过splice删除当前点击的元素并添加一个name为''item

再判断当前点击的元素在不在操作的数组里,在就找到存在的数组,放到一起,不在就放到前面,

有三个一样就清除。都是通过findIndexsplice

当前层级都清除完了,就进入下一关 level+1,重新生成游戏区域。

import React, {useState, useEffect} from 'react';
import {itemsArr} from './content';
import './page.css';
import {isItemCanClick} from './action';

let hasThreeItem = 0;
const GameBox = () => {
    // 分数
    const [score, setScore] = useState(0);
    // 第几关
    const [level, setLevel] = useState(1);
    // 游戏的item
    const [gameItemsArr, setGameItemsArr] = useState(itemsArr(level));
    // 操作的数组
    const [operateArr, setOperateArr] = useState([null, null, null, null, null, null, null]);
    // 当前点击的item,撤回用
    const [nowClickItemInfo, setNowClickItemInfo] = useState([null, null, null]);
    // 操作次数
    const [isOperate, setIsOperate] = useState([0, 0, 0]);

    useEffect(() => {
        if (operateArr.filter((item) => item).length === 7) {
            alert('游戏失败!');
            window.location.reload();
        }
    }, [operateArr]);

    // 判断游戏是否下一关
    useEffect(() => {
        if (gameItemsArr.length === 0) {
            alert(`恭喜你通过第${level}关了!!!`);
            if (level === 6) {
                alert('恭喜你通关了!!!');
                return;
            }
            setLevel((prev) => prev + 1);
            setGameItemsArr((prev) => {
                prev = itemsArr(level + 1);
                return [...prev];
            });
        }
    }, [gameItemsArr, level]);
    // 点击item
    const moveItem = (item, index, whichFloor) => {
        hasThreeItem = 0;
        let hasThreeindex = 0;
        // 记录当前的点击item信息
        const nowClickItem = [item, index, whichFloor];
        setNowClickItemInfo(nowClickItem);

        // 放到操作区
        setOperateArr((prev) => {
            const currentIndex = prev.findIndex((k) => k && k.name === item.name);
            prev.pop();
            if (currentIndex > -1) {
                prev.splice(currentIndex, 0, item);
            } else {
                prev.unshift(item);
            }
            return [...prev];
        });
        // 操作原始数组
        setGameItemsArr((prev) => {
            prev[whichFloor].arr.splice(index, 1, {...item, name: '', color: ''});
            if (prev[prev.length - 1].arr.filter((item) => item.name !== '').length === 0) {
                return [];
            } else {
                return [...prev];
            }
        });

        // 判断清除逻辑
        operateArr.map((newItem, newIndex) => {
            if (newItem && newItem.name === item.name) {
                hasThreeItem++;
                hasThreeindex = newIndex;
            }
            return null;
        });

        // 如果有三个一样的
        if (hasThreeItem === 2) {
            setOperateArr((prev) => {
                prev.splice(hasThreeindex - 1, 3);
                prev.push(null);
                prev.push(null);
                prev.push(null);
                return [...prev];
            });
            setScore((prev) => prev + 100);
        }
    };

    return (
        <div className="gamebox">
            {/* 标题区域 */}
            <div className="titleArea">
                <div className="titleAreaTitle">汉字方块</div>
                <div className="titleAreaScore">
                    <span>分数:</span>
                    <span>{score}</span>
                </div>
            </div>
            {/* 游戏区域 */}
            <div className="gameArea">
                {gameItemsArr.map((item, index) => {
                    return (
                        <div
                            className="gameAreaFloor"
                            key={item.zIndex}
                            style={
                                item.arr.filter((k) => k.name !== '').length !== 0
                                    ? {zIndex: item.zIndex, width: item.width, height: item.width}
                                    : {display: 'none'}
                            }>
                            {item.arr.map((gameItem, gameIndex) => {
                                return (
                                    <div
                                        onClick={() => {
                                            if (gameItem.name === '' || !isItemCanClick(gameItem, gameItemsArr)) return;

                                            moveItem(gameItem, gameIndex, index);
                                        }}
                                        key={gameIndex}
                                        style={
                                            gameItem.name === ''
                                                ? {opacity: 0, pointerEvents: 'none'}
                                                : isItemCanClick(gameItem, gameItemsArr)
                                                ? {background: gameItem.color}
                                                : {background: '#c2cbcbee'}
                                        }
                                        className="gameItem">
                                        {gameItem.name}
                                    </div>
                                );
                            })}
                        </div>
                    );
                })}
            </div>

            {/* 下方格子 */}
            <div className="operateArea">
                {operateArr.map((item, index) => {
                    if (!item) {
                        return <div key={index} className="gameItemOperate"></div>;
                    } else {
                        return (
                            <div key={index} style={{background: item.color}} className="gameItemOperate">
                                {item.name}
                            </div>
                        );
                    }
                })}
            </div>
            <div className="operateBtnArr">
                <span
                    className="operateBtn"
                    style={isOperate[0] === 1 ? {background: 'grey'} : {}}
                    onClick={() => {
                        if (isOperate[0] === 1) return;
                        setGameItemsArr((prev) => {
                            prev = itemsArr(level);
                            return [...prev];
                        });
                        setIsOperate((prev) => {
                            prev[0] = 1;
                            return [...prev];
                        });
                    }}>
                    随机
                </span>
                <span
                    className="operateBtn"
                    style={isOperate[1] === 1 ? {background: 'grey'} : {}}
                    onClick={() => {
                        if (isOperate[1] === 1) return;
                        setOperateArr((prev) => {
                            const lastIndex = prev.findIndex((item) => item && item.name === nowClickItemInfo[0].name);
                            prev.splice(lastIndex, 1);
                            return [...prev];
                        });
                        setGameItemsArr((prev) => {
                            prev[nowClickItemInfo[2]].arr[nowClickItemInfo[1]] = nowClickItemInfo[0];
                            return [...prev];
                        });

                        setIsOperate((prev) => {
                            prev[1] = 1;
                            return [...prev];
                        });
                    }}>
                    撤回
                </span>
                <span className="operateBtn">加三个格子</span>
            </div>
        </div>
    );
};

export default GameBox;

在这里插入图片描述

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值