0

I'm trying to learn swift by creating different short games or apps. while trying to test my new gain knowledge on a game, I realized that I need to create a func that I didnt know how to create. I've looked around and none of the answers I've found really helped me understand what I have to do.

I'll summarize my game:

Its a single view app. I've got five func.

I want to randomly pick a function to be executed.

After the function is executed the user will press a button that runs the random pick function again to randomly pick a func, but this time only out of the four other func that are left, and so on. At the same time once the five functions have been executed I want to restart the pick a random func all over again. so the game goes on and on for ever.

I'm not sure how to place the func In an array to make it work.

For example I've been using the following script in the game.

Func one generates a Label that shows a random string.

I've used the following script to create a random word generator for a label with out repeats and once it runs through all the words in the array it restarts again randomly. (It works perfectly)

    struct randword {
     var wordstring : String! }


   var stentenceword = [randword]
   var stentecenumber = Int


  func wordsinsentence (){
     sentenceword = [randoword(wordstring:"House"), randoword(wordstring:"Truck"), randoword(wordstring:"Ladder")]
   }

  func pickword(){
      if sentenceword.count > 0 {
          sentencenumber = random () % sentenceword.count
          wordlabel.text = sentecneword[sentencenumber].wordstring

      sentenceword.removeAtIndex(sentencenumber)

        ); if sentenceword.count <= 0{
          wordsinsentence() }

Func two generates a random Image using the same script as before, just slightly modified for images.

Func three is a timer game with another script... and so on..etc etc.

Now I want all five func to randomly be picked and removed then once there aren't anymore left to restart, as on the example script I placed above.

I've tried using the same script and modifying it to replace the string! array with a function array, but with no positive result.

Can anyone help me with a solution or showing me another option of how I should do it?

3 Answers 3

1

Your question is a little difficult to follow, but let's focus on your most clear questions:

  • I'm not sure how to place the func In an array to make it work.
  • I want to randomly pick a function to be executed.
  • no repeats

First, to pick values randomly with no repeats you take a list and shuffle it into a random order. There's no need to keep track of previously selected items. Shuffling in Swift is explained very well by Nate Cook at How do I shuffle an array in Swift?

So that brings us to the second question, how do we create an array of functions? That's the simplest part. You just make an array of functions.

func first() { print("first") }
func second() { print("second") }
func third() { print("third") }

let fs = [first, second, third]

That's all there is to it. Now let's put them together and call them in a random order:

for f in fs.shuffle() {
    f()
}
1

I tried to copy paste your code to a playground and try to fix it but its kinda unreadable. Indentation is really good habit especially if someone else has to look at your code. Anyway imagine if you could just say Int.radomOutOf(5) and it just returns some random number between 0 and 5. well you can do just that by adding extension to the class Int or CGFloat or Double as you wish. and have function to keep track of your the games life time and call those random functions. here is how to do it (I hope I didn't forget anything)

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var textLabel: UILabel!

    var randomIndex = Int()
    let NumberOfFunctions = 4
    var chosenIndexes: [Int] = []{
        didSet{
            if chosenIndexes.count == NumberOfFunctions { chosenIndexes.removeAll() }
        }
    }

    @IBAction func buttonPressed(sender: UIButton) {
        functionSelector()
    }

    func functionSelector(){

        repeat{
            randomIndex = Int.randomOutOf(NumberOfFunctions)
            print("selected: \(randomIndex) \(chosenIndexes)")
        } while chosenIndexes.contains(randomIndex) 

        chosenIndexes.append(randomIndex)

        switch randomIndex {
        case 0: function1()
        case 1: function2()
        case 2: function3()
        case 3: function4()
        default: break
        }
    }


    func function1(){
        textLabel.text = "sentence 1"
    }
    func function2(){
        textLabel.text = "sentence 2"
    }
    func function3(){
        textLabel.text = "sentence 3"
    }
    func function4(){
        textLabel.text = "sentence 4"
    }


}
//your extension to pick random
private extension Int {
    static func randomOutOf(max:Int) ->Int{
        print("max: \(max)")
        return Int(arc4random() % UInt32(max)) // returns 0 - max
    }
}
14
  • I added return in the -if gameLifeCount == 0 because otherwise it will call the fifth case everytime you call restart. I just remembered :) , sorry about that
    – Lukas
    Sep 23, 2015 at 13:07
  • I've placed the example script you provide me and it doesn't work. Right on the repeat statement it generates an error saying I'm missing an ; and an { . If I place the them both it generates 3 new errors. 1) Implicit use of 'self' in closure, use self. to make semantics explicit. 2) missing argument for parameter 'count' in call. 3) '[(Int)]'does not have a member named 'contains' Sep 23, 2015 at 21:26
  • How or what should I do to fix the errors? And can you please review the example script you gave me and edit it if you forgot something. Thank you Lukas. Sep 23, 2015 at 21:33
  • I assumed you're using swift 2.0, if not the repeat while loop won't work. replace it with do while or just while and loop out with if condition. I'll edit it above
    – Lukas
    Sep 24, 2015 at 0:14
  • and also 'array.contains(element)' is the new version (swift 2) of 'contains(array, element)' in swift 1.2
    – Lukas
    Sep 24, 2015 at 0:25
0

Not a separate answer

This is just to show the first answer runs just fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.