益智游戏:我如何检查可排序的列表项是否在正确的位置

时间:2016-12-17 19:38:45

标签: javascript jquery

我正在用Javascript构建一个3x3益智游戏。

 <script type="text/javascript">

    window.onload = populate;

    var imgArray = new Array("images/Untitled-0.png","images/Untitled-1.png","images/Untitled-2.png","images/Untitled-3.png","images/Untitled-4.png","images/Untitled-5.png","images/Untitled-6.png","images/Untitled-7.png","images/Untitled-8.png");

    var usedImg = new Array()

    var itemArray = new Array ("item0", "item1", "item2", "item3", "item4", "item5", "item6", "item7", "item8")

    var div = document.getElementById("pieces");

    var list = document.getElementsByTagName('li')

    function populate(){



        for (i=0; i<list.length;i++){

                var randomNum = Math.floor(Math.random()*imgArray.length);//generates a random #

                var img = new Image(); // creates a new image object
                img.src = imgArray[randomNum]; //source of the image is based on the random # and correlating item in imgArray

                do {
                    randomNum = Math.floor(Math.random()*imgArray.length);
                    img.src = imgArray[randomNum]; //generates a new number
                } while (usedImg[img.src]); // but only if the source of the image is in used images


                usedImg[img.src] = true; //copies img.src to used image

                var imgPlace=document.createElement('img'); //instruct it to create an img tag
                imgPlace.src=img.src; //defines source

                var item = list[i]

                list[i].id = itemArray[randomNum];


                list[i].appendChild(imgPlace);

        };


        $( function() {
            $( "#pieces" ).sortable({
                cancel: ".ui-state-disabled"
            });
            $( "#pieces" ).disableSelection();
          } );

        do {list[0].className = "ui-state-disabled"}
        while (list[0].id = "item0")
};
</script>

我已对其设置,以便在加载页面时图片随机填充HTML中的<li>标记(例如,随机标记为id="item0"并且图片为src="untitled-0" )可以使用sortable() JQueryUI在页面上拖动图像来对这些项目进行排序。实际上,当一件物品移动到特定空间时,所有其他件都相应地移动。我想构建它,以便当一个片段位于正确的<li>插槽中时,它会变得不合格。理想情况下,点击后它会再次排序。

最简单的方法似乎是为每个部分编写一行代码。我试过了

if (list[0].id = "item0") {
 list[0].className = "ui-state-disabled"}

以及

do {list[0].className = "ui-state-disabled"}
    while (list[0].id = "item0")

具有相同的结果,在function populate后,无论id如何,list[0]都会立即生成unsortable。我还在学习,但这真让我难过。任何帮助将不胜感激。

生成的html:

<ul id="pieces" class="ui-sortable">

  <li id="item5" class="ui-state-disabled ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-5.png"></li>
  <li id="item3" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-3.png"></li>
  <li id="item6" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-6.png"></li>
  <li id="item1" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-1.png"></li>
  <li id="item2" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-2.png"></li>
  <li id="item7" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-7.png"></li>
  <li id="item4" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-4.png"></li>
  <li id="item0" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-0.png"></li>
  <li id="item8" class="ui-sortable-handle"><img src="file:///E:/Puzzle/images/Untitled-8.png"></li>

</ul>

2 个答案:

答案 0 :(得分:0)

当您使用单个等于字符=时,您要为list[0].id分配新值,而不是比较它。尝试:

if (list[0].id === "item0") {
   list[0].className = "ui-state-disabled"
}

答案 1 :(得分:0)

您可以执行禁用以响应jQueryUI stop事件,将其传递给sortable方法,如下所示:

sortable({
    stop: function() {
        // Iterate over all the items and check their positions
        $('li').each(function (i) {
            // Turn disabled class on or off, depending on position:
            $(this).toggleClass('ui-state-disabled', $(this).data('num') === i);
        });
    }
})

您还可以应用其他改进措施。例如,您可以改进选择随机序列的方式,这样您就不需要在选择未使用的数字之前重试。

请注意,虽然您可以禁用拖动项目,但如果您将项目移到已禁用的项目上,它们仍会移动:这也会更改这些禁用项目的位置。

这是一个工作片段(具有不同的图像位置:根据需要进行调整):

$(function () {
    var ids = [];
    $('li').each(function (i) {
        ids.push(i);
    });
    $('li').each(function (i) {
        var randomNum = Math.floor(Math.random() * ids.length);// pick random index
        // translate it to original index, and remove
        randomNum = ids.splice(randomNum, 1)[0]; 
        // Assign id of chosen image to list item
        $(this).data('num', randomNum)
            // Assign chosen image to a new img element and append it to item
            .append($('<img>')
                .prop('height', 20).prop('width', 20) // size set for demo only
                // TODO: Adapt image location to 'images/Untitled-' + randomNum + '.png'
                .prop('src', 'https://www.cs.uic.edu/~troy/fall05/cs340/mp2images/' 
                              + randomNum + '.gif'));
    });

    $( "#pieces" ).sortable({
        cancel: ".ui-state-disabled",
        stop: function() {
            // Iterate over all the items and check their positions
            $('li').each(function (i) {
                // Turn disabled class on or off, depending on position:
                $(this).toggleClass('ui-state-disabled', $(this).data('num') === i);
            });
        }
    }).disableSelection();
});
.ui-state-disabled { background-color: #ccc }
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/jquery-ui-git.js"></script>
<ul id="pieces">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>