15个拼图只能使空的附近的数字/盒子可移动

时间:2014-11-22 14:15:14

标签: javascript jquery puzzle 8-puzzle

我尝试使用jquery和javascript创建一个15益智游戏(就像这个:http://migo.sixbit.org/puzzles/fifteen/)。我已经走了很远的代码,但现在我遇到了一个小问题。我的问题是,当我只希望左/右/下/上的空盒子可移动时,所有盒子/数字都是可移动的。

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script>

    $(document).ready(function(){ // Wait for the page to finish loading

      var currentBoard = new Array(' ','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15');

      //
      // Randomize the array values 
      for(i=0 ; i++<100 ; x = Math.floor(Math.random()*16), y = Math.floor(Math.random()*16), currentBoard[x] = currentBoard.splice(y, 1, currentBoard[x])[0]);


      repaint(); // Redraw puzzle board     

      //
      // Function repaint()
      // Redraw puzzle board
      function repaint(){
        currentString = "";
        for(i=1;i<17;i++){
          currentString += "<input type='button'  id='" + i + "' value='" + currentBoard[i-1] + "' />";
          if ( (i%4) == 0 ) currentString += "<br />";
        }
        $("#board").html(currentString);
      }

      //
      // Function used to swap elements in array currentBoard ; input is the element indexes
      function swapArrElems(index_a, index_b) {
          var temp = currentBoard[index_a];
          currentBoard[index_a] = currentBoard[index_b];
          currentBoard[index_b] = temp;
      }

      //
      // Wait for the upcoming click events from the puzzle board.
      $('#board').click(function(event){
        current = $(event.target).attr("id")-1;

        for(i=0;i<16;i++) if( currentBoard[i]==0 ) zeroIndex = i; // Get the index of the empty square

        swapArrElems(current, zeroIndex);
        repaint();

      });


     });

  </script>

  <style>
    input[type="button"] { width: 80px; height: 80px; font-size: 30px; }
  </style>
</head>


<body>

<div id="board">
</div>

0 个答案:

没有答案