Reputation: 139
So when I use my skill it takes 10 mana from mana total then adds 50 to cookie total but if I use the skill again it keeps taking mana. i have it set so cookies does not increase but my mana keeps going down. how do i prevent values from going negative.
I haven't tried much not sure how to prevent it
This is my Javascript code:
function Bigclick() {
if (ManaPoints >= 10)
if (rebirths >=1)
cookies = cookies + 50
ManaPoints = ManaPoints - 10;
document.getElementById('cookies').innerHTML = cookies;
document.getElementById("ManaPoints").innerHTML = ManaPoints;
checkCursor()
}
I expect If im below 10 mana or at 0 mana for the function to not do anything. but the actual output the Mana keeps going down http://prntscr.com/ns2d0m
Upvotes: 0
Views: 37
Reputation: 21465
Those if
s only works for cookies = cookies + 50
. You need to open a block and wrap all calculations that depends on those conditions, e.g.:
function Bigclick() {
if (ManaPoints >= 10 && rebirths >=1) {
cookies = cookies + 50
ManaPoints = ManaPoints - 10;
document.getElementById('cookies').innerHTML = cookies;
document.getElementById("ManaPoints").innerHTML = ManaPoints;
}
checkCursor()
}
Not sure if the code above is exactly what you need, it is just an example.
Another example of how your conditions were woring initially:
var truthy = false;
if (truthy)
if (!!truthy)
console.log("truthy");
console.log("not truthy");
UPDATE:
let button = document.getElementById("use-mana"),
manaQty = document.getElementById("mana-qty");
const manaCost = 10;
button.addEventListener("click", () =>
{
let qty = Number(manaQty.innerText);
if (qty >= manaCost)
{
qty-= manaCost;
manaQty.innerText = qty;
}
else
{
window.alert("Not enough mana!");
}
});
<div id="mana-qty">29</div>
<button id="use-mana">Use Mana</button>
Upvotes: 3
Reputation: 12891
Generally - if you want to avoid a number becoming negative after subtraction - you have to check if it would be smaller than 0 if you subtract a specific value. If it does make it zero, if it doesn't subtract the desired amount.
if (ManaPoints - 10 < 0) {
ManaPoints = 0;
} else {
ManaPoints -= 10;
}
Upvotes: 1