Created
June 3, 2019 14:32
-
-
Save f-11/287163e697a03a5b3cfb8fcd44a3850c to your computer and use it in GitHub Desktop.
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
| (defparameter *board-size* 60) | |
| (defparameter x-list '(-1 0 1 -1 1 -1 0 1)) | |
| (defparameter y-list '(-1 -1 -1 0 0 1 1 1)) | |
| (defparameter *board* (make-hash-table :test #'equal)) | |
| ; anaphoric macro | |
| ; x moves from 0 to num | |
| ; y also moves from 0 to num | |
| (defmacro double-loop (num &body body) | |
| (let ((end (gensym))) | |
| `(let ((,end ,num)) | |
| (loop for y below ,end | |
| do (loop for x below ,end | |
| do ,@body))))) | |
| (defun display (board) | |
| (loop for y below *board-size* | |
| do (progn | |
| (loop for x below *board-size* | |
| do (format t "~A" (if (gethash (cons x y) board) | |
| #\@ | |
| #\.))) | |
| (fresh-line)))) | |
| (defun alive-p (pos board) | |
| (gethash pos board)) | |
| (defun live (pos board) | |
| (setf (gethash pos board) t)) | |
| (defun kill (pos board) | |
| (setf (gethash pos board) nil)) | |
| (defun count-living-cells (pos board) | |
| (count-if (lambda (p) (alive-p p board)) | |
| (loop for i below 8 | |
| collect (cons (+ (car pos) (nth i x-list)) | |
| (+ (cdr pos) (nth i y-list)))))) | |
| (defun update (board) | |
| (let ((new-board (make-hash-table :test #'equal))) | |
| (double-loop *board-size* | |
| (let* ((pos (cons x y)) | |
| (mawari (count-living-cells pos board)) | |
| (living (alive-p pos board))) | |
| (cond | |
| ((< mawari 2) (kill pos new-board)) | |
| ((and (= mawari 3) (not living)) (live pos new-board)) | |
| ((and (< mawari 4) living) (live pos new-board)) | |
| (t (kill pos new-board))))) | |
| new-board)) | |
| ; initialize | |
| (defun initialize () | |
| (dotimes (i 1000) | |
| (live (cons (random *board-size*) (random *board-size*)) *board*))) | |
| ; main loop | |
| (defun run () | |
| (display *board*) | |
| (setq *board* (update *board*)) | |
| (sleep 1) | |
| (run)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment