Last active
July 9, 2021 07:24
-
-
Save lispyclouds/7548cce7fa66ca656673a061b0d3d955 to your computer and use it in GitHub Desktop.
Guess the animal game with learning, runs on https://babashka.org
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; 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! 👋"))) |
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
Here is a demo: https://asciinema.org/a/380960
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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