How to move Mario using javascript

My son loves playing Super Mario video games. As I was chilling out with him on a winter evening, I created a simple javascript to move a Mario image using keyboard up, down, left and right arrow keys. He was impressed with him mom’s skills to create a simple video game:-)

Notes

  • Use the document keydown event and capture the key pressed.
  • Write a simple switch statement with four cases based on the four keys-up, down, left, right.
  • Use jQuery animate to change the position of the image.

The html code snippet

<img src="http://i71.photobucket.com/albums/i129/Sarad_Thamia/Mario.jpg ">

The javascript code snippet

$(document).ready(function() {
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
// Right Arrow Pressed
case 37:
$('img').animate({left: "-=10px"}, 'fast');
break;
// Down Arrow Pressed
case 38:
$('img').animate({top: "-=10px"}, 'fast');
break;
// Left arrow key pressed
case 39:
$('img').animate({left: "+=10px"}, 'fast');
break;
// Up Arrow Pressed
case 40:
$('img').animate({top: "+=10px"}, 'fast');
break;
}
});
});

Hope you had fun playing with my simple video game.

Leave a Reply

Your email address will not be published. Required fields are marked *

Endorsed by these folks ...

Femy is detail oriented and creative in her approach, and thorough in her execution, of any project. She is a great team player and always willing to stretch herself in any direction that the project needs. It has been wonderful working with Femy!

Alpana Verma-Alag Co-founder and CEO, Upgrademe, Inc