资源描述
一、先看代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>拼图游戏</title>
</head>
<body>
<table>
<tr>
<td><img src="" onmousedown="move(0,0,1,0,3)" height="97" width="97"></td>
<td><img src="" onmousedown="move(1,1,1,0,3)" height="97" width="97"></td>
<td><img src="" onmousedown="move(2,1,0,0,3)" height="97" width="97"></td>
</tr>
<tr>
<td><img src="" onmousedown="move(3,0,1,3,3)" height="97" width="97"></td>
<td><img src="" onmousedown="move(4,1,1,3,3)" height="97" width="97"></td>
<td><img src="" onmousedown="move(5,1,0,3,3)" height="97" width="97"></td>
</tr>
<tr>
<td><img src="" onmousedown="move(6,0,1,3,0)" height="97" width="97"></td>
<td><img src="" onmousedown="move(7,1,1,3,0)" height="97" width="97"></td>
<td><img src="" onmousedown="move(8,1,0,3,0)" height="97" width="97"></td>
</tr>
</table>
<script type="text/javascript" language="javascript">
index=new Array(1,1,1,1,1,1,1,1,0);
for(i=1;i<10;i++){
document.images[i-1].src="pic/psb_0"+i+i+".jpg";
}
function move(imageindex,left,right,up,down){
if(index[imageindex-left]==0){
transfer(imageindex,imageindex-left);
}
if(index[imageindex+right]==0){
transfer(imageindex,imageindex+right);
}
if(index[imageindex-up]==0){
transfer(imageindex,imageindex-up);
}
if(index[imageindex+down]==0){
transfer(imageindex,imageindex+down);
}
}
function transfer(image1,image2){
img=new Image();
img.src=document.images[image1].src;
document.images[image1].src=document.images[image2].src;
document.images[image2].src=img.src;
index[image2]=1;
index[image1]=0;
}
</script>
</body>
</html>
二、最终效果:
三、分析
(第9张是空白图,,psb.jpg是完整图,,前面都是切割出来的碎片图)
1,先在<table>里规划好图片的位置和大小,三行三列,并给每个图片添加一个事件监听。
2,在<table>下面写javascript脚本,实现监听方法
index=new Array(1,1,1,1,1,1,1,1,0);
用来判断的, 1表示一般图片, 0表示空白图片.
用for循环给src赋值
算法: move()里传入要移动的图片下标(下标从0开始),以及移动到左右上下位置的步数.
判断左右上下移动的条件:
以左为例,只有当左边的图片是空白图时才可移动, 而空白图的index是0, 所以判断
如果 要移动的图片下标减去向左移动的步数(即等于左边图的index)为0, 则表示此处是一张空白图, 可以移动, 判断完后就开始交换两张图的src和index. 以此类推.
展开阅读全文