go-poker/card.go

107 lines
2.0 KiB
Go

package poker
import . "github.com/logrusorgru/aurora"
import "fmt"
import "strings"
type Suit rune
type Rank rune
const (
CLUB Suit = '\u2663'
SPADE Suit = '\u2660'
DIAMOND Suit = '\u2666'
HEART Suit = '\u2665'
)
const (
ACE Rank = 'A'
DEUCE Rank = '2'
THREE Rank = '3'
FOUR Rank = '4'
FIVE Rank = '5'
SIX Rank = '6'
SEVEN Rank = '7'
EIGHT Rank = '8'
NINE Rank = '9'
TEN Rank = 'T'
JACK Rank = 'J'
QUEEN Rank = 'Q'
KING Rank = 'K'
)
type Card struct {
Rank Rank
Suit Suit
}
type Cards []*Card
func NewCardsFromString(input string) (*Cards, error) {
c := make(Cards, 0)
sl := strings.Split(input, ",")
for _, pc := range sl {
newCard, err := NewCardFromString(pc)
if err != nil {
return nil, err
}
c = append(c, newCard)
}
return &c, nil
}
func NewCardFromString(input string) (*Card, error) {
if len(input) != 2 {
return nil, fmt.Errorf("invalid card string: '%s'", input)
}
nc := new(Card)
pr := input[0:1]
ps := input[1:2]
panic(fmt.Sprintf("pr=%s ps=%s nc=%s\n", pr, ps, nc))
return nil, nil
}
func (c *Cards) formatForTerminal() (output string) {
var cardstrings []string
for _, card := range *c {
cardstrings = append(cardstrings, card.formatForTerminal())
}
output = strings.Join(cardstrings, ",")
return output
}
func (c *Card) formatForTerminal() (output string) {
var rank string
var suit string
color := Red
switch c.Suit {
case Suit(DIAMOND):
color = Blue
case Suit(HEART):
color = Red
case Suit(CLUB):
color = Green
case Suit(SPADE):
color = Black
}
rank = fmt.Sprintf("%s", BgGray(12, Bold(color(c.Rank))))
suit = fmt.Sprintf("%s", BgGray(12, Bold(color(c.Suit))))
output = fmt.Sprintf("%s%s", rank, suit)
return output
}
func (self *Card) String() string {
return fmt.Sprintf("%s%s", string(self.Rank), string(self.Suit))
}
func (s Cards) String() (output string) {
var cardstrings []string
for i := 0; i < len(s); i++ {
cardstrings = append(cardstrings, s[i].String())
}
output = strings.Join(cardstrings, ",")
return output
}