65 lines
1.2 KiB
Go
65 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io/ioutil"
|
|
"math/rand"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type deck []string
|
|
|
|
func (d deck) print() {
|
|
for i, card := range d {
|
|
fmt.Println(i, card)
|
|
}
|
|
}
|
|
|
|
func (d deck) toString(seperator string) string {
|
|
return strings.Join(d, "\n")
|
|
}
|
|
|
|
func (d deck) save(filename string) error {
|
|
return ioutil.WriteFile(filename, []byte(d.toString("\n")), 0644)
|
|
}
|
|
|
|
func (d deck) shuffle() deck {
|
|
rand.Seed(time.Now().UnixNano())
|
|
for i, _ := range d {
|
|
indexToSwap := rand.Intn(len(d) - 1)
|
|
d[i], d[indexToSwap] = d[indexToSwap], d[i]
|
|
}
|
|
return d
|
|
}
|
|
|
|
func newDeck() deck {
|
|
cards := deck{}
|
|
cardSuits := []string{"Spades", "Diamonds", "Hearts", "Clubs"}
|
|
cardValues := []string{"Ace", "Two", "Three", "Four"}
|
|
for _, suite := range cardSuits {
|
|
for _, value := range cardValues {
|
|
cards = append(cards, value+" of "+suite)
|
|
}
|
|
}
|
|
return cards
|
|
}
|
|
|
|
func deal(d deck, handsize int) (deck, deck) {
|
|
return d[:handsize], d[handsize:]
|
|
}
|
|
|
|
func fromString(input []byte, seperator string) deck {
|
|
return deck(strings.Split(string(input), seperator))
|
|
}
|
|
|
|
func load(filename string) deck {
|
|
bytes, err := ioutil.ReadFile(filename)
|
|
if err != nil {
|
|
fmt.Println("Error: ", err)
|
|
os.Exit(1)
|
|
}
|
|
return fromString(bytes, "\n")
|
|
}
|