<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<script>
var a = new Array();
for (i = 0 ;i < 4 ; i++)
{
a[i] = new Array();
for (j = 0 ; j < 4 ; j ++)
a[i][j] = Math.floor(Math.random() * 3);
}
function dump(t)
{
console.log("-------");
for (i=0;i<4;i++)
{
console.log(t[i]);
}
console.log("-------");
}
dump(a);
function left(t,i)
{
var len = t[i].length;
for (j=0;j<len-1;j++)
{
if (t[i][j] == 0 && t[i][j+1] != 0)
{
temp = t[i][j];
t[i][j] = t[i][j+1];
t[i][j+1] = temp;
left(t,i);
}
}
}
function right(t,i)
{
var len = t[i].length;
for (j=len-1;j>0;j--)
{
if (t[i][j] == 0 && t[i][j-1] != 0)
{
temp = t[i][j];
t[i][j] = t[i][j-1];
t[i][j-1] = temp;
right(t,i);
}
}
}
function up(t,j)
{
var len = t.length;
for (i=0;i<len-1;i++)
{
if (t[i][j] == 0 && t[i+1][j] != 0)
{
temp = t[i][j];
t[i][j] = t[i+1][j];
t[i+1][j] = temp;
up(t,j);
}
}
}
function down(t,j)
{
var len = t.length;
for (i=len-1;i>0;i--)
{
if (t[i][j] == 0 && t[i-1][j] != 0)
{
temp = t[i][j];
t[i][j] = t[i-1][j];
t[i-1][j] = temp;
down(t,j);
}
}
}
for (j=0;j<4;j++)
down(a,j);
dump(a);
for(i=0;i<4;i++)
right(a,i);
dump(a);
</script>
<body>
</body>
</html>
转载于:https://my.oschina.net/xmanjn/blog/263172