基于jquery实现九宫格拼图小游戏

2020-05-17 06:18:02易采站长站整理

当然,只有在空白div旁边的图片才能与其互换。不然游戏就太简单了。如何实现?下面先使用一种比较笨的方式来实现。


<script>
$(function(){
var menu = {
"1":["2","4"],
"2":["1","3","5"],
"3":["2","6"],
"4":["1","5","7"],
"5":["2","4","6","8"],
"6":["3","5","9"],
"7":["4","8"],
"8":["5","7","9"],
"9":["6","8"] }
$('.in').click(function(){
var click_num = $(this).index()+1;
var no_see_num = $('.no_see').index()+1;
var arr = menu[no_see_num];
if(jQuery.inArray(String(click_num), arr)=='-1'){
//这里是无法交换位置的逻辑。可以做点什么。
}else{
var t = $(this).clone();
$('.no_see').before(t);
$(this).before($('.no_see'));
t.before($(this))
t.remove();
}
})
})
</script>

是的,这种方法很蠢,但是可以实现。通过数组的方式,先找到空白div,再查看空白div所在位置四周有哪些位置的图片可以与其交换。

当然,九宫格使用这样的方式来实现没有问题,毕竟数组是可列的。但是如果变成16宫格,36宫格呢?先不说要去列数组,还要修改代码。这样就很费劲了。所以我需要通过别的方式,让代码以后扩展更容易。

通过算法保证互换条件


<script>
$(function(){

$('.in').click(function(){
var tmp = false;
var click_num = $(this).index();
var no_see_num = $('.no_see').index();

var click_x = click_num % 3;
var click_y = Math.floor(click_num / 3);

var no_see_x = no_see_num % 3;
var no_see_y = Math.floor(no_see_num / 3);

if (click_x==no_see_x) { //同一行
if (click_y==no_see_y+1||click_y==no_see_y-1) {
tmp = true; //保证相邻
}
}else if (click_y==no_see_y) { //同一列
if (click_x==no_see_x+1||click_x==no_see_x-1) {
tmp = true; //保证相邻
}
}

if (tmp) {
var t = $(this).clone();
t.addClass('bit');
$('.no_see').before(t);
$(this).before($('.no_see'));
t.before($(this))
t.remove();
}

})

})
</script>

算法看起来会比较乱。简单的说是通过求余和相除取最小整数的方式来计算。

画几个表可能就清楚了。

1.在九宫格下每个图的顺序如下。

这里写图片描述

2.在九宫格下每个位置求余后的值如下。