Reanimation
Reanimation

Reputation: 3336

How do I do something every n-th attempt?

I have a game that is based on attempts rather than score. And I wish to display a pop up every 10 attempts. What is the best way, using Swift, to calculate every 10 intervals of something?

Currently I call a function to increment the attempts value which includes: gamesPlayedSaved += 1. The closest question I found on here uses timers, which wouldn't work in my case.

So far, I have this (WHICH IS EXTREMELY UGLY):

if(gamesPlayedSaved == 10 ||
                    gamesPlayedSaved == 20 ||
                    gamesPlayedSaved == 30 ||
                    gamesPlayedSaved == 40 ||
                    gamesPlayedSaved == 50 ||
                    gamesPlayedSaved == 60 ||
                    gamesPlayedSaved == 70 ||
                    gamesPlayedSaved == 80 ||
                    gamesPlayedSaved == 90 ||
                    gamesPlayedSaved == 100){
    // call pop up
}

And it also doesn't account for any intervals over 100.

Upvotes: 2

Views: 55

Answers (3)

Sweeper
Sweeper

Reputation: 272905

This can be solved using maths. You just need to decide whether gamesPlayedSaved is a multiple of 10. To do this, find the remainder of gamesPlayedSaved / 10 using the modulo operator % and check if it is 0:

if gamesPlayedSaved % 10 == 0 && gamesPlayedSaved > 0 {
    // show pop up
}

Alternatively, reset the counter every time it reaches 10:

if gamesPlayedSaved == 10 {
    // show pop up
    gamesPlayedSaved = 0
}

Upvotes: 2

xmhafiz
xmhafiz

Reputation: 3538

use modulus %. if (gamesPlayedSaved % 10 == 0)

It will finds the remainder after division of 10

Upvotes: 1

zoul
zoul

Reputation: 104075

Take a look at this:

for i in 1...100 {
    if i % 10 == 0 {
        print("Yep: \(i)")
    }
}

Which outputs:

Yep: 10
Yep: 20
Yep: 30
Yep: 40
Yep: 50
Yep: 60
Yep: 70
Yep: 80
Yep: 90
Yep: 100

The % operator is called modulo, it returns the remainder when dividing a number A with number B. In your case you are interested in the cases when the number of games played is divisible by 10, ie. numberOfGamesPlayed % 10 == 0.

Upvotes: 2

Related Questions