;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE:               mine.lisp
;;;;LANGUAGE:           Common-Lisp
;;;;SYSTEM:             Common-Lisp
;;;;USER-INTERFACE:     NONE
;;;;DESCRIPTION
;;;;
;;;;    Implements the game of Mine.
;;;;
;;;;AUTHORS
;;;;    <PJB> Pascal Bourguignon <pjb@informatimago.com>
;;;;MODIFICATIONS
;;;;    2008-05-10 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;;    GPL
;;;;
;;;;    Copyright Pascal Bourguignon 2008 - 2008
;;;;
;;;;    This program is free software; you can redistribute it and/or
;;;;    modify it under the terms of the GNU General Public License
;;;;    as published by the Free Software Foundation; either version
;;;;    2 of the License, or (at your option) any later version.
;;;;
;;;;    This program is distributed in the hope that it will be
;;;;    useful, but WITHOUT ANY WARRANTY; without even the implied
;;;;    warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;;    PURPOSE.  See the GNU General Public License for more details.
;;;;
;;;;    You should have received a copy of the GNU General Public
;;;;    License along with this program; if not, write to the Free
;;;;    Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;;    Boston, MA 02111-1307 USA
;;;;**************************************************************************

(in-package "COM.INFORMATIMAGO.GAME.MINE")


(deftype cell () '(integer 0 1))
(eval-when (:compile-toplevel :load-toplevel :execute)
  (defconstant +empty-cell+ 0)
  (defconstant +mine-cell+  1))
(defun empty-cell-p (x) (eql +empty-cell+ x))

(defstruct (board (:constructor %make-board))
  width height cells display exploded-p mine-count)

(defun 2+ (x) (+ x 2))
(defun 2- (x) (- x 2))

(defun board-cells-ref (board x y)
  (aref (board-cells board) (1+ x) (1+ y)))
(defun (setf board-cells-ref) (new-cell board x y)
  (setf (aref (board-cells board) (1+ x) (1+ y)) new-cell))
(defun board-display-ref (board x y)
  (aref (board-display board) x y))
(defun (setf board-display-ref) (new-cell board x y)
  (setf (aref (board-display board) x y) new-cell))


(defun count-mines (board x y)
  (assert (<= 0 x (1- (board-width  board))))
  (assert (<= 0 y (1- (board-height board))))
  (let ((c (board-cells board)))
    (flet ((p (x) x)
           (i (x) (1+ x))
           (n (x) (2+ x))
           (ref (x y) (aref c x y)))
      (declare (inline p i n ref))
      (+ (ref (p x) (p y)) (ref (i x) (p y)) (ref (n x) (p y))
         (ref (p x) (i y))                   (ref (n x) (i y))
         (ref (p x) (n y)) (ref (i x) (n y)) (ref (n x) (n y))))))


(defun fill-mines (board mine-count)
  (assert (< mine-count (* (board-width board) (board-height board))))
  (loop
     :while (plusp mine-count)
     :do (let ((x (random (board-width board)))
               (y (random (board-height board))))
           (when (empty-cell-p (board-cells-ref board x y))
             (setf (board-cells-ref board x y) +mine-cell+)
             (decf mine-count))))
  board)


(defun make-board (width height mine-count)
  (assert (< 0 width))
  (assert (< 0 height))
  (let ((board (%make-board :width width
                            :height height
                            :mine-count mine-count
                            :cells   (make-array (list (2+ width) (2+ height))
                                                 :element-type 'cell
                                                 :initial-element +empty-cell+)
                            :display (make-array (list width height)
                                                 :element-type 't
                                                 :initial-element ':nothing))))
    (fill-mines board mine-count)
    board))


(defun count-flags (board)
  (loop
     :with d = (board-display board)
     :for i :from 0 :below (array-total-size d)
     :when (eq ':flag (row-major-aref d i))
     :sum 1))

(defun board-all-covered-p (board)
  (loop
     :with d = (board-display board)
     :for i :from 0 :below (array-total-size d)
     :never (eq ':nothing (row-major-aref d i))))


(defun reveal-board (board)
  (loop
       :for i :from 0 :below (board-width board)
       :do (loop
              :for j :from 0 :below (board-height board)
              :do (case  (board-display-ref board i j)
                    ((:flag)
                     (when (empty-cell-p (board-cells-ref board i j))
                       (setf (board-display-ref board i j) ':wrong)))
                    ((:exploded))
                    (otherwise
                     (unless (empty-cell-p (board-cells-ref board i j))
                       (setf (board-display-ref board i j) ':mine))))))
  board)


(defun walk-board (board x y forcep)
  (let ((mines (count-mines  board x y))
        (w     (board-width  board))
        (h     (board-height board)))
    (setf (board-display-ref board x y) mines)
    (when (or forcep (zerop mines))
      (flet ((p (x) (1- x))
             (i (x)     x)
             (n (x) (1+ x))
             (ref (x y)
               (when (and (not (or (< x 0) (< y 0) (<= w x) (<= h y)
                                   (eq ':flag (board-display-ref board x y))))
                           (eq (board-display-ref board x y) ':nothing))
                 (if (empty-cell-p (board-cells-ref board x y))
                     (walk-board board x y nil)
                     (progn
                       (setf (board-display-ref board x y) ':exploded
                             (board-exploded-p board) t)
                       (reveal-board board))))))
        (declare (inline p i n ref))
        (progn
          (ref (p x) (p y)) (ref (i x) (p y)) (ref (n x) (p y))
          (ref (p x) (i y))                   (ref (n x) (i y))
          (ref (p x) (n y)) (ref (i x) (n y)) (ref (n x) (n y))))))
  board)



(defun move (board x y action)
  (assert (<= 0 x (1- (board-width  board))))
  (assert (<= 0 y (1- (board-height board))))
  (ecase action
    ((:flag)
     (setf (board-display-ref board x y)
           (case (board-display-ref board x y)
             ((:nothing) ':flag)
             ((:flag)    ':beware)
             ((:beware)  ':nothing)
             (otherwise  (board-display-ref board x y)))))
    ((:step)
     (cond
       ((eq (board-display-ref board x y) ':nothing)
        (if (empty-cell-p (board-cells-ref board x y))
            (walk-board board x y nil)
            (progn
              (setf (board-display-ref board x y) ':exploded
                    (board-exploded-p board) t)
              (reveal-board board))))
       ((integerp (board-display-ref board x y))
        ;; check whether there's no mine nearby.
        (walk-board board x y t)))))
  board)


(defun terminal-display-board (display remaining-mine-count)
  (format t "~&Mine~P~:* remaining to be found: ~A" remaining-mine-count)
  (let ((width  (array-dimension display 0))
        (height (array-dimension display 1)))
    (flet ((print-line ()
             (loop
                :for i :from 0 :below width
                :initially (terpri) (princ "     ")
                :do (princ "+---")
                :finally (princ "+")))
           (print-digits  ()
             (loop
                :for i :from 0 :below width
                :initially (terpri) (princ "    ")
                :do (format t "~4D" i))))
      (loop
         :for j :from 0 :below height
         :initially (print-digits)
         :do (loop
                :for i :from 0 :below width
                :initially (print-line) (terpri) (format t "~4D " j)
                :do (progn
                      (princ "| ")
                      (princ
                       (case (aref display i j)
                         ((:nothing)  " ")
                         ((:mine)     "*")
                         ((:wrong)    "!")
                         ((:exploded) "#")
                         ((:flag)     ">")
                         ((:beware)   "?")
                         ((0)         ".")
                         (otherwise
                          (princ-to-string (aref display i j)))))
                      (princ " "))
                :finally (format t "| ~4D" j))
         :finally (print-line) (print-digits) (terpri)))))


(defun terminal-player (message &key display total-mine-count remaining-mine-count)
  "
Must return (values :step x y) or (values :flag x y) unless message is :explosion or :win.
"
  (let ((width  (array-dimension display 0))
        (height (array-dimension display 1)))
    (loop :named terminal-player :do
       (terminal-display-board display remaining-mine-count)
       (case message
         ((:explosion)
          (format t "~%=== You loose! ===~%")
          (return-from terminal-player (values)))
         ((:win)
          (format t "~%=== You win! ====~%")
          (return-from terminal-player (values)))
         (otherwise
          (restart-case
              (let ((*package* (find-package "COMMON-LISP-USER")))
                (format *query-io* "x y [flag|step] ? ")
                (let ((x (read *query-io*))
                      (y (read *query-io*))
                      (action (read *query-io*)))
                  (when (and (<= 0 x (1- width))
                             (<= 0 y (1- height))
                             (member action '(:step :flag)
                                     :test (function string-equal)))
                    (return-from terminal-player
                      (values (intern (string-upcase action) "KEYWORD") x y)))))
            (continue ()
              :report "Continue playing"
              (values))))))))



(defun mine (&key (width 20) (height 15) (mines 40)
             (player (function terminal-player)))
  (let ((board (make-board width height mines)))
    (loop
       :do (multiple-value-bind (action x y)
               (funcall player :play
                        :display (board-display board)
                        :total-mine-count (board-mine-count board)
                        :remaining-mine-count (- (board-mine-count board)
                                                 (count-flags board)))
             (move board x y action))
       :until (or (board-exploded-p board) (board-all-covered-p board))
       :finally (funcall player (if (board-exploded-p board)
                                    :explosion
                                    :win)
                         :display (board-display board)
                         :total-mine-count (board-mine-count board)
                         :remaining-mine-count (- (board-mine-count board)
                                                  (count-flags board))))))


;;;; THE END ;;;;
ViewGit