如何解决为什么当我尝试在 javascript 中仅清空“完全填充”的行时,我的电路板的行会颠倒
我正在尝试编写一种算法,该算法会检查一行中的所有字段,除非您找到值“#”(如果它们都已满)。如果是,则该行变为空行并且在棋盘内未移动。但是,当我将初始板作为参数执行该函数时,行会颠倒。
举例说明:
如果这是我的初始板:
[
Array(18).fill('#'),['#','','#'],'1','b',Array(18).fill('#')
]
变成这样:
[
Array(18).fill('#'),Array(18).fill('#')
]
而不是使那些 '1' 值字段保持不变。为什么会发生这种情况?
这是函数(我作为参数给出的板子是顶部示例中的初始板):
function checkFilledRow(board) {
// The new board that'll be returned
let newBoard = []
for (var row=1;row<board.length - 1;row++) {
const currentRow = board[row]
let newRow = []
for (var i=1;i<currentRow.length - 1;i++) {
if (currentRow[i] === '') {
// If there's an empty spot,push the row as-is and break
newBoard.push(currentRow)
break
} else if (i === currentRow.length - 2) {
// If it is the last element of the row(not having taken '#' into account) and still haven't came across one empty spot,an empty array should be unshifted
newRow = ['#','#']
newBoard.unshift(newRow)
}
}
}
newBoard.unshift(Array(18).fill('#'))
newBoard.push(Array(18).fill('#'))
return newBoard
}
顺便说一下,我尝试使用 reverse() 方法,虽然显示不再混乱,但我仍然遇到同样的问题(输出显示行仍然颠倒)。
你有什么建议吗?
UDPATE:
function dropdownElements(board) {
let newBoard = board
for (var row=1;row<board.length - 1;row++) {
for (var col=1;col<board[0].length - 1;coL++) {
const currentBrick = board[row][col]
if (currentBrick !== '' && currentBrick !== 'b') {
const elemCords = checkForElementType(board,currentBrick)
for (var i=0;i<elemCords.length;i++) {
const current = elemCords[i]
// The problem is that when there's a brick underneath which there's another one of the same element,it does the wrong thing. Solve it
if ((newBoard[current[0] + 1][current[1]] !== '' && newBoard[current[0] + 1][current[1]] !== currentBrick)) {
// Turn bricks into 'b'
for (var b=0;b<newBoard.length;b++) {
for (var bc=0;bc<newBoard[0].length;bc++) {
let elem = newBoard[b][bc]
newBoard[b][bc] = (elem === currentBrick) ? 'b' : elem
}
}
return newBoard
} else if (i === elemCords.length - 1) {
// Create the new board by lowering the y value of all its bricks
// When two squares are on top of each other,it reduces the number of squares in the column
for (var r=elemCords.length - 1;r>=0;r--) {
const applying = elemCords[r]
newBoard[applying[0]][applying[1]] = ''
newBoard[applying[0] + 1][applying[1]] = currentBrick
}
return newBoard
}
}
}
}
}
}
解释它的作用;它降低了所有尚未被阻止的俄罗斯方块元素(是的,这是用于俄罗斯方块游戏)。此外,如果他们被阻止,他们的价值就会变成'b'-意味着他们不能再跌-。
如果您能帮助我,我将不胜感激:)
新更新:
我将 newBoard === board
登录到控制台以检查它是哪个,但我震惊地发现错误出在我发布的初始函数中。我也将行一一打印出来进行比较,结果是一样的;在应该相同的情况下,它会被颠倒。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。