Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Clojure and Swing

Name: Anonymous 2010-03-05 1:45

Hey /prog/riders, I'm not a LISPer but I'm learning. I was wondering if it were possible to dynamically create a grid of buttons in swing, instead of initializing all of them individually. I was thinking of making a tic-tac-toe game, but I can't work out how to make it work without making nine specific variable buttons.

Name: Anonymous 2010-03-05 23:42

I finished it. Took me ages to think up a LISPy way to sort it, I stole the idea from a wiki but I implemented it myself. First Java/Lisp thing I've ever made. I know it's shit, I just don't like leaving things unfinished.

(import '(javax.swing JFrame JButton)
 '(java.awt.event ActionListener)
 '(java.awt GridLayout))

(def player (ref true))
(def length 3)
(def size (* length length))
(def boxes (make-array JButton size))

(defn clear-boxes []
  (loop [idx 0]
    (when (< idx size)
      (.setText (aget boxes idx) "")
      (recur (inc idx)))))

(defn get-boxes [string list idx]
  (if (= idx size) list
    (if (= (.getText (aget boxes idx)) string)
      (get-boxes string (cons idx list) (inc idx))
      (get-boxes string list (inc idx)))))

(defn sum-boxes [list idx idt]
  (let [n-val '(2 9 4 7 5 3 6 1 8)]
    (cond
      (= idx 0) (= idt 0)
      (< idt 0) nil
      (empty? list) nil
      (sum-boxes (rest list) (- idx 1) (- idt (nth n-val (first list)))) true
      (sum-boxes (rest list) idx idt) true)))

(defn check-boxes [string]
  (or sum-boxes (get-boxes string '() 0) length 15) (empty? (get-boxes "" '() 0)))

(defn set-box [temp]
  (when (= (.getText temp) "")
    (dosync
      (if (deref player)
        (do
          (.setText temp "x")
          (ref-set player false)
          (if (check-boxes "x") (clear-boxes)))
        (do
          (.setText temp "o")
          (ref-set player true)
          (if (check-boxes "o") (clear-boxes)))))))

(let [frame (new JFrame "NAC")]
  (loop [idx 0]
    (when (< idx size)
      (let [temp (new JButton "")]
        (doto temp
          (.addActionListener
            (proxy [ActionListener] []
              (actionPerformed [evt]
                (set-box temp)))))
        (doto frame
          (.add temp))
        (aset boxes idx temp))
      (recur (inc idx))))
  (doto frame
    (.setDefaultCloseOperation (. JFrame EXIT_ON_CLOSE))
    (.setLayout (new GridLayout 3 3 3 3))
    (.setSize 200 200)
    (.setVisible true)))

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List