I'm writing a function for a battleship game that creates a 8x8 grid, and then places two 'ships' at random positions within that grid:
//generates 8x8 board
const generateBoard = () => {
const gridRow = []
const gridContainer = []
for(let i=0; i<8; i++){
gridRow[i] = ['x']
gridContainer.push(gridRow)
}
return gridContainer
}
//puts ships at two random positions
const generateBoardWithShips = (board) => {
for (let i=0; i<2; i++) {
const x = Math.floor(Math.random() * 8);
const y = Math.floor(Math.random() * 8);
board[y][x] = ['🚢'];
coordinates.push(x,y)
}
return board
}
//I also have an entire grid saved to variable initialBoardState
const initialBoardState = [
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
[['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']]
]
What's confusing me is this: when I pass initialBoardState as an argument to generateBoardWithShips, it works as desired and creates an 8x8 grid with ships at two random positions.
However, when I pass the output of generateBoard (also an 8x8 grid) to generateBoardWIthTwoShips, the output is an grid with two ships in the same position on every row.
I've logged the output of createBoard and it is identical to initialBoardState, so if I'm putting the exact same input into generateBoardWithTwoShips, why is it giving me different outputs?
Summary:
const grid = generateBoard()
generateBoardWithTwoShips(initialBoardState) : works fine
generateBoardWithTwoShips(grid) : prints 2 ships, but in every row