;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: agents/environments/two-square-vacuum.lisp

;;;; The Two-Square Vacuum World of [Fig. 2.2]

;;; There are two squares, A and B, each clean or dirty.  The agent
;;; perceives its location and the status of that location, as a list
;;; such as (A dirty), and can do RIGHT, LEFT, SUCK or NO-OP.  The
;;; performance measure awards one point for each clean square at each
;;; time step.

(defstructure (two-square-vacuum-world (:include environment (max-steps 10)))
  "The two-square vacuum world.  By default the dirt and the agent are placed
  at random; give :status and :location to fix them."
  (aspec '(simple-reflex-vacuum-agent)) ; Agents built when :agents is empty
  (status (list (cons 'A (random-element '(clean dirty)))
		(cons 'B (random-element '(clean dirty)))))
  (location (random-element '(A B))))

(defmethod initialize ((env two-square-vacuum-world))
  "Build the agents from the ASPEC slot if none were given."
  (when (null (environment-agents env))
    (setf (environment-agents env)
	  (mapcar #'(lambda (type) (if (symbolp type) (make type) type))
		  (two-square-vacuum-world-aspec env))))
  (call-next-method))

(defmethod get-percept ((env two-square-vacuum-world) agent)
  "The percept is (location status)."
  (declare-ignore agent)
  (let ((loc (two-square-vacuum-world-location env)))
    (list loc (cdr (assoc loc (two-square-vacuum-world-status env))))))

(defmethod update-fn ((env two-square-vacuum-world))
  "Execute the action of the (single) agent."
  (let ((action (agent-action (first (environment-agents env))))
	(loc (two-square-vacuum-world-location env)))
    (case action
      (right (setf (two-square-vacuum-world-location env) 'B))
      (left  (setf (two-square-vacuum-world-location env) 'A))
      (suck  (setf (cdr (assoc loc (two-square-vacuum-world-status env)))
		   'clean))
      (t nil))))

(defmethod performance-measure ((env two-square-vacuum-world) agent)
  "One point for each clean square, summed over the time steps."
  (+ (agent-score agent)
     (count 'clean (two-square-vacuum-world-status env) :key #'cdr)))

(defmethod display-environment-snapshot ((env two-square-vacuum-world))
  (format (environment-stream env) "~&Agent at ~A; squares ~A~%"
	  (two-square-vacuum-world-location env)
	  (two-square-vacuum-world-status env)))

(defun two-square-vacuum-clean? (env)
  "Are both squares clean?"
  (every #'(lambda (pair) (eq (cdr pair) 'clean))
	 (two-square-vacuum-world-status env)))
