1 实现效果视频
拼图1.0
2 功能实现思路
布局忽略
(小白学前端,不献丑了)
左侧拼图格
左侧4*4的拼图小格子
利用表格实现,规划好td的大小,给每个格子加上背景图片(将完整的图片裁剪为16张,命名规则为数字.png(1-16),利用二维数组存放四行四列的值从1-16,在遍历数组时,给他动态加上背景图片即可)item就是二维数组存的值,动态拼接上;photo是文件夹的名字images_1(或2,3,4)实现动态切换拼图图片
let print = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
function updateUI() {
print.forEach((subArr, i) => {
subArr.forEach((item, j) => {
tds[i * 4 + j].style.backgroundImage = "url(./images/" + photo + "/" + item +".png)";
if (isStart && i == x0 && j == y0) {
tds[i * 4 + j].style.border = "3px solid red";
} else {
tds[i * 4 + j].style.border = "";
}
})
})
更换拼图图片
先获取元素,给其绑定单击事件。产生随机[1-4]的索引值(我当前有image_x文件四个,命名从_1到_4所以我需要的索引是1-4),获取当前展示的拼图的_x,确保产生的随机值与上次不同,不同之后就动态拼接新的src,在调用上面实现的ui函数,实现切换背景。
changeBtn.onclick = function () {
isStart = false;
print = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
step=0;
let index = parseInt(Math.random() * 4) + 1;
let photo_id = look.src.split('/')[look.src.split('/').length - 2].split('_')[1];
while (index == photo_id) {
index = parseInt(Math.random() * 4) + 1;
}
photo = 'images_' + index;
look.src = "./images/" + photo + "/canzhaotu.png";
updateUI();
}
重置功能(开始游戏或者打乱拼图)
随机交换打乱顺序(1.0版)
随机索引,实现随机的交换,调用自实现ui函数动态拼接,达到背景的更换,实现打乱拼图效果。
获取对应元素,绑定点击事件,点击调用之后,完成相应的初始化,此时给求助按钮绑定点击事件,开始播放背景音乐。
let restBtn = document.getElementById('rest');
restBtn.onclick = function () {
step = 0;
isStart = true;
shuffle();
updateUI();
initEvent();
helpBtn.onclick = helpBake;
bgMusic.play();
}
// 打乱图片
function shuffle() {
print.forEach((subArr, i) => {
subArr.forEach((item, j) => {
let x = parseInt(Math.random() * 4);
let y = parseInt(Math.random() * 4);
let temp = print[i][j];
print[i][j] = print[x][y];
print[x][y] = temp;
})
})
}
initEvent函数
(给每一个td加点击事件)
1.0版本玩法不同,可以任意更换原始块(想要控制移动的块)
给每一个td也帮上点击事件,在点击时计算出对应的二维数组的i(行)和j(列)。tds是一维数组索引值从0-16,print二维数组,行索引0-3,列索引0-3。可以根据二维行列推出对应的移位tds中的索引位置,也可以反过来。
例如:
如果 是二维的第三行第三列(对应的行列索引是2,2),此时对应的td索引应该是10=2×4+2;index=i*(每一行的长度)+j;反过来就是i=向下取整[index/每行的长度],j=[index%每行的长度]
// 选择初始化位置
function initEvent() {
tds.forEach((td, index) => {
td.onclick = function () {
let x = parseInt(index / 4);
let y = parseInt(index % 4);
x0 = x;
y0 = y;
updateUI();
}
})
}
给移动按钮加点击事件
当然,也加了键盘监听事件,监听上下左右键
leftBtn.onclick = function () {
if (isStart) {
direction = 'left';
move(direction);
}
}
rightBtn.onclick = function () {
if (isStart) {
direction = 'right';
move(direction);
}
}
upBtn.onclick = function () {
if (isStart) {
direction = 'up';
move(direction);
}
}
downBtn.onclick = function () {
if (isStart) {
direction = 'down';
move(direction);
}
}
window.onkeyup = function (e) {
if (isStart) {
if (e.keyCode == 37) {
direction = 'left';
move(direction);
} else if (e.keyCode == 38) {
direction = 'up';
move(direction);
} else if (e.keyCode == 39) {
direction = 'right';
move(direction);
} else if (e.keyCode == 40) {
direction = 'down';
move(direction);
}
}
}
move函数
定义一个direction全局变量