Created
February 2, 2018 21:29
-
-
Save dav1x/8c03c6b15db6cf217d960a9347a0ea6c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"math/rand" | |
"os" | |
"strings" | |
) | |
// Create a new type of 'deck' | |
// which is a slice of strings | |
type deck []string | |
func (d deck) print() { | |
for _, card := range d { | |
fmt.Println(card) | |
} | |
} | |
func newDeck() deck { | |
cards := deck{} | |
cardSuits := []string{"Spades", "Hearts", "Diamonds", "Clubs"} | |
cardValues := []string{"Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"} | |
for _, suit := range cardSuits { | |
for _, value := range cardValues { | |
cards = append(cards, value+" of "+suit) | |
} | |
} | |
return cards | |
} | |
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 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 print out err and make a call to new deck function | |
// Option #2 print out err and and exit | |
fmt.Println("Error:", err) | |
os.Exit(1) | |
} | |
s := strings.Split(string(bs), ",") | |
return deck(s) | |
} | |
func (d deck) shuffle() { | |
for i := range d { | |
newPosition := rand.Intn(len(d) - 1) | |
d[i], d[newPosition] = d[newPosition], d[i] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment