Last active
July 28, 2018 06:56
-
-
Save montanaflynn/330c7a384ac87868cd6550d7439d2393 to your computer and use it in GitHub Desktop.
A simple program to deal Tien Len hands
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" | |
"math/rand" | |
"sort" | |
"time" | |
"github.com/fatih/color" | |
) | |
type card struct { | |
name string | |
suit string | |
order int | |
} | |
type hand []card | |
type hands []hand | |
func (h hands) sort() { | |
for _, hand := range h { | |
sort.Slice(hand, func(i, j int) bool { return hand[i].order < hand[j].order }) | |
} | |
} | |
func (h hands) print() { | |
h.sort() | |
fmt.Print("\n") | |
for _, hand := range h { | |
for _, card := range hand { | |
cardColor := &color.Color{} | |
if card.suit == "♦" || card.suit == "♥" { | |
cardColor = color.New(color.FgHiRed) | |
} else { | |
cardColor = color.New(color.FgHiBlack) | |
} | |
bold := cardColor.Add(color.Bold) | |
whiteBackground := bold.Add(color.BgHiWhite) | |
whiteBackground.Printf("[%s%s]", card.name, card.suit) | |
fmt.Print(" ") | |
color.Unset() | |
} | |
fmt.Print("\n\n") | |
} | |
} | |
type deck []card | |
func (d deck) deal() hands { | |
dealtHands := hands{hand{}, hand{}, hand{}, hand{}} | |
handIndex := 0 | |
for _, card := range d { | |
dealtHands[handIndex] = append(dealtHands[handIndex], card) | |
handIndex++ | |
if handIndex == 4 { | |
handIndex = 0 | |
} | |
} | |
return dealtHands | |
} | |
func (d deck) shuffle() deck { | |
for i := 1; i < len(d); i++ { | |
r := rand.Intn(i + 1) | |
if i != r { | |
d[r], d[i] = d[i], d[r] | |
} | |
} | |
return d | |
} | |
func newDeck() (d deck) { | |
types := []string{" 3 ", " 4 ", " 5 ", " 6 ", " 7 ", " 8 ", " 9 ", "10 ", " J ", " Q ", " K ", " A ", " 2 "} | |
suits := []string{"♠", "♣", "♦", "♥"} | |
orderCounter := 0 | |
for i := 0; i < len(types); i++ { | |
for n := 0; n < len(suits); n++ { | |
orderCounter++ | |
c := card{types[i], suits[n], orderCounter} | |
d = append(d, c) | |
} | |
} | |
return d | |
} | |
func init() { | |
rand.Seed(time.Now().UnixNano()) | |
} | |
func main() { | |
newDeck().shuffle().deal().print() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: