Diving into javascript with Tetris

16. March 2010

To prepare for the Devnology meeting next month I have to write a version of Tetris in a language of my choosing. I had already fired up Visual Studio to build a kick-ass C# XNA version with explosions and 3D visuals when I realized it would be much more fun and educational to pick a language I’m less familiar with. I’m pretty sure there will be Ruby, Python, Java and Haskell implementations by some people who are pretty good at programming in those languages so I decided not to pick any of those obvious languages. But I’d still like to invest my time learning something I’m actually going to use, so Cobol wasn't an option.

So I picked javascript.

The next couple of posts I’m going to be building Tetris using Javascript and jQuery. I’ll pick a couple of stories every few days to implement and if I’m lucky I’ll have something resembling Tetris in a couple of weeks to show off. I actually hope I’ll get some feedback when I do things wrong. Most of my javascript experience has been adding simple onclick handlers to html files and pulling my hair out because of DOM incompatibilities. The new javascript frameworks hide all the DOM uglyness so it’s a good time to dive into javascript again.

In this first post we’ll get started implementing a couple of easy stories. I chose the following three.

  • As a user I can see a playing field that is 10 units wide and 18 units high.
  • Blocks fall one unit every second.
  • As a user I can steer blocks left and right with the arrows on the numeric keypad.

Lets get started.

As a user I can see a playing field that is 10 units wide and 18 units high

The first story is too easy. The display is just going to be a div. So we create a tetris.html file like this:

   1: <!DOCTYPE HTML>
   2: <html>
   3:     <head>
   4:         <link rel="stylesheet" href="tetris.css" />
   5:     </head>
   6:     <body>
   7:         <div id="field"></div>
   8:     </body>
   9: </html>

and the stylesheet:

   1: #field
   2: {
   3:     position: relative;
   4:     top: 40px;
   5:     left: 50%;
   6:     margin-left: -100px;
   7:  
   8:     width: 200px;
   9:     height: 360px;
  10:     
  11:     border: solid grey 2px;
  12: }

I decided on a blocksize of 20 pixels so the field is 200 by 360 pixels.

Blocks fall one unit every second

For this story to work we first need to be able to draw blocks. jQuery makes this pretty easy. Especually since blocks are just going to be small div’s with a big border in this first version, so our first pieces of javascript look like this:

   1: function drawBlock(x, y) {
   2:     var block = $("<div class='block'></div>").css('top', (17 - x) * 20).css('left', y * 20);
   3:     $('#field').append(block);
   4: }
 
   1: function clearBlocks() {
   2:     $('.block').remove();
   3: }

In order to draw a block every second we need some sort of gameloop that is called every second. So I put something like this in the jQuery document ready handler :

   1: $(document).ready(function() {
   2:     setInterval( "gameLoop()", 1000);
   3: });

and the gameloop:

   1: var verticalPosition = 18;
   2: var horizontalPosition = 5;
   3:  
   4: function gameLoop() {
   5:     verticalPosition--;
   6:     clearBlocks();
   7:     drawBlock(verticalPosition, horizontalPosition);
   8: }
 
some css for the blocks:
 
   1: div.block
   2: {
   3:     position: absolute;
   4:     
   5:     width: 12px;
   6:     height: 12px;
   7:     border: solid black 4px;
   8: }
 
And voila, we’ve got movement on our screen. Pretty easy actually.

As a user I can steer blocks left and right with the arrows on the numeric keypad.

We still can’t call this a game though. Movement is nice but without interactivity we might as well be looking at dancing hamsters. We want to be able to steer our block around.

jQuery makes registering a keyboard handler pretty easy. We can just add:

   1: $(document).keydown(keyHandler);
and the handler:
 
   1: const keyCodeMoveLeft = 100;
   2: const keyCodeMoveRight = 102;
   3: const keyCodeMoveDown = 98;
   4:  
   5: function keyHandler(keyEvent) {
   6:  
   7:     if(keyEvent.keyCode === keyCodeMoveLeft) {
   8:         horizontalPosition--;
   9:     }
  10:  
  11:     if(keyEvent.keyCode === keyCodeMoveRight) {
  12:         horizontalPosition++;
  13:     }
  14:     
  15:     if(keyEvent.keyCode === keyCodeMoveDown) {
  16:         verticalPosition--;
  17:     }
  18:     
  19:     clearBlocks();
  20:     drawBlock(verticalPosition, horizontalPosition);
  21: }

Next time we’re going to look at tooling to make testing and debugging all this a bit easier and we’re going to get a bit more OO.

You can download the code in this post here:

tetris0.01.rar (1.02 kb)

Comments

3/19/2010 5:22:58 AM

Sebastiaan Janssen

Instead of chaining the css arguments, you could make it a little bit cleaner and put them into an array of arguments, so that would change this:
.css('top', (17 - x) * 20).css('left', y * 20);

to this:
.css({ top: (17 - x) * 20, left: y * 20 });

const is not supported in IE (stackoverflow.com/.../are-there-constants-in-javascript ), I would choose to move the keyCode's into the keyHandler.

Where did you get these keyCodes anyway? They're wrong and should be: left = 27, right = 39 and down = 40 (http://www.quirksmode.org/js/keys.html ).

I'm not sure why you're putting javascript inline with your HTML. What if you want to add a tetris game to another html file in your site? You'd be duplicating code! Wink
On a more serious note, mixing mark-up with behaviour is bad, you know that.

Sebastiaan Janssen Netherlands

3/19/2010 5:29:06 AM

Sebastiaan Janssen

Ah, I see the keyCodes map to the numeric keyboard, not everybody has one of those (laptops!). It might be better to support both the numeric keyboard arrows as well as the "normal" arrows.

Sebastiaan Janssen Netherlands

3/19/2010 9:49:02 AM

Mendelt

Thanks Sebastiaan, that's just the kind of feedback I was looking for!

I'm using the numeric keypad because I want to be able to use the 7 and 9 key for rotating blocks left or right later. Tetris games that only allow you to rotate in one direction with the up key irritate me Smile But I'll add support for arrow key-only gameplay in the next version.

The reason I put some javascript inline with the html actually was because I wanted a clean separation of concerns. So I decided to keep the code to hook up the game loop and keyboard handlers to the view separate from the rest of the javascript. This separation is a bit leaky in the current version, drawBlock and clearBlocks still talk directly to the DOM too but this will be refactored in a future version. I'll probably try to clean things up with a nice MVP architecture or something.

Mendelt United States

3/24/2010 9:05:08 AM

Robert Schaap

Good read! Not so much because you're using Javascript to create Tetris. I mean, we've already seen Javascript versions of Wolfenstein and Lemmings. The reason I like it is because it shows a real-world example of TDD.

Robert Schaap Netherlands

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme adapted from BlogEngine.NET standard theme by Mads Kristensen

Mendelt Siebenga

Mendelt Siebenga with coffeeMendelt Siebenga works as a C# programmer. In his spare time he's been known to pick up Python, Lisp and even a soldering iron from time to time.

You can also find me here