Keep in mind one rule in this function:
If enemyType
is 0
we create a bomb, otherwise we create a penguin.
var enemyType = Int.random(in: 0...6)
We are creating a new enemy and assign it a type randomly. This is a number within the range of 0
to 6
. This line adds an element of randomness to whether we will create a bomb or a penguin each time the function is called.
This function takes an optional parameter that can be either .random
(the default), .never
, or .always
, which determines whether or not the newly spawned enemy can be a bomb.
If the forceBomb
parameter is set to .random
(which it is by default), then we can just use the number generated for enemyType
above.
However we should take the forceBomb
parameter into account...
if forceBomb == .never {
enemyType = 1
} else if forceBomb == .always {
enemyType = 0
}
If the forceBomb
parameter is set to .never
, we don't ever want a bomb. We set enemyType
to 1
.
If the forceBomb
parameter is set to .always
, well, we always want a bomb. We set enemyType
to 0
.
Remember the rule I stated at the beginning of this post.
Now we come to the meat of this function. We create a new enemy based on the value of enemyType
.
if enemyType == 0 {
//create a bomb
} else {
//create some other non-bomb type of enemy
}
If we have an enemyType
that is 0
we create a bomb. If the forceBomb
parameter was set to .always
, then enemyType
has been set to 0
and we'll always get a bomb.
If we have an enemyType
that is not 0
, we create a penguin. If the forceBomb
parameter was set to .never
, then enemyType
has been set to 1
, which is not 0
, and we'll never get a bomb.
Essentially, we use a random number to determine if we get a bomb or a penguin, but then use the value of the forceBomb
parameter to supersede that random number and force the outcome we want.
Make sense?