;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: multiagent/domains/doubles-tennis.lisp

;;;; The Doubles Tennis Problem [Figure 18.1]

;;; Two actors, A and B, play together and can be at one of four locations.
;;; The ball can be returned only by an actor at the place where it is
;;; approaching.  The actions are (hit actor ball), (go actor to) and
;;; (noop actor); as in Section 18.1, two actors may not hit the ball at the
;;; same time.

(defparameter *tennis-locations* '(left-baseline right-baseline left-net right-net))

(defun actor-location (actor state)
  (third (find-if #'(lambda (literal) (and (eq (first literal) 'at) (eq (second literal) actor)))
                  state)))

(defun make-doubles-tennis-problem ()
  (make-multiactor-problem
   :actors '(a b)
   :initial-state '((at a left-baseline) (at b right-net)
                    (approaching ball right-baseline) (partner a b) (partner b a))
   :goal-test #'(lambda (state)
                  (and (member '(returned ball) state :test #'equal)
                       (some #'(lambda (actor)
                                 (member (actor-location actor state) '(left-net right-net)))
                             '(a b))))
   :actions #'(lambda (actor state)
                (append (list (list 'noop actor) (list 'hit actor 'ball))
                        (mapcar #'(lambda (to) (list 'go actor to))
                                (remove (actor-location actor state) *tennis-locations*))))
   :applicable #'(lambda (action state)
                   (ecase (first action)
                     (noop t)
                     (hit (member (list 'approaching (third action) (actor-location (second action) state))
                                  state :test #'equal))
                     (go (let ((loc (actor-location (second action) state)))
                           (and loc (not (eq loc (third action))))))))
   :effects #'(lambda (action state)
                (ecase (first action)
                  (noop (cons nil nil))
                  (hit (cons (list (list 'returned (third action))) nil))
                  (go (cons (list (list 'at (second action) (third action)))
                            (list (list 'at (second action)
                                        (actor-location (second action) state)))))))
   :concurrent-ok #'(lambda (joint-action)
                      (<= (count 'hit joint-action :key #'first) 1))))
