-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepl.go
81 lines (71 loc) · 1.32 KB
/
repl.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
package main
import (
"fmt"
)
type Command struct {
Name string
Help string
Callback func()
}
func getCommands(g *Game) []Command {
return []Command{
{
Name: "hit",
Help: "Draw a card from the deck",
Callback: g.Hit,
},
{
Name: "stand",
Help: "End your turn",
Callback: g.Stand,
},
{
Name: "cards",
Help: "Show your hand",
Callback: g.Hand,
},
{
Name: "score",
Help: "Show your score",
Callback: g.Score,
},
{
Name: "exit",
Help: "Exit the game",
Callback: g.Exit,
},
}
}
func findCommand(commands []Command, name string) (Command, bool) {
for _, command := range commands {
if command.Name == name {
return command, true
}
}
return Command{}, false
}
func showHelp(commands []Command) {
fmt.Println("help:")
for _, command := range commands {
fmt.Printf("- %v: %v\n", command.Name, command.Help)
}
}
func startRepl(g *Game) {
g.Start()
commands := getCommands(g)
var commandName string
for g.Playing {
fmt.Print("> ")
fmt.Scanf("%s", &commandName)
if commandName == "help" {
showHelp(commands)
continue
}
command, ok := findCommand(commands, commandName)
if !ok {
fmt.Println("Invalid command! ... type 'help' for a list of commands")
continue
}
command.Callback()
}
}