-
Notifications
You must be signed in to change notification settings - Fork 23
/
pathbot.go
103 lines (81 loc) · 1.96 KB
/
pathbot.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
)
type PathbotDirection struct {
Direction string `json:"direction"`
}
type PathbotLocation struct {
Status string `json:"status"`
Message string `json:"message"`
Exits []string `json:"exits"`
Description string `json:"description"`
MazeExitDirection string `json:"mazeExitDirection"`
MazeExitDistance int `json:"mazeExitDistance"`
LocationPath string `json:"locationPath"`
}
func main() {
var location = start()
explore(location)
}
func start() PathbotLocation {
return apiPost("/pathbot/start", strings.NewReader("{}"))
}
func explore(location PathbotLocation) {
reader := bufio.NewReader(os.Stdin)
for {
printLocation(location)
if location.Status == "finished" {
fmt.Println(location.Message)
os.Exit(0)
}
printPrompt(location.Exits)
direction, err := reader.ReadString('\n')
if err != nil {
panic(err.Error())
}
dir := PathbotDirection{Direction: strings.ToUpper(direction[0:1])}
body, err := json.Marshal(dir)
if err != nil {
panic(err.Error())
}
location = apiPost(location.LocationPath, bytes.NewBuffer(body))
}
}
func printPrompt(directions []string) {
fmt.Println("What direction will you go?")
fmt.Println(directions)
}
func printLocation(location PathbotLocation) {
fmt.Println()
fmt.Println(location.Message)
fmt.Println(location.Description)
}
func apiPost(path string, body io.Reader) PathbotLocation {
domain := "https://api.noopschallenge.com"
res, err := http.Post(domain+path, "application/json", body)
if err != nil {
panic(err.Error())
}
return parseResponse(res)
}
func parseResponse(res *http.Response) PathbotLocation {
var response PathbotLocation
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err.Error())
}
err = json.Unmarshal(body, &response)
if err != nil {
panic(err.Error())
}
return response
}