Snake was fun, but Tetris is better!

2018-06-13

A couple of weeks ago I make a snake clone. Then I made Whac-a-Mole and now I stopped at Tetris.

You can find this and the other games here. Like the last games this one is also build with jQuery, Javascript, HTML and CSS. This game was a lot more painful to write, because there are several boundary checks at serveral positions. Also I ran into some interesting bugs which makes me more careful when using the || operator.

Often this is used like this

a = a || default_value;

to asign default values if no value is given. This works due to JS values being truthy or falsy. The || operator takes the first truthy value and returns this. Basically as long as a is not null, undefined or false one gets the left value. But there are more falsy values. There are also 0, -0, NaN and empty strings like "", '' (to be accureate the specs say every string of length 0 is falsy). While digging deeper I realized that there are some further caveats, this stackoverflow answer sums them up. In conclusion: You have to be careful when using this operator because you could get a 0 or an empty string as an input which might screw you, because this might have been a value which you wouldn't want to replace.

My workaround looks like this:

if(rotation === undefined){
    rotation = current_tetromino.rotation;
}

rotation is a parameter of the function that contains this code and has undefined as a default value. This works but there are probably some nicer versions. Maybe this one is better, but still looks very clumsy due to the long variable names.

rotation = (rotation === undefined) ? current_tetromino.rotation : rotation;

A with shorter names it looks like this:

rot = (rot === undefined) ? cur.rot : rot;

This is a bit shorter, but the ternary operator still looks a bit weird to me. I never really liked that fellow but peerhaps I should use it every now and then.

Okay, back to the game. There is still something left to do: I want to change the way the field is drawn. Currently the complete field is redrawn every time something changes. It feels a bit slow sometimes, especially when you rotate a tetromino (thats the name of a block) twice. Most of the time at most 8 grid cells need to be adjusted. When the player fills one or more lines those lines need to be deleted and everything from that point upwards needs to be drawn again.