Created
July 11, 2017 13:22
-
-
Save spadafiva/b0ebfa706299a015fb8e9c0010f531dd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
enum ToyAction { | |
case inert | |
case smashIt | |
case flipIt | |
case rotateIt | |
case flickIt | |
case spinIt | |
case passIt | |
static let all: [ToyAction] = [.inert, .smashIt, .rotateIt, .flipIt, .flickIt, .spinIt, .passIt] | |
} | |
protocol ToyActionDelegate: class { | |
func toyActionDidChange(_ toy: Toy, from oldAction: ToyAction, to newAction: ToyAction) | |
} | |
class Toy { | |
weak var delegate: ToyActionDelegate? | |
var name: String | |
var currentAction: ToyAction = .inert { | |
didSet { | |
delegate?.toyActionDidChange(self, from: oldValue, to: currentAction) | |
} | |
} | |
init(name: String) { | |
self.name = name | |
} | |
func performAction(_ action: ToyAction) -> Bool { | |
let wasCorrectAction = action == currentAction | |
setNewRandomAction() | |
return wasCorrectAction | |
} | |
func startNewGame() { | |
currentAction = .inert | |
} | |
func play(_ rounds: Int) { | |
for _ in 0..<rounds { | |
setNewRandomAction() | |
} | |
startNewGame() | |
} | |
func setNewRandomAction() { | |
let randomIndex = Int(arc4random_uniform(UInt32(ToyAction.all.count - 1))) + 1 | |
currentAction = ToyAction.all[randomIndex] | |
} | |
} | |
class ToyActionPrinter: ToyActionDelegate { | |
func toyActionDidChange(_ toy: Toy, from oldAction: ToyAction, to newAction: ToyAction) { | |
print("\(toy.name) changed from \(oldAction) to \(newAction)") | |
} | |
} | |
var toy = Toy(name: "SmashMe") | |
var printer = ToyActionPrinter() | |
toy.delegate = printer | |
toy.startNewGame() | |
toy.play(15) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment