Skip to content

Instantly share code, notes, and snippets.

@jColeChanged
Created August 6, 2011 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jColeChanged/1128840 to your computer and use it in GitHub Desktop.
Save jColeChanged/1128840 to your computer and use it in GitHub Desktop.
Just Wrote the Game Twenty Questions in Common Lisp
(defun input-question ()
(print "Please enter a question which has a yes answer for your word. This question should result in a no for the incorrect word given earlier:")
(read-line))
(defun input-chosen-word ()
(print "Please enter the word that you chose at the start of the game:")
(read-line))
(defun input-question-answer (question)
(print question)
(print "The only valid answers are yes and no.")
(if (equalp "yes"
(let ((response (read-line)))
(if (or (equalp response "yes") (equalp response "no"))
response
(input-question-answer question))))
T
NIL))
(defun get-question (tree) (first tree))
(defun get-yes-child (tree) (second tree))
(defun get-no-child (tree) (third tree))
(defun is-branch (node) (consp node))
(defun twenty-questions (tree)
(if (input-question-answer (get-question tree))
(let ((current-node (get-yes-child tree)))
(if current-node
(if (is-branch current-node)
(twenty-questions current-node)
(unless (input-question-answer current-node)
(setf (second tree)
(let ((question (input-question))
(answer (input-chosen-word))
(old (second tree)))
(list question answer old)))))
(setf (second tree) (input-chosen-word))))
(let ((current-node (get-no-child tree)))
(if current-node
(if (is-branch current-node)
(twenty-questions current-node)
(unless (input-question-answer current-node)
(setf (third tree)
(let ((question (input-question))
(answer (input-chosen-word))
(old (third tree)))
(list question answer old)))))
(setf (third tree) (input-chosen-word))))))
(defparameter q-tree '("Is it bigger than a breadbox?" "Airplane" nil))
(defun main ()
(loop
while (input-question-answer "Do you want to play another round?")
do
(print "Please choose a word and I'll try to guess it.")
(twenty-questions q-tree)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment