Skip to content

Instantly share code, notes, and snippets.

@mjgpy3
Created June 20, 2022 03:51
Show Gist options
  • Save mjgpy3/f1ca91e91064e6207e08bb7ebc0081c6 to your computer and use it in GitHub Desktop.
Save mjgpy3/f1ca91e91064e6207e08bb7ebc0081c6 to your computer and use it in GitHub Desktop.
conway.el
(defun conway-current-buffer (alive-char)
(interactive "cAlive-charater: ")
(defun key (x y)
(concat (number-to-string x) "-" (number-to-string y)))
(defun pair-to-key (p)
(concat (number-to-string (car p)) "-" (number-to-string (cadr p))))
(defun neighbors (x y)
(list
(list (+ x 1) (+ y 1))
(list (+ x 1) (- y 1))
(list (- x 1) (- y 1))
(list (- x 1) (+ y 1))
(list (+ x 1) y)
(list (- x 1) y)
(list x (- y 1))
(list x (+ y 1))))
(defun alive-neighbor-count (x y state)
(progn
(setq alive-neighbors 0)
(dolist (neighbor (neighbors x y))
(if (gethash (pair-to-key neighbor) state)
(setq alive-neighbors (+ 1 alive-neighbors))))
alive-neighbors))
(defun lives-on (x y state)
(let ((alive-ns (alive-neighbor-count x y state))
(alive (gethash (key x y) state nil)))
(or (eq alive-ns 3) (and alive (eq alive-ns 2)))))
(defun clear-buffer ()
(kill-region (point-min) (point-max)))
(defun render (height width state)
(progn
(clear-buffer)
(setq y 0)
(while (< y height)
(progn
(setq x 1)
(while (<= x width)
(if (gethash (key x y) state)
(insert (char-to-string alive-char))
(insert " "))
(setq x (+ 1 x)))
(setq y (+ 1 y))
(if (< y height) (insert "\n"))))))
(defun next-state (height width state)
(progn
(setq next (make-hash-table :test #'equal))
(setq y 0)
(while (< y height)
(progn
(setq x 0)
(while (< x width)
(if (lives-on x y state) (puthash (key x y) t next))
(setq x (+ 1 x)))
(setq y (+ 1 y))))
next))
(let ((text (buffer-string))
(state (make-hash-table :test #'equal)))
(progn
(setq lines (split-string text "\n"))
(setq width 0)
(setq height (length lines))
(setq y 0)
(dolist (line lines)
(progn
(setq width (max width (length line)))
(setq x 0)
(dolist (c (split-string line ""))
(progn
(if (eq alive-char (string-to-char c)) (puthash (key x y) t state))
(setq x (+ 1 x))))
(setq y (+ 1 y)))
)
(render height width (next-state height width state)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment