Skip to content

Instantly share code, notes, and snippets.

@danneu
Last active August 29, 2015 14:02
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save danneu/c8f33d32b634a7d939c5 to your computer and use it in GitHub Desktop.
my friend next to me at this coffee shop is learning python http://inventwithpython.com/chapter9.html
(ns scratch.hangman
(:require
[clojure.java.io :as io]
[clojure.string :as str]))
(def hangman-frames
(str/split
(slurp (io/resource "data/hangmen.txt"))
#"\n\n"))
(defn start-game! [word]
(loop [guessed-chars #{}
frame-idx 0]
;; Check if user won
(if (every? identity (for [chr word] (contains? guessed-chars chr)))
(println (str "You saved him! The word was " word))
;; Hasn't won yet...
(do
;; Print the hangman stage
(println (nth hangman-frames frame-idx))
;; Print the word hint
(doseq [chr word]
(if (contains? guessed-chars chr)
(print chr)
(print "_"))
(print " "))
(println (str "\nGuesses: " (str/join (mapv str (sort guessed-chars)))))
;; Check if user has run out of turns
(if (= frame-idx (dec (count hangman-frames)))
(println "You killed him. :(")
;; Get user input
(do
(print "\nGuess a letter: ") (flush)
(let [guess-char (first (str/lower-case (read-line)))]
(if (contains? (set word) guess-char)
;; Good guess
(recur (conj guessed-chars guess-char) frame-idx)
;; Bad guess
(recur (conj guessed-chars guess-char) (inc frame-idx))))))))))
(defn -main [& args]
(start-game! "banana"))
+---+
| |
|
|
|
|
=========
+---+
| |
O |
|
|
|
=========
+---+
| |
O |
| |
|
|
=========
+---+
| |
O |
/| |
|
|
=========
+---+
| |
O |
/|\ |
|
|
=========
+---+
| |
O |
/|\ |
/ |
|
=========
+---+
| |
O |
/|\ |
/ \ |
|
=========
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment