Skip to content

Instantly share code, notes, and snippets.

@pljones
Created April 21, 2015 21:36
Show Gist options
  • Save pljones/c053adc0f00f21f6d224 to your computer and use it in GitHub Desktop.
Save pljones/c053adc0f00f21f6d224 to your computer and use it in GitHub Desktop.
West London Hack Night WLHN April 2015 Text Adventure
package adventure
import scala.collection.mutable.{ Map => MMap }
trait Direction
case object North extends Direction
case object South extends Direction
case object East extends Direction
case object West extends Direction
case object Wrong extends Direction
case class Item(description: String, longDescription: String)
case class Scene(description: String, contents: MMap[String, Item])
object Game extends App {
val internet = Item("The internet", "There is a small internet here. There is a series of tubes.")
// ... do set up
val scene3 = Scene("Even darker.", MMap())
val scene2 = Scene("Its still pretty dark, but there is a cone of light.", MMap())
val scene1 = Scene("Its dark...", MMap("internet" -> internet))
var currScene = scene1
// ... do main loop
val links = Map[(Scene, Direction), Scene](
(scene1, West) -> scene2,
(scene1, North) -> scene3,
(scene2, East) -> scene1,
(scene3, South) -> scene1)
val inventory = MMap[String, Item]()
def getItem(noun: String) {
val itemOpt = currScene.contents.remove(noun)
itemOpt match {
case Some(item) => {
inventory.put(noun, item)
println("You steal the " + noun)
}
case None => println("What " + noun + "?")
}
}
try {
while (true) {
Console.println("What do you want to do? ");
var command = Console.readLine();
command.split(" ") match {
case Array("go", foo) => {
var direction: Direction = getDirection(foo)
if (direction == Wrong) {
println("That made little, if any, sense.")
} else {
println("You go " + direction + ".")
links.get((currScene, direction)).map { scene =>
currScene = scene
println(currScene.description)
}.getOrElse {
println("You bump into a hard object.")
}
}
}
case Array("get", noun) => getItem(noun)
case Array("take", noun) => getItem(noun)
case Array(verb, noun) =>
if (verb == "examine") {
println("there is no " + noun + " here")
}
case Array("look") =>
println(currScene.description)
if (!currScene.contents.isEmpty) {
currScene.contents.foreach(x => {
println("You can see " + x._2.description)
})
}
case Array("get") | Array("take") =>
println("You will need to be more specific, I am a computer.")
case _ => {
println("I didn't catch that...")
}
}
if (command == "give up")
throw new Exception("Done")
}
} finally {}
// ... eventually they gave up, so exit
def getDirection(foo: String) = {
foo match {
case "n" | "north" => North
case "s" | "south" => South
case "e" | "east" => East
case "w" | "west" => West
case _ => Wrong
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment