Dooster
Dooster

Reputation: 3

How to implement a decreasing life system in Javascript and canvas

I'm trying to implement a decreasing life system in a basic frogger style Javascript game. I had a counter system work in which lives were displayed numerically, counting down from 3 to 0 when the player character hits an enemy.

Now, I'm trying to replace the numeric countdown with displayed unicode hearts. Ideally, there would be three hearts at game launch, and each collision would decrease the displayed hearts by 1.

With my code, this works if I display the lives as an array, but it shows the commas separating the hearts. If I try to display it as a string, the commas are gone but the hearts no longer decrease. I feel like I'm so close, but I'm stumped.

Thanks!

var playerLives = ['💚', '💚', '💚'];
var hearts = playerLives.join(' ');
//turn playerLives array into hearts string

var playerScore = 0;
var scoreEl = document.getElementById('score');

function checkCollisions() {
    for (var i = 0; i < allEnemies.length; i++) {
        if (player.x <= allEnemies[i].x + 70
            && player.x + 70 >= allEnemies[i].x
            && player.y <= allEnemies[i].y + 50
            && player.y + 50 >= allEnemies[i].y)
        {
                player.x = 200;
                player.y = 415;
                hearts.slice(-10);
                //attempt to remove string from hearts, but doesn't
                //work
                playerLives.splice(-1, 1);
                //decrease playerLives array by 1 on collision
                if (playerScore >= 50) {
                    playerScore -= 50;
                    scoreEl.textContent = 'Score: ' + playerScore;
                }
                //reset(); //create reset function
        }
    }
}

function score() {
    if (player.y < 60) {
        player.x = 200;
        player.y = 415;
        playerScore += 100;
        scoreEl.textContent = 'Score: ' + playerScore;
        level++;
        levelEl.textContent = 'Level: ' + level;
    }
}

function playerLife() {
    for (var i = 1; i <= 3; i++) {
        var lifeEl = document.getElementById('life');
        lifeEl.innerHTML = 'Lives: ' + hearts; // lives appear as 
        //string and do not decrease on collision
        //if use "'Lives: ' + playerLives" hearts do decrease 
        //but appear as an array with commas separating
    }
}

Upvotes: 0

Views: 1181

Answers (1)

c-smile
c-smile

Reputation: 27470

To convert array to string without delimiters use .join() with empty string :

playerLives.join("");

Upvotes: 1

Related Questions