The classic block puzzle game!
Action | Key Input |
---|---|
Movement | Left, down, right |
Clockwise Turn | Up |
Counterclockwise Turn | W |
Hard-drop | Spacebar |
JavaScript to create game logic, physics, and event handlers. HTML 5 Canvas to render shapes and game space.
In order to create an even distribution of random pieces:
- I used the Fisher-Yates shuffling algorithm to shuffle arrays. Learn more here
- I created a
shapeBag
array with 2 shuffled sets of the 7 tetrominoes. - A new piece type would be generated by shifting the first piece off of the bag.
- If the bag was left with less than 7 tetrominoes, the bag is replenished.
function replenishShapeBag() {
return shuffle("ITOLSZJ".split(""));
}
function randomType() {
const type = shapeBag.shift();
if (shapeBag.length < 7) {
shapeBag = shapeBag.concat(replenishShapeBag()).concat(replenishShapeBag());
}
setNext();
return type;
}
- Add a boolean called
keepHardDropping
to the existing drop function, which starts off astrue
with each new piece. keepHardDropping
switches tofalse
when the piece is no longer able to move down.- The
hardDrop
method was tied to an event listener and triggers awhile
loop to repeatedly drop the piece untilkeepHardDropping
is false.
function drop() {
keepHardDropping = true;
currentPiece.pos.y++;
if (collide(grid, currentPiece)) {
currentPiece.pos.y--;
keepHardDropping = false;
if (dropInterval > 100) {
dropInterval -= 1;
}
merge(grid, currentPiece);
clearLines();
resetPiece();
}
dropCounter = 0;
}
function hardDrop() {
while (keepHardDropping) {
drop();
score++;
}
}
- Add two-player battle tetris mode.
- Use storage to track players' high score.