78 lines
1.3 KiB
Go
78 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type Players [16]Player
|
|
|
|
type Game struct {
|
|
Pot Currency
|
|
Players Players
|
|
}
|
|
|
|
type Player struct {
|
|
ID string
|
|
Name string
|
|
Card string
|
|
Balance Currency
|
|
}
|
|
|
|
type Currency int
|
|
|
|
func (game Game) GetPlayers() []Player {
|
|
players := []Player{}
|
|
for _, player := range game.Players {
|
|
if !player.Empty() {
|
|
players = append(players, player)
|
|
}
|
|
}
|
|
return players
|
|
}
|
|
|
|
func (p Player) Empty() bool {
|
|
return p == (Player{})
|
|
}
|
|
|
|
func (c Currency) MarshalJSON() ([]byte, error) {
|
|
return json.Marshal(fmt.Sprintf(`$%v.%02d`, c/100, c%100))
|
|
}
|
|
|
|
func (c *Currency) UnmarshalJSON(b []byte) error {
|
|
var s string
|
|
if err := json.Unmarshal(b, &s); err != nil {
|
|
return err
|
|
}
|
|
re := regexp.MustCompile(`^\$([0-9]+(\.[0-9][0-9])?|\.[0-9]{2})$`)
|
|
if !re.MatchString(s) {
|
|
return fmt.Errorf("illegal currency format: %q", s)
|
|
}
|
|
s = strings.TrimPrefix(s, "$")
|
|
dollars := strings.Split(s, ".")[0]
|
|
cents := strings.TrimPrefix(s, dollars+".")
|
|
if !strings.HasPrefix(s, dollars+".") {
|
|
cents = "0"
|
|
}
|
|
if dollars == "" {
|
|
dollars = "0"
|
|
}
|
|
if cents == "00" {
|
|
cents = "0"
|
|
}
|
|
dI, err := strconv.Atoi(dollars)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cI, err := strconv.Atoi(cents)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c2 := Currency(dI*100 + cI)
|
|
*c = c2
|
|
return nil
|
|
}
|