委托模式初体验

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

猜你喜欢

转载自blog.csdn.net/shijie97/article/details/84491649