-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeck.go
67 lines (56 loc) · 1.36 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
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
type deck []string
func newDeck() deck {
var cards deck
cardSuits := []string{"Heart", "Spades", "Diamond", "Clubs"}
cardValues := []string{"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}
for _, s := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" Of "+s)
}
}
return cards
}
func (d deck) print() {
for _, card := range d {
fmt.Println(card)
}
}
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
func (d deck) toString() 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 newDeck method and return a new Deck
// Option #2 - log the error and exit the program
fmt.Println("Error ", err)
os.Exit(1)
}
return deck(strings.Split(string(bs), ","))
}
func (d deck) suffle() deck {
// Sourse of new Random
sourse := rand.NewSource(time.Now().UnixNano())
r := rand.New(sourse)
for i := range d {
rndPos := r.Intn(len(d) - 1)
// Swap the values
d[rndPos], d[i] = d[i], d[rndPos]
}
return d
}