Skip to content

Instantly share code, notes, and snippets.

@jebberjeb
Last active August 29, 2015 14:11
Show Gist options
  • Save jebberjeb/f57753cede4b7faddba5 to your computer and use it in GitHub Desktop.
Save jebberjeb/f57753cede4b7faddba5 to your computer and use it in GitHub Desktop.
core.async demo reloaded w/ minecraft
(ns system
(:require [clojure.core.async :as ca]
[cljminecraft.core :as core]
[cljminecraft.player :as p]
[cljminecraft.bukkit :as bk])
(:import [org.bukkit Material DyeColor]))
;; Helpers start
(defn loc->coords [l] (-> l bean (select-keys [:x :y :z :world])))
(defn ->coords [e] (-> e .getLocation loc->coords))
(def world (comp first bk/worlds))
(defn get-block-at [w p] (.getBlockAt w (:x p) (:y p) (:z p)))
(defn get-block-type [w p] (.getType (get-block-at w p)))
(defn get-spawn-point [] (-> (world) .getSpawnLocation loc->coords))
(defn unregister-all! [] (HandlerList/unregisterAll @core/clj-plugin))
;; Helpers end
(defn set-blocks!
"block state - {{:x :y :z} Material/DIRT}"
[block-state]
(let [w (world)]
(bk/ui-sync
@core/clj-plugin
#(doseq [[k v] block-state]
(let [b (.getBlockAt w (:x k) (:y k) (:z k))]
(.setTypeId b (.getId v))
(when (= v Material/WOOL) (.setData b 0x0)))))))
(defn clear-blocks!
[points]
(set-blocks! (zipmap points (repeat Material/AIR))))
(def running (atom true))
(let [p (get-spawn-point)
rad 50
blocks (for [x (range (- (:x p) rad) (+ (:x p) rad))
z (range (- (:z p) rad) (+ (:z p) rad))]
{:x x :z z :y (+ 25 (:y p))})
colors [DyeColor/BLUE DyeColor/RED DyeColor/GREEN DyeColor/ORANGE
DyeColor/YELLOW DyeColor/MAGENTA DyeColor/WHITE DyeColor/BLACK]]
(defn render! [queue]
(bk/ui-sync
@core/clj-plugin
#(doseq [point queue]
(let [block (get-block-at (world) point)]
(.setData block (.getData (rand-nth colors)))))))
(defn mk-render-ch [rate]
(let [render-ch (ca/chan (ca/sliding-buffer 1000))]
(ca/go (loop [refresh-ch (ca/timeout rate) queue []]
(when @running
(let [[v c] (ca/alts! [refresh-ch render-ch])]
(condp = c
refresh-ch (do (render! queue)
;; TODO - from original blog post -- why
;; block here?
(ca/<! (ca/timeout 0))
(recur (ca/timeout rate) []))
render-ch (recur refresh-ch (conj queue v)))))))
render-ch))
(defn start! [refresh-rate change-count]
(let [render-ch (mk-render-ch refresh-rate)]
(dotimes [i (/ (count blocks) 10)]
(ca/go (while true
(when @running
(ca/<! (ca/timeout (+ 1000 (rand-int 10000))))
(ca/>! render-ch (rand-nth blocks))))))))
#_(clear-blocks! blocks)
#_(reset! running false)
#_(reset! running true)
(set-blocks! (zipmap blocks (repeat Material/WOOL)))
(start! 50 10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment