-
-
Save rightfold/e57a87378dac70e38d3c 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
(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