Created
March 20, 2024 05:18
-
-
Save AutoRecursive/fa7b297e13172ee5c050405ffc7d0b14 to your computer and use it in GitHub Desktop.
Game of life in clojure
This file contains 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
;; Game of life generated by Claude3-Opus | |
(ns game-of-life.core | |
(:require [clojure.string :as str]) | |
(:gen-class)) | |
(def rows 50) | |
(def cols 50) | |
(def steps 100) | |
(defn create-board [] | |
(vec (repeat rows (vec (repeat cols false))))) | |
(defn rand-bool [] | |
(< (rand) 0.5)) | |
(defn rand-board [] | |
(vec (repeatedly rows #(vec (repeatedly cols rand-bool))))) | |
(defn neighbors [[x y]] | |
(for [dx [-1 0 1] | |
dy [-1 0 1] | |
:when (not= 0 dx dy)] | |
[(mod (+ x dx) rows) (mod (+ y dy) cols)])) | |
(defn alive? [board pos] | |
(get-in board pos)) | |
(defn count-neighbors [board pos] | |
(count (filter #(alive? board %) (neighbors pos)))) | |
(defn next-cell [board pos] | |
(let [alive (alive? board pos) | |
cnt (count-neighbors board pos)] | |
(or (and alive (#{2 3} cnt)) | |
(and (not alive) (= 3 cnt))))) | |
(defn next-board [board] | |
(vec (for [i (range rows)] | |
(vec (for [j (range cols)] | |
(next-cell board [i j])))))) | |
(defn board-str [board] | |
(str/join "\n" (for [row board] | |
(str/join " " (for [cell row] | |
(if cell "●" " ")))))) | |
(defn clear-screen [] | |
(print (str (char 27) "[2J")) | |
(print (str (char 27) "[;H"))) | |
(defn game-loop [board step] | |
(clear-screen) | |
(println "Step:" step) | |
(println (board-str board)) | |
(Thread/sleep 200) | |
(if (< step steps) | |
(recur (next-board board) (inc step)) | |
(println "Game over!"))) | |
(defn -main [] | |
(game-loop (rand-board) 0)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment