JavaScript拼图游戏:按钮随机选图与点击循环切换功能实现咨询
JavaScript拼图游戏:随机初始图片与点击循环切换实现
需求说明
- 从
imageNames中对应类型的图片数组里随机选取初始图片,展示在网格按钮上 - 点击按钮时,切换为数组中的下一张图片,循环往复(例如选中
img/cableTriple4.png后,点击依次切换为img/cableTriple1.png、img/cableTriple2.png、img/cableTriple3.png,再回到img/cableTriple4.png)
现有基础代码
const gridSize = 4; const juegoTablero = [ [1, 2, 2, 1], [1, 0, 0, 1], [2, 3, 4, 3], [1, 0, 0, 2], ]; // 网格按钮使用的图片 const imageNames = { // 直电缆 0: ["img/cableRecto1.png", "img/cableRecto1.png"], // 灯泡 1: ["img/bombilla1.png", "img/bombilla2.png", "img/bombilla3.png", "img/bombilla4.png"], // 双电缆 2: ["img/cableDoble1.png", "img/cableDoble2.png", "img/cableDoble3.png", "img/cableDoble4.png"], // 三电缆 3: ["img/cableTriple1.png", "img/cableTriple2.png", "img/cableTriple3.png", "img/cableTriple4.png"], // 中心 4: ["img/centro1.png", "img/centro2.png", "img/centro3.png", "img/centro4.png"] };
实现方案
1. 页面结构准备
先在HTML中添加网格容器:
<div id="gameGrid"></div>
2. 初始化网格与按钮逻辑
const gameGrid = document.getElementById('gameGrid'); // 基础网格样式(可迁移至CSS文件优化) gameGrid.style.display = 'grid'; gameGrid.style.gridTemplateColumns = `repeat(${gridSize}, 1fr)`; gameGrid.style.gap = '5px'; // 遍历游戏矩阵生成按钮 for (let row = 0; row < gridSize; row++) { for (let col = 0; col < gridSize; col++) { const tileType = juegoTablero[row][col]; const imageList = imageNames[tileType]; if (!imageList) continue; const button = document.createElement('button'); button.style.width = '100px'; button.style.height = '100px'; // 随机生成初始图片索引 let currentIndex = Math.floor(Math.random() * imageList.length); // 用data属性存储当前索引,实现按钮独立状态管理 button.dataset.currentIndex = currentIndex; // 设置初始背景图 button.style.backgroundImage = `url(${imageList[currentIndex]})`; button.style.backgroundSize = 'cover'; // 绑定点击切换事件 button.addEventListener('click', () => { currentIndex = (parseInt(button.dataset.currentIndex) + 1) % imageList.length; button.dataset.currentIndex = currentIndex; button.style.backgroundImage = `url(${imageList[currentIndex]})`; }); gameGrid.appendChild(button); } }
关键逻辑说明
- 随机初始图片:通过
Math.floor(Math.random() * imageList.length)生成对应图片数组的随机索引,作为按钮初始显示的图片 - 循环切换:点击时用
(currentIndex + 1) % imageList.length计算下一个索引,利用取模运算实现循环(当索引到数组末尾时,自动回到起始位置) - 独立状态管理:使用按钮的
data-current-index属性存储当前显示的图片索引,避免全局变量污染,让每个按钮独立维护自身切换状态
内容的提问来源于stack exchange,提问作者filip
相关产品推荐
相关产品推荐

