Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created November 2, 2011 23:11
Show Gist options
  • Save jonelf/1335248 to your computer and use it in GitHub Desktop.
Save jonelf/1335248 to your computer and use it in GitHub Desktop.
Leif in Clojure
(import (javax.swing JFrame JPanel)
(java.awt Color Dimension Graphics)
(java.awt.image BufferedImage WritableRaster))
(defn construct-frame [width height panel]
"Creates and displays a JFrame of the given dimensions with
the panel added to it"
(let [frame (JFrame.)]
(.setPreferredSize panel (Dimension. width height))
(doto frame
(.add panel)
.pack
(.setLocationRelativeTo nil)
(.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
.show)))
(defn get-pixel [x y #^WritableRaster wr]
(let [pix (int-array [0,0,0])]
(.getPixel wr (int x) (int y) pix)
(int-array pix)))
(defn set-pixel [x y pixel #^WritableRaster wr]
(.setPixel wr (int x) (int y) (int-array pixel)))
(defn random-red-green-blue []
([[255,0,0] [0,255,0] [0,0,255]] (rand-int 3)))
(defn randomize-canvas [width height #^WritableRaster wr]
(doseq [pixel (for [y (range height) x (range width)] [x y])]
(let [[x y] pixel]
(set-pixel x y (random-red-green-blue) wr))))
(defn render-pixels [width height #^WritableRaster wr]
(let [x (inc (rand-int (- width 2)))
y (inc (rand-int (- height 2)))
pixel (get-pixel x y wr)]
(set-pixel x (dec y) pixel wr)
(set-pixel x (inc y) pixel wr)
(set-pixel (inc x) y pixel wr)
(set-pixel (dec x) y pixel wr)))
(defn leif [width height iters-per-frame]
(let [img (BufferedImage. width height (BufferedImage/TYPE_INT_RGB))
panel (proxy [JPanel] [] (paint [g] (.drawImage g img 0 0 (Color/white) nil)))
writeable-raster (.getRaster img)]
(construct-frame width height panel)
(randomize-canvas width height writeable-raster)
(while true
(dotimes [n iters-per-frame]
(render-pixels width height writeable-raster))
(Thread/sleep 15)
(.repaint panel))))
(leif 640 400 4711)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment