Advertisement
Guest User

Untitled

a guest
Mar 10th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 2.29 KB | None | 0 0
  1. (defun spawn-snake (board-dim &key (pos '(0 0)) (direction :down) (body-length 3))
  2.   "Create instance of snake on board.
  3. ARGS:
  4. `board-dim'   - a list like '(16 9)
  5. `pos'         - position of the head of the snake e.g.: '(3 5)
  6. `direction'   - :up, :down, :left, :right
  7. `body-length' - length mony snake-parts the snake consists of"
  8.   (let ((x-dim (first  board-dim))
  9.         (y-dim (second board-dim))
  10.         (x-pos (first  pos))
  11.         (y-pos (second pos)))
  12.     (unless (outside-board-p) ;; checks weather the snake can be created
  13.       (make-instance 'snake
  14.                      :body   (snake-make-body)
  15.                      :length body-length
  16.                      :head-direction direction)
  17.  
  18.  
  19.       (defun snake-make-body ()
  20.         "create list out of `body-length' snake-parts. Starting from the tail"
  21.         (do* ((i 0 (1+ i))
  22.              (previous-part nil)
  23.              (curr-part nil)
  24.              (result '() (cons curr-part result)))
  25.              ((= i 3) result)
  26.           (setf curr-part (make-instance 'snake-part
  27.                                          :position `(,(calc-x-pos i) ,(calc-y-pos i))
  28.                                          :previous previous-part))
  29.           (setf previous-part curr-part))
  30.         (defun calc-x-pos (index)
  31.           (case direction
  32.             (:up    x-pos)
  33.             (:down  x-pos)
  34.             (:left  (+ x-pos (1- (- body-length index))))
  35.             (:right (- x-pos (1- (- body-length index))))))
  36.         (defun calc-y-pos (index)
  37.           (case direction
  38.             (:up    (- y-pos (1- (- body-length index))))
  39.             (:down  (+ y-pos (1- (- body-length index))))
  40.             (:left  y-pos)
  41.             (:right y-pos))))
  42.  
  43.       (defun outside-board-p ()
  44.         "Checks weather the snake fits completely onto the board."
  45.         (or (head-not-on-board-p)
  46.             (tail-in-wall-p))
  47.         (defun head-not-on-board-p ()
  48.           (or (or (> 0 x-pos) (>= x-pos x-dim))
  49.               (or (> 0 y-pos) (>= y-pos y-dim))))
  50.         (defun tail-in-wall-p ()
  51.           (case direction
  52.             (:up    (> 0     (- y-pos (1- body-length))))
  53.             (:down  (< y-dim (+ y-pos (1- body-length))))
  54.             (:left  (< x-dim (+ x-pos (1- body-length))))
  55.             (:right (> 0     (- x-pos (1- body-length))))))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement