在父类中设计委托

protocol TurnBasedGame {
    var turn: Int { get set }
    func play()
}

protocol TurnBasedGameDelegate {
    func gameStart()
    func PlayerMove()
    func gameEnd()

    func turnStart()
    func gameOver() -> Bool
}


class SinglePlayerTurnBasedGame: TurnBasedGame {
    var turn = 0
    var delegate: TurnBasedGameDelegate!
    func play() {
        delegate.gameStart()
        while !delegate.gameOver() {
            turnStart()
            delegate.playerMove()
            turn += 1
        }
        delegata.turnEnd?()
        delegate.gameEnd()
    }
}

class RollNumberGame: SinglePlayerTurnBasedGame, TurnBasedGameDelegate {
    var score = 0
    override init() {
        super.init()
        delegate = self
    }
    func gameStart() {
        score = 0
        truen = 0
    }
    func gameOver() -> Bool {
        return score >= 100
    }

    func playerMove() {
        let rollNumber = Int( arc4random() )%6 + 1 
        score += rollNumber
    }
    func gameEnd() {
        print ("gameEnd")
    }
}

let rollNumberGame = RollNumberGame()
rollNumberGame.play()

你可能感兴趣的:(在父类中设计委托)