Last active
January 3, 2018 02:15
-
-
Save souenzzo/96630868f59976e03bbb4477bc3059cb to your computer and use it in GitHub Desktop.
simple hanoi tower game. Available at https://souenzzo.github.io/hanoi.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns hanoi.core | |
(:require [reagent.core :as reagent :refer [atom]])) | |
(def init | |
{:tabuleiro {0 [4 3 2 1] | |
1 [] | |
2 []}}) | |
(defn atualizar-tabuleiro | |
[st from to] | |
(let [tabuleiro (get st :tabuleiro) | |
coluna-from (get tabuleiro from) | |
coluna-to (get tabuleiro to) | |
novo-tabuleiro (merge tabuleiro | |
{from (vec (butlast coluna-from)) | |
to (conj coluna-to (last coluna-from))})] | |
(assoc st :tabuleiro novo-tabuleiro))) | |
(defn atualizar-jogadas | |
[st] | |
(assoc st :jogadas (for [[from from-coluna] (:tabuleiro st) | |
[to to-coluna] (:tabuleiro st) | |
:let [max1 (or (last from-coluna) 100) | |
max2 (or (last to-coluna) 100)] | |
:when (> max2 max1)] | |
[from to]))) | |
(defonce state | |
(atom (atualizar-jogadas init))) | |
(defn tabuleiro | |
[tabuleiro] | |
[:svg | |
(for [[id-torre pecas] tabuleiro] | |
[:rect {:key id-torre | |
:x (* id-torre 40) | |
:y 0 | |
:width 30 | |
:height 100 | |
:stroke "black" | |
:fill "transparent" | |
:stroke-width 1}]) | |
(for [[id-torre pecas] tabuleiro] | |
(map-indexed (fn [i peca] | |
[:circle {:key i | |
:cx (+ 15 (* 40 id-torre)) | |
:cy (- 90 (* 20 i)) | |
:stroke "black" | |
:stroke-width 1 | |
:r (* peca 2)}]) pecas))]) | |
(defn fazer-jogada | |
[st from to] | |
(-> (atualizar-tabuleiro st from to) | |
(atualizar-jogadas) | |
(update :ops (fnil inc 0)))) | |
(defn botoes | |
[jogadas] | |
[:div (for [[from to] jogadas] | |
[:button {:key (str [from to]) | |
:on-click (fn [] | |
(swap! state fazer-jogada from to))} | |
(str from " -> " to)])]) | |
(defn hello-world [] | |
(let [st @state] | |
[:div | |
[:div "Torre de hanoi!!"] | |
(when (:ops st) | |
[:div "Jogadas: " (:ops st)]) | |
[tabuleiro (:tabuleiro st)] | |
[botoes (:jogadas st)] | |
[:br]])) | |
(reagent/render-component [hello-world] (. js/document (getElementById "app"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment