<canvas id="canvas" width="320" height="480"></canvas>
#canvas {
border: 2px solid black;
cursor: i
}
document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var sprite = new Image();
sprite.src = "sprite.png";
var x = 0;
var y = 0;
var press = 0;
var bullets = [];
var enemys = [];
var explosive = [];
var ax = 0;
var aex = 0;
var t = 0;
var score = 0;
var lives = -1;
var speed = 1;
var spawn = 100;
var fireSpeed = 20;
var enemysbullets = [];
var fireSpeedss = 20;
document.addEventListener("mousemove", function(e) {
x = e.pageX - 16;
y = e.pageY - 17;
if (x + 16 >= 320) {
x = 304;
}
if (x <= 0) {
x = 1;
}
if (y + 17 >= 480) {
y = 463;
}
if (y <= 0) {
y = 0;
}
});
document.addEventListener("mousedown", function(e) {
if (lives < 0) {
bullets = [];
enemys = [];
explosive = [];
enemysbullets = [];
lives = 3;
speed = 1;
fireSpeed = fireSpeedss;
score = 0;
spawn = 100;
}
});
function game() {
ctx.clearRect(0, 0, 320, 480);
ctx.beginPath();
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 320, 480);
ctx.closePath();
ctx.drawImage(sprite, 0, 0, 16, 17, x, y, 16, 17);
for (i in enemys) {
ctx.drawImage(sprite, 0, 17, 16, 16, enemys[i].x, enemys[i].y, 16, 16);
enemys[i].y += 2;
for (j in bullets) {
if (enemys[i].x <= bullets[j].x && enemys[i].x + 16 >= bullets[j].x + 6) {
if (bullets[i].y + 16 >= bullets[i].y) {
enemys.splice(i, 1);
bullet.splice(j, 1);
}
}
}
if (enemys[i].y > 480) {
enemys.splice(i, 1);
}
}
for (i in bullets) {
ctx.drawImage(sprite, 0, 32, 6, 6, bullets[i].x, bullets[i].y, 6, 6);
bullets[i].y -= 5;
if (bullets[i].y <= 19) {
bullets.splice(i, 1);
}
}
ctx.beginPath();
ctx.font = "16px Serif";
ctx.fillStyle = "white";
ctx.fillText("Score: " + score, 0, 16);
ctx.fillText("Lives: " + lives, 250, 17);
ctx.fillRect(0, 19, 320, 1);
ctx.closePath();
if (t % spawn == 0) {
enemys.push({
x: Math.floor(Math.random() * (304 - 1)) + 1,
y: -16
});
}
if (t % 20 == 0) {
bullets.push({
x: x + 3,
y: y
});
}
t += 1
}
setInterval(game, 20);