Skip to content

Instantly share code, notes, and snippets.

@MattRoelle
Last active December 17, 2021 01:32
Show Gist options
  • Save MattRoelle/480f1fd58f19a221ba4e7bf84c5c35de to your computer and use it in GitHub Desktop.
Save MattRoelle/480f1fd58f19a221ba4e7bf84c5c35de to your computer and use it in GitHub Desktop.
;; Redux style state management
(local initial-state
{:screen nil
:energy 0
:deck (icollect [_ ct (ipairs [:scout :warrior :healer :archer :scout :scout :scout])]
(make-card ct))
:hand []
:field []
:discard []})
;; All actions go through a reducer. nil action returns initial state
(fn state-reducer [state ...]
(let [action [...]]
(match action
[:level-complete] (lume.merge state {:screen :bottom})
[:begin-level] (lume.merge state {:screen :top})
[:play-card card]
(let [{: deck : hand : field : discard} state
_ (print "args" (inspect ...))
new-hand (lume.filter hand #(not= $1.id card.id))
new-field (lume.concat field [card])]
(lume.merge state {:field new-field :hand new-hand}))
[:discard card]
(let [{: deck : hand : field : discard} state
new-field (lume.filter field #(not= $1.id card.id))
new-discard (lume.concat discard card)]
(lume.merge state {:field new-field :discard new-discard}))
[:draw-card]
(let [{: deck : hand : discard} state]
(var new-deck (lume.clone deck))
(var new-discard (lume.concat state.discard hand))
(var new-hand [])
(when (= (length state.deck) 0)
(set new-deck (lume.shuffle discard))
(set new-discard []))
(for [i 1 3]
(table.insert new-hand (table.remove new-deck 1)))
(lume.merge state
{:energy 3
:deck new-deck
:discard new-discard
:hand new-hand}))
_ initial-state)))
;; Store object tracks state over time
(local store (golly.create-store state-reducer))
;; Actions are dispatched to the store
(store:dispatch :discard self.card)
(store:dispatch :begin-level)
;; Game objects subscribe to changes in the state
(entity:on :state-change
(fn [new-state]
(each [_ c (ipairs (self.scene:find-all :card))]
(when (not (lume.match new-state.hand #(not= $1.id c.card.id)))
(c:destroy!)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment