如何用随机位置填充数组

时间:2018-07-20 04:09:27

标签: javascript

我在玩《战舰》游戏,游戏板由10 x 10的正方形阵列组成:

const board = [
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0.0.0.0,0,0,0,0,0,0]
    ]

我想用数字2的形式在船上装满船,这意味着船还活着,并且已经将游戏更改为例如-1以了解船被击中了。我能够在初始化期间使用随机位置填充游戏板,但问题是飞船彼此接触,您可能会认为飞船在开始时的位置彼此不接触。他们之间的距离是至少一个空笼子的距离。

1 个答案:

答案 0 :(得分:0)

这是示例代码。也许这会对您有所帮助。

const board = [
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0],
      [0,0,0,0,0,0,0,0,0,0]
    ]

    xMax=9;
    yMax=9   

    function placeBoat(numberOfBoat, fillWith){
        boatPlaced=0;
        while(boatPlaced < numberOfBoat){
            var randX=Math.floor(Math.random() * 10);
            var randY=Math.floor(Math.random() * 10);
            ok=true;
            if(randX!=0 && randY!=0){
              if(board[randX-1][randY]!=0){
                ok=false;
              }
              if(board[randX-1][randY-1]!=0){
                ok=false;
              }
              if(board[randX][randY-1]!=0){
                ok=false;
              }
            }
            else if(randX!=0){
              if(board[randX-1][randY]!=0){
                ok=false;
              }
            }
            else{
              if(board[randX][randY-1]!=0){
                ok=false;
              }
            }

            if(randX!=xMax && randY!=yMax){
              if(board[randX+1][randY]!=0){
                ok=false;
              }
              if(board[randX+1][randY+1]!=0){
                ok=false;
              }
              if(board[randX][randY+1]!=0){
                ok=false;
              }
            }
            else if(randY!=yMax){
               if(board[randX][randY+1]!=0){
                ok=false;
              }
            }
            else{
               if(board[randX][randY+1]!=0){
                ok=false;
              }
            }
            if(randX!=0 && randY!=yMax){
              if(board[randX-1][randY+1]!=0){
                ok=false;
              }
            }
            if(randX!=xMax && randY!=0){
              if(board[randX+1][randY-1]!=0){
                ok=false;
              }
            }
            if(board[randX][randY]!=0){
              ok=false;
            }


            if(ok){
              board[randX][randY]=fillWith;
              boatPlaced++;
            }
        }
    }  
    placeBoat(1,'L');
    placeBoat(1,'I');
    placeBoat(2,'.');