 (defn bounded-coords? [[x y]]
   (and (>= x 0) (< x dim) (>= y 0) (< y dim)))
 
+(defn manhattan [p1 p2]
+  (map #(clojure.contrib.math/abs (- %1 %2)) p1 p2))
+
+(defn distance [p1 p2]
+  (apply + (manhattan p1 p2)))
+
 (defn location [board [x y]]
   (nth board (+ (* x dim) y)))
 
 (defn position [board piece]
-  (.indexOf board piece))
+  (first (clojure.contrib.seq/positions #(= piece %) board)))
 
 (defn coords [board piece]
   (let [pos (position board piece)]


(def solve (partial solver best-carlo '()))

(defn run-solution [solution]
  (doseq [next solution]
    (render-move next)))

;; (defn path-to
;;   [board piece location]
;;   (let [empty-pos (position board 0)
;;         pos (position board piece)]
;;     (if (= empty-pos pos)
;;       '()
;;       (path-to board location)))
;;   [board location]
;;   (cons ))

(defn render [#^Graphics2D g]
  (dorun
   (for [x (range dim) y (range dim)]
     (let [tile (location @*board* [x y])
           color (if (= tile 0)
             Color/WHITE
             (colors (rem tile (count colors))))
           [cx cy] [(* x scale) (* y scale)]]
       (doto g
         (.setColor color)
         (.fillRect cx cy scale scale)
         (.setColor (if (= Color/BLACK color) Color/WHITE Color/BLACK))
         (.setFont (Font. "Serif" (. Font PLAIN) 24))
         (.drawString (.toString tile)
                      (+ cx (quot scale 2))
                      (+ cy (quot scale 2))
                      ))))))

(def *board* (ref (shuffle (vec (range 0 (* dim dim))))))

(def panel
  (let [size (* dim scale)]
    (doto (proxy [JPanel] []
            (paint [g] (render g)))
      (.setPreferredSize (Dimension. size size)))))

(defn render-move [piece]
  (dosync (when (can-move? @*board* piece)
            (alter *board* move piece)))
  (. panel (repaint)))

(def frame (doto (new JFrame) (.add panel) .pack .show))



(ns tile-game.core
  (:require (clojure.contrib seq math))
  (:import (javax.swing JFrame JPanel )
           (java.awt Color Graphics Graphics2D Dimension Font)
           (java.awt.event KeyListener KeyEvent)))

(set! *warn-on-reflection* true)

(def dim 5)
(def scale 150)

(def colors [Color/RED Color/ORANGE Color/YELLOW Color/GREEN
