gpt4 book ai didi

javascript - 访问交错数组中的元素

转载 作者:行者123 更新时间:2023-11-30 13:46:44 25 4
gpt4 key购买 nike

我开始编写一个在控制台打印的递归回溯迷宫系统,但我已经遇到了一个小问题,我无法从我的网格结构中设置线条,如下所示:

console.log("Teste de Labirinto - Recursive Backtracking")

let grid = []
let cells = []

const width = 8
const height = 10

for (let i = 0; i < width; i++){
cells.push(".")
}
for (let j = 0; j < height; j++){
grid.push(cells)
}

function printMaze(){
let line = " "
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
line += " " + grid[j][i] + " "
}
console.log(line)
line = " "
}
}

function createMazeBorder() {
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
if(i == 0) {
grid[j][i] = "X"
}
}
}
}

createMazeBorder()
printMaze()

如何在我的网格中创建一个“X”墙?我尝试了所有可能的“ifs”,并交换了“i”和“j”,widht,height,仍然做不到......谢谢你的时间。

最佳答案

好吧,解决了,因为我所有的单元格都有相同的引用,所以无法创建墙,有代码:

console.log("Teste de Labirinto - Recursive Backtracking")

let grid = []

const width = 8
const height = 10

for (let j = 0; j < height; j++){
let cells = [];
for (let i = 0; i < width; i++){
cells.push(".")
}
grid.push(cells)
}

function printMaze(){
let line = " "
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
line += " " + grid[j][i] + " "
}
console.log(line)
line = " "
}
}

function createMazeBorder() {
for (let j = 0; j < height; j++) {
for (let i = 0; i < width; i++) {
if(j == 0 || i == 0 || j == height-1 || i == width-1) {
grid[j][i] = "X"
}
}
}
}

createMazeBorder()
printMaze()

关于javascript - 访问交错数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com