Skip to content

Instantly share code, notes, and snippets.

@jaimefjorge
Created June 10, 2011 05:06
Show Gist options
  • Save jaimefjorge/1018261 to your computer and use it in GitHub Desktop.
Save jaimefjorge/1018261 to your computer and use it in GitHub Desktop.
cliff hanger in Scala done in 15 minutes
object cliffHanger extends App{
val man = List(" 0\n","-","-","-\n"," |\n"," /","\\\n")
def drawState(tries:Int,word:String,letters:List[Char]) = {
println("\n\n\n")
println(man.dropRight(tries).mkString)
word.toList.foreach(c => if (letters.exists(c == _)) print(c) else print("_"))
println()
}
def won(word:String,letters:List[Char])= word.toList.forall(c => letters.exists(c == _))
def cliffHanger(word:String,tries:Int,letters:List[Char]):Unit={
drawState(tries,word,letters)
(won(word,letters),tries) match{
case (true,_) => println("You Won!")
case (_,0) => println("You lost. The word was "+word)
case (_,n) => {
val input = readLine()
if (word.contains(input.head) && !letters.contains(input.head)){
println("got letter "+input.head+" correct")
cliffHanger(word,tries,input.head :: letters)
}
else { println(input.head +" is "+(if (letters.contains(input.head)) "already" else "not") +" a letter of the word")
cliffHanger(word,tries-1,letters)
}
}
}
}
println("Playing cliff hanger!")
cliffHanger("foobarbaz",man.size,Nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment