Skip to content

Instantly share code, notes, and snippets.

@shengyou
Created May 11, 2020 03:47
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save shengyou/f6b816c6220eb18cde2f423d9e773d5d to your computer and use it in GitHub Desktop.
package chapter15
fun main() {
Game.play()
}
package chapter15
import java.lang.Exception
import java.lang.IllegalStateException
object Game {
private var running = true
private val player = Player("Madrigal")
private var currentRoom: Room = TownSquare()
private var worldMap = listOf(
listOf(currentRoom, Room("Tavern"), Room("Back Room")),
listOf(Room("Long Corridor"), Room("Generic Room"))
)
init {
println("Welcome, adventurer.")
player.castFireball()
}
fun play() {
while (running) {
print("> Enter you command: ")
println(GameInput(readLine()).processCommand())
}
}
private fun move(directionInput: String) =
try {
val direction = Direction.valueOf(directionInput.toUpperCase())
val newPosition = direction.updateCoordinate(player.currentPosition)
if (!newPosition.isInBounds) {
throw IllegalStateException("$direction is out of bounds.")
}
val newRoom = worldMap[newPosition.y][newPosition.x]
player.currentPosition = newPosition
currentRoom = newRoom
"OK, you move $direction to the ${newRoom.name}.\n${newRoom.load()}"
} catch (e: Exception) {
"Invalid direction: $directionInput."
}
private fun map(): String {
var output = ""
for (row in worldMap) {
for (column in row) {
output += if (column.name == currentRoom.name) {
"O"
} else {
"X"
}
}
output += "\n"
}
return output
}
private fun ring(): String {
return currentRoom.ringBell()
}
private fun quit(): String {
running = false
return "Bye, adventurer"
}
private fun printPlayerStatus(player: Player) {
println("(Aura: ${player.auraColor()}) " +
"(Blessed: ${if (player.isBlessed) "YES" else "NO"}")
println("${player.name} ${player.formatHealthStatus()}")
}
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)
"map" -> map()
"ring" -> ring()
"quit" -> quit()
else -> commandNotFound()
}
private fun commandNotFound() = "I'm not quite sure what you're trying to do!"
}
}
package chapter15
enum class Direction(private val coordinate: Coordinate) {
NORTH(Coordinate(0, -1)),
EAST(Coordinate(1, 0)),
SOUTH(Coordinate(0, 1)),
WEST(Coordinate(-1, 0));
fun updateCoordinate(playerCoordinate: Coordinate) =
Coordinate(playerCoordinate.x + coordinate.x, playerCoordinate.y + coordinate.y)
}
data class Coordinate(val x: Int, val y: Int) {
val isInBounds = x >= 0 && y >= 0
operator fun plus(other: Coordinate) = Coordinate(x + other.x, y + other.y)
}
package chapter15
class Player(_name: String,
var healthPoints: Int = 100,
val isBlessed: Boolean,
private val isImmortal: Boolean) {
var name = _name
get() = "${field.capitalize()} of $hometown"
private set(value) {
field = value.trim()
}
val hometown by lazy { selectHometown() }
var currentPosition = Coordinate(0, 0)
init {
require(healthPoints > 0, { "healthPoints must be greater than zero." })
require(name.isNotBlank(), { "Player must have a namel" })
}
constructor(name: String): this(name, isBlessed = true, isImmortal = false) {
if (name.toLowerCase() == "kar") healthPoints = 40
}
private fun selectHometown(): String {
return listOf(
"Taipei",
"Taichung",
"Kaohsiung",
"Taitung"
).shuffled().first()
}
fun castFireball(numFirballs: Int = 2) {
//println("A glass of Fireball springs into existence. (x$numFirballs)")
}
fun formatHealthStatus(): String {
return "Health Status: ..."
}
fun auraColor(): String {
return "Aura Color: ..."
}
}
package chapter15
open class Room(val name: String) {
protected open val dangerLevel = 5
protected open val bellSound = "DING"
fun description() = "Room: $name\nDanger level: $dangerLevel"
open fun load() = "Nothing much to see here..."
open fun ringBell() = "$bellSound from $name"
}
package chapter15
open class TownSquare : Room("Town Square") {
override val dangerLevel = super.dangerLevel - 3
override val bellSound = "GWONG"
override fun load() = "The villagers rally and cheer as you enter!\n${ringBell()}"
override fun ringBell() = "The bell tower announce your arrival. $bellSound"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment