Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(ns tic.tac.toe
(:require [reagent.core :as r]))
(enable-console-print!)
(defn vanilla-state []
(r/atom {:squares (vec (repeat 9 nil))
:x-is-next true
:winner nil}))
(defn attempt-turn [state i]
(if (-> state :squares (get i))
state ;; Return state unmodified
(-> state
(assoc-in [:squares i] (if (:x-is-next state) "X" "O"))
(update-in [:x-is-next] not))))
(defn handle-click [state i]
(swap! state attempt-turn i))
(defn square [state i]
[:button.square {:key i :on-click #(handle-click state i)}
(-> @state :squares (get i))])
(defn render [state]
(let [square (partial square state)]
[:div
[:div.status "Next player " (if (:x-is-next @state) "X" "O")]
[:div.board-row (doall (map square [0 1 2]))]
[:div.board-row (doall (map square [3 4 5]))]
[:div.board-row (doall (map square [6 7 8]))]
[:button {:on-click #(reset! state (vanilla-state))} "Reset game!"]]))
(r/render [render (vanilla-state)] js/klipse-container)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.