Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
(ns daily.ch-163-fallout-hacking-game
(:require
[clojure.java.io :as io]
[clojure.string :as str]))
(def all-words
"The entire dictionary of available words."
(str/split-lines (slurp (io/resource "enable1.txt"))))
(defn word-difference
"Returns the number of character positional matches between two words.
Ex: (word-difference aaa bba) ;=> 1
(word-difference aaa baa) ;=> 2"
[guess answer]
(->> (for [idx (range (count answer))]
(= (nth guess idx) (nth answer idx)))
(filter true?)
count))
(defn gen-word-length
"Difficulty is an Integer 1-5.
1: Words are length 4-5
2: Words are length 6-8
3: Words are length 9-10
4: Words are length 11-12
5: Words are length 13-15"
[difficulty]
(case difficulty
1 (rand-nth [4 5])
2 (rand-nth [6 7 8])
3 (rand-nth [9 10])
4 (rand-nth [11 12])
5 (rand-nth [13 14 15])))
(defn gen-new-game
"Returns the representation of a game that the user will make attempts against.
Difficulty is an Integer 1-5."
[difficulty]
(let [word-length (gen-word-length difficulty)
words (->> (shuffle all-words)
(filter #(= word-length (count %)))
(take 8)
(int #{}))]
{:words words
:word-length word-length
:answer (rand-nth (shuffle words))}))
(defn -main [& args]
(print (str "Difficulty (1-5)? ")) (flush)
(let [difficulty (Integer/parseInt (read-line))]
(let [game (gen-new-game difficulty)]
;; Print out word list
(println)
(doseq [word (:words game)]
(println word))
(loop [attempts 1]
;; Get user input
(print (str "\n(Attempt " attempts "/4) Guess: ")) (flush)
(let [guess (read-line)]
;; Ensure user guess is actually one of the words in the game
(if-not (contains? (:words game) guess)
(if (= 4 attempts)
(println "You lose")
(do (println "That's not one of the words.")
(recur (inc attempts))))
;; Check difference
(let [diff (word-difference guess (:answer game))]
(println)
(println (str "You guessed: " guess ". "
diff " characters were correct. "))
;; Check for win
(if (= (:word-length game) diff)
(println "You win")
(if (= 4 attempts)
(println "You lose")
(recur (inc attempts)))))))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.