Thursday 23 September 2010

Tetris - JavaScript - PART 1 KeyBoard Input

I'm feeling Tetris today, we going to make our very own tetris. Using JavaScript with JQuery and plain dom.

Things to consider for making tetris
  • Keyboard Input
  • Block manipulation
  • Score
  • Collision Detection
  • Graphic 
$(function(){//Only call this script when the dom is ready
    
    Tetris = function(p_holder) {
        //We don't need multiple instance
        if(window._Tetris != undefined){
            return window._Tetris;
        }
        
        window._Tetris = this;
        this.m_keyCode = {40:'down', 38: 'up', 37:'left', 39:'right'};
        this.m_holder = p_holder;
        this.m_action = null;
        
        // Bind window event to tetris
        $(window).keydown(function(event){
            Tetris().keyDown(event);
        });
        
        // Bind window event to tetris
        $(window).keyup(function(event){
            Tetris().keyUp(event);
        });
        
        //Event handler for KeyDown
        this.keyDown = function(event){
            if(this.m_keyCode[event.keyCode] != undefined){
                console.log(this.m_keyCode[event.keyCode]);
                //Converting keycode into, up, down, left,
                //right action and set tetris action.
                this.m_action = this.m_keyCode[event.keyCode];
            };
        };
        
        //Event handler for KeyUp
        this.keyUp = function(event){
            //Clearing up the action so tetris will be idle
            this.m_action = null;
        }
    };
    
    
    new Tetris($("#tetrisHolder"));
});

No comments:

Post a Comment