Home > Back-end >  Filling multidimensional array in react
Filling multidimensional array in react

Time:06-11

I am trying to fill 10X10 minesweeper board and I am having problems adding bombs at random coordinates. All the cells on the board have their isBomb field as true when I am using console.log Also here is the stackblitz link https://stackblitz.com/edit/react-uqcox1?file=src/components/Board.js

import React, { useEffect, useState } from 'react'

const INITIAL_CELL = {
    isClicked: false,
    isBomb: false,
    isFlagged: false,
}

const CreateInitialBoard = () => {
    let board = Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => INITIAL_CELL))
    board = AddBombs(board);
    return board;
}

const AddBombs = (board) => {
    let _board = board;
    console.log(board, "before");
    let randomX, randomY, bombsAdded = 0;

    while (bombsAdded < BOMB_COUNT) {
        randomX = Math.floor(Math.random() * BOARD_SIZE);
        randomY = Math.floor(Math.random() * BOARD_SIZE);
        _board[randomX][randomY].isBomb = true;
        bombsAdded  ;
    }
    console.log(_board, "after");
    return _board
}

const BOARD_SIZE = 10;
const BOMB_COUNT = 10;

const INITIAL_BOARD = CreateInitialBoard();

export default function Board() {
    const [board, setBoard] = useState(INITIAL_BOARD);

    return (
        <div className='board'>
            {
                board.map((row, rowIndex) => {
                    return row.map((cell, cellIndex) => {
                        return (
                            <div key={`${rowIndex}-${cellIndex}`} className='cell'>
                                {rowIndex}, {cellIndex}
                            </div>
                        )
                    })
                })
            }
        </div>
    )
}

CodePudding user response:

You have to replace

let board = Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => INITIAL_CELL))

with

let board = Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => { return { ...INITIAL_CELL } })

What you did there was setting INITIAL_CELL's isBomb field to set true and then reusing it everywhere. Suggest you to check @ASDFGerte 's comment for further information.

  • Related