Skip to content

Commit

Permalink
added anticollision support
Browse files Browse the repository at this point in the history
  • Loading branch information
Robert Campbell committed Dec 11, 2011
1 parent 0cd249d commit 6187dff
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/aichallenge/bot.clj
Expand Up @@ -2,7 +2,8 @@
(:require
(aichallenge [ant :as ant]
[matrix :as m]
[fow :as fow])))
[fow :as fow]
[collisions :as cs])))

(defn init-bot [{:keys [rows cols viewradius2]}]
(let [visible-positions (fow/visibility-pattern viewradius2 rows cols)]
Expand All @@ -14,8 +15,11 @@
(m/pr-matrix knowledge #(if (zero? %) \# \space))
{:knowledge (fow/update-visibilities knowledge (mapcat visible-positions
(ant/my-ants state)))
:moves (for [ant (:ants state)
:let [dir (first (filter #(ant/valid-move? state ant %)
[:north :east :west :south]))]
:when dir]
[ant dir])})}))
:moves (->> (for [ant (:ants state)
:let [dir (first (filter #(ant/valid-move? state ant %)
[:north :east :west :south]))]
:when dir]
[ant dir])
(cs/fix-collisions {}))})}))


55 changes: 55 additions & 0 deletions src/aichallenge/collisions.clj
@@ -0,0 +1,55 @@
(ns aichallenge.collisions
(:use [clojure.pprint :only (pprint)]
[clojure.set :only (difference)])
(:require [aichallenge.ant :as ant]))

(defn fpprint [filename data]
(spit (java.io.File. filename)
(with-out-str (pprint data))))

(defn init-matrix [x y]
(letfn [(row [] (vec (take x (repeat 0))))]
(vec (repeatedly y row))))

(defn collisions [moves]
(loop [m {}
ms moves]
(if (seq ms)
(recur (let [move (first ms)
next-loc (apply ant/move-ant move)]
(if (m next-loc)
(update-in m [next-loc] conj move)
(assoc m next-loc [move])))
(next ms))
m)))

(def directions #{:north :south :east :west})

(defn find-alternative [m ant dirs]
(let [poss (map (fn [ant dir]
[ant dir (ant/move-ant ant dir)])
(repeat ant)
dirs)]
(first (remove (fn [[_ _ next-move]] (m next-move))
poss))))


(defn all-alternatives [collisions]
(for [collision collisions
:let [moves (val collision)]
:when (> (count moves) 1)
[ant dir] moves]
(find-alternative collisions ant (difference directions #{dir}))))

(defn fix-collisions [matrix moves]
(let [cs (collisions moves)
alts (reduce (fn [m [ant dir _]]
(assoc m ant dir)) {}
(all-alternatives cs))]
(for [[ant dir] moves]
[ant (if-let [new-dir (alts ant)]
new-dir
dir)])))

#_(zipmap (map first moves)
(map second moves))

0 comments on commit 6187dff

Please sign in to comment.