Let's create parts of a text-based adventure to see how we can use switch statements to make decisions:
- First, let's define an enum to represent the directions we can travel in:
enum CompassPoint {
case north
case south
case east
case west
}
- Next, let's create a function that describes what the player of the text adventure will see when they look in that direction:
func lookTowards(_ direction: CompassPoint) {
switch direction {
case .north:
print("To the north lies a winding road")
case .south:
print("To the south is the Prancing Pony tavern")
case .east:
print("To the east is a blacksmith")
case .west:
print("The the west is the town square")
}
}
lookTowards(.south) // To the south is the Prancing Pony tavern
- In our text adventure, users can pick up items and attempt to combine them to produce new items and solve problems. Let's define our available items as an enum:
enum Item {
case key
case lockedDoor
case openDoor
case bluntKnife
case sharpeningStone
case sharpKnife
}
- Now, we'll write a function that takes two items and tries to combine them into a new item. If the items cannot be combined, it will return nil:
func combine(_ firstItem: Item, with secondItem: Item) -> Item? {
switch (firstItem, secondItem) {
case (.key, .lockedDoor):
print("You have unlocked the door!")
return .openDoor
case (.bluntKnife, .sharpeningStone):
print("Your knife is now sharp")
return .sharpKnife
default:
print("\(firstItem) and \(secondItem) cannot be combined)")
return nil
}
}
let door = combine(.key, with: .lockedDoor) // openDoor
let oilAndWater = combine(.bluntKnife, with: .lockedDoor) // nil
- In our text adventure, the player will meet different characters and can interact with them; so first, let's define the characters that the player can meet:
enum Character: String {
case wizard
case bartender
case dragon
}
- Now, let's write a function that will allow the player to say something, and optionally provide a character to say it to. The interaction that will occur will depend on what say is and the character it is said to:
func say(_ textToSay: String, to character: Character? = nil) {
switch (textToSay, character) {
case ("abracadabra", .wizard?):
print("The wizard says, \"Hey, that's my line!\"")
case ("Pour me a drink", .bartender?):
print("The bartender pours you a drink")
case ("Can I have some of your gold?", .dragon?):
print("The dragon burns you to death with his firey breath")
case (let textSaid, nil):
print("You say \"\(textSaid)\", to no-one.")
case (_, let anyCharacter?):
print("The \(anyCharacter) looks at you, blankly)")
}
}
say("Is anybody there?") // You say "Is anybody there?", to no-one.
say("Pour me a drink", to: .bartender) // The bartender pours you a drink
say("Can I open a tab?", to: .bartender) // The bartender looks at you, blankly