Skip to content

Instantly share code, notes, and snippets.

@viebel
Forked from ingesolvoll/tictactoe.cljs
Last active January 13, 2017 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viebel/9c0201a060d75b2c722d4e77dbf79907 to your computer and use it in GitHub Desktop.
Save viebel/9c0201a060d75b2c722d4e77dbf79907 to your computer and use it in GitHub Desktop.
(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