var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var interval = setInterval(gameloop, 33); var speed = 2, score = 0; var img = [new Image(), new Image(), new Image(), new Image(), new Image(), new Image()]; img[0].src = "images/space.png"; img[1].src = "images/alien1.png"; img[2].src = "images/alien2.png"; img[3].src = "images/alien3.png"; img[4].src = "images/ship.png"; img[5].src = "images/laser.png"; var shipX = 0; var a1X = 0, a2X = 200, a3X = 400, aY = 0; var shotX = -100, shotY = -100; function gameloop() { ctx.clearRect(0, 0, 1500, 1500); if (shotY != -100) { shotY -= 30; } if (a3X > 600 || a1X < 0) { speed *= -1; aY += 10; } a1X += speed; a2X += speed; a3X += speed; if (aY + 75 >= 800) { clearInterval(interval); } if (shotY - 100 <= aY && shotX - a1X < 90 && a1X - shotX < 10) { score++; a1X = 5000; } if (shotY - 100 <= aY && shotX - a2X < 90 && a2X - shotX < 10) { score++; a2X = 5000; } if (shotY - 100 <= aY && shotX - a3X < 90 && a3X - shotX < 10) { score++; a3X = -5000; } if (a1X >= 4000 && a2X >= 4000 && a3X <= -4000) { a1X = 0; a2X = 200; a3X = 400; speed++; } ctx.drawImage(img[0], 0, 0, canvas.width, canvas.height); ctx.drawImage(img[1], a1X, aY, 100, 100); ctx.drawImage(img[2], a2X, aY, 100, 100); ctx.drawImage(img[3], a3X, aY, 100, 100); ctx.drawImage(img[4], shipX, 800, 100, 100); ctx.drawImage(img[5], shotX, shotY, 10, 100); ctx.font = "48px Impact"; ctx.fillStyle = "#ffffff"; ctx.fillText(score, 50, 50); } function shoot() { shotX = shipX + 50; shotY = 750; } document.addEventListener("keydown", keyDownHandler); function keyDownHandler(event){ if (event.keyCode == 32) { shoot(); } else if (event.keyCode == 37) { shipX -= 5; } else if (event.keyCode == 39) { shipX += 5; } }