Relatively new programmer here. I have a fully functioning Tetris game written in Javascript. I am having problems with the final function - where splice is not working as expected in removing a row filled with color. Im sure there might be something wrong with the way I have looped through the arrays but I cannot work it out and was wandering if anyone could offer some advice. Here is my current function that is called everytime a shape collides with another:
for(let y = arena.length-1; y < 0; y--){
for(let x = 0; x < arena[y].length; x++){
if (arena[y][x] === 0) {
continue;
}
}
const row = arena.splice(y,1)[0].fill(0);
arena.unshift(row);
y++;
};
}
Fixed it up for ya. You had a couple of concepts wrong:
function arenaSweep() {
for(let y = arena.length-1; y >= 0; y--){
const row = arena[y];
let filled = true;
for(let x = 0; x < row.length; x++){
if (row[x] === 0) {
filled = false;
break;
}
}
if (filled) {
arena.splice(y,1);
row.fill(0);
arena.unshift(row);
y++;
}
};
}
The conditional in your for loop had the wrong direction (y < 0 should be y >= 0) for reverse loops.
Next you assumed continue
would break out of the inner loop so you could start checking next row; however, it's break that stops the current loop. Continue just made you move to the next iteration of the nested loop.
I also optimized a little by reducing array calls.