I'm having trouble grabbing the current piece as I program tetris. Right now, when I try to move one tetromino, all of them move. I've been stuck on this problem for a while, and I'd really appreciate some help. Below is a snippet of the code, and I put the whole thing on jsfiddle. http://jsfiddle.net/L5q6g/
Thank you!
//CONTROLS
function controls(e){
tetrominoList.forEach(function(tetromino){
//RIGHT
if(e.keyCode == 39){
e.preventDefault();
if(tetromino.gravity < 500 - 4*rows && tetromino.x < 3*cols){
tetromino.x += cols;
console.log(tetromino.gravity);
}
}
//LEFT
if(e.keyCode == 37){
e.preventDefault();
if(tetromino.gravity < 500 -4*rows&& tetromino.x > -6*cols){
tetromino.x -= cols;
}
}
//DOWN
if(e.keyCode == 40){
e.preventDefault();
if(tetromino.gravity < 500 - 4*rows){
tetromino.gravity += rows;
}
}
});
//CRASH
if(e.keyCode == 32){
e.preventDefault();
if(tetromino.gravity < 500 - 4*rows){
tetromino.gravity +=500;
}
}
});
}
The issue actually isn't really in this function. You are assigning the eventlistener to every tetromino
in tetrominoList
. So any time you press a button it is going to affect all of them.
Instead you could try adding the event listeners when you create the tetromino
, and then later removing the listeners on tetrominoLand
.
Edit:
I see you actually keep track of your last (active) tetromino with tetrominoID
. So instead of updating all the pieces in the list tetrominoList.foreach
, get rid of the foreach and simply create move the last piece
var tetromino = tetrominoList[tetrominoID];
Working fork http://jsfiddle.net/8pVzp/