Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a win in Tic-Tac-Toe

Okay, so I'm about finished with my latest project, a (admittedly not very good) implementation of Tic Tac Toe in Common Lisp (the whole program available here), but I'm stuck on one last part; I can't figure out how to get my function that checks for a winner working. The function (and its subordinate function) look like this:

(defun check-for-win ()
    (cond ((is-line 1 2 3) t)
            ((is-line 1 4 7) t)
            ((is-line 1 5 9) t)
            ((is-line 2 5 8) t)
            ((is-line 3 6 9) t)
            ((is-line 3 5 7) t)
            ((is-line 4 5 6) t)
            ((is-line 7 8 9) t))
    nil)

(defun is-line (a b c)
    (let ((a (aref *board* (- a 1)))
              (b (aref *board* (- b 1)))
              (c (aref *board* (- c 1))))
        (if (and 
                  (eql a b)
                  (eql a c)
                  (eql b c))
            t
            nil)))

(albeit not indented so deeply), and in (is-line), a, b and c will be (in a winning scenario) set to a symbol (either :X or :O). How do I get the equality checks working?

like image 697
Oso Avatar asked Dec 12 '22 18:12

Oso


1 Answers

There's implicit progn in defun statement, so it is evaluated in a such way:

  1. statements are evaluated one after another;
  2. value of last statement is returned as a function result.

In your check-for-win you have 2 statements: cond and nil. In accordance with progn evaluation rules, value of nil will be returned for any call, and result of cond will be just ignored.

Try this code:

(defun check-for-win ()
  (cond ((is-line 1 2 3) t)
          ((is-line 1 4 7) t)
          ((is-line 1 5 9) t)
          ((is-line 2 5 8) t)
          ((is-line 3 6 9) t)
          ((is-line 3 5 7) t)
          ((is-line 4 5 6) t)
          ((is-line 7 8 9) t)
          (:else nil)))

:else is just a keyword, and as any keyword it is evaluated to true. You can use any other keyword or just true. So, if no statement before gave true, the result of cond (and all the function) will be nil.

like image 186
ffriend Avatar answered Jan 18 '23 01:01

ffriend