Reputation: 51
So, I have been working on this code for way to long for one day. I am sure there has to be a simple way to solve this but I can't think anything right now. First a small section of the code:
if(Settings.totalHits >= 50 && Settings.totalHits <= 99)
{
Settings.medal1 = true;
Settings.save(game.getFileIO());
totalMedals = totalMedals + 1;
}
This is a very basic achievement/medal system. Basically, once the user has done a total of 50 hits, it sets the value of "medal1" to true, which will remove the "lock" image which only displays when medal1 = false.
The issue deals with the totalMedals section. Basically, there is a total of 32 medals a user can earn, and after one is unlocked, it needs to update the totalMedals by 1. So in this case, the output would be "1/32". Except, now after the medal is unlocked (by hitting 50), the lock image is removed correctly, but the totalMedals keeps increasing by 1 extremely fast instead of just increasing to "1" and stopping.
Like I said, there has to be something small that I am overlooking here. I tried tossing into a for loop but that didn't work (or I did it wrong). Any idea what I can change to fix this?
Upvotes: 0
Views: 108
Reputation: 881463
You only want to unlock the medal if you've reached the threshold and you haven't already unlocked it (the upper limit is irrelevant here), so you can use:
if (Settings.totalHits >= 50 && !Settings.medal1) {
Settings.medal1 = true;
Settings.save(game.getFileIO());
totalMedals++;
}
if (Settings.totalHits >= 100 && !Settings.medal2) {
Settings.medal2 = true;
Settings.save(game.getFileIO());
totalMedals++;
}
// and so on.
Though of course, this positively calls out for refactoring so as to efficiently use arrays, something like:
for (i = 1; i < 33; i++) {
if (Settings.totalHits >= 50 * i && !Settings.medal[i-1]) {
Settings.medal[i-1] = true;
Settings.save(game.getFileIO());
totalMedals++;
}
}
And, if the thresholds aren't a direct multiple of 50, you can easily place an arbitrarily complex function (or array lookup) into the if
statement to match your needs.
Upvotes: 0
Reputation:
Instead of
if(Settings.totalHits >= 50 && Settings.totalHits <= 99)
Try:
if(Settings.totalHits >= 50 && Settings.totalHits <= 99 && !Settings.medal1)
This way, once the medal has been triggered, it cannot be triggered again. Thus, totalMedals
is only incremented once.
Upvotes: 3