Skip to content

Instantly share code, notes, and snippets.

@danneu
Last active August 29, 2015 14:02
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 danneu/79185ad23e0bfb34886c to your computer and use it in GitHub Desktop.
Save danneu/79185ad23e0bfb34886c to your computer and use it in GitHub Desktop.
(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