In my spritekit game, I spawn one of two enemies. The enemy to be spawned is decided on a random generated bool, using arc4random_uniform(2)
.
I'm trying to create a way of controlling the distribution. Basically, I don't want it to generate 3 1
's (true
's) in a row...
I figured the best way to do that would be to check each time somethings generated, and increment a count, and if it exceeds the count, change the generated bool
to the opposite value.
I think I'm confusing myself a little though as I can't get it to work.
Is there a simple way to do this, or can my code be modified to get it working? Thanks.
var randomSequenceNumber = Int(arc4random_uniform(2)) == 0 ? true: false
if randomSequenceNumber {
seqCount = randomSequenceNumber
obNum++
print("Obstacle Count: ", obNum)
}
if obNum <= 3 {
randomSequenceNumber = !seqCount
obNum = 0
}
(probably having a major brain fart)
I wanted to generate random bools
in a sequence, but should the same bool
value get generated more than 3 times in a row, it was changed to the opposite.
But at the same time, I didn't just want it to just alternate, like true false true false true false
etc
So it could gerate true false true false true false
, or true true false false true false true false false true false
but never true true true true false true false true false false false false
... etc
This meant I needed to store the values, compare them, change the value if the last x
amount matched, and reset the stored values ready to compare next time around.
This is how I did it:
var randSeqArray: [Bool] = [] //empty array for bools
In my function that generates bools
:
randSeqArray.append(randomBool) //add bool to array
if randSeqArray.count == 2 { //if matches count
if randSeqArray[0] == randSeqArray[1] { //if elements match
print("-------> last two bools matched!")
randomBool = !randomBool //change bool to opposite
}
randSeqArray.removeAll(keepCapacity: true) //empty array
randSeqArray.append(randomBool) //add bool back, ready to check next time
}
Obviously, this code ensures the random bool alternates (for testing), but it can be adopted to allow a possibility of up to x
matching bools in a row before it gets reset.
This is the above example that checks if the last 3 generated bools match, ensuring that you never get more than 2 of the same bools in a row:
randSeqArray.append(randomBool)
if randSeqArray.count == 3 {
if randSeqArray[0] == randSeqArray[1] && randSeqArray[1] == randSeqArray[2] {
print("-------> last three bools matched!")
randomBool = !randomBool
}
randSeqArray.removeAll(keepCapacity: true)
randSeqArray.append(randomBool)
}