Ronald Snew
Ronald Snew

Reputation: 95

Javascript Functions not Functioning

I've been instructed to make a simple game in which click on an image increases your score and eventually allows upgrades. When I click the image, it displays the amount of clicks left the first time, however, subsequent times do not seem to work. Is this a problem with how my functions call each other?

Javascript

//Variables
var clicks = 0;
var level = 2;
var clickInterval = 1;
var holdClick = 0;

function imgClicked() { //Activated by clicking on image
    var clicks = clicks + clickInterval; //Increasing clicks
    upgradeCheck();
    if (holdClick === 1) { //If holding down the image activated
        window.onmousedown = holding();
    }
}

function upgradeCheck() { //Check if eligible for new level
    if (clicks > Math.pow(level, 2)) { //If clicks more than current level^2
        level = level + 1; //Next level
        upgrade();

    } else { //If not
        var clicksLeft = Math.pow(level, 2) - clicks; //Determine clicks until eligible
        document.getElementById("toUpgrade").innerHTML = clicksLeft + " clicks left until upgrade"; //Display
    }
}

function upgrade() { //Upgrading
    document.getElementById("clickImg").src = "level" + level + ".png"; //Change to new level
    var clickInterval = clickInterval * 2; //Increase points per click
    if (Math.pow(level, 2) / clickInterval > 400) { //If it take more than 400 clicks to get to next level
        var holdClick = 1; //Activate hold clicking
        document.getElementById("message").innerHTML = "You can now hold down the image";
    }
}

function holding() {
    var clicks = clicks + clickInterval; //Adding more clicks
}

HTML

<p id="toUpgrade"></p>
<img id="clickImg" src="level2.png" onclick="imgClicked()" />
<p> id="message"></p>

Upvotes: 0

Views: 61

Answers (1)

David
David

Reputation: 219096

I don't think this is doing what you think it's doing:

var clicks = clicks + clickInterval; //Adding more clicks

You're not modifying the global clicks variable, you're creating an entirely new variable called clicks only within the scope of that function. Then that variable goes away when the function completes. You never actually modify the existing clicks variable. I think you want this instead:

clicks = clicks + clickInterval; //Adding more clicks

The same mistake is made elsewhere, such as:

var clickInterval = clickInterval * 2; //Increase points per click

and:

var holdClick = 1; //Activate hold clicking

Remove the var keywords to prevent declaring new variables.

Upvotes: 3

Related Questions