Software Engineer & Web Developer

Corona Killer Game Tutorial

Learn how to create a simple Corona Killer game using JavaScript and HTML.

Introduction

This tutorial will guide you through creating a Corona Killer game where you shoot bullets to destroy virus elements that move down the screen.

HTML Structure

Below is the basic HTML structure for our game:

<div id="container">
    <div id="pointsDiv">Score: 0 ||| Lost: 0</div>
    <div id="injection"></div>
</div>

This code creates a container div that holds the score display and the injection element used for shooting bullets.

JavaScript Code

The JavaScript code handles the game logic, including generating virus elements, moving them, shooting bullets, and detecting collisions.

1. Setting Up the Game Environment

We start by selecting the necessary HTML elements:

// get html elements
const container = document.querySelector('#container');
const injection = document.querySelector('#injection');
const pointsDiv = document.querySelector('#pointsDiv');

2. Moving the Injection Element

We add an event listener to the container to move the injection element with the mouse:

container.addEventListener('mousemove', e => {
    injection.style.left = (e.clientX - 12.5) + 'px';
});

3. Generating Virus Elements

We create an array to save virus objects and use an interval to generate virus elements:

// create array to save corona objects 
const coronaArr = [];

// interval to generate coronDivs
setInterval(() => {
    // create and add coronaDiv to container
    ...
}, 1000);

4. Moving Virus Elements

We use another interval to move the virus elements down the screen:

setInterval(() => {
    // loop through coronaArr to change the top of coronaElements
    ...
}, 50);

5. Shooting Bullets

We add a click event listener to create and move bullet elements:

container.addEventListener('click', e => {
    // create and move bulletDiv
    ...
});

6. Collision Detection

We define the explode function to detect collisions between bullets and virus elements:

function explode(bulletElement, interval) {
    // loop through coronaArr to check for collisions
    ...
}

Complete JavaScript Code

Here is the complete JavaScript code for reference:

// get html elements
const container = document.querySelector('#container');
const injection = document.querySelector('#injection');
const pointsDiv = document.querySelector('#pointsDiv');

// add mousemove event listener to container to control injection position
container.addEventListener('mousemove', e => {
    injection.style.left = (e.clientX - 12.5) + 'px';
})

// create array to save corona objects 
const coronaArr = [];

// interval to generate coronDivs
setInterval(() => {
    // create and add coronaDiv to container
    let containerWidth = container.offsetWidth;
    const coronaDiv = document.createElement('div');
    coronaDiv.classList.add('corona');
    let coronaLeft = Math.floor(Math.random() * containerWidth) + 1;
    coronaDiv.style.left = coronaLeft + 'px';
    container.append(coronaDiv);
    let coronaObj = { coronaElement: coronaDiv, top: 0, left: coronaLeft };
    coronaArr.push(coronaObj);
}, 1000)

let lost = 0;

// interval to move the coronaDivs down
setInterval(() => {
    let containerHeight = container.offsetHeight;
    coronaArr.forEach((element, idx) => {
        if (element.top > containerHeight) {
            container.removeChild(element.coronaElement);
            coronaArr.splice(idx, 1);
            lost++;
            pointsDiv.innerHTML = 'Score: ' + score + ' ||| Lost:' + lost;
        } else {
            element.top += 10;
            element.coronaElement.style.top = element.top + 'px';
        }
    })
}, 50);

// create bullet sound
let bulletSound = document.createElement('audio')
bulletSound.src = './sounds/bullet.wav';
bulletSound.setAttribute('controls', 'none');
bulletSound.setAttribute('preload', 'auto');
bulletSound.style.display = 'none';
bulletSound.volume = 0.1;
container.append(bulletSound);

// create game sound
let gameSound = document.createElement('audio')
gameSound.src = './sounds/game.mp3';
gameSound.setAttribute('controls', 'none');
gameSound.setAttribute('preload', 'auto');
gameSound.style.display = 'none';
gameSound.volume = 0.1;
gameSound.loop = true;
container.append(gameSound);

// create click event listener for container to create the bullet
container.addEventListener('click', e => {
    gameSound.play();
    bulletSound.play();
    const bulletDiv = document.createElement('div');
    bulletDiv.classList.add('bullet');
    bulletDiv.style.left = e.clientX + 'px';
    container.append(bulletDiv);
    let bottom = 100;
    let containerHeight = container.offsetHeight;
    const interval = setInterval(() => {
        if (bottom > containerHeight) {
            clearInterval(interval);
            container.removeChild(bulletDiv);
        } else {
            bottom += 25;
            bulletDiv.style.bottom = bottom + 'px';
            explode(bulletDiv, interval);
        }
    }, 50);
})

// create explosion sound
let explosionSound = document.createElement('audio')
explosionSound.src = './sounds/explosion.wav';
explosionSound.setAttribute('controls', 'none');
explosionSound.setAttribute('preload', 'auto');
explosionSound.style.display = 'none';
explosionSound.volume = 0.1;
container.append(explosionSound);

let score = 0;
function explode(bulletElement, interval) {
    coronaArr.forEach((corona, idx) => {
        if (is_colliding(bulletElement, corona.coronaElement)) {
            clearInterval(interval);
            container.removeChild(bulletElement);
            coronaArr.splice(idx, 1);
            container.removeChild(corona.coronaElement);
            score++;
            pointsDiv.innerHTML = 'Score: ' + score + ' ||| Lost:' + lost;
            explosionSound.play();
        }
    })
}

var is_colliding = function($div1, $div2) {
    var d1_height = $div1.offsetHeight;
    var d1_width = $div1.offsetWidth;
    var d1_distance_from_top = $div1.offsetTop + d1_height;
    var d1_distance_from_left = $div1.offsetLeft + d1_width;
    var d2_height = $div2.offsetHeight;
    var d2_width = $div2.offsetWidth;
    var d2_distance_from_top = $div2.offsetTop + d2_height;
    var d2_distance_from_left = $div2.offsetLeft + d2_width;
    var not_colliding = (d1_distance_from_top < $div2.offsetTop || $div1.offsetTop > d2_distance_from_top || d1_distance_from_left < $div2.offsetLeft || $div1.offsetLeft > d2_distance_from_left);
    return !not_colliding;
};

Complete CSS Code

Here is the complete CSS code for reference:

*{
   padding: 0;
   margin: 0; 
   box-sizing: border-box;
}

body{
    overflow: hidden;
}

#container{
    width: 100vw;
    height: 100vh;
    background-image: url('../imgs/container.gif');
    background-repeat: no-repeat;
    background-size: cover;
    overflow: hidden;
}

#injection{
    position: absolute;
    width: 25px;
    height: 100px;
    bottom: 0;
    left: calc(50% - 12.5px);
    background-image: url('../imgs/syring.png');
    background-size: cover;
    background-repeat: no-repeat;
    background-position-y: center;

}

.corona{
    position: absolute;
    width: 100px;
    height: 100px;
    background-image: url('../imgs/coronavirus.png');
    background-repeat: no-repeat;
    background-size: cover;
}

.bullet{
    position: absolute;
    width: 2px;
    height: 10px;
    background-color: white;
    bottom: 100px;
}

#pointsDiv{
background-color: rgba(255, 255, 255, 0.747);
font-size: 50px;
height: 50px;
}

Add your comment