委託模式初體驗
阿新 • • 發佈:2018-12-12
1. 個人遊戲
import UIKit protocol TurnBasedGameDelegate { func gameStart() func playerMove() func gameEnd() func gameOver() -> Bool } protocol TurnBasedGame { var turn: Int {get set} func play() } class SinglePlayerTurnBasedGame: TurnBasedGame { var delegate: TurnBasedGameDelegate! var turn = 0 func play() { delegate.gameStart() while !delegate.gameOver() { print("ROUND", turn, ":") delegate.playerMove() turn += 1 } delegate.gameEnd() } } class RollNumberGame: SinglePlayerTurnBasedGame, TurnBasedGameDelegate { var score = 0 override init() { super.init() delegate = self } func gameStart() { score = 0 turn = 0 print("Welcome to Roll Number Game.") print("Try to use least turn to make total 100 scores") } func playerMove() { let rollNumber = Int(arc4random()) % 6 + 1 // 返回1~6之間隨機數 score += rollNumber print("You rolled a", rollNumber, "! The score is", score, "now!") } func gameEnd() { print("Congratulation! You win the game in", turn, "ROUND!") } func gameOver() -> Bool { return score >= 100 } } let rollingNumber = RollNumberGame() rollingNumber.play()
2. 石頭剪刀布
import UIKit protocol TurnBasedGameDelegate { func gameStart() func playerMove() func gameEnd() func gameOver() -> Bool } protocol TurnBasedGame { var turn: Int {get set} func play() } class SinglePlayerTurnBasedGame: TurnBasedGame { var delegate: TurnBasedGameDelegate! var turn = 0 func play() { delegate.gameStart() while !delegate.gameOver() { turn += 1 print("ROUND", turn, ":") delegate.playerMove() } delegate.gameEnd() } } class RockPaperSscissors: SinglePlayerTurnBasedGame, TurnBasedGameDelegate { enum Shape: Int, CustomStringConvertible { case Rock // 0 case Scissors // 1 case Paper // 2 // 列舉裡面也可以有函式 func beat(shape: Shape) -> Bool { // 看自己能否打敗傳進來的引數 return (self.rawValue + 1) % 3 == shape.rawValue // 這個可以體會一下 } var description: String { // 輸出該變數的時候應該是這種格式 switch self { case .Paper: return "Paper" case .Rock: return "Rock" case .Scissors: return "Scissors" } } } var wins = 0 var otherWins = 0 override init() { super.init() delegate = self } static func go() -> Shape { return Shape(rawValue: Int(arc4random()) % 3)! } func gameStart() { wins = 0 otherWins = 0 print("== Rock Paper Scissor ==") } func gameOver() -> Bool { return wins == 2 || otherWins == 2 } func gameEnd() { if wins == 2 { print("AFTER \(turn) ROUNDS, YOU WIN!") } else { print("AFTER \(turn) ROUNDS, YOU LOSE...") } } func playerMove() { let yourShape = RockPaperSscissors.go() let otherShape = RockPaperSscissors.go() print("Your: \(yourShape)") print("Other: \(otherShape)") if yourShape.beat(shape: otherShape) { print("You win this round") wins += 1 } else if otherShape.beat(shape: yourShape) { print("You lose this round") otherWins += 1 } else { print("Tie in this round") } } } let rockPaperScissors = RockPaperSscissors() rockPaperScissors.play()