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?

Cristian Siles
  • 783
  • 1
  • 7
  • 13

3 Answers3

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
    }
}
Lukas
  • 3,423
  • 2
  • 14
  • 26
  • 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 '15 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' – Cristian Siles Sep 23 '15 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. – Cristian Siles Sep 23 '15 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 '15 at 00:14
  • and also 'array.contains(element)' is the new version (swift 2) of 'contains(array, element)' in swift 1.2 – Lukas Sep 24 '15 at 00:25
  • I just upgraded to swift 2.0 and I'm still getting the same error. In the Repeat statement, right after the } before the While, its still asking me to place an ;. After I insert the ; with the fix it, another error comes up. Expected { after while condition. And if placed the { } the same error comes up. Missing argument for parameter count in call. If I try the last edit you share with me i get an error that says do while statement is not allowed use repeat while instead. – Cristian Siles Sep 24 '15 at 16:27
  • Never mind Lukas I rewrote everything and now it worked. However when I run it to test it after a couple of clicks of the button to run the next random function it stops working. it doesn't cycle back. The test screen freezes. – Cristian Siles Sep 24 '15 at 16:40
  • Its running fine in my playground so I was confused for a sec there :) I'm glad I could help ;) – Lukas Sep 24 '15 at 16:44
  • Im running it in a project right now, running with four functions that just change a label with a new sentence. I've placed a button that every time its pressed it runs the functionselector func. It freezes after a couple of taps and its not restarting to cycle back once again through the four functions. – Cristian Siles Sep 24 '15 at 17:09
  • Sorry I can't help you right now, I'll check if you got help in about 3 hours – Lukas Sep 24 '15 at 17:30
  • I edited the whole thing to a simpler form, I'm guessing you intend to do more than just change label with those functions because if not, this is the messiest code just to do that – Lukas Sep 24 '15 at 21:04
  • Thanks Lukas but I copied exactly as your script. and again I've got two errors. Its on the Variable chosenIndexes, Its says 1} use of unresolved identifier didset and 2} variable used within its own initial value. I dont understand why it works for you and when I copy it I get errors. Anyhow Thanks for your Help. And yes the functions are more complex then just a label.text, I was just trying to simplify it as an example. – Cristian Siles Sep 24 '15 at 23:32
  • I actually created a project (not just a playground) to run the whole thing and it changes the label as you intended it just fine – Lukas Sep 24 '15 at 23:38
  • for "use of unresolved identifier didset" make sure its didSet{} with capital s and its also initialized as empty array. the didSet is a property observer and its called only when the variable is set so it should be ok, but maybe try willSet{}. it doesnt affect the outcome in this case so worth trying – Lukas Sep 24 '15 at 23:43
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()
}
Community
  • 1
  • 1
Rob Napier
  • 286,113
  • 34
  • 456
  • 610
0

Not a separate answer

This is just to show the first answer runs just fine

Community
  • 1
  • 1
Lukas
  • 3,423
  • 2
  • 14
  • 26