JSFiddle - React, Tailwind, and code Playground
JavaScript
var canvas;
var ctx;
var width = 600;
var height = 600;
var starfield;
var starX = 0;
var starY = 0;
var starY2 = -600;
var score = 0;
var highscore = 10;
var alive = true;
var lives = 3;
var gameStarted = false;
livesimage = new Image()
livesimage.src = 'hart.png';
var levens3 = true;
var levens2 = false;
var levens1 = false;
function livedraw()
{
if(lives == 3)
{
ctx.drawImage(livesimage,10,10,50,38);
ctx.drawImage(livesimage,50,10,50,38);
ctx.drawImage(livesimage,90,10,50,38);
}
if(lives == 2)
{
ctx.drawImage(livesimage,10,10,50,38);
ctx.drawImage(livesimage,50,10,50,38);
}
if(lives == 1)
{
ctx.drawImage(livesimage,10,10,50,38);
}
}
function clearCanvas() {
ctx.clearRect(0, 0, width, height);
}
function init() {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
ship = new Image();
ship.src = 'ship.png';
starfield = new Image();
starfield.src = 'starfield.jpg';
document.addEventListener('keydown', keyDown, false);
document.addEventListener('keyup', keyUp, false);
canvas.addEventListener('click', gameStart, false);
gameLoop();
}
function gameStart() {
gameStarted = true;
canvas.removeEventListener('click', gameStart, false);
}
function gameLoop() {
clearCanvas();
drawStarfield();
if (alive && gameStarted && lives > 0) {
hitTest();
moveEnemies();
moveLaser();
drawEnemies();
drawShip();
drawLaser();
shipCollision();
livedraw();
update();
DeleteItems();
console.log(localStorage.getItem("highscore"));
}
scoreTotal();
setTimeout(gameLoop, 1000 / 30);
}
function scoreTotal() {
ctx.font = 'bold 18px VT323';
ctx.fillStyle = '#fff';
ctx.fillText('Score: ', 10, 55);
ctx.fillText(score, 70, 55);
ctx.fillText('Lives: ', 10, 30);
ctx.fillText(lives, 68, 30);
if (!alive) {
ctx.fillText('Game Over!', 245, (height / 2));
ctx.fillRect((width / 2) - 65, (height / 2) + 10, 100, 40);
ctx.fillStyle = '#000';
...