Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
マルバツゲーム
(defparameter *board*
(list #\_ #\_ #\_
#\_ #\_ #\_
#\_ #\_ #\_))
(defun show-board (board)
(format t " 012~%")
(format t "0 ~{~a~}~%" (subseq board 0 3))
(format t "1 ~{~a~}~%" (subseq board 3 6))
(format t "2 ~{~a~}~%" (subseq board 6 9)))
;; row * 3 + column
(defun access (row column board)
(nth (+ column (* 3 row)) board))
(defun check-win (char board)
(let (result)
(dolist (i (list 0 3 6) result)
(or result (setf result (every (lambda (c) (equal c char))
(subseq board i (+ i 3))))))
(dolist (i (list 0 1 2) result)
(or result (setf result (every (lambda (c) (equal c char))
(list (access 0 i board)
(access 1 i board)
(access 2 i board))))))
(or result (setf result (every (lambda (c) (equal c char))
(list (access 0 0 board)
(access 1 1 board)
(access 2 2 board)))))
(or result (setf result (every (lambda (c) (equal c char))
(list (access 0 2 board)
(access 1 1 board)
(access 2 0 board)))))
result))
(defun put-char (char row column board)
(if (equal #\_ (access row column board))
(setf (nth (+ column (* 3 row)) board) char)
nil))
(defun finished-p (board)
(not (some (lambda (c) (equal #\_ c)) board)))
(defun get-input (char)
(format t "~c turn (row column)> " char)
(let ((r (read))
(c (read)))
(unless (put-char char r c *board*)
(get-input char))))
(defun game-loop ()
(show-board *board*)
(loop
(get-input #\o)
(show-board *board*)
(when (check-win #\o *board*)
(format t "o win!!~%")
(return))
(when (finished-p *board*)
(format t "draw~%")
(return))
(get-input #\x)
(show-board *board*)
(when (check-win #\x *board*)
(format t "x win!!~%")
(return))
(when (finished-p *board*)
(format t "draw~%")
(return))))
(defun reset-game ()
(setf *board*
(list #\_ #\_ #\_
#\_ #\_ #\_
#\_ #\_ #\_)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.