Add food management
This commit is contained in:
parent
8ca0bf8b42
commit
f72400bf22
1 changed files with 25 additions and 3 deletions
|
@ -11,7 +11,12 @@
|
||||||
:accessor snake)
|
:accessor snake)
|
||||||
(dir
|
(dir
|
||||||
:initarg :initial-direction
|
:initarg :initial-direction
|
||||||
:initform :right)))
|
:initform :right)
|
||||||
|
(grid-size
|
||||||
|
:initarg :grid-size
|
||||||
|
:initform (list 30 30))
|
||||||
|
(food
|
||||||
|
:initform (make-array 0))))
|
||||||
|
|
||||||
;;; Class constructor to initialize the snake
|
;;; Class constructor to initialize the snake
|
||||||
(defmethod initialize-instance :after ((g game) &key)
|
(defmethod initialize-instance :after ((g game) &key)
|
||||||
|
@ -20,7 +25,7 @@
|
||||||
|
|
||||||
;;; Pretty-print a game
|
;;; Pretty-print a game
|
||||||
(defmethod print-object ((g game) stream)
|
(defmethod print-object ((g game) stream)
|
||||||
(with-slots (snake dir) g
|
(with-slots (snake dir food) g
|
||||||
(format t "Snake: ")
|
(format t "Snake: ")
|
||||||
(dotimes (i (first (array-dimensions snake)))
|
(dotimes (i (first (array-dimensions snake)))
|
||||||
(let ((elem (aref snake i)))
|
(let ((elem (aref snake i)))
|
||||||
|
@ -28,7 +33,11 @@
|
||||||
(format t "<="))
|
(format t "<="))
|
||||||
(format t "(~a,~a)" (first elem) (second elem))))
|
(format t "(~a,~a)" (first elem) (second elem))))
|
||||||
(format t "~%Size: ~a" (first (array-dimensions snake)))
|
(format t "~%Size: ~a" (first (array-dimensions snake)))
|
||||||
(format t "~%Direction: ~a" dir)))
|
(format t "~%Direction: ~a" dir)
|
||||||
|
(format t "~%Food: ~a" food)))
|
||||||
|
|
||||||
|
(defgeneric add-food (g nb)
|
||||||
|
(:documentation "Add food on the game grid."))
|
||||||
|
|
||||||
(defgeneric refresh (g &key)
|
(defgeneric refresh (g &key)
|
||||||
(:documentation "Refresh the game g (move forward or change direction)."))
|
(:documentation "Refresh the game g (move forward or change direction)."))
|
||||||
|
@ -86,3 +95,16 @@
|
||||||
|
|
||||||
;; Check if we loose
|
;; Check if we loose
|
||||||
)
|
)
|
||||||
|
|
||||||
|
(defmethod add-food ((g game) nb)
|
||||||
|
(with-slots (snake grid-size food) g
|
||||||
|
(let ((snake-list (coerce snake 'list)) ; To be able to use the function member later
|
||||||
|
(food-list (coerce food 'list))
|
||||||
|
(size-x (first grid-size))
|
||||||
|
(size-y (second grid-size))
|
||||||
|
(food-size (first (array-dimensions food))))
|
||||||
|
(dotimes (i nb)
|
||||||
|
(let ((x (random size-x))
|
||||||
|
(y (random size-y)))
|
||||||
|
(when (eq (member (list x y) snake-list) nil) ; Add if there is no conflict between snake and food position
|
||||||
|
(setf food (make-array (1+ food-size) :initial-contents `(,@food-list ,(list x y))))))))))
|
||||||
|
|
Loading…
Add table
Reference in a new issue