M. Young's Swift Playground Rendition of the Craps Flowchart

M. Young Leading Swift Playground Craps Flowchart Discussion
student leader teaching Swift
peer teaching in Swift

In the iPhone programming class, M. Young came up with an elegant rendition of the Craps flowchart in Swift1 code:


func rollDice()->Int{
   var dice1 = (arc4random() % 5) + 1
   var dice2 = (arc4random() % 5) + 1
   var sum = dice1 + dice2
   return Int(sum)
}

func playGame() ->Bool{
   var sum = rollDice()
   if(sum == 7 || sum == 11){
      return true //win!
   }else if(sum == 2 || sum == 3 || sum == 12){
      return false //lose!
  }else{ //establish point and play till reach it or bust with a 7
      var point = sum
      do{
         var newRoll = rollDice()
         if(newRoll == point){
            return true //win! exits loop
         }else if(newRoll == 7){
            return false //lose! exits loop
         }
      }while(true)
  }
}

var winCount = 0
var lossCount = 0
for i in 1...15000{
   var didWin = playGame()
   if(didWin){winCount++}
   if(!didWin){lossCount++}
}
println(winCount)
println(lossCount)

Comments

admin's picture

CG hated to admit it but this code knocked the ball out of the playground! It even threw in additional functionality to examine the win-loss counts for a large number of games. Well done, M.Young!

admin's picture

M. Young just finished an impromptu lecture on his Swift playground rendition of the Craps flowchart. It was logical, clear and inspiring. CG may be out of a job....