I found a very interesting board game in Apple's Mac Developer Library. It is a simple playground of codes. Based on those codes, I added random dice function to make the game more fun.
The updated codes work very well in Xcode playground, however, the same one does not work in IBM Swift Sandbox. The random function arc4random_uniform
is not supported there. Soon I found another Swift on-line complier so that I can share my codes with people who do not have Xcode nor Mac.
Here are the rules of the game:
- Start from square 1
- Get dice number: 1-6
- Move to next square based on dice number, for example, 3, moving 3 steps forward.
- Move to the end of ladder if ladder, up to 11 on square 3, or
- slip down to snake's tail if snake there,for example slip to 8 on square 19
- Stay if steps are more than 25.
- Game over when moving to exactly square 25.
- // function to get dice value
- func dice(diceValue : Int) -> Int {
- var value = diceValue
- if value >= 7 {
- // generate random number
- drand48()
- value = Int(arc4random_uniform(6) + 1)
- } else {
- // increment number in sequence till 7
- ++value
- value = value == 7 ? 1 : value
- }
- return value
- }
- let finalSquare = 25
- // Initialize array with 0s
- var board = [Int](count: finalSquare + 1, repeatedValue: 0)
- // Set jump and slip values for laders and snakes
- board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
- board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
- var square = 0
- var diceRoll = 0 // 0..6 for increment sequnce or > 6 for random number
- var step = 0
- print("你好,我是「茶樹油客」改寫的程序,讓我來玩遊戲吧!")
- gameLoop: while square != finalSquare {
- step++
- //diceRoll = dice(7) // random number
- diceRoll = dice(diceRoll) // sequence 1-6 number
- print("第\(step)步: 骰子: \(diceRoll), ", terminator: "")
- switch square + diceRoll {
- case finalSquare:
- // diceRoll will move us to the final square, so the game is over
- print("走到 \(finalSquare). \n祝賀,遊戲完成了!")
- break gameLoop
- case let newSquare where newSquare > finalSquare:
- // diceRoll will move us beyond the final square, so roll again
- print("太大, 不走")
- continue gameLoop
- default:
- // this is a valid move, so find out its effect
- square += diceRoll
- square += board[square]
- print("走到 \(square)")
- }
- }
The result is as follows:
你好,我是「茶樹油客」改寫的程序,讓我來玩遊戲吧!
第1步: 骰子: 1, 走到 1
第2步: 骰子: 2, 走到 11
第3步: 骰子: 3, 走到 4
第4步: 骰子: 4, 走到 8
第5步: 骰子: 5, 走到 13
第6步: 骰子: 6, 走到 8
第7步: 骰子: 1, 走到 18
第8步: 骰子: 2, 走到 20
第9步: 骰子: 3, 走到 23
第10步: 骰子: 4, 太大, 不走
第11步: 骰子: 5, 太大, 不走
第12步: 骰子: 6, 太大, 不走
第13步: 骰子: 1, 走到 16
第14步: 骰子: 2, 走到 18
第15步: 骰子: 3, 走到 21
第16步: 骰子: 4, 走到 25.
祝賀,遊戲完成了!
The original codes for the game are near the end in the section of Control Flow.
References
- Swift on-line compiler: My board game code
- Apple Developer Library: Swift Programming Language 2.1
0 comments:
Post a Comment