-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeck.go
More file actions
73 lines (60 loc) · 1.6 KB
/
deck.go
File metadata and controls
73 lines (60 loc) · 1.6 KB
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
package main
import (
"fmt"
"io/ioutil"
"math/rand"
"os"
"strings"
"time"
)
// Creating a type deck
type deck []string
// Method to return a new deck of 52 cards
func newDeck() deck {
cards := deck{}
cardSuits := []string{"Spades", "Clubs", "Hearts", "Diamonds"}
cardValues := []string{"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}
for _, suit := range cardSuits {
for _, value := range cardValues {
cards = append(cards, value+" of "+suit)
}
}
return cards
}
// Method to deal cards, returns cards dealt of handSize and remainingCards
func deal(d deck, handSize int) (deck, deck) {
return d[:handSize], d[handSize:]
}
// Method to print cards in the deck
func (d deck) print() {
for _, card := range d {
fmt.Println(card)
}
}
// Method to convert a deck to a String
func (d deck) toString() string {
return strings.Join([]string(d), ",")
}
// Method to write / save deck contents to a file [0666 = All Permissions]
func (d deck) saveToFile(fileName string) error {
return ioutil.WriteFile(fileName, []byte(d.toString()), 0666)
}
// Method to read deck from a file
func readDeckFromFile(fileName string) deck {
bs, err := ioutil.ReadFile(fileName)
if err != nil {
// if for some reason, the file reading fails, we handle it here
fmt.Println("Error : ", err)
os.Exit(1)
}
return deck(strings.Split(string(bs), ","))
}
// Method to shuffle deck of cards
func (d deck) shuffle() {
source := rand.NewSource(time.Now().UnixNano())
r := rand.New(source)
for i := range d {
newPosition := r.Intn(len(d) - 1)
d[i], d[newPosition] = d[newPosition], d[i]
}
}