card_id/common/game/game.go

102 lines
1.9 KiB
Go

package game
import (
"strconv"
"git.tuxpa.in/a/card_id/common/errs"
"git.tuxpa.in/a/card_id/common/game/card"
"git.tuxpa.in/a/card_id/common/game/score"
"lukechampine.com/frand"
)
type Game struct {
Lives float64
Score int
Combo int
BestCombo int
CurrentTrial int
Trial *Trial
Trials []Trial
Player string
PlayerId string
Dealer *card.Dealer `json:"-"`
}
func New(user string, dealer *card.Dealer) *Game {
return &Game{
Dealer: dealer,
Player: user,
}
}
func (g *Game) Resolve(action string, args []string) (resp any, err error) {
switch action {
case "click":
resp, err = g.ActionClick(args)
default:
err = errs.Invalid("cmd not found")
}
return
}
func (g *Game) ActionClick(args []string) (resp any, err error) {
if len(args) > 1 {
num, _ := strconv.Atoi(args[1])
_, err := g.Trial.SelectCard(num)
if err != nil {
return nil, err
}
}
return nil, errs.Invalid("missing arg")
}
func (g *Game) Tick() (err error) {
sc, lives := g.Trial.CheckSelection()
if sc != 0 {
g.Combo = g.Combo + 1
g.Score = g.Score + sc*score.DefaultTable.Ratio(g.Combo)*g.CurrentTrial
} else {
g.Combo = 0
}
g.Lives = g.Lives + lives
return nil
}
func (g *Game) CreateTrial(pairs int, extra int) *Trial {
if pairs > 10 {
pairs = 10
}
cards := make([]card.Card, 0, pairs*2+extra)
ids := map[int]struct{}{}
deck := g.Dealer.GetBrand().GetDeck()
for i := 0; i < pairs; {
card := deck.Draw()
if _, ok := ids[card.Id]; !ok {
ids[card.Id] = struct{}{}
cards = append(cards, card, card)
i = i + 1
}
}
for i := 0; i < extra; {
card := deck.Draw()
if _, ok := ids[card.Id]; !ok {
ids[card.Id] = struct{}{}
cards = append(cards, card)
i = i + 1
}
}
frand.Shuffle(len(cards), func(i, j int) { cards[i], cards[j] = cards[j], cards[i] })
trial := NewTrial()
for k, v := range cards {
trial.Cards[k+1] = v
}
return trial
}