const maze = [[1,1,1,1,1,1,1],
[1,0,0,0,0,0,3],
[1,0,1,0,1,0,1],
[0,0,1,0,0,0,1],
[1,0,1,0,1,0,1],
[1,0,0,0,0,0,1],
[1,2,1,0,1,0,1]]
function mazeRunner(maze, directions) {
const mazeCopy = maze.slice(0)
let playerPos = 0
let finishPos = 0
// Поиск позиции игрока
mazeCopy.forEach((row, posRow) => {
row.forEach((value, posCell) => {
if (value == 2) playerPos = [posRow, posCell]
else if (value == 3) finishPos = [posRow, posCell]
})
})
// N - top, E - right, S - down, W - left
// Передвижение
for (direction of directions) {
// Если идём наверх и верхняя клетка - пол (0 в матрице)
if (direction == 'N' && mazeCopy[playerPos[0] - 1][playerPos[1]] != 1) {
mazeCopy[playerPos[0]][playerPos[1]] = 0
mazeCopy[--playerPos[0]][playerPos[1]] = 2
} else if (direction == 'E' && mazeCopy[playerPos[0]][playerPos[1] + 1] != 1) {
mazeCopy[playerPos[0]][playerPos[1]] = 0
mazeCopy[playerPos[0]][++playerPos[1]] = 2
} else if (direction == 'S' && mazeCopy[playerPos[0] + 1][playerPos[1]] != 1) {
mazeCopy[playerPos[0]][playerPos[1]] = 0
mazeCopy[++playerPos[0]][playerPos[1]] = 2
} else if (direction == 'W' && mazeCopy[playerPos[0]][playerPos[1] - 1] != 1) {
mazeCopy[playerPos[0]][playerPos[1]] = 0
mazeCopy[playerPos[0]][--playerPos[1]] = 2
} else {
// Врезались в стену
return 'Dead'
}
// Финиш достигнут
if (playerPos[0] == finishPos[0] && playerPos[1] == finishPos[1]) {
return 'Finish'
}
}
// Не дошли до финиша
return 'Lost'
}
console.table(mazeRunner(maze, ["N","N","N","N","N","E","E","E","E","E"]))
console.table(maze)
// В функции я работал тоглько с mazeCopy (копией массива), а не с самим maze, почему тогда после выполнения функции я получаю измененный maze ([...maze] тоже не работает)?