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?
There's implicit progn
in defun
statement, so it is evaluated in a such way:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With