1

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.

Peter L
  • 315
  • 1
  • 4
  • 8

3 Answers3

3
  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()
}
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
1

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)
}

}
matthias
  • 947
  • 1
  • 9
  • 27
1

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)
}
Community
  • 1
  • 1
Godlike
  • 1,621
  • 2
  • 20
  • 33