【问题标题】:The fifteen puzzle game十五个益智游戏
【发布时间】:2017-02-17 11:09:36
【问题描述】:

我正在做一个 15 人的益智游戏,我希望你只能点击空白框旁边的数字,但现在你可以点击任何地方...如何更改?我认为你可以为列和行做一个 if 语句..

<!DOCTYPE html>

<html>
<head>
  <title>The Fifteen Puzzle Game</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

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

    $(document).ready(function(){ 

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

   
     
	  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     

      //
      // Funktion 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 swapArrElems(index_a, index_b) {
          var temp = currentBoard[index_a];
          currentBoard[index_a] = currentBoard[index_b];
          currentBoard[index_b] = temp;
      }

     
      $('#board').click(function(event){
        current = $(event.target).attr("id")-1;

        for(i=0;i<16;i++) if( currentBoard[i]==0 ) zeroIndex = i; 
        swapArrElems(current, zeroIndex);
        repaint();
        
      });


     });
    
  </script>

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

<body>

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

</body>
</html>

【问题讨论】:

    标签: javascript html puzzle


    【解决方案1】:

    根据我理解您的代码的方式,您有 16 个按 4 行标识的按钮。每次单击按钮时,该按钮的数组值和空白按钮交换。你快到了。这里最重要的细节是按钮 ID,它们始终保持不变。

    你需要在点击按钮的ID和空白按钮的ID之间添加一个比较,这需要一个条件。

    我不会为您提供代码,因为我不想直接给出答案。我将为您提供逻辑:

    在你的最后一个函数中,在 if( currentBoard[i]==0 ) zeroIndex = i;

    **Else if** the id(clicked button) == id(blank button)-1. OR id(blank button)+1. OR
    id(blank button)-4. OR id(blank button)+4 ........
    
    Swap the elements.
    
    Else
    
    don't swap the elements.
    

    祝你好运!希望这会有所帮助。

    【讨论】:

      【解决方案2】:
      for (i = 0; i < 16; i++) {
        if (currentBoard[i] == 0) {
          if ((i - current) == 4 || (current - i) == 4 || (current - i) == 1 || (i - current) == 1) {
            zeroIndex = i;
            swapArrElems(current, zeroIndex);
            repaint();
          }
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-18
        • 2011-03-05
        相关资源
        最近更新 更多