priceiswrong.Open().Players()

main
Bel LaPointe 2025-02-12 12:08:20 -07:00
parent caea2926c5
commit 17c0e2c259
4 changed files with 41 additions and 7 deletions

View File

@ -4,11 +4,11 @@ import (
"context" "context"
"gitea/price-is-wrong/src/lib/db" "gitea/price-is-wrong/src/lib/db"
priceiswrong "gitea/price-is-wrong/src/state/fsm/priceiswrong/internal" priceiswrong "gitea/price-is-wrong/src/state/fsm/priceiswrong/internal"
"io" "math/rand"
) )
func (p *PriceIsWrong) TODO(ctx context.Context, id int) error { func (p *PriceIsWrong) Players(ctx context.Context, ids []int) error {
return io.EOF return p.upsertEvent(ctx, &priceiswrong.Players{IDs: ids})
} }
func (p *PriceIsWrong) upsertEvent(ctx context.Context, e priceiswrong.Event) error { func (p *PriceIsWrong) upsertEvent(ctx context.Context, e priceiswrong.Event) error {
@ -39,8 +39,14 @@ func upsertEvent(ctx context.Context, priceIsWrongID int, e priceiswrong.Event)
func (p *PriceIsWrong) apply(e priceiswrong.Event) error { func (p *PriceIsWrong) apply(e priceiswrong.Event) error {
switch e := e.(type) { switch e := e.(type) {
case *int: case *priceiswrong.Players:
_ = e p.Contestants = p.Contestants[:0]
for _, id := range e.IDs {
p.Contestants = append(p.Contestants, Player{ID: id})
}
if n := len(p.Contestants); n > 0 {
p.Host = p.Contestants[rand.Intn(n)].ID
}
} }
return nil return nil
} }

View File

@ -7,9 +7,13 @@ import (
type Event interface{} type Event interface{}
type Players struct {
IDs []int
}
func ParseEvent(b []byte) (Event, error) { func ParseEvent(b []byte) (Event, error) {
typesToPointers := map[string]any{ typesToPointers := map[string]any{
"*any": &b, "*priceiswrong.Players": &Players{},
} }
t, err := event.Parse(b, typesToPointers) t, err := event.Parse(b, typesToPointers)
return typesToPointers[t], err return typesToPointers[t], err

View File

@ -11,7 +11,7 @@ import (
type PriceIsWrong struct { type PriceIsWrong struct {
id int id int
Host int Host int
Contestants Player Contestants []Player
} }
type Player struct { type Player struct {

View File

@ -0,0 +1,24 @@
package priceiswrong_test
import (
"gitea/price-is-wrong/src/lib"
"gitea/price-is-wrong/src/state/fsm/priceiswrong"
"testing"
)
func TestPriceIsWrong(t *testing.T) {
ctx := lib.NewTestCtx(t)
p, err := priceiswrong.Open(ctx, "name")
if err != nil {
t.Fatal(err)
}
if err := p.Players(ctx, []int{4, 5, 6}); err != nil {
t.Fatal(err)
} else if len(p.Contestants) != 3 {
t.Errorf("bad contestants: %+v", p.Contestants)
} else if p.Host < 4 || p.Host > 6 {
t.Errorf("bad host: %+v", p.Host)
}
}