Peter L
Peter L

Reputation: 315

How do I make a function choose random paths?

So what I'm trying to do is call a function, that will run only 1 function out of 4 possible functions, so it randomly decides which one to do.

In this case those 4 functions that I'm trying to have randomly be chosen are moveUp() moveDown() moveRight() and moveLeft().

This is what I've got right now and its not really working out well. I haven't found anything to help.

func moveComputerPlayer() {

//This is where I have no idea what to do.
"randomly choose to run: moveRight(), moveLeft(), moveUp(), moveDown()


}

Thanks.

Upvotes: 1

Views: 84

Answers (3)

matthias
matthias

Reputation: 947

Use arc4random() or arc4random_uniform() to generate a random number. Use e.g. switch case statement to associate number with one of the functions.

In your case:

func moveComputerPlayer() {
let rd = Int(arc4random_uniform(4) + 1)
switch rd {
case 1:
    moveRight()
case 2:
    moveLeft()
case 3:
    moveUp()
case 4:
    moveDown()
default:
   print(rd)
}

}

Upvotes: 1

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

  1. Create an array of possible functions/methods.
  2. Select a random element.
  3. Call the chosen function.

Remember, functions are types in Swift.

func moveUp() {}
func moveDown() {}
func moveLeft() {}
func moveRight() {}

func moveComputerPlayer() {
    let moves = [
        moveUp,
        moveDown,
        moveLeft,
        moveRight,
    ]

    let randomIndex = Int(arc4random_uniform(UInt32(moves.count)))
    let selectedMove = moves[randomIndex]
    selectedMove()
}

Upvotes: 3

Godlike
Godlike

Reputation: 1948

Take a look here:

https://stackoverflow.com/a/24098445/4906484

And then:

  let diceRoll = Int(arc4random_uniform(4) + 1)

switch (diceRoll) {
    case 1: 
        moveRight()
    case 2:
        moveLeft()
    case 3:
        moveUp()
    case 4:
        moveDown()
    default: 
        print("Something was wrong:" + diceRoll)
}

Upvotes: 1

Related Questions