How would I find positions relative to an index of an array of arrays

46 views Asked by At

I'm attempting to make Minesweeper as an exercise and I'm starting out by generating a board, it looks somewhat like this:

[
  [ null, null, null, null, null, null ],
]
// OR new Array(5).fill(new Array(6).fill(null))

and I pick two random places on the board by merging all the arrays together; then surround each randomly targetted index with another string.

['1', 'B', '1', null, null, null, '1', '1', '1', null, null, null, null, null, null, null, null, null]
to
[
  [ '1', 'B', '1', null, null, null ],
  [ '1', '1', '1', null, null, null ],
  [ null, null, null, null, null, null ]
]

This is the code for the main function -- I added comments to explain what's going on

 function chooseRandom(arr,fill,fillCount) {
    let length = arr[0].length;
    arr = arr.flat(1);
    // combine all arrays
    while(fillCount > 0) {
        // if its filled with whatever then we don't need to worry about it
        if(arr.every(e=>e===fill)) break;
        // get a random index of the array
        let ind = Math.floor(Math.random() * arr.length);
        if(arr[ind] !== fill) { 
            // set it to 'B'
            arr[ind] = fill; --fillCount;
            // code check to fill in relative right
            if((ind+1) % length !== 0 && ind+1 < arr.length) arr[ind+1] = '1';
            // relative down
            if(ind+length < arr.length) arr[ind+length] = '1';
            // relative left
            if((ind-1) % length !== length-1 && ind-1 >= 0) arr[ind-1] = '1';
            // relative up
            if(ind-length >= 0) arr[ind-length] = '1';

            // relative down right
            if(ind+1+length < arr.length && (ind+1+length) % length !== 0) arr[ind+1+length] = "1";
            // down left
            // not sure why but it likes to appear on the right side when `ind` is set to 0 so i have to implement it differently
            if(ind-1+length < arr.length && ![1,(length-1)*-1].includes((ind+1-length) % length)) arr[ind-1+length] = "1";
            // up right
            if(ind+1-length < arr.length && (ind+1-length) % length !== 0) arr[ind+1-length] = "1";
            // up left
            if(ind-1-length < arr.length && (ind-1-length) % length !== length-1) arr[ind-1-length] = "1";
        };
    };
    // this is the chunking function from https://stackoverflow.com/a/8495740
    return chunk(arr,length);
};

console.log(chooseRandom(a,"B",1));

It definitely works-- but it looks quite messy with the if spam. How would I optimize this? I'm not even sure what it's called so I just call it "finding positions relative to an index of a ""birds eye view"" array".

0

There are 0 answers