Very Basic JavaScript Game Code

posted in Code Snippets
Published March 03, 2014
Advertisement
The following is a very basic JavaScript game were you move a square around the screen. This script demonstrated how easy it is to set up your canvas and elements.
.[code=js:0] var c=document.getElementById("x");var ctx=c.getContext("2d");var FPS = 30;var SPEED = 10;var px = 200;var py = 200;var wx = 500;var wy = 500;setInterval(function(){update();draw();},1000/FPS);var textX = 50;var textY = 50;function update(){key();}var player = {color:"#00A",width:32,height:32,draw: function(){ctx.fillStyle = this.color;ctx.fillRect(px,py,this.width,this.height);}} ;function draw(){ctx.clearRect(0,0,wx,wy);player.draw();}function key(){var x = 0;var y = 0;document.onkeydown=function(e){ var e=window.event || e x = String.fromCharCode(e.keyCode); y = e.keyCode; //alert(x + " " + y );if ( y == 38 && (py < wy && py > 0)){py -= SPEED; } // upif ( y == 40 && (py < wy && py > 0)){ py += SPEED; } // downif ( y == 37 && (px < wx && px > 0)){ px -= SPEED; } // leftif ( y == 39 && (px < wx && px > 0)){ px += SPEED; } // right}}
0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement