// Text Adventure -- main loop (starter). // // Finish the TODOs so the game plays as described on the chapter page // (project-04-text-adventure.html). As it is, the file runs: it prints // placeholder lines, and quit stops it. // // When you need them, add "slices" to the import list. // // Run from this folder: // cd projects/04-text-adventure/starter // go run . package main import ( "bufio" "fmt" "os" "strings" "textadventure/world" ) var reader = bufio.NewReader(os.Stdin) var currentRoom = world.StartID var inventory = []string{} // TODO: write describe so that it prints: // // -- -- // // Items here: (only if the room has items) // Exits: func describe(room int) { // Replace this placeholder line: fmt.Println("TODO: replace this line", room) } // TODO: write goTo so that it looks up the exit on the current room. If the // exit exists, change currentRoom and describe the new room. Otherwise print // "You cannot go that way." func goTo(direction string) { // Replace this placeholder line: fmt.Println("TODO: replace this line", direction) } // TODO: write take so that it looks for itemName in the current room's items. // If found, remove it from the room, add it to inventory, and print // "You pick up the ." If not found, print "There is no here." // Return true if the player just picked up the gold coin, so that the main // loop can end. func take(itemName string) bool { // Replace this placeholder line: fmt.Println("TODO: replace this line", itemName) return false } // TODO: write showInventory so that it prints the items separated by commas. // If there are none, print "You are carrying nothing." func showInventory() { // Replace this placeholder line: fmt.Println("TODO: replace this line", inventory) } // readLine prints the prompt and gives back one trimmed line. The error is // not nil when there is no more input. func readLine(prompt string) (string, error) { fmt.Print(prompt) text, err := reader.ReadString('\n') line := strings.TrimSpace(text) if err != nil && line == "" { return "", err } return line, nil } // parse splits a typed line into a verb and an argument. Items like // "gold coin" are two words, so everything after the verb is the argument. func parse(line string) (string, string) { words := strings.Fields(line) if len(words) == 0 { return "", "" } return words[0], strings.Join(words[1:], " ") } func main() { describe(currentRoom) for { line, err := readLine("> ") if err != nil { fmt.Println() fmt.Println("Goodbye.") break } verb, arg := parse(line) if verb == "quit" { fmt.Println("Goodbye.") break } // TODO: send the other verbs to the right function: look, go, take, // inv. Leave the loop with break after take returns true. Use an if // chain, because break inside a switch would not leave the loop. // Replace this placeholder line: fmt.Println("TODO: replace this line", verb, arg) } }