Skip to content

Instantly share code, notes, and snippets.

@spadafiva
Created July 11, 2017 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spadafiva/b0ebfa706299a015fb8e9c0010f531dd to your computer and use it in GitHub Desktop.
Save spadafiva/b0ebfa706299a015fb8e9c0010f531dd to your computer and use it in GitHub Desktop.
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