首页 > 代码库 > Game of Life

Game of Life

clojure实现生存游戏

游戏规则:

The game of life is a cellular automaton devised by mathematician John Conway.

The ‘board‘ consists of both live (#) and dead ( ) cells. Each cell interacts with its eight neighbours (horizontal, vertical, > diagonal), and its next state is dependent on the following rules:

1) Any live cell with fewer than two live neighbours dies, as if caused by under-population.
2) Any live cell with two or three live neighbours lives on to the next generation.
3) Any live cell with more than three live neighbours dies, as if by overcrowding.
4) Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

代码

(defn test [chessboard]
    (let [nrow (count chessboard)
          ncol (count (nth chessboard 0))
          get-coord (fn [x y] (nth (nth chessboard x) y))
          coords (fn [x y] (filter 
                              #(let [row-num (first %)
                                   col-num (last %)] 
                                (and (>= row-num 0) 
                                     (>= col-num 0)
                                     (< row-num nrow) 
                                     (< col-num ncol)))
                              [[x (inc y)]
                               [x (dec y)]
                               [(dec x) y]
                               [(inc x) y]
                               [(dec x) (dec y)]
                               [(dec x) (inc y)]
                               [(inc x) (inc y)]
                               [(inc x) (dec y)]]))
          neighbors (fn [x y] (map (partial apply get-coord) (coords x y)))
          nlive (fn [x y] (count (filter #(= \# %) (neighbors x y))))
          result (for [x (range 0 nrow)
                       y (range 0 ncol)] 
                    (let [element (get-coord x y)
                          live-num (nlive x y)]
                        (if (= \# element)
                            (if (or (< live-num 2) (> live-num 3)) \space \#)
                            (if (= live-num 3) \# \space))))]
          (map (partial apply str) (partition ncol result))))

(defn print-chessboard [chessboard]
    (print (str (clojure.string/join "|\n" chessboard) "|\n")))

(def a ["           "  
        "   ##      "
        "           "
        "   ######  "
        "           "
        "           "])

(defn run [n chessboard sleep-time]
    (loop [i 0
           tmp chessboard]
        (if (> i n)
            (println "over")
            (do
                (println "第" i "次进化")
                (Thread/sleep sleep-time)
                (println "------------")
                (print-chessboard tmp)
                (println "------------")
                (recur (inc i) (test tmp))))))

(run 10 a 300)

Game of Life