Skip to content

Instantly share code, notes, and snippets.

@davidwallacejackson
Created October 3, 2012 07:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidwallacejackson/3825501 to your computer and use it in GitHub Desktop.
Save davidwallacejackson/3825501 to your computer and use it in GitHub Desktop.
clj-game
(ns clj-game.core)
;; hacky first pass at making a functional style game loop
;;
;; game state is just a map
;; behaviors represent a transformation on a state
;;;
;; this is a stub of a pong implementation containing two paddles and a ball
;; the only behavior in the system moves the ball right by 10 every step
(def paddle {:position {:x 0 :y 0}
:dimensions {:x 10 :y 40}})
(def pong-state {:players {:a paddle}
:dimensions {:x 400 :y 300}
:ball ball})
(defn move [x y]
{:target :position,
:function (fn [position]
{:x (+ (position :x) x)
:y (+ (position :y) y)})
:args [:position] })
(def ball {:position {:x 200 :y 150}
:dimensions {:x 10 :y 10}
:behaviors [(move 10 1)]})
(defn get-property [property-map & lookup]
(if (= (count lookup) 1)
(property-map (first lookup))
(apply get-property (cons (property-map (first lookup)) (rest lookup)))))
(defn do-behavior [source-map
behavior]
(let [function (behavior :function)
args (map source-map (behavior :args))
target (behavior :target)]
{target (apply function args)}))
(defn all-behaviors [state-map]
(let [results ( map (fn [behavior] (do-behavior state-map behavior)) (state-map :behaviors))]
(if (not (= results []))
(reduce conj {} results)
{})))
(defn recurse-update [property]
(if (not (map? property))
property ;;atomic values have no update behavior
(let [state-map property,
updated-children (reduce conj
(map (fn [[ key value]] {key (recurse-update value)})
state-map))
updated-parent (all-behaviors state-map)]
(conj updated-children updated-parent))))
(defn pong-loop [state]
(print state)
(if (> (get-property state :ball :position :x) 350)
nil
(recur (recurse-update state))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment