JavaScript WebGrid type game

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

5

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;
}

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

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>

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật