Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (ns mastercly.core
- (:require [reagent.core :as reagent :refer [atom]]
- [secretary.core :as secretary :include-macros true]
- [accountant.core :as accountant]))
- ;; -------------------------
- ;; Views
- (defn initial-state [] {:goal [:blue :blue :blue :red]
- :attempts []
- :current-attempt [:blue :blue :blue :blue]})
- (def *game (atom (initial-state)))
- (def colors [:blue :red :yellow :orange :green])
- (def size 4)
- (defn color-selector [x idx]
- [:input {:type "button"
- :value x
- :on-click #(swap! *game update-in [:current-attempt idx] (fn [] x))
- :style (if (= x (get-in @*game [:current-attempt idx]))
- {:background-color x}
- {})}])
- (defn score-render [attempt gold]
- [:span
- (let [total-correct (reduce + (map (fn [a g] (if (= a g) 1 0)) attempt gold))
- color-correct (reduce + (map (fn [c] (let [in-attempt (filter (fn [x] (= c x)) attempt)
- in-goal (filter (fn [x] (= c x)) gold)]
- (min (count in-attempt) (count in-goal)))) colors))]
- (str (- color-correct total-correct) " " total-correct)
- )])
- (defn attempt-report [attempt]
- [:div (score-render attempt (:goal @*game)) (map (fn [x] (str x)) attempt)])
- (defn home-page []
- [:div [:h2 "Mastermind :)"]
- [:input {:type "button" :value "start"
- :on-click #(reset! *game (initial-state))}]
- [:div (str @*game)]
- (map (fn [idx] [:div (map (fn [x] (color-selector x idx)) colors)]) (range 4))
- [:input {:type "button"
- :value "attempt!"
- :on-click #(swap! *game assoc :attempts (conj (:attempts @*game) (:current-attempt @*game)))
- }]
- (map attempt-report (reverse (:attempts @*game)))
- [:div [:a {:href "/about"} "go to about page"]]])
- (defn about-page []
- [:div [:h2 "About mastercly"]
- [:div [:a {:href "/"} "go to the home page!!!"]]])
- ;; -------------------------
- ;; Routes
- (def page (atom #'home-page))
- (defn current-page []
- [:div [@page]])
- (secretary/defroute "/" []
- (reset! page #'home-page))
- (secretary/defroute "/about" []
- (reset! page #'about-page))
- ;; -------------------------
- ;; Initialize app
- (defn mount-root []
- (reagent/render [current-page] (.getElementById js/document "app")))
- (defn init! []
- (accountant/configure-navigation!
- {:nav-handler
- (fn [path]
- (secretary/dispatch! path))
- :path-exists?
- (fn [path]
- (secretary/locate-route path))})
- (accountant/dispatch-current!)
- (mount-root))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement