Last active
December 6, 2015 18:29
-
-
Save Nitive/822eb9ace487a761b392 to your computer and use it in GitHub Desktop.
Life game before learning Clojure and reading SICP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns life-game) | |
(use '[clojure.string :only (join)]) | |
(def n 30) | |
(def table | |
(->> | |
(range n) | |
(map (fn [x] n)) | |
(map (fn [x] (into [] (map (fn [x] (Math/round (rand))) | |
(range x))))) | |
(into []))) | |
(defn is-valid-index [number] | |
(and (>= number 0) | |
(< number n))) | |
; testing is-valid-index | |
(assert (= (is-valid-index -1) false)) | |
(assert (= (is-valid-index 0) true)) | |
(assert (= (is-valid-index n) false)) | |
(assert (= (is-valid-index (- n 1)) true)) | |
(defn replace-to-read [x] | |
(if (= x 1) "◼︎" " ")) | |
; testing replace-to-read | |
(assert (= (replace-to-read 1) "◼︎")) | |
(assert (= (replace-to-read 0) " ")) | |
(defn output [] | |
(println | |
(str | |
(join "\n" (repeat 100 "\n")) ; print a lot to clearing console | |
(join "\n" | |
(map | |
(fn [list] (join " " (map replace-to-read list))) | |
table))))) | |
(defn is-valid [x] | |
(and | |
(>= x 0) | |
(< x n))) | |
(defn is-near [x0 x] | |
(and | |
(is-valid x) | |
())) | |
(defn will-alive [i j] | |
(let [neighbors [[-1 -1] [-1 0] [-1 1] [0 -1] [0 1] [1 -1] [1 0] [1 1]]] | |
(let [count | |
(count | |
(->> | |
(range (count neighbors)) | |
(map (fn [x] (let [neighbor (neighbors x)] | |
[(+ i (neighbor 0)) (+ j (neighbor 1))]))) | |
(filter (fn [x] (and | |
(is-valid (x 0)) | |
(is-valid (x 1))))) | |
(map (fn [x] ((table (x 0)) (x 1)))) | |
(filter (fn [x] (= x 1)))))] | |
(or | |
(and | |
(= 3 count) | |
(= 0 ((table i) j))) | |
(and | |
(or | |
(= 2 count) | |
(= 3 count)) | |
(= 1 ((table i) j))))))) | |
(defn next-tick [] | |
(def table | |
(into [] | |
(map-indexed | |
(fn [i row] | |
(into [] | |
(map-indexed | |
(fn [j field] | |
(if (will-alive i j) 1 0)) | |
row))) | |
table)))) | |
(defn main [] | |
(output) | |
(next-tick) | |
(Thread/sleep 1000) | |
(main)) | |
(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment