diff options
| author | El-BG-1970 <elouangros@hotmail.com> | 2022-07-28 22:01:43 +0200 |
|---|---|---|
| committer | El-BG-1970 <elouangros@hotmail.com> | 2022-07-28 22:01:43 +0200 |
| commit | 39730c70367bcaa96e34982b90268d2170c75e90 (patch) | |
| tree | df23eb96ff5db84ab6b6c82488f433c85758b893 | |
| parent | 201bdac932778ccf420df492acb7eecaa209b0dd (diff) | |
| download | transacc-39730c70367bcaa96e34982b90268d2170c75e90.tar.gz | |
added some checks to commodities and inventory to pass tests
| -rw-r--r-- | src/commodities.lisp | 7 | ||||
| -rw-r--r-- | src/inventory.lisp | 58 |
2 files changed, 36 insertions, 29 deletions
diff --git a/src/commodities.lisp b/src/commodities.lisp index 474fe7d..1302a98 100644 --- a/src/commodities.lisp +++ b/src/commodities.lisp @@ -13,6 +13,7 @@ :accessor price))) (defun new-commodity (name price) - (make-instance 'commodity - :name name - :price price)) + (when (> price 0) + (make-instance 'commodity + :name name + :price price))) diff --git a/src/inventory.lisp b/src/inventory.lisp index 17c02e7..429f666 100644 --- a/src/inventory.lisp +++ b/src/inventory.lisp @@ -1,6 +1,7 @@ (defpackage inventory (:use :cl) - (:export :inventory + (:export :new-inventory + :filled :add-item :remove-item)) @@ -15,6 +16,10 @@ (items :initform '() :accessor items))) +(defun new-inventory (size) + (when (> size 0) + (make-instance 'inventory :size size))) + (defmethod find-item ((inv inventory) name) (with-slots (items) inv (find-if @@ -31,32 +36,33 @@ (defmethod add-item ((inv inventory) item quantity) ;; add <quantity> of <item> to inventory - (with-slots (size filled items) inv - (when (> size (+ filled quantity)) - (let* ((old-item - (find-item inv (commodities:name item))) - (qt (if old-item - (progn - (delete-item inv old-item) - (+ quantity (cdr old-item))) - quantity))) - (prog1 - (setq filled (+ filled qt)) - (push (cons item qt) - items)))))) + (when (> quantity 0) + (with-slots (size filled items) inv + (when (> size (+ filled quantity)) + (let* ((old-item + (find-item inv (commodities:name item))) + (qt + (if old-item + (progn + (delete-item inv old-item) + (+ quantity (cdr old-item))) + quantity))) + (prog1 (setq filled (+ filled qt)) + (push (cons item qt) + items))))))) (defmethod remove-item ((inv inventory) name quantity) ;; remove <quantity> of <item> from inventory ;; quantity must be positive or zero - (assert (>= quantity 0)) - (with-slots (filled items) inv - (let ((item (find-item inv name))) - (when item - (delete-item inv item) - (if (< quantity (cdr item)) - (progn - (add-item inv - (car item) - (- (cdr item) quantity)) - (cons (car item) quantity)) - item))))) + (when (> quantity 0) + (with-slots (filled items) inv + (let ((item (find-item inv name))) + (when item + (delete-item inv item) + (if (< quantity (cdr item)) + (progn + (add-item inv + (car item) + (- (cdr item) quantity)) + (cons (car item) quantity)) + item)))))) |
