aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLoic Guegan <manzerberdes@gmx.com>2019-05-08 18:12:09 +0200
committerLoic Guegan <manzerberdes@gmx.com>2019-05-08 18:12:09 +0200
commitf72400bf2216828d442d161bd48158508c4f4526 (patch)
treef8da5b5d6fe4ee3754eb69e5482b09686fa97657
parent8ca0bf8b42f1b8c0dee5abdfd56b3e84aaf9f118 (diff)
Add food management
-rw-r--r--server/game.lisp28
1 files changed, 25 insertions, 3 deletions
diff --git a/server/game.lisp b/server/game.lisp
index 207b669..a43cd10 100644
--- a/server/game.lisp
+++ b/server/game.lisp
@@ -11,7 +11,12 @@
:accessor snake)
(dir
: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
(defmethod initialize-instance :after ((g game) &key)
@@ -20,7 +25,7 @@
;;; Pretty-print a game
(defmethod print-object ((g game) stream)
- (with-slots (snake dir) g
+ (with-slots (snake dir food) g
(format t "Snake: ")
(dotimes (i (first (array-dimensions snake)))
(let ((elem (aref snake i)))
@@ -28,7 +33,11 @@
(format t "<="))
(format t "(~a,~a)" (first elem) (second elem))))
(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)
(:documentation "Refresh the game g (move forward or change direction)."))
@@ -86,3 +95,16 @@
;; 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))))))))))