-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCLI.go
64 lines (52 loc) · 1.23 KB
/
CLI.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
package poker
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
)
const (
PlayerPrompt = "Please enter the number of players: "
BadPlayerInputErrMsg = "Bad value received for number of players, please try again with a number"
)
type CLI struct {
in *bufio.Scanner
out io.Writer
game Game
}
func NewCLI(in io.Reader, out io.Writer, game Game) *CLI {
return &CLI{
in: bufio.NewScanner(in),
out: out,
game: game,
}
}
func (cli *CLI) PlayPoker() error {
fmt.Fprint(cli.out, PlayerPrompt)
numberOfPlayersInput := cli.readLine()
numberOfPlayers, err := strconv.Atoi(strings.Trim(numberOfPlayersInput, "\n"))
if err != nil {
fmt.Fprint(cli.out, BadPlayerInputErrMsg)
return err
}
cli.game.Start(numberOfPlayers, cli.out)
winnerInput := cli.readLine()
winner, err := extractWinner(winnerInput)
if err != nil {
return err
}
cli.game.Finish(winner)
return nil
}
func extractWinner(userInput string) (string, error) {
if strings.Contains(userInput, " wins") {
return strings.Replace(userInput, " wins", "", 1), nil
} else {
return "", fmt.Errorf("The proper input format is: %v\n you entered: %v", PlayerPrompt, userInput)
}
}
func (cli *CLI) readLine() string {
cli.in.Scan()
return cli.in.Text()
}