Created
March 11, 2016 18:44
-
-
Save rpazyaquian/659dab0a46bb07578d17 to your computer and use it in GitHub Desktop.
libwar - A library for playing War.
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
(ns libwar.domain) | |
;; Domain data structures and knowledge for war. | |
;; A War game | |
;; War has two players, and current state. | |
(def war-example | |
{:p1 {:deck [{:type :red | |
:value 1} | |
{:type :black | |
:value 2} | |
{:type :red | |
:value 3}] | |
:cards []} | |
:p2 {:deck [{:type :black | |
:value 1} | |
{:type :red | |
:value 2} | |
{:type :black | |
:value 3}] | |
:cards []} | |
:state :peace}) | |
;; utility functions | |
(defn top-card-value [p] | |
(:value (first (:cards p)))) | |
(defn award-winnings [{:keys [deck] :as p} cards] | |
;; TODO: make less awful | |
(-> p | |
(assoc :deck (vec (concat deck (shuffle (concat (:cards p) cards))))) | |
(assoc :cards []))) | |
;; queries and updates | |
(defn evenly-matched? [p1 p2] | |
(= (top-card-value p1) (top-card-value p2))) | |
(defn no-cards? [p] | |
(= 0 (count (:deck p)))) | |
(defn resolve-match [{:keys [p1 p2] :as game}] | |
; TODO: make this less awful | |
(let [p1-card (first (:cards p1)) | |
p2-card (first (:cards p2))] | |
(if (> p1-card p2-card) | |
(-> game | |
(update :p1 #(award-winnings % (:cards p2))) | |
(update :p2 #(assoc % :cards []))) | |
(-> game | |
(update :p2 #(award-winnings % (:cards p1))) | |
(update :p1 #(assoc % :cards []))))) | |
) | |
(defn play-n-cards [n {:keys [deck] :as p}] | |
(-> p | |
(update :deck #(drop n %)) | |
(update :cards #(concat (vec (take n deck)) %)))) | |
(defn play-cards [game n] | |
(-> game | |
(update :p1 #(play-n-cards n %)) | |
(update :p2 #(play-n-cards n %)))) | |
;; state transitions | |
(defn reset-game [game] | |
war-example) | |
(defn war-transition [{:keys [p1 p2] :as game}] | |
(if (evenly-matched? p1 p2) | |
(play-cards game 3) | |
(assoc (resolve-match game) :state :peace))) | |
(defn peace-transition [{:keys [p1 p2] :as game}] | |
(if (or (no-cards? p1) (no-cards? p2)) | |
(assoc game :state :game-over) | |
(assoc (play-cards game 1) :state :war))) | |
(defn tick-game [{:keys [state] :as game}] | |
(case state | |
:peace (peace-transition game) | |
:war (war-transition game) | |
:game-over (reset-game game))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment