object Game {
private var currentRoom : Room = TownSquare()
var whileIsTrue = true
fun play() {
while (whileIsTrue) {
print("> Enter your command: ")
println(GameInput(readLine()).processCommand())
}
}
private class GameInput(arg: String?) {
private val input = arg ?: ""
val command = input.split(" ")[0]
val argument = input.split(" ").getOrElse(1, { "" })
fun processCommand() = when (command.toLowerCase()){
"move" -> move(argument)
"quit", "exit" -> {whileIsTrue = false; "Quitting..."}
"map" -> printMap()
"ring" -> ringBell(currentRoom)
else -> commandNotFound()
}
}
private fun ringBell(currentRoom : Room) : String {
if (currentRoom == TownSquare()) {
return "The town square bell is ringing!"
} else {
return "Ring what? There is nothing here to ring."
}
}
}
Functional solution:
in processCommand:
“ring” -> ringBell()
private fun ringBell() = currentRoom.let {
if (it is TownSquare) “You ring the bell: ${it.bellSound}”
else “There are no bells nearby you can ring.”
}
Process command:
"ring" -> ring()
And funnction:
private fun ring() = currentRoom.let { room ->
if (room is TownSquare) room.ringBell()
else "There's nothing to ring."
}
room
is a TownSquare
, so we can call ringBell()
method.
Before doing this, do not forget to make the method public.