A Hangman game is usually played by people who enjoy the vocabulary. You have to play by guessing a word by choosing the letters one by one. For every wrong attempt a picture of a man hanging is drawn step by step. When the picture of the hanged man is complete (when the man is hanged!!!) the game is over.
I tried implementing this game using Scala. Of course, no picture was drawn, but the alphabets H A N G M A N are written for every wrong guess. You have to guess simple four letter words.
It was quite easy to implement this using imperative style in Scala. The biggest challenge was implementing this game using functional style in Scala. The code is given below.
import scala.util.Random object Hangman { val words = Map(1->"bore",2->"clue",3->"mint",4->"star",5->"cart",6->"land",7->"tame",8->"role",9->"bask",10->"maze") def hangman(wrongAttempt:Int):String = { wrongAttempt match{ case 0=>"" case 1=>"H_ _ _ _ _ _" case 2=>"HA_ _ _ _ _" case 3=>"HAN _ _ _ _" case 4=>"HANG _ _ _" case 5=>"HANGM _ _" case 6=>"HANGMA _" case 7=>"HANGMAN" } } def checkMatch(wrongAttempt:Int,letter:String,enteredWord:String,word:String): (Boolean,Int,String,String) = { val pos:Int = word.indexOf(letter) if(pos != -1){ val output = enteredWord.replace(pos+"",letter) return (true,wrongAttempt,output,hangman(wrongAttempt)) } else{ return (false,wrongAttempt+1,enteredWord,hangman(wrongAttempt+1)) } } def printOutput(op:(Boolean,Int,String,String)) { if(op._1) op._3 foreach(it=>if(Character.isDigit(it))print("_ ") else print(it)) else println(op._4) } def main(args:Array[String]){ val word = words(new Random().nextInt(10)+1) println("_ _ _ _") var op = checkMatch(0,readLine(),"0123",word) printOutput(op) while(op._2 != 7 && word != op._3){ op = checkMatch(op._2,readLine(),op._3,word) printOutput(op) } if(op._2 == 7 && word != op._3) println("The word is " + word) } }
Couple of console-based screenshots of the game is shown below
There’s still a lot of scope for the code to be refactored and made better.