Skip to content

Instantly share code, notes, and snippets.

@lispyclouds
Last active July 9, 2021 07:24
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 lispyclouds/7548cce7fa66ca656673a061b0d3d955 to your computer and use it in GitHub Desktop.
Save lispyclouds/7548cce7fa66ca656673a061b0d3d955 to your computer and use it in GitHub Desktop.
Guess the animal game with learning, runs on https://babashka.org
; JSON Schema
; {
; "definitions": {
; "fact": {
; "type": "object",
; "properties": {
; "question": { "type": "string" },
; "guess": { "type": "string" },
; "no": { "$ref": "#/definitions/fact" },
; "wrongGuess": { "$ref": "#/definitions/fact" }
; },
; "required": ["question", "guess"]
; }
; },
; "schema": { "$ref": "#/definitions/fact" }
; }
(require '[clojure.java.io :as io]
'[cheshire.core :as json])
(def brains "brains.json")
(defn load-facts
[]
(if (.exists ^java.io.File (io/file brains))
(json/parse-string (slurp brains) true)
{:question "Is it 4 legged?"
:guess "Dog"}))
(defn prompt
[message]
(printf "%s: " message)
(flush)
(read-line))
(defn learn-new-fact
[]
(let [question (prompt "I give up! Tell me a question describing the animal you thought of")
guess (prompt "What's the name of this animal?")]
{:question question
:guess guess}))
(defn traverse
[{:keys [question guess no wrongGuess]
:as fact}]
(if (nil? fact)
(learn-new-fact)
(case (prompt (str question " [y/N]"))
("y" "Y" "yes")
(case (prompt (format "Is it a %s? [y/N]" guess))
("y" "Y" "yes")
(do
(println "Yayy!!! Done it!!! 🤩🤓")
fact)
(assoc fact :wrongGuess (traverse wrongGuess)))
(assoc fact :no (traverse no)))))
(loop [facts (load-facts)]
(spit brains (json/generate-string (traverse facts) {:pretty true}))
(case (prompt "Play again? [y/N]")
("y" "Y" "yes")
(recur (load-facts))
(println "Bye for now! 👋")))
@lispyclouds
Copy link
Author

This is a simple Guess the Animal game where the program tries to guess an animal you thought of and tries to learn wherever it cannot guess anymore. Remembers the animals in a file brains.json

@lispyclouds
Copy link
Author

To run it:

  • Download babashka for your OS
  • have the script in a file called animals.clj for instance
  • Let it rip! bb animals.clj

@lispyclouds
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment