A JavaScript Tetris clone in 509b.
- 10x18 playing field (Game Boy version dimensions)
- Move, turn, and speed up pieces with arrow keys
- Score with bonus for multiple lines
- Beautiful UI ;)
- Pieces turn differently than in original version.
Note that some tricks may have been replaced in the most recent version.
- The cells in a row of the playing field are encoded as bits simplifying operations like
removing rows (pop the row) or checking whether a row is filled (row equals
1023, ie.1111111111in binary). - The spread operator
...is used to cheaply copy the playing field. Thanks to the copy adding the piece to the field (for drawing, updating the field, and checking for overlaps) is one operation without having to remove the piece afterwards. - The shapes of the tetrominos are stored in a single string with coordinates overlapping each other. E.g. three blocks of the I tetromino are also part of the L.
- The shape string has a length of 18 which is also the height of the playing field. Thus the string can be used to cheaply create the array for the field.
- Pieces are moved by mapping their coordinates.
Because that always looks the same apart from the
Array.mapbody the mapping functionMis called as a template literal tag function with the body as an argument which is then passed toeval(). - Operators like
|=store the original value of the assigned variable before evaluating the right side. This way the variableScan be used to keep the score and build the UI at the same time. After the UI has been created, the right side ofS|=…evaluates to0resettingSto the score. onkeyupis shorter thanonkeydownthough less responsive.KeyboardEvent.whichis shorter thanKeyboardEvent.keyCode.- The key code is stored in the global variable
kand can thus be used outside of the event handler. setTimeout()returns a random identifier which can be used forclearTimeout()or as random value to select tetrominos.- The
<body>tag doubles as cheap way to execute the code (viaonload) and element to insert the UI. - With
Node.innerTextline breaks can be done with\ninstead of<br>when usingElement.innerHTML. A&&Bis used in favor ofif(A)BbutA?B:0is used when B is an assignment to avoid wrapping it in parentheses.
If you want to join us or see other golfing projects we’ve made, see this list.