0

I have a game where you click the circles as they fall into the target, but right now I have it so they all just fall from left to right and so on. I want them to fall in a random order, but I have no clue how. Here is my code for it:

var alternator = 0
var flag:Bool = true
var fallTimer:NSTimer?

func fallCircleWrapper() {

    if (flag == true) {
        self.alternator += 1
    } else {
        self.alternator -= 1
    }

    if (self.alternator == 0) {
        flag = true
    } else if (self.alternator == 5) {
        flag = false
    }

    self.hitAreaArray[self.alternator].emitNote(self.texture!)

}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
shadokyr
  • 65
  • 4

2 Answers2

0

To get random numbers, you use one of the arc4random-functions, so in this case for example

let directionLeft = arc4random()%2 == 0

Other remark: it is not necessary to compare the flag to true.

This answer How does one generate a random number in Apple's Swift language? tells you more about random numbers.

Community
  • 1
  • 1
Gerriet
  • 1,302
  • 14
  • 20
  • I am new to this and still learning, could you tell me what to do with this in my code? Thanks – shadokyr May 02 '17 at 19:14
  • This would give you a boolean flag for the direction with a random value each time you call it. 50% of the time it would be true, 50% it would be false. This is achieved by computing a random integer and computing modulo 2, so for each even number directionLeft is true and otherwise false. – Gerriet May 03 '17 at 06:21
-1
// import GameplayKit for it's random generator capabilities
import GameplayKit

// this expression generates an array of NSNumbers where the values
// are 0 to 4 - [0, 1, 2, 3, 4] but wrapped in NSNumbers 
let circleIndexes = (0..<5).map { return NSNumber(value: $0) }

// uses a function in GameplayKit to shuffle the indexes in
// the circleIndexes array
let randomIndexes = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: circleIndexes) as! [Int]

func fallCircleWrapper() {

    if (flag == true) {
        self.alternator += 1
    } else {
        self.alternator -= 1
    }

    if (self.alternator == 0) {
        flag = true
    } else if (self.alternator == 5) {
        flag = false
    }

   // Now we select the circle to drop by choosing
   // the next item out of the list of randomized indexes
   self.hitAreaArray[randomIndexes[self.alternator]].emitNote(self.texture!)
}
Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • While this may work, you haven't explained what it's doing. Many new developers have no idea what .map does and have never used GK. – TheValyreanGroup May 02 '17 at 23:22