-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
317 lines (282 loc) · 6.8 KB
/
main.go
File metadata and controls
317 lines (282 loc) · 6.8 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"math/rand"
"net/http"
"os"
"strings"
"time"
"example.com/simon/pokedexcli/internal/pokecache"
)
func cleanInput(text string) []string {
return strings.Fields(strings.ToLower(text))
}
var commands = map[string]cliCommand{}
func commandExit(cfg *config, params []string) error {
fmt.Println("Closing the Pokedex... Goodbye!")
os.Exit(0)
return nil
}
func commandHelp(cfg *config, params []string) error {
fmt.Println("Welcome to the Pokedex!")
fmt.Println("Usage:")
fmt.Println("")
for _, cmd := range commands {
fmt.Printf("%s: %s\n", cmd.name, cmd.description)
}
return nil
}
type responseBody struct {
Count int `json:"count"`
Next string `json:"next"`
Previous string `json:"previous"`
Results []responseResult `json:"results"`
}
type pokemonResponse struct {
BaseExperience int `json:"base_experience"`
}
type responseResult struct {
Name string `json:"name"`
Url string `json:"url"`
}
func getUrl(url string, cfg *config) ([]byte, error) {
if len(url) == 0 {
return nil, errors.New("Url empty")
}
cached, found := cfg.cache.Get(url)
if found {
fmt.Println("Found url in cache, skipping http request")
return cached, nil
}
fmt.Println("Not found in cache, loading via http")
res, err := http.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Request not successful got %s", res.Status)
}
bytes, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
cfg.cache.Add(url, bytes)
return bytes, nil
}
func getMap(url string, cfg *config) error {
bytes, err := getUrl(url, cfg)
if err != nil {
return err
}
var js responseBody
err = json.Unmarshal(bytes, &js)
if err != nil {
return err
}
cfg.next = js.Next
cfg.previous = js.Previous
for _, area := range js.Results {
fmt.Println(area.Name)
}
return nil
}
func commandMap(cfg *config, params []string) error {
return getMap(cfg.next, cfg)
}
func commandMapb(cfg *config, params []string) error {
if len(cfg.previous) == 0 {
fmt.Println("you're on the first page")
return nil
}
return getMap(cfg.previous, cfg)
}
func commandCatch(cfg *config, params []string) error {
if len(params) == 0 {
return errors.New("No name given")
}
bytes, err := getUrl("https://pokeapi.co/api/v2/pokemon/"+params[0], cfg)
if err != nil {
return err
}
var js pokemon
err = json.Unmarshal(bytes, &js)
if err != nil {
return err
}
fmt.Printf("Throwing a Pokeball at %s...\n", params[0])
num := rand.Float64()
baseChance := 0.9
penalty := math.Max(0.5, float64(js.BaseExperience)/1000.0)
if num < baseChance-penalty {
fmt.Printf("%s was caught!\n", params[0])
fmt.Println("You may now inspect it with the inspect command.")
cfg.pokemons[params[0]] = js
} else {
fmt.Printf("%s escaped!\n", params[0])
}
return nil
}
func commandExplore(cfg *config, params []string) error {
if len(params) == 0 {
return errors.New("No name given")
}
bytes, err := getUrl("https://pokeapi.co/api/v2/location-area/"+params[0], cfg)
if err != nil {
return err
}
var js areaResponse
err = json.Unmarshal(bytes, &js)
if err != nil {
return err
}
fmt.Printf("Exploring %s...\n", js.Name)
if len(js.Encounters) > 0 {
fmt.Println("Found Pokemon:")
for _, enc := range js.Encounters {
fmt.Printf("- %s\n", enc.Pokemon.Name)
}
}
return nil
}
func commandInspect(cfg *config, params []string) error {
if len(params) == 0 {
return errors.New("No name given")
}
poke, found := cfg.pokemons[params[0]]
if !found {
fmt.Println("you have not caught that pokemon")
return nil
}
fmt.Printf("Name: %s\nHeight: %d\nWeight: %d\n", poke.Name, poke.Height, poke.Weight)
if len(poke.Stats) > 0 {
fmt.Println("Stats:")
for _, stat := range poke.Stats {
fmt.Printf(" -%s: %d\n", stat.Stat.Name, stat.Value)
}
}
if len(poke.Types) > 0 {
fmt.Println("Types:")
for _, tp := range poke.Types {
fmt.Printf(" - %s\n", tp.Type.Name)
}
}
return nil
}
func commandPokedex(cfg *config, params []string) error {
fmt.Println("Your Pokedex:")
for _, poke := range cfg.pokemons {
fmt.Printf(" - %s\n", poke.Name)
}
return nil
}
type areaResponse struct {
Name string `json:"name"`
Encounters []encounter `json:"pokemon_encounters"`
}
type encounter struct {
Pokemon pokemonEncounter `json:"pokemon`
}
type pokemonEncounter struct {
Name string `json:"name"`
}
type pokemon struct {
Name string `json:"name"`
Height int `json:"height"`
Weight int `json:"weight"`
BaseExperience int `json:"base_experience"`
Stats []pokemonStat `json:"stats"`
Types []struct {
Type struct {
Name string `json:"name"`
} `json:"type"`
} `json:"types"`
}
type pokemonStat struct {
Stat struct {
Name string `json:"name"`
} `json:"stat"`
Value int `json:"base_stat"`
}
type cliCommand struct {
name string
description string
callback func(*config, []string) error
}
type config struct {
next string
previous string
cache *pokecache.Cache
pokemons map[string]pokemon
}
func main() {
commands["help"] = cliCommand{
name: "help",
description: "Displays a help message",
callback: commandHelp,
}
commands["exit"] = cliCommand{
name: "exit",
description: "Exit the Pokedex",
callback: commandExit,
}
commands["map"] = cliCommand{
name: "map",
description: "Display next 20 areas",
callback: commandMap,
}
commands["mapb"] = cliCommand{
name: "mapb",
description: "Display previous 20 areas",
callback: commandMapb,
}
commands["catch"] = cliCommand{
name: "catch [name]",
description: "Catch a pokemon by the given name",
callback: commandCatch,
}
commands["explore"] = cliCommand{
name: "explore [area]",
description: "Explore pokemons in a specific area",
callback: commandExplore,
}
commands["inspect"] = cliCommand{
name: "inspect [name]",
description: "Inspect a caught pokemon by name",
callback: commandInspect,
}
commands["pokedex"] = cliCommand{
name: "pokedex",
description: "List all caught pokemons",
callback: commandPokedex,
}
cfg := config{
next: "https://pokeapi.co/api/v2/location-area",
previous: "",
cache: pokecache.NewCache(1 * time.Minute),
pokemons: map[string]pokemon{},
}
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("Pokedex > ")
for scanner.Scan() {
input := cleanInput(scanner.Text())
if len(input) == 0 {
continue
}
cmd, exists := commands[input[0]]
if exists {
err := cmd.callback(&cfg, input[1:])
if (err) != nil {
fmt.Printf("Error: %s\n", err.Error())
}
} else {
fmt.Println("Unknown command")
}
fmt.Print("Pokedex > ")
}
}