snengame/internal/game/deck.go

96 lines
1.6 KiB
Go
Raw Normal View History

2021-07-22 15:37:25 -04:00
package game
2021-07-15 19:26:57 -04:00
2021-07-16 14:53:45 -04:00
import (
"encoding/json"
2021-07-23 17:42:12 -04:00
"fmt"
2021-07-16 14:53:45 -04:00
"math/rand"
"time"
)
2021-07-15 19:26:57 -04:00
type Deck struct {
Cards []Card `json:"cards"`
2021-07-15 19:26:57 -04:00
}
2021-07-23 17:42:12 -04:00
func (d *Deck) String() string {
if d == nil {
return "||"
}
return fmt.Sprintf("|%v|", d.Cards)
}
2021-07-15 19:26:57 -04:00
func NewDeck() *Deck {
cards := []Card{CreateCard(0)}
2021-07-15 19:26:57 -04:00
for i := 0; i < 3; i++ {
2021-07-16 14:53:45 -04:00
for j := 1; j < 9; j++ {
cards = append(cards, Card(CreateCard(j)))
2021-07-15 19:26:57 -04:00
}
}
return &Deck{
Cards: cards,
}
}
func DeckFromCards(c []Card) *Deck {
return &Deck{
Cards: c,
}
}
2021-07-15 19:26:57 -04:00
func (d *Deck) Shuffle() {
cards := d.Cards
2021-07-16 14:53:45 -04:00
r := rand.New(rand.NewSource(time.Now().UnixNano()))
2021-07-15 19:26:57 -04:00
for i := range cards {
2021-07-16 14:53:45 -04:00
j := r.Intn(i + 1)
2021-07-15 19:26:57 -04:00
cards[i], cards[j] = cards[j], cards[i]
}
d.Cards = cards
}
func (d *Deck) Scry(s int) []Card {
seen := []Card{}
if len(d.Cards) < s {
seen = d.Cards
d.Cards = []Card{}
return seen
}
seen = d.Cards[(len(d.Cards) - s):len(d.Cards)]
d.Cards = d.Cards[0 : len(d.Cards)-s]
return seen
}
func (d *Deck) Bottom(result []Card) {
d.Cards = append(result, d.Cards...) //Should shuffle result first?
}
func (d *Deck) Size() int {
return len(d.Cards)
}
func (d *Deck) MarshalJSON() ([]byte, error) {
var ported []*PortableCard
for i, _ := range d.Cards {
ported = append(ported, d.Cards[i].Port())
}
return json.Marshal(ported)
}
func (d *Deck) UnmarshalJSON(data []byte) (err error) {
var ported []PortableCard
err = json.Unmarshal(data, &ported)
if err != nil {
return err
}
cards := []Card{}
for _, v := range ported {
2021-07-23 17:42:12 -04:00
c := NewCard(v.Type, v.ID)
if v.Sick {
c.Act()
} else {
c.Refresh()
}
cards = append(cards, c)
}
d.Cards = cards
return
}