undefinedfix
Sign in

JS how to generate random position without repetition and a certain area can not appear?

silentPlanet edited in Sun, 13 Nov 2022

As shown in the figure, the gray areas appear randomly, do not overlap and exclude the yellow areas, and solve the problem.

image.png

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .demo {
      height: 350px;
      background: #f5f5f5;
      position: relative;
    }

    .demo .item {
      width: 50px;
      height: 50px;
      background: #f00;
      position: absolute;
      top: 0;
      left: 0;
    }

    .button {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: #ff0;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <div class="demo">
    <div class="item-list">

    </div>
    <div class="button"></div>
  </div>

  <script>
    let data = [1, 2, 3];
    let arr = [
      {
        top: 100,
        left: 0
      },
      {
        top: 0,
        left: 0
      },
      {
        top: 300,
        left: 150
      },
      {
        top: 350,
        left: 250
      }
    ]
    let resArr = '';
    data.forEach((v, i) => {
      console.log(sendNum(arr));
      resArr += `<div class="item" style="top:${sendNum(arr).top}px;left:${sendNum(arr).left}px">${v}</div>`
    });
    document.querySelector('.item-list').innerHTML = resArr;
    function sendNum(arr) { 
      return arr[Math.floor(Math.random() * arr.length)]; 
    };
  </script>
</body>

</html>
2 Replies
fbnmv
commented on Sun, 13 Nov 2022

Not in line with the rules again?

xtu
commented on Mon, 14 Nov 2022

1. Life is a two-dimensional array, which is used to represent the coordinates in the page.

[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. The position coordinates of the yellow area are represented in a two-dimensional array

[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0]
]

3. Once the Red Square appears, it will be represented once in the two-dimensional array. When the randomly generated coordinates are repeated, it will not be displayed

[1,0,0,0,0,0,0],
[0,1,0,0,0,1,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0],
[0,0,1,1,1,0,0]
]

Hope to help you.