I have put my review of the code on JsFiddleJsFiddle.
console.log("Game starting...");
var ship = {
name: "Enterprise",
x: 125,
y: 100120,
width: 50,
height: 40,
left: false,
right: false,
up: false,
down: false,
fire: false,
firerate: 5,
cfirerate: 0,
moveInterval: 5,
color: "#000000"
},
map = {
width: 300,
height: 300,
color: "#808080",
drawInterval: 30
},
laser = {
height: 20,
moveInterval: 6,
color: "#FF0000"
},
lasers = [],
keys = {
left: 37,
up: 38,
right: 39,
down: 40,
fire: 90 //Z
},
getKey = function(key) {
for (var i in keys) {
if (keys.hasOwnProperty(i)) {
if (keys[i] === key) {
return i
};
}
}
},
eventValues = {
keyup: false,
keydown: true
},
types = {
right: 1,
left: 2
};
var world = document.getElementById('world');
var cxt = world.getContext("2d");
$(document).bind('keydown keyup', function(e) {
var key = getKey(e.keyCode);
ship[key] = eventValues[e.type];
});
function createLaser(type) {
var x = ship.x;
if (type === types.right) {
x += ship.width;
}
var y = laser.height + ship.y;
return {
type: type,
x: x,
y: y,
}
}
function drawWorld() {
cxt.fillStyle = map.color;
cxt.fillRect(0, 0, map.width, map.height);
}
function drawLasers() {
cxt.beginPath();
cxt.strokeStyle = laser.color;
for (var i = 0; i < lasers.length; i++) {
var lsr = lasers[i];
if (lsr.y < -20laser.height) {
lasers.splice(i, 1);
continue;
}
cxt.moveTo(lsr.x, lsr.y);
cxt.lineTo(lsr.x, lsr.y - laser.height);
cxt.stroke();
lsr.y -= 6;laser.moveInterval;
}
}
function drawShip() {
if (ship.left) {
ship.x -= 5;ship.moveInterval;
}
if (ship.right) {
ship.x += 5;ship.moveInterval;
}
if (ship.up) {
ship.y -= 5;ship.moveInterval;
}
if (ship.down) {
ship.y += 5;ship.moveInterval;
}
if (ship.fire) {
if (ship.cfirerate === 0) {
lasers.push(createLaser(types.left), createLaser(types.right));
ship.cfirerate = ship.firerate;
}
}
if (ship.cfirerate !== 0) {
ship.cfirerate--;
}
cxt.beginPath();
cxt.strokeStyle = ship.color;
cxt.moveTo(ship.x, ship.y + (ship.height / 2));
cxt.lineTo(ship.x + (ship.width / 2), ship.y);
cxt.lineTo(ship.x + ship.width, ship.y + (ship.height / 2));
cxt.stroke();
}
function gameLoop() {
drawWorld();
drawShip();
drawLasers();
}
setInterval(gameLoop, 30map.drawInterval)