skip to Main Content

I’m a beginner with only 2 months experience in front-end. I’m trying to make a simple web-grid game.

I’ve got a 10×10 grid table (grid container with 100 div child elements in it), and my goal is that, when the site is opened, a random grid item out of the 100 gets automatically selected, and when the user clicks on that randomly selected grid item, another grid item out of the 100 gets randomly selected automatically, and the previously selected item gets de-selected (color goes back to the default state for example).

I was thinking I could do something with Math.random, but I don’t know how. Any help or suggestions is appreciated!

HTML code is just

<div class="grid-container"></div>
  <div class="grid-item"></div>
  <div class="grid-item"></div>
  <!-- ... a hundred of these child elements for 10x10. -->
</div>

JavaScript is blank

3

Answers


  1. after creating 100 grids give them dynamic Id with using (for)
    then use below function:

    function getRandomInt(max) {
      return Math.floor(Math.random() * max);
    }
    
    getRandomInt(100)
    

    // it returns you a number between 1 to 100 then get the item as bellow:

    document.getElementById("returned number from getRandomInt function")
    

    and other step you want

    Login or Signup to reply.
  2. You will have to technically view each grid as a number to achieve what you stated above. So:

    1. Generate a list of random numbers from 1 – 100. Each number denotes a grid that you can show on the screen.

    2. You will need a state variable to store the selected grid (represented as a number). According to your question, you need a grid to be selected at random on load, so that means you will need to set the state variable to be equal to a random number from 1 – 100 on load. Whatever number is selected as random will denote the randomly selected grid on load.

    3. Whenever you click on a grid (technically a number), you set the state variable to the new grid click (number).

    4. You can then style as you want, you can assign a selected class(CSS) to the grid whose ID is the same as the state variable.

    Here is a rough example.

    index.html

    <div>
      <h2> GRID GAME </h2>
      <div class="grids-container"><div>
    </div>
    

    index.js

    let selectedGrid = null // state variable
    const gridContainer = document.querySelector('.grids-container')
    
    function randomInteger(min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    function generateGridIds (){
      return Array(100)
      .fill()
      .map((_, i) => i + 1);
    }
    
    // STEP 1: Generate a list of random numbers from 1 - 100
    const grids = generateGridIds()
    
    // STEP 2: State variable to store the selected grid
    const selectRandomGrid = randomInteger(1, 100)
    selectedGrid = selectRandomGrid
    
    /* Functions to generateGrid for HTML UI. Loop through the grids array (numbers) to get a grid item UI for each item in the array (1 - 100) */
    function generateGridHTML(grid) {
        return `<div 
                  class="grid-item${Number(selectedGrid) === Number(grid) 
                     ? ' selected' 
                     :''
                  }"
                >
                 ${grid}
                </div>`
    };
    
    function createGrid (){
      function createHTML() {
        let gridUI = "";
        grids.forEach(function(grid) {
          const genHTML = generateGridHTML(grid);
          gridUI += genHTML;
        })
        
        return gridUI;
      };
      
      gridContainer.innerHTML = createHTML()
    }
    
    // Invoke CreateGrid
    createGrid()
    
    
    /* Step 3: Whenever you click on a grid (technically a number), 
     you set the state variable to the new grid click (number). */
    
    document.body.addEventListener('click', function ( event ) {
      console.log({t:event.target.className})
      if( event.target.className == 'grid-item' ) {
        const grid = event.target.innerHTML
        selectedGrid = grid
        createGrid()
        console.log({selectedGrid, grid})
      };
    } );
    

    style.css

    /* Step 4: You can then style as you want, you can assign a selected
    class(CSS) to the grid whose ID is the same as the state variable.
    */
    
    .grids-container{
      display:grid;
       grid-template-columns: repeat(10, 1fr);
      margin-top:50px;
    }
    
    .grid-item{
      border:1px solid green;
      padding:20px;
      text-align:center;
      cursor:pointer;
    }
    
    .grid-item.selected{
       border:3px solid red;
    }
    
    Login or Signup to reply.
  3. I don’t think you necessarily even need to give each div an id; you could use its index in a querySelectorAll()

    //generate grid
    const gridCellCount = 100;
    for (g = 0; g < gridCellCount; g++) {
      const theDiv = document.createElement("div");
      theDiv.classList.add("grid-item");
      theDiv.innerText = g;
      document.querySelector(".grid-container").appendChild(theDiv);
    }
    
    function randomIntFromInterval(min, max) { // min and max included 
      return Math.floor(Math.random() * (max - min + 1) + min);
    }
    
    function selectOne() {
      const selected = randomIntFromInterval(0,gridCellCount-1);
      console.log(selected);
      
      document.querySelectorAll(".grid-item").forEach(
        (el,idx) => {
          el.classList.remove("selected");
          if (idx == selected) {
            el.classList.add("selected");
          }
        }
      );
    }
    
    selectOne()
    .selected {color: red;}
    <div class="grid-container"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search