Skip to content

Instantly share code, notes, and snippets.

@jaju
Created September 13, 2015 04:46
Show Gist options
  • Save jaju/1158a439c974b76772ff to your computer and use it in GitHub Desktop.
Save jaju/1158a439c974b76772ff to your computer and use it in GitHub Desktop.
(ns s-and-l.main)
#?(:cljs (set! *print-fn* #(.log js/console %)))
#?(:cljs (def log print))
#?(:clj (def log println))
(def max-board-value 100)
(defn roll-dice []
(-> #?(:cljs (.random js/Math) :clj (java.lang.Math/random))
(* 100)
int
(rem 6)
(+ 1)))
(def board {03 10, 18 51, 26 04,
32 62, 37 80, 44 91,
56 22, 60 89, 97 15})
(defn climb-or-drop-position [current-position]
(let [next-position (board current-position current-position)]
(if-not (= current-position next-position)
(log "And we've been promoted/demoted from " current-position " to " next-position))
next-position))
(defn get-next-position [current-position dice-value]
(let [provisional-position (+ current-position dice-value)]
(if (> provisional-position max-board-value)
current-position
(climb-or-drop-position provisional-position))))
(defonce ^:dynamic *player-positions* (atom {}))
(defn create-players [num-players]
(reset! *player-positions* (zipmap (iterate inc 0) (take num-players (iterate identity 0)))))
(defn game-over? []
(some #(= max-board-value (second %)) @*player-positions*))
(defn update-player-position [player-number new-position]
(swap! *player-positions* assoc player-number new-position))
(defn play [player]
(let [dice-value (roll-dice)]
(log (str "Player " player " rolled dice to get " dice-value))
(update-player-position player (get-next-position (@*player-positions* player) dice-value))))
(defn ^:export play-a-game [num-players]
(let [_ (create-players num-players)]
(loop [player 0]
(play player)
(if (game-over?)
(log (str "Game over. Player " player " won."))
(recur (rem (inc player) num-players))))))
(defn -main [& args]
(let [num-players (str (or (first args) "2"))]
(play-a-game #?(:cljs (js/parseInt num-players) :clj (java.lang.Integer/parseInt num-players)))))
#?(:cljs (set! *main-cli-fn* -main))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment