You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS记忆游戏开发:如何为每两张卡片设置相同颜色?

实现记忆游戏的卡片颜色配对功能

要让每两张卡片拥有相同颜色,核心是先生成成对的颜色集合,再打乱后分配给卡片,而不是给每张卡片单独生成随机色。下面是具体实现方案:

核心步骤

  1. 生成配对颜色数组:根据卡片总数(50张),生成25个唯一随机颜色,每个颜色复制一份,形成包含50个元素的数组(每个颜色恰好出现两次)。
  2. 打乱颜色数组:用标准洗牌算法打乱数组,保证颜色随机分布。
  3. 批量创建并设置卡片:遍历打乱后的颜色数组,为每个颜色创建卡片并设置背景色。

修改后的完整代码

document.addEventListener('DOMContentLoaded', () => {
    // 生成随机十六进制颜色
    function generateRandomColor() {
        return '#' + Math.floor(Math.random() * 16777215).toString(16);
    }

    // 生成指定数量的颜色配对数组
    function generateColorPairs(pairCount) {
        const colors = [];
        for (let i = 0; i < pairCount; i++) {
            const color = generateRandomColor();
            // 每个颜色添加两次,形成配对
            colors.push(color, color);
        }
        return colors;
    }

    // Fisher-Yates洗牌算法:公平打乱数组
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            // 交换数组元素
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    }

    const grid = document.querySelector(".grid");
    // 50张卡片需要25对颜色
    const colorPairs = generateColorPairs(25);
    // 打乱颜色数组,保证随机分布
    const shuffledColors = shuffleArray(colorPairs);

    // 批量创建卡片并设置颜色(比innerHTML拼接性能更高)
    shuffledColors.forEach(color => {
        const card = document.createElement("div");
        card.classList.add("card");
        card.style.backgroundColor = color;
        grid.appendChild(card);
    });
})

关键说明

  • 避免重复查询DOM:原代码每次循环都重新查询所有卡片,性能极低。现在通过document.createElement批量创建并添加,效率更高。
  • 公平洗牌:Fisher-Yates算法能保证每个元素出现在任意位置的概率相等,避免随机打乱时的偏倚。
  • 颜色配对逻辑:通过generateColorPairs生成成对颜色,确保每个颜色恰好对应两张卡片,满足记忆游戏的核心需求。

内容的提问来源于stack exchange,提问作者ארי פיין

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:07:16