-
Notifications
You must be signed in to change notification settings - Fork 0
/
deck.go
85 lines (56 loc) · 1.35 KB
/
deck.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
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
//Create a new type of deck which is a slice of strings
type deck []string
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "DIamonds", "Hearts", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four"}
for _, cardSuit := range cardSuits {
for _, cardValue := range cardValues {
cards = append(cards, cardValue+" of "+cardSuit)
}
}
return cards
}
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() string {
//take a deck to a string
return strings.Join([]string(d), ",")
}
func (d deck) saveToFile(filename string) error {
return ioutil.WriteFile(filename, []byte(d.toString()), 0666)
}
func newDeckFromFile(filename string) deck {
bs, err := ioutil.ReadFile(filename)
if err != nil {
//Option 1 - log the error and call to newDeck()
//Option 2 - log the error and quit
fmt.Println("Error:", err)
os.Exit(1)
}
deckString := string(bs[:])
newDeck := strings.Split(deckString, ",")
return newDeck
}
func (d deck) shuffleDeck() {
d.print()
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(d), func(i, j int) { d[i], d[j] = d[j], d[i] })
fmt.Println("--------------")
d.print()
}