I'm in the process of creating my own Battleship game, and I've been researching for about 10 hours but haven't been able to crack it yet.
The issue I'm facing is related to making a deep copy using Array.from
; whenever I modify the plateauAfter
array, it also alters the plateauBefore
array.
//function to create a two-dimensional array
function plateau() {
let grid = new Array();
for (let i = 0; i < 10; i++) {
grid[i] = new Array();
for (let j = 0; j < 10; j++) {
grid[i][j] = '[]';enter code here
}
}
return grid;
}
let CPU = {
ships: [
{
AircraftCarrier: 5,
Position: ['B', 3],
Direction: 'down',
Symbol: '[P]'
},
{
Submarine: 4,
Position: ['D', 1],
Direction: 'right',
Symbol: '[S]'
},
{
Frigate: 3,
Position: ['E', 4],
Direction: 'left',
Symbol: '[F]'
}
]
}
function placeShip(grid, shipType, position, direction, symbol) {
let plateauBefore = Array.from(grid);
let plateauAfter = Array.from(grid);
let letter = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
let row = position[1] - 1;
let column = letter.indexOf(position[0]);
for (i = 0; i < shipType; i++) {
if (-1 in plateauAfter[row]) {
console.log('The ship exceeds the grid! Please try again.');
return plateauBefore;
} else {
switch (direction) {
case 'up':
try {
plateauAfter[row - i][column] = symbol;
break;
} catch (error) {
console.log('The ship exceeds the grid! Please try again.');
return plateauBefore;
}
case 'down':
try {
plateauAfter[row + i][column] = symbol;
break;
} catch (error) {
console.log('The ship exceeds the grid! Please try again.');
return plateauBefore;
}
case 'left':
try {
plateauAfter[row][column - i] = symbol;
break;
} catch (error) {
console.log('The ship exceeds the grid! Please try again.');
return plateauBefore;
}
case 'right':
try {
plateauAfter[row][column + i] = symbol;
break;
} catch (error) {
console.log('The ship exceeds the grid! Please try again.');
return plateauBefore;
}
};
}
}
return plateauAfter;
}
let gridCPU = plateau();
gridCPU = placeShip(gridCPU, CPU.ships[0].AircraftCarrier, CPU.ships[0].Position, CPU.ships[0].Direction, CPU.ships[0].Symbol);
gridCPU = placeShip(gridCPU, CPU.ships[1].Submarine, CPU.ships[1].Position, CPU.ships[1].Direction, CPU.ships[1].Symbol);
gridCPU = placeShip(gridCPU, CPU.ships[2].Frigate, CPU.ships[2].Position, CPU.ships[2].Direction, CPU.ships[2].Symbol);
console.log(gridCPU);