Browse Source

Add Parse function

master
Trevor Slocum 1 year ago
parent
commit
1d155db190
2 changed files with 67 additions and 56 deletions
  1. +1
    -0
      CHANGELOG
  2. +66
    -56
      card.go

+ 1
- 0
CHANGELOG View File

@ -1,4 +1,5 @@
0.1.2:
- Add Parse function
- Add Permutations method to Cards
- Rename library from cards to joker


+ 66
- 56
card.go View File

@ -15,6 +15,68 @@ type Card struct {
Suit CardSuit
}
// Parse parses a card identifier to construct a card.
func Parse(identifier string) (Card, bool) {
identifier = strings.TrimSpace(strings.ToUpper(identifier))
l := len(identifier)
if l != 2 && l != 3 {
return Card{}, false
}
var cardFace CardFace
switch identifier[:l-1] {
case "A":
cardFace = FaceAce
case "2":
cardFace = Face2
case "3":
cardFace = Face3
case "4":
cardFace = Face4
case "5":
cardFace = Face5
case "6":
cardFace = Face6
case "7":
cardFace = Face7
case "8":
cardFace = Face8
case "9":
cardFace = Face9
case "10":
cardFace = Face10
case "J":
cardFace = FaceJack
case "Q":
cardFace = FaceQueen
case "K":
cardFace = FaceKing
case "!":
cardFace = FaceJoker
default:
return Card{}, false
}
var cardSuit CardSuit
switch identifier[l-1:] {
case "H":
cardSuit = SuitHearts
case "D":
cardSuit = SuitDiamonds
case "C":
cardSuit = SuitClubs
case "S":
cardSuit = SuitSpades
case "!":
cardSuit = SuitJoker
default:
return Card{}, false
}
return Card{cardFace, cardSuit}, true
}
// Value returns the numeric value of a card.
func (c Card) Value() int {
return (int(c.Face) * 100) + int(c.Suit)
@ -74,64 +136,12 @@ func (c Card) MarshalJSON() ([]byte, error) {
// UnmarshalJSON unmarshals a Card.
func (c *Card) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
var identifier string
if err := json.Unmarshal(b, &identifier); err != nil {
return err
}
if sLen := len(s); sLen < 2 || sLen > 3 {
return fmt.Errorf("invalid card identifier: %s", s)
}
var cardFace CardFace
switch s[:len(s)-1] {
case "A":
cardFace = FaceAce
case "2":
cardFace = Face2
case "3":
cardFace = Face3
case "4":
cardFace = Face4
case "5":
cardFace = Face5
case "6":
cardFace = Face6
case "7":
cardFace = Face7
case "8":
cardFace = Face8
case "9":
cardFace = Face9
case "10":
cardFace = Face10
case "J":
cardFace = FaceJack
case "Q":
cardFace = FaceQueen
case "K":
cardFace = FaceKing
case "!":
cardFace = FaceJoker
default:
return fmt.Errorf("invalid face identifier %s", s)
}
var cardSuit CardSuit
switch s[len(s)-1:] {
case "H":
cardSuit = SuitHearts
case "D":
cardSuit = SuitDiamonds
case "C":
cardSuit = SuitClubs
case "S":
cardSuit = SuitSpades
case "!":
cardSuit = SuitJoker
default:
return fmt.Errorf("invalid suit identifier %s", s)
}
*c = Card{cardFace, cardSuit}
card, _ := Parse(identifier) // Ignore ok
*c = card
return nil
}

Loading…
Cancel
Save