1
0

sample.clojure.txt 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. (ns game-of-life
  2. "Conway's Game of Life, based on the work of
  3. Christophe Grand (http://clj-me.cgrand.net/2011/08/19/conways-game-of-life)
  4. and Laurent Petit (https://gist.github.com/1200343).")
  5. ;;; Core game of life's algorithm functions
  6. (defn neighbors
  7. "Given a cell's coordinates `[x y]`, returns the coordinates of its
  8. neighbors."
  9. [[x y]]
  10. (for [dx [-1 0 1]
  11. dy (if (zero? dx)
  12. [-1 1]
  13. [-1 0 1])]
  14. [(+ dx x) (+ dy y)]))
  15. (defn step
  16. "Given a set of living `cells`, computes the new set of living cells."
  17. [cells]
  18. (set (for [[cell n] (frequencies (mapcat neighbors cells))
  19. :when (or (= n 3)
  20. (and (= n 2)
  21. (cells cell)))]
  22. cell)))
  23. ;;; Utility methods for displaying game on a text terminal
  24. (defn print-grid
  25. "Prints a `grid` of `w` columns and `h` rows, on *out*, representing a
  26. step in the game."
  27. [grid w h]
  28. (doseq [x (range (inc w))
  29. y (range (inc h))]
  30. (when (= y 0) (println))
  31. (print (if (grid [x y])
  32. "[X]"
  33. " . "))))
  34. (defn print-grids
  35. "Prints a sequence of `grids` of `w` columns and `h` rows on *out*,
  36. representing several steps."
  37. [grids w h]
  38. (doseq [grid grids]
  39. (print-grid grid w h)
  40. (println)))
  41. ;;; Launches an example grid
  42. (def grid
  43. "`grid` represents the initial set of living cells"
  44. #{[2 1] [2 2] [2 3]})
  45. (print-grids (take 3 (iterate step grid)) 5 5)