snengame/internal/game/player.go
Steve eb7b405641 cards are now passed as PortableCard objects
client supports all actions
A bunch of stuff uses *Decks now instead of []Card since json marshaling
all of this code is absolutely awful
2021-07-23 16:43:39 -04:00

67 lines
1.3 KiB
Go

package game
import (
"encoding/json"
"fmt"
"log"
"github.com/google/uuid"
)
type Player struct {
Name string `json:"name"`
Id int `json:"id"`
Hand []Card `json:"hand"`
Life int `json:"life"`
}
func NewPlayer(name string, id int) *Player {
return &Player{
Name: name,
Id: id,
Hand: []Card{},
Life: 3,
}
}
func (p *Player) MarshalJSON() ([]byte, error) {
var ported_hand []*PortableCard
for i, _ := range p.Hand {
ported_hand = append(ported_hand, p.Hand[i].Port())
}
res := []interface{}{p.Name, p.Id, ported_hand, p.Life}
return json.Marshal(res)
}
func (p *Player) UnmarshalJSON(data []byte) (err error) {
ported := []interface{}{}
err = json.Unmarshal(data, &ported)
if err != nil {
return err
}
fmt.Println(ported)
p.Name = ported[0].(string)
p.Id = int(ported[1].(float64))
var tmp []interface{}
if ported[2] != nil {
tmp = ported[2].([]interface{})
} else {
tmp = []interface{}{}
}
p.Life = int(ported[3].(float64))
hand := []Card{}
for _, v := range tmp {
m := v.(map[string]interface{})
t := int(m["type"].(float64))
i := m["ID"].(string)
uid, err := uuid.Parse(i)
if err != nil {
log.Println("invalid card parse")
} else {
hand = append(hand, NewCard(t, uid))
}
}
p.Hand = hand
return
}