Skip to content

Instantly share code, notes, and snippets.

@rightfold
Last active August 29, 2015 14:08
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 rightfold/e57a87378dac70e38d3c to your computer and use it in GitHub Desktop.
Save rightfold/e57a87378dac70e38d3c to your computer and use it in GitHub Desktop.
(defprotocol FSM
(state [this])
(accept-state? [this state])
(resume [this input]))
(defn resume-until-acceptance [fsm inputs]
(let [input (first inputs)
next-fsm (resume fsm input)]
(if (accept-state? next-fsm (state next-fsm))
next-fsm
(recur next-fsm (next inputs)))))
(defrecord Battle [player-health enemy-health battle-state]
FSM
(state [this] battle-state)
(accept-state? [this state] (#{:player-won :enemy-won} battle-state))
(resume [this input]
(case battle-state
:player-turn (let [new-enemy-health (dec enemy-health)]
(if (= 0 new-enemy-health)
(assoc this :battle-state :player-won, :enemy-health new-enemy-health)
(assoc this :battle-state :enemy-turn, :enemy-health new-enemy-health)))
:enemy-turn (let [new-player-health (dec player-health)]
(if (= 0 new-player-health)
(assoc this :battle-state :enemy-won, :player-health new-player-health)
(assoc this :battle-state :player-turn, :player-health new-player-health)))
:player-won this
:enemy-won this)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment