Skip to main content

Diving into JavaScript with Tetris

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.

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 ugliness 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 block size 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. Especially 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

Popular posts from this blog

Using xUnit.Net with .Net 4.0

I’ve been using xUnit.Net for a while now. It’s just a tiny bit cleaner and slightly less abrasive than other .Net unit testing frameworks. Leaving out unnecessary stuff like [TestFixture] and shortening Assert.AreEqual to the equally clear but shorter Assert.Equal don’t seem like big improvements but when you type them several times a day tiny improvements start to add up. I also like the use of the [Fact] attribute instead of [Test]. It shifts the focus from testing to defining behavior. So how do we get all this goodness working with the Visual Studio 2010 beta?

Square One available on the Android market

This is just a short post to let you know that a first version of the Android app I’ve been working on for the last couple of weeks is available on the Android market. The app is called Square One and it’s a simple bassline synthesizer. It’s free so try it out and let me know what you think of it, but be prepared it’s still an early version. I hope to add more features in the next few months and maybe build something that can be used to create real music.The lower part of the screen contains the sequencer controls that can be used to program your own bass lines. On the left is a four by four grid of buttons where you can select a step in the sequence. On the right you can select the note to be played on that step. When you’re done you can press Start and the sequence starts playing. The knobs on the top can be used to control a couple of parameters from the synthesizer engine that creates the sound. You can control the cutoff frequency and resonance of the low-pass filter, attack and …

Building Android projects with Jenkins, Ant and Mercurial

I have recently set up a Jenkins build server for my Android projects hosted on Bitbucket. It’s not difficult but there are a couple pitfalls and the information on how to do this isn’t available from one single place so I decided to document the process and put up the information over here. Maybe other people will benefit from having a step-by-step guide too.