Skip to content

Instantly share code, notes, and snippets.

@danneu

danneu/hangman.clj

Last active Aug 29, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.