Я пытаюсь сделать игру на линкоре.Я искал повсюду и не мог понять это после примерно 10 часов исследований.
Проблема в том, что, хотя я пытался сделать глубокую копию с Array.from
, изменение массива plateauAfter
также меняетмассив plateauBefore
.
//function which make a two-dimensional array
function plateau() {
let plateau = new Array();
for (let i = 0; i < 10; i++) {
plateau[i] = new Array();
for (let j = 0; j < 10; j++) {
plateau[i][j] = '[]';enter code here
}
}
return plateau;
}
let CPU = {
navire: [
{
PorteAvion: 5,
Position: ['B', 3],
Direction: 'bas',
Symbol: '[P]'
},
{
SousMarin: 4,
Position: ['D', 1],
Direction: 'droite',
Symbol: '[S]'
},
{
Fregate: 3,
Position: ['E', 4],
Direction: 'gauche',
Symbol: '[F]'
}
]
}
function placementBateau(plateau, typeNavire, position, direction, symbol) {
let plateauBefore = Array.from(plateau);
let plateauAfter = Array.from(plateau);
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 < typeNavire; i++) {
if (-1 in plateauAfter[row]) {
console.log('Le navire dépasse du plateau ! recommancer svp');
return plateauBefore;
} else {
switch (direction) {
case 'haut':
try {
plateauAfter[row - i][column] = symbol;
break;
} catch (error) {
console.log('Le navire dépasse du plateau ! recommancer svp');
return plateauBefore;
}
case 'bas':
try {
plateauAfter[row + i][column] = symbol;
break;
} catch (error) {
console.log('Le navire dépasse du plateau ! recommancer svp');
return plateauBefore;
}
case 'gauche':
try {
plateauAfter[row][column - i] = symbol;
break;
} catch (error) {
console.log('Le navire dépasse du plateau ! recommancer svp');
return plateauBefore;
}
case 'droite':
try {
plateauAfter[row][column + i] = symbol;
break;
} catch (error) {
console.log('Le navire dépasse du plateau ! recommancer svp');
return plateauBefore;
}
};
}
}
return plateauAfter;
}
let plateauCPU = plateau();
plateauCPU = placementBateau(plateauCPU, CPU.navire[0].PorteAvion, CPU.navire[0].Position, CPU.navire[0].Direction, CPU.navire[0].Symbol);
plateauCPU = placementBateau(plateauCPU, CPU.navire[1].SousMarin, CPU.navire[1].Position, CPU.navire[1].Direction, CPU.navire[1].Symbol);
plateauCPU = placementBateau(plateauCPU, CPU.navire[2].Fregate, CPU.navire[2].Position, CPU.navire[2].Direction, CPU.navire[2].Symbol);
console.log(plateauCPU);