Skip to main content
GameDev.net gamedev.net

PRO Tired of ads? Read GameDev.net ad-free and help keep the community independent with GameDev Pro — $3/month.

Very Basic JavaScript Game Code

Very Basic JavaScript Game Code

RLS0812
RLS0812
Code Snippets · · 1 min read
2,362 0
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}}

Discussion

Loading comments...