Skip to content

Instantly share code, notes, and snippets.

@craftybones
Created May 9, 2021 15:50
Show Gist options
  • Save craftybones/c03c2ba186fcc7c9eaa7fa5de39ed2ea to your computer and use it in GitHub Desktop.
Save craftybones/c03c2ba186fcc7c9eaa7fa5de39ed2ea to your computer and use it in GitHub Desktop.
(defn make-set-of-positions
[positions]
(->> positions
(mapcat second)
(into #{})))
(defn create-game
"Creates a game consisting of players and their ship positions.
positions is expected as a map {:carrier #{1 2 3 4 5}, :destroyer...}"
[player-1-positions player-2-positions]
{:current {:positions player-1-positions
:name "player 1"
:hits #{}
:safe (make-set-of-positions player-1-positions)}
:opponent {:positions player-2-positions
:name "player 2"
:hits #{}
:safe (make-set-of-positions player-2-positions)}})
(defn make-move
[game position]
(let [opp-pos-valid? (get-in game [:opponent :safe position])]
(cond-> game
opp-pos-valid? (update-in [:opponent :hits] conj position)
opp-pos-valid? (update-in [:opponent :safe] disj position)
true (rename-keys {:current :opponent :opponent :current}))))
(defn get-latest-status [{:keys [current opponent] :as game}]
{:opponent-hits (:hits opponent)
:my-hits (:hits current)
:my-safe (:safe current)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment