learn_go/cards/deck.go

65 lines
1.2 KiB
Go
Raw Normal View History

2022-02-06 22:13:36 +01:00
package main
2022-02-07 23:04:01 +01:00
import (
"fmt"
"io/ioutil"
2022-02-08 22:17:44 +01:00
"math/rand"
"os"
2022-02-07 23:04:01 +01:00
"strings"
2022-02-08 22:17:44 +01:00
"time"
2022-02-07 23:04:01 +01:00
)
2022-02-06 22:13:36 +01:00
type deck []string
func (d deck) print() {
for i, card := range d {
fmt.Println(i, card)
}
}
2022-02-08 22:17:44 +01:00
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
}
2022-02-06 22:13:36 +01:00
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
}
2022-02-07 23:04:01 +01:00
func deal(d deck, handsize int) (deck, deck) {
return d[:handsize], d[handsize:]
}
func fromString(input []byte, seperator string) deck {
2022-02-08 22:17:44 +01:00
return deck(strings.Split(string(input), seperator))
2022-02-07 23:04:01 +01:00
}
2022-02-08 22:17:44 +01:00
func load(filename string) deck {
2022-02-07 23:04:01 +01:00
bytes, err := ioutil.ReadFile(filename)
2022-02-08 22:17:44 +01:00
if err != nil {
fmt.Println("Error: ", err)
os.Exit(1)
}
return fromString(bytes, "\n")
2022-02-07 23:04:01 +01:00
}