jQuery Image Puzzle:图像随机化问题

时间:2015-06-23 23:25:34

标签: javascript jquery

当我点击“随机化”按钮时,我试图使图像片随机化但不重叠。相反,他们开始重叠。关于如何随机化图像或将其改组的任何想法?

此处的完整代码: https://jsfiddle.net/Klammertime/guus9df7/

尝试随机化图片的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);
    }
});

此处的完整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);
 });

2 个答案:

答案 0 :(得分:2)

您的随机函数(Math.floor(Math.random() * 15) + 1;)并不保证没有重复的随机数,因此在您随机化它们后,很有可能会有两个或多个图像占据相同的空间。

也许你可以制作一个包含图像索引号的数组,然后将其改组。在线有大量的数组shuffle示例,例如:https://stackoverflow.com/a/6274381/965907

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

&#13;
&#13;
function shuffle() {
  var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  var newArr = [];
  var len = arr.length;
  while (newArr.length != len) {
    newArr.push(arr.splice(Math.floor(Math.random() * arr.length), 1));
  }
  alert(newArr);
}
&#13;
<button onclick="shuffle()">Shuffle</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

就像Shomz已经回答的那样,你想要洗牌你的图像。 (从How to randomize (shuffle) a JavaScript array?偷来)

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]);
    });
});

fiddle