-
Notifications
You must be signed in to change notification settings - Fork 0
/
blackjack.go
94 lines (71 loc) · 1.64 KB
/
blackjack.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
package gotesting
import (
"errors"
"net/http"
"strconv"
"strings"
)
var validCards = "23456789JQKA"
// CheckIfBlackjack checks if the hand is a blackjack
func CheckIfBlackjack(hand string) bool {
if len(hand) != 2 {
return false
}
return (hand[0] == 'A' && strings.Contains("JQK", string(hand[1]))) || (hand[1] == 'A' && strings.Contains("JQK", string(hand[0])))
}
// ComputeScore computes the score for a blackjack hand
func ComputeScore(hand string) int {
total := 0
for _, card := range hand {
c := string(card)
if strings.Contains("JQK", c) {
total += 10
} else if c == "A" {
total += 11
} else {
t, err := strconv.Atoi(c)
if err != nil {
return 0
}
total += t
}
}
return total
}
// CheckIfValidHand checks if the given hand is valid
func CheckIfValidHand(hand string) bool {
for _, c := range hand {
if !strings.Contains(validCards, string(c)) {
return false
}
}
return true
}
// EvaluateHand reads the hand and returns if it's a busted hand, a blackjack orthe score of the hand.
func EvaluateHand(hand string) (string, error) {
if !CheckIfValidHand(hand) {
return "", errors.New("Invalid Card found")
}
if CheckIfBlackjack(hand) {
return "BLACKJACK", nil
}
score := ComputeScore(hand)
if score > 22 {
return "BUSTED", nil
}
return strconv.Itoa(score), nil
}
// BlackJackHandler handles requests to check hands
func BlackJackHandler(w http.ResponseWriter, r *http.Request) {
hand := r.URL.Query().Get("hand")
if hand == "" {
w.WriteHeader(422)
return
}
result, err := EvaluateHand(hand)
if err != nil {
w.WriteHeader(422)
}
w.WriteHeader(200)
w.Write([]byte(result))
}