Skip to content

Instantly share code, notes, and snippets.

@bendisposto
Created December 5, 2013 11:07
Show Gist options
  • Save bendisposto/7803619 to your computer and use it in GitHub Desktop.
Save bendisposto/7803619 to your computer and use it in GitHub Desktop.
(ns muster.core)
;Aufgabe 1
(defn flip [f] (fn [& args] (apply f (reverse args))))
(defn mycomp [& fs]
(fn [& args] (reduce (fn [a f] (f a))
(apply identity args)
(reverse fs))))
(defn myjuxt [& fs]
(fn [& args]
(vec (for [f fs] (apply f args)))))
;; Aufgabe 2
(def width 7)
(def height 6)
(def winners (read-string (slurp "winners.clj")))
(def state (atom nil))
(def next-turn {:r :y, :y :r})
(defn- swap-turn [state]
(next-turn (:turn state)))
(defn- col [state x] ((group-by ffirst (:board state)) x))
(defn- col-size [state x] (count (col state x)))
(defn- place! [x]
(let [s @state
y (col-size s x)
c (:turn s)
c' (swap-turn s)
b' (assoc (:board s) [x y] c)]
(swap! state assoc
:board b'
:turn c'
:last [x y])))
(defn won? [state ts]
(when (and
(seq ts)
(apply = (map (:board state) ts))) ts))
(defn- watch-fkt [_ r o n]
(let [w (winners (:last n))]
(when-let [x (some (partial won? n) w)]
(println "Spiel beendet! Gewonnen hat" (:turn o) "Gewinnsteine:" x)
(remove-watch state :win)
(swap! state assoc :won (:turn o))
)))
(defn init! []
(reset! state {:board {} :turn :r})
(add-watch state :win watch-fkt))
(defn full? [state column]
(= height (col-size state column)))
(defn turn!
([column color] (when (= color (:turn @state)) (turn! column)))
([column]
(let [s @state]
(when-not
(or
(full? s column)
(:won s)
(>= column width))
(place! column)))))
(defn delta [t]
(- (apply max t) (apply min t)))
(defn aligned? [& p]
(or (and (apply = (map first p)) (= 3 (delta (map second p))))
(and (apply = (map second p)) (= 3 (delta (map first p))))
(and (apply = (map (fn [[x y]] (+ x y)) p))
(= 3 (delta (map first p))))
(and (apply = (map (fn [[x y]] (- x y)) p))
(= 3 (delta (map first p))))))
(defn tuples [tx ty] (for [x (range tx) y (range ty)] [x y]))
(defn quadruples [tx ty]
(set (remove (fn [x] (< (count x) 4))
(let [t (tuples tx ty)]
(for [t1 t t2 t t3 t t4 t
:when (aligned? t1 t2 t3 t4)]
(hash-set t1 t2 t3 t4))))))
(defn make-map [tx ty]
(into {}
(let [q (quadruples tx ty)]
(for [t (tuples tx ty)]
[t (filter (fn [x] (x t)) q)]))))
(defn save-winners [tx ty]
(spit "winners.clj"
(prn-str (make-map tx ty))))
(def print-map {:r "r" :y "y" nil "*"})
(defn pb [b]
(doseq [y (range (dec height) -1 -1)]
(doseq [x (range width)]
(let [color (print-map (b [x y]))]
(print color)))
(println)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment