Javascript jQuery图像难题:图像随机化问题

Javascript jQuery图像难题:图像随机化问题,javascript,jquery,Javascript,Jquery,我试图让图像片段随机化,但在单击“随机化”按钮时不会重叠。相反,它们开始重叠。有没有关于如何将图像随机或随机排列的想法 完整代码如下: 尝试随机化图像的JavaScript代码: $('button').click(function() { for (var i = 0; i < 100; i++) { var randomN = Math.floor(Math.random() * 15) + 1; console.log(randomN);

我试图让图像片段随机化,但在单击“随机化”按钮时不会重叠。相反,它们开始重叠。有没有关于如何将图像随机或随机排列的想法

完整代码如下:

尝试随机化图像的JavaScript代码:

$('button').click(function() {
    for (var i = 0; i < 100; i++) {
        var randomN = Math.floor(Math.random() * 15) + 1;
        console.log(randomN);
        var imageBox = $('#board').children("div:nth-child(" + randomN + ")");
        console.log(imageBox);
        Move(imageBox, 175);
    }
});
$(“按钮”)。单击(函数(){
对于(变量i=0;i<100;i++){
var randomN=Math.floor(Math.random()*15)+1;
console.log(随机数);
var-imageBox=$('#board').children(“div:nth child(“+randomN+”));
控制台日志(imageBox);
移动(imageBox,175);
}
});
完整的JavaScript代码如下:

 $(document).ready(function() {
     var zi = 1;
     var EmptySquare = 16;

     $.fn.extend({
         fifteen:

             function(square_size) {
             var gameObjectElement = '#' + $(this).attr('id');

             var sqSize = square_size + 'px';
             var boardSize = (square_size * 4) + 'px';

             $(gameObjectElement).html('<div id="board"></div>');

             $('#board').css({
                 position: 'absolute',
                 width: boardSize,
                 height: boardSize,
                 border: '1px solid gray'
             });

             for (var i = 0; i < 16; i++) {
                 $('#board').append("<div class='" + i + "' style='left:" + ((i % 4) * square_size) + "px; top: " + Math.floor(i / 4) * square_size + "px; width: " + square_size + "px; height: " + square_size + "px; background-position: " + (-(i % 4) * square_size) + "px " + -Math.floor(i / 4) * square_size + "px; '></div>");

                 // Select the children of #board ID that are divs, and the 16th one, then make backgroundImage nothing, and background color of white. 
                 // This emptys the 16th square.
                 $('#board').children("div:nth-child(" + EmptySquare + ")").css({
                     backgroundImage: "",
                     background: "#ffffff"
                 });

                 // Attach a click event to each of the squares, or divs.
                 $('#board').children('div').click(function() {
                     Move(this, square_size);
                 });

                 $('button').click(function() {
                     for (var i = 0; i < 100; i++) {
                         var randomN = Math.floor(Math.random() * 15) + 1;
                         console.log(randomN);
                         var imageBox = $('#board').children("div:nth-child(" + randomN + ")");
                         console.log(imageBox);
                         Move(imageBox, 175);
                     }

                 });
             }
         }
     });

     function Move(clicked_square, square_size) {
         var movable = false;

         // oldx is really just empty square x and empty square y
         // swap the old with the new, just make it so new has x and y for top and bottom of the empty spot

         var empty_x = $('#board').children("div:nth-child(" + EmptySquare + ")").css('left');
         var empty_y = $('#board').children("div:nth-child(" + EmptySquare + ")").css('top');

         var image_x = $(clicked_square).css('left');
         var image_y = $(clicked_square).css('top');

         // parseInt is used because the oldy has 'px' in it, you just want the number
         // check to see if clicked square or image_x and image_y is north of empty square
         if (empty_x == image_x && image_y == (parseInt(empty_y) - square_size) + 'px') movable = true;

         // check to see if clicked square is south of empty square, so its y would be more, so +
         if (empty_x == image_x && image_y == (parseInt(empty_y) + square_size) + 'px') movable = true;

         // check to see if clicked square is left of empty square, which makes left less, or x less
         if ((parseInt(empty_x) - square_size) + 'px' == image_x && image_y == empty_y) movable = true;

         // check to see if clicked square is right of empty square, so left is more
         if ((parseInt(empty_x) + square_size) + 'px' == image_x && image_y == empty_y) movable = true;

         if (movable) {
             // increment z-index up from 1 so that new tile is on top of others
             $(clicked_square).css('z-index', zi++);

             // move image square into the empty square position using animate
             // Durations are given in milliseconds; higher values indicate slower animations, not faster ones. 200 is ms
             $(clicked_square).animate({
                 left: empty_x,
                 top: empty_y
             }, 100, function() {
                 // move empty square where image square you just moved was
                 $('#board').children("div:nth-child(" + EmptySquare + ")").css('left', image_x);
                 $('#board').children("div:nth-child(" + EmptySquare + ")").css('top', image_y);
             });
         }
     }

     // initialize game with 175 by 175 squares inside the #game_object div
     $('#game_object').fifteen(175);
 });
$(文档).ready(函数(){
var-zi=1;
var EmptySquare=16;
$.fn.extend({
十五:
功能(方形尺寸){
var gameObjectElement='#'+$(this.attr('id');
var sqSize=平方_大小+px;
var boardSize=(正方形大小*4)+‘px’;
$(gameObjectElement).html(“”);
$('#board').css({
位置:'绝对',
宽度:boardSize,
身高:木板尺寸,
边框:“1px纯色灰色”
});
对于(变量i=0;i<16;i++){
$('董事会')。追加(“”);
//选择#board ID的子项,即div和第16个,然后使backgroundImage为空,背景色为白色。
//这将清空第16个广场。
$(“#board”).children(“div:nth child(“+EmptySquare+”).css({
背景图片:“,
背景:“ffffff”
});
//将单击事件附加到每个正方形或div。
$('#board')。子项('div')。单击(函数(){
移动(此为方形尺寸);
});
$(“按钮”)。单击(函数(){
对于(变量i=0;i<100;i++){
var randomN=Math.floor(Math.random()*15)+1;
console.log(随机数);
var-imageBox=$('#board').children(“div:nth child(“+randomN+”));
控制台日志(imageBox);
移动(imageBox,175);
}
});
}
}
});
功能移动(点击方格,方格大小){
var=false;
//oldx实际上只是空的正方形x和空的正方形y
//把旧的换成新的,只是让它成为新的,让x和y代表空点的顶部和底部
var empty_x=$('#board').children(“div:nth child(“+EmptySquare+”)).css('left');
var empty_y=$(“#board”).children(“div:nth child(“+EmptySquare+”)).css(“top”);
var image_x=$(单击_square.css('left');
var image_y=$(单击了_square.css('top');
//之所以使用parseInt,是因为其中包含“px”,您只需要数字
//检查单击的正方形或图像x和图像y是否位于空正方形的北部
if(empty_x==image_x&&image_y==(parseInt(empty_y)-square_size)+“px”)movable=true;
//检查一下点击的方块是否在空方块的南部,所以它的y会更大,所以+
if(empty_x==image_x&&image_y==(parseInt(empty_y)+square_size)+“px”)movable=true;
//检查单击的正方形是否为空正方形的左侧,这会使左侧变小,或使x变小
如果((parseInt(empty_x)-square_size)+'px'==image_x&&image_y==empty_y)movable=true;
//检查点击的方块是否在空方块的右边,所以左边的方块更多
如果((parseInt(empty_x)+square_size)+'px'==image_x&&image_y==empty_y)movable=true;
如果(可移动){
//将z索引从1向上递增,以便新磁贴位于其他磁贴之上
$(点击了“_square”).css('z-index',zi++);
//使用“动画”将图像方形移动到空方形位置
//持续时间以毫秒为单位;值越高表示动画速度越慢,而不是速度越快。200是毫秒
$(单击方)。设置动画({
左:空_x,
顶部:空的
},100,函数(){
//将空方块移动到刚才移动的图像方块所在的位置
$('#board').children(“div:nth child(“+EmptySquare+”)).css('left',image_x));
$(“#board”).children(“div:nth child”(+EmptySquare+)).css('top',image#y);
});
}
}
//在#game#u object div中使用175×175个方块初始化游戏
$(“游戏对象”)。十五(175);
});
您的随机函数(
Math.floor(Math.random()*15)+1;
)不能保证没有重复的随机数,因此在随机化后,两个或多个图像很有可能占据相同的空间

也许你可以制作一个包含图像索引号的数组,然后将其洗牌。在线上有大量的数组洗牌示例,例如:

我很快写了一个简单的例子——它从原始数组中弹出一个随机元素,并将其推入一个新数组,直到所有插槽都被填满。我认为它可以很好地与您的代码配合使用:

函数shuffle(){
var-arr=[1,2,3,4,5,6,7,8,9];
var newArr=[];
var len=阵列长度;
while(newArr.length!=len){
新arr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
}
警报(newArr);
}

Shuffle
就像Shomz已经回答的那样,你想洗牌你的图像。(偷自)


谢谢你,@dippas!(哈哈,我比那个知道什么时候的人投了更高的票)另外,我在我的答案中添加了一个简单的答案。非常感谢你们所有人的帮助。我根据这条评论创建了一个洗牌函数:不客气,@klamertime!看起来不错,顺便说一句,拉比
function shuffle(array) {
    var currentIndex = array.length,
        temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {

        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;
}

$('button').click(function() {
    var positions = [];
    $('#board div').each(function(idx, div) {
        positions.push($(div).offset());
    });

    shuffle(positions);

    $('#board div').each(function(idx, div) {
        $(div).offset(positions[idx]);
    });
});