feat(server): complete arcade gameplay, rewards and shared rankings
Implement PackMan and complete Survival, Sichuan, Rhythm, Hopscotch and field games, including Action missions and Defense rewards. Correct cumulative daily rewards, timed records and ghost replays; persist player progress and publish shared rankings through the outbox.
This commit is contained in:
1 parent
d5fdb2f9bc
commit
f06cd97b01
25 files changed
+4408
-732
No files matched your search
@@ -0,0 +1,199 @@
|
||||
//go:build integration
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RacingHUD reports point-table IDs, shared by multiple ordinary map objects.
|
||||
// Its score packets and the reward guide define cumulative daily tiers. This
|
||||
// runs those requests with installed GameData, the production economy and an
|
||||
// account SQLite transaction, then closes and reopens the player.
|
||||
func TestArcadeRacingMapObjectsCommitDailyInventoryRewardsOnce(t *testing.T) {
|
||||
factory, accounts := newIntegrationFactory(t)
|
||||
catalog := factory.design.eventPlay
|
||||
var gameID, pointID, target, itemID, itemType, itemReward uint64
|
||||
var field *gamedata.EventField
|
||||
for _, game := range catalog.Tables["PackEventMiniGameTable"] {
|
||||
if appValue(game, 3) != 2 {
|
||||
continue
|
||||
}
|
||||
candidate, err := catalog.Field(appValue(game, 8))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for id, object := range candidate.Objects {
|
||||
if object.RandomGroup != 0 || object.Type != 1 || object.Point <= 0 {
|
||||
continue
|
||||
}
|
||||
for _, row := range catalog.Rows("FieldMiniGameRewardTable", 1, appValue(game, 10)) {
|
||||
types, e := arcadeNumbers(row, 6)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ids, e := arcadeNumbers(row, 5)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
counts, e := arcadeNumbers(row, 4)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(types) != 1 || types[0] != 8 || len(ids) != 1 || len(counts) != 1 {
|
||||
continue
|
||||
}
|
||||
if appValue(row, 3) > uint64(object.Point) {
|
||||
gameID, pointID, target = appValue(game, 8), id, appValue(row, 3)
|
||||
field, itemID, itemType, itemReward = candidate, ids[0], types[0], counts[0]
|
||||
break
|
||||
}
|
||||
}
|
||||
if gameID != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if gameID != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if gameID == 0 {
|
||||
t.Fatal("installed Racing design has no ordinary shared point objects with an inventory reward tier")
|
||||
}
|
||||
now := time.Now()
|
||||
schedule := events.Schedule{UID: gameID, Type: 11, ID: gameID, Start: now.Add(-time.Hour).UnixMilli(), End: now.Add(time.Hour).UnixMilli()}
|
||||
factory.options.calendars.Events = []events.Schedule{schedule}
|
||||
shared, err := openSharedRuntime(context.Background(), factory.options, factory.design)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := shared.store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
factory.shared = shared
|
||||
owner, err := factory.open(accounts[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
|
||||
t.Cleanup(func() {
|
||||
if g.owner != nil {
|
||||
if err := g.owner.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
})
|
||||
before := g.itemCount(itemType, itemID)
|
||||
start := g.request("/MiniGameFieldStart", appScalar(2, schedule.UID))
|
||||
body := g.execute(start, false)
|
||||
if retry := g.execute(start, false); string(retry) != string(body) {
|
||||
t.Fatal("committed start retry changed selected map objects")
|
||||
}
|
||||
selected, err := arcadeNumbers(body, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
allowed := map[uint64]bool{}
|
||||
for _, id := range selected {
|
||||
allowed[id] = true
|
||||
}
|
||||
if !allowed[pointID] {
|
||||
t.Fatal("ordinary point objects disabled at start")
|
||||
}
|
||||
for id, object := range field.Objects {
|
||||
if object.RandomGroup > 0 && !allowed[id] {
|
||||
g.execute(g.request("/MiniGameFieldScore", append(appScalar(2, schedule.UID), appScalar(3, id)...)), true)
|
||||
break
|
||||
}
|
||||
}
|
||||
point := uint64(field.Objects[pointID].Point)
|
||||
count := (target + point - 1) / point
|
||||
var request []byte
|
||||
request = wire.AppendVarint(request, 2, schedule.UID)
|
||||
for range count {
|
||||
request = wire.AppendVarint(request, 3, pointID)
|
||||
}
|
||||
result := g.call("/MiniGameFieldScore", request)
|
||||
if appValue(result, 1) != count*point {
|
||||
t.Fatal("distinct ordinary map objects sharing the same point-table ID were dropped")
|
||||
}
|
||||
end := g.request("/MiniGameFieldEnd", nil)
|
||||
g.execute(end, false)
|
||||
game, err := catalog.Row("PackEventMiniGameTable", 8, gameID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var expected uint64
|
||||
for _, row := range catalog.Rows("FieldMiniGameRewardTable", 1, appValue(game, 10)) {
|
||||
if appValue(row, 3) > count*point {
|
||||
continue
|
||||
}
|
||||
types, e := arcadeNumbers(row, 6)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ids, e := arcadeNumbers(row, 5)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
counts, e := arcadeNumbers(row, 4)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(types) != len(ids) || len(types) != len(counts) {
|
||||
t.Fatal("inconsistent authored reward arrays")
|
||||
}
|
||||
for i, typ := range types {
|
||||
if typ == itemType && ids[i] == itemID {
|
||||
expected += counts[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
if expected < itemReward {
|
||||
t.Fatal("selected inventory reward tier not included")
|
||||
}
|
||||
if g.itemCount(itemType, itemID) != before+expected {
|
||||
t.Fatal("completed score did not deposit the authored inventory reward")
|
||||
}
|
||||
paid := g.itemCount(itemType, itemID)
|
||||
g.reopen()
|
||||
g.execute(end, false)
|
||||
if g.itemCount(itemType, itemID) != paid {
|
||||
t.Fatal("reopened settlement retry duplicated inventory rewards")
|
||||
}
|
||||
info := g.call("/MiniGameFieldInfo", appScalar(2, schedule.UID))
|
||||
record, _, err := wire.Bytes(info, 1)
|
||||
if err != nil || appValue(record, 3) != count*point || appValue(record, 2) == 0 || appValue(record, 4) != 0 {
|
||||
t.Fatal("reopened score or claimed daily reward differs from actual settlement")
|
||||
}
|
||||
}
|
||||
|
||||
func arcadeNumbers(raw []byte, field int) ([]uint64, error) {
|
||||
var result []uint64
|
||||
err := wire.Walk(raw, func(value wire.Field) error {
|
||||
if value.Number != field {
|
||||
return nil
|
||||
}
|
||||
if value.Type != 0 && value.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
for data := value.Value; len(data) > 0; {
|
||||
number, n := binary.Uvarint(data)
|
||||
if n <= 0 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
result = append(result, number)
|
||||
data = data[n:]
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
"bd2server/internal/server/storage/outbox"
|
||||
)
|
||||
|
||||
func arcadeRankingChanged(requests []player.Request) bool {
|
||||
for _, request := range requests {
|
||||
if strings.HasPrefix(request.Path, "/MiniGame") && strings.HasSuffix(request.Path, "End") {
|
||||
return true
|
||||
}
|
||||
switch request.Path {
|
||||
case "/UserNicknameChange", "/UserTitleChange", "/UserPortraitChange", "/AchievementClear":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (p *playerAssembly) arcadeRankingGuilds(ctx command.Context, owners []uint64) (map[uint64][]byte, error) {
|
||||
accounts := make([]string, 0, len(owners))
|
||||
byOwner := make(map[uint64]string, len(owners))
|
||||
own, err := p.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, owner := range owners {
|
||||
account := p.shared.arcadeRanks.Account(owner)
|
||||
if owner == own {
|
||||
account = ctx.AccountID
|
||||
}
|
||||
if account == "" {
|
||||
continue
|
||||
}
|
||||
byOwner[owner] = account
|
||||
accounts = append(accounts, account)
|
||||
}
|
||||
values, err := p.shared.guild.GuildBases(context.Background(), accounts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make(map[uint64][]byte, len(byOwner))
|
||||
for owner, account := range byOwner {
|
||||
result[owner] = values[account]
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p *playerAssembly) arcadeRankingProfile(ctx command.Context) (ranking.ArcadeProfile, error) {
|
||||
owner, err := p.ProfileOwner(ctx)
|
||||
if err != nil {
|
||||
return ranking.ArcadeProfile{}, err
|
||||
}
|
||||
profile, err := p.PublicProfile(ctx, owner)
|
||||
if err != nil {
|
||||
return ranking.ArcadeProfile{}, err
|
||||
}
|
||||
xp, err := p.missionService.AchievementExperience()
|
||||
if err != nil {
|
||||
return ranking.ArcadeProfile{}, err
|
||||
}
|
||||
return ranking.ArcadeProfile{Owner: owner, Name: profile.UserID, XP: xp, Portrait: profile.PortraitCostumeID, PortraitDesign: profile.PortraitDesignID, Title: profile.TitleID, Guild: profile.GuildBase}, nil
|
||||
}
|
||||
|
||||
func (p *playerAssembly) publishArcadeRanking(ctx command.Context) error {
|
||||
if p.shared == nil || p.shared.arcadeRanks == nil || p.eventPlayService == nil {
|
||||
return nil
|
||||
}
|
||||
records := p.eventPlayService.RankRecords()
|
||||
if len(records) == 0 {
|
||||
return nil
|
||||
}
|
||||
profile, err := p.arcadeRankingProfile(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
next := ranking.ArcadePublication{Account: ctx.AccountID, Profile: profile, Records: records}
|
||||
oldRaw, found, err := ctx.State.LoadEntry("directory", "arcade_publication", "current")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if found {
|
||||
var old ranking.ArcadePublication
|
||||
if err := json.Unmarshal(oldRaw, &old); err != nil {
|
||||
return err
|
||||
}
|
||||
next.Version = old.Version
|
||||
raw, err := json.Marshal(next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bytes.Equal(raw, oldRaw) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if next.Version == ^uint64(0) {
|
||||
return errors.New("arcade publication version exhausted")
|
||||
}
|
||||
next.Version++
|
||||
raw, err := json.Marshal(next)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Publish(command.Event{ID: fmt.Sprintf("arcade-ranking:%d", next.Version), Topic: "arcade.ranking", Payload: raw}); err != nil {
|
||||
return err
|
||||
}
|
||||
return ctx.State.PutEntry("directory", "arcade_publication", "current", raw)
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) consumeArcadeRanking(ctx context.Context, event outbox.Pending) error {
|
||||
var publication ranking.ArcadePublication
|
||||
if err := json.Unmarshal(event.Envelope.Event.Payload, &publication); err != nil {
|
||||
return err
|
||||
}
|
||||
if publication.Account != event.Envelope.Source {
|
||||
return errors.New("arcade ranking source mismatch")
|
||||
}
|
||||
if event.Envelope.Event.ID != fmt.Sprintf("arcade-ranking:%d", publication.Version) {
|
||||
return errors.New("arcade ranking event identity mismatch")
|
||||
}
|
||||
return s.arcadeRanks.Publish(ctx, publication)
|
||||
}
|
||||
@@ -41,6 +41,10 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
return fmt.Errorf("load event play state: %w", err)
|
||||
}
|
||||
p.eventPlayService.AttachBattleChallenges(p.design.eventBattleChallenges)
|
||||
if p.shared != nil {
|
||||
p.eventPlayService.AttachArcadeRankings(p.shared.arcadeRanks, p.arcadeRankingProfile)
|
||||
p.eventPlayService.AttachRankingGuilds(p.arcadeRankingGuilds)
|
||||
}
|
||||
if p.roomResults != nil {
|
||||
p.eventPlayService.AttachRooms(p.roomResults)
|
||||
}
|
||||
@@ -110,7 +114,10 @@ func (p *playerAssembly) events(ctx command.Context) error {
|
||||
return p.eventTasksService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
|
||||
})
|
||||
p.eventPlayService.AttachProgress(func(ctx command.Context, condition, sub, count uint64) error {
|
||||
return p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
|
||||
if err := p.missionService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked); err != nil {
|
||||
return err
|
||||
}
|
||||
return p.eventTasksService.RecordEvent(ctx, condition, sub, count, p.worldService.MissionsUnlocked)
|
||||
})
|
||||
p.eventTasksService.AttachAssociatedMissionGroup(func(schedule events.Schedule) uint64 {
|
||||
if group := p.eventActionsService.AssociatedMissionGroup(schedule); group != 0 {
|
||||
|
||||
@@ -243,6 +243,11 @@ func (p *playerInstance) Execute(ctx context.Context, request player.Command) (r
|
||||
reply.Responses = append(reply.Responses, response)
|
||||
}
|
||||
if !isSystem && (tx.Dirty() || isLogin) {
|
||||
if isLogin || arcadeRankingChanged(request.Requests) {
|
||||
if err := assembly.publishArcadeRanking(identity); err != nil {
|
||||
return reply, failCommand(err)
|
||||
}
|
||||
}
|
||||
if isLogin || huntRankingChanged(request.Requests) {
|
||||
if err := assembly.publishHuntRanking(identity); err != nil {
|
||||
return reply, failCommand(err)
|
||||
|
||||
@@ -20,16 +20,17 @@ import (
|
||||
)
|
||||
|
||||
type sharedRuntime struct {
|
||||
directory *publicDirectory
|
||||
rooms *roomResults
|
||||
store *shared.Store
|
||||
pvp *ranking.PVP
|
||||
huntRanks *ranking.MonsterHunt
|
||||
guild *social.Owner
|
||||
friends *social.Friends
|
||||
delivery atomic.Pointer[delivery.Dispatcher]
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
directory *publicDirectory
|
||||
rooms *roomResults
|
||||
store *shared.Store
|
||||
pvp *ranking.PVP
|
||||
huntRanks *ranking.MonsterHunt
|
||||
arcadeRanks *ranking.Arcade
|
||||
guild *social.Owner
|
||||
friends *social.Friends
|
||||
delivery atomic.Pointer[delivery.Dispatcher]
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func openSharedRuntime(ctx context.Context, c *configuration, design *designCatalog) (*sharedRuntime, error) {
|
||||
@@ -45,6 +46,10 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
arcadeRanks, err := ranking.NewArcade(ctx, rankingStore{store})
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
guild, err := social.New(socialStore{store}, design.guild)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
@@ -61,7 +66,7 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, store.Close())
|
||||
}
|
||||
return &sharedRuntime{store: store, pvp: pvp, huntRanks: huntRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
|
||||
return &sharedRuntime{store: store, pvp: pvp, huntRanks: huntRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
|
||||
}
|
||||
|
||||
func (s *sharedRuntime) wake(account string) {
|
||||
@@ -77,6 +82,9 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
|
||||
if event.Envelope.Event.Topic == "monster_hunt.ranking" {
|
||||
return s.consumeHuntRanking(ctx, event)
|
||||
}
|
||||
if event.Envelope.Event.Topic == "arcade.ranking" {
|
||||
return s.consumeArcadeRanking(ctx, event)
|
||||
}
|
||||
if event.Envelope.Event.Topic == "fishing.projection" {
|
||||
return s.rooms.updateFishing(ctx, event)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ func LoadEventPlayCatalog(root, version string) (*EventPlayCatalog, error) {
|
||||
}
|
||||
names := []string{"PackEventHubTable", "PackEventListTable", "PackEventStoryGroupTable", "PackEventStoryTable", "PackEventBattleGroupTable", "PackEventBattleTable", "PackEventMiniGameTable", "FieldMiniGameRewardTable", "FieldMiniGameSpeedTable", "RhythmGameMusicTable", "RhythmGameGradeTable", "SichuanStageTable", "SichuanEventTable", "SichuanRewardTable", "HopscotchStageTable", "HopscotchRewardTable", "HopscotchDefaultTable", "FieldMiniGameSurvivalTable", "ActionGameDefaultTable", "ActionGameMissionTable", "ActionGameStageTable", "FieldMiniGameCharTable", "FieldMiniGameMapTable", "FieldMiniGameUpgradeTable", "FieldMiniGameUpgradeGroupTable", "FieldMiniGameSkillGroupTable", "FieldMiniGameSkillTable", "FieldMiniGameCharLevelTable", "FieldMiniGameMonsterTable", "FieldMiniGameSurvivalItemTable", "FieldMiniGameSurvivalBoxTable", "MGDRewardTable", "MGDWaveTable", "MGDDefaultTable"}
|
||||
names = append(names, "EventLostCoinTable")
|
||||
names = append(names, "FieldMiniGameCollectionTable", "FieldMiniGameMapGroupTable", "FieldMiniGameStarterTable", "SichuanDefaultTable", "SichuanBlockDesignTable", "RhythmGameDefaultTable", "RhythmGameCharTable", "HopscotchGalleryTable", "HopscotchRankingTable", "HopscotchAbuseTable")
|
||||
names = append(names, "PackManDefaultTable", "PackManModeTable", "PackManModeRuleTable", "PackManScoreTable", "PackManMapTable", "PackManObjectTable", "PackManItemTable", "PackManChaserTable", "PackManChaserSpawnTable", "PackManChainTable", "PackManGalleryTable", "PackManGuideTable")
|
||||
names = append(names, "ActionGameTable", "ActionGameCharTable")
|
||||
names = append(names, "FishingDefaultTable", "FishingMapTable", "FishingMapGroupTable", "FishingBoatTable", "FishingBoatDesignTable", "FishingRodTable", "FishingItemTable", "FishingCharTable", "FishingFishTable", "FishingFishPoolTable", "FishingFishSizePoolTable", "FishingGradePoolTable", "FishingCastingTable", "FishingBuffTable", "FishingBoatBuffTable", "FishingFishSkillTable", "FishingTimeTable")
|
||||
names = append(names, "FishingBuyItemTable", "FishingSellItemTable", "FishingShopTable", "FishingPricePremiumDefaultTable")
|
||||
@@ -84,8 +86,11 @@ func (c *EventPlayCatalog) Story(group, id uint64) ([]byte, error) {
|
||||
}
|
||||
return nil, fmt.Errorf("gamedata: missing event story")
|
||||
}
|
||||
func (c *EventPlayCatalog) ScoreRewards(group, score uint64) (uint64, []BattleReward, error) {
|
||||
var picked []byte
|
||||
func (c *EventPlayCatalog) ScoreRewards(group, score, kind uint64) (uint64, []BattleReward, error) {
|
||||
if score == 0 {
|
||||
return 0, nil, nil
|
||||
}
|
||||
var rewards []BattleReward
|
||||
point := uint64(0)
|
||||
rows := c.Rows("FieldMiniGameRewardTable", 1, group)
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
@@ -98,14 +103,20 @@ func (c *EventPlayCatalog) ScoreRewards(group, score uint64) (uint64, []BattleRe
|
||||
if e != nil {
|
||||
return 0, nil, e
|
||||
}
|
||||
if p <= score && p >= point {
|
||||
picked = r
|
||||
if kind == 3 || kind == 4 {
|
||||
p *= 1000
|
||||
}
|
||||
if kind == 3 && score > p || kind != 3 && score < p {
|
||||
continue
|
||||
}
|
||||
if point == 0 || kind == 3 && p < point || kind != 3 && p > point {
|
||||
point = p
|
||||
}
|
||||
earned, e := eventGameRewards(r, 6, 5, 4)
|
||||
if e != nil {
|
||||
return 0, nil, e
|
||||
}
|
||||
rewards = append(rewards, earned...)
|
||||
}
|
||||
if picked == nil {
|
||||
return 0, nil, nil
|
||||
}
|
||||
rewards, e := eventGameRewards(picked, 6, 5, 4)
|
||||
return point, rewards, e
|
||||
return point, rewards, nil
|
||||
}
|
||||
@@ -3,8 +3,14 @@ package gamedata
|
||||
import "fmt"
|
||||
|
||||
type EventField struct {
|
||||
HP, Limit uint64
|
||||
Objects map[uint64]struct{ Point, Type uint64 }
|
||||
HP, Limit uint64
|
||||
Objects map[uint64]FieldGameObject
|
||||
RandomCounts map[uint64]uint64
|
||||
}
|
||||
|
||||
type FieldGameObject struct {
|
||||
Point int64
|
||||
Type, RandomGroup uint64
|
||||
}
|
||||
|
||||
func (c *EventPlayCatalog) Field(game uint64) (*EventField, error) {
|
||||
@@ -24,9 +30,29 @@ func (c *EventPlayCatalog) Field(game uint64) (*EventField, error) {
|
||||
return nil, e
|
||||
}
|
||||
group, _ := optionalScalar(raw, 3)
|
||||
d := &EventField{Objects: map[uint64]struct{ Point, Type uint64 }{}}
|
||||
d := &EventField{Objects: map[uint64]FieldGameObject{}, RandomCounts: map[uint64]uint64{}}
|
||||
d.HP, _ = optionalScalar(raw, 6)
|
||||
d.Limit, _ = optionalScalar(raw, 7)
|
||||
counts, e := packedInts(raw, 4)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
groups, e := packedInts(raw, 5)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if len(counts) != len(groups) {
|
||||
return nil, fmt.Errorf("gamedata: field random group counts differ")
|
||||
}
|
||||
for i, group := range groups {
|
||||
if group == 0 {
|
||||
return nil, fmt.Errorf("gamedata: invalid field random group")
|
||||
}
|
||||
if _, exists := d.RandomCounts[group]; exists {
|
||||
return nil, fmt.Errorf("gamedata: duplicate field random group")
|
||||
}
|
||||
d.RandomCounts[group] = counts[i]
|
||||
}
|
||||
rows, e := db.Query("SELECT ProtoBuf FROM FieldMiniGameObjectTable WHERE groupId=? ORDER BY id", group)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
@@ -39,7 +65,11 @@ func (c *EventPlayCatalog) Field(game uint64) (*EventField, error) {
|
||||
id, _ := optionalScalar(raw, 2)
|
||||
point, _ := optionalScalar(raw, 3)
|
||||
typ, _ := optionalScalar(raw, 4)
|
||||
d.Objects[id] = struct{ Point, Type uint64 }{point, typ}
|
||||
randomGroup, _ := optionalScalar(raw, 5)
|
||||
if id == 0 || typ < 1 || typ > 3 {
|
||||
return nil, fmt.Errorf("gamedata: invalid field object")
|
||||
}
|
||||
d.Objects[id] = FieldGameObject{Point: int64(int32(point)), Type: typ, RandomGroup: randomGroup}
|
||||
}
|
||||
if len(d.Objects) == 0 {
|
||||
return nil, fmt.Errorf("gamedata: field game objects missing")
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
func (s *Service) actionMissions(ctx command.Context, req []byte, a Run, result NativeResult, st *snapshot, key string) ([]byte, error) {
|
||||
if a.Native == nil {
|
||||
return nil, fmt.Errorf("eventplay: action mission lacks authoritative room run")
|
||||
}
|
||||
for field := 8; field <= 18; field++ {
|
||||
if num(req, field) > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("eventplay: invalid action mission counter")
|
||||
}
|
||||
}
|
||||
if num(req, 24) > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("eventplay: invalid received damage")
|
||||
}
|
||||
monster, err := s.design.Row("ActionGameCharTable", 14, a.Char)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if num(req, 17) > num(req, 10) || num(req, 17) > num(req, 18) {
|
||||
return nil, fmt.Errorf("eventplay: rage groggy count contradicts report")
|
||||
}
|
||||
profile, err := s.arcadeProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
character := uint64(0)
|
||||
err = wire.Walk(result.Evidence, func(f wire.Field) error {
|
||||
if f.Number == 2 && f.Type == 2 && num(f.Value, 1) == profile.Owner {
|
||||
if character != 0 {
|
||||
return fmt.Errorf("eventplay: duplicate native action member")
|
||||
}
|
||||
character = num(f.Value, 2)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ledger := playRecord(st, a.UID, a.Game, 0, 0, a.Family)
|
||||
var out []byte
|
||||
var rewards []gamedata.BattleReward
|
||||
for _, row := range s.design.Tables["ActionGameMissionTable"] {
|
||||
id, condition, threshold, target := num(row, 4), num(row, 3), num(row, 1), num(row, 2)
|
||||
identity := fmt.Sprintf("mission:%d", id)
|
||||
if ledger.Clears[identity] || num(row, 7) != num(monster, 16) || !result.Clear {
|
||||
continue
|
||||
}
|
||||
if condition != 1 && condition != 11 && target != a.Char {
|
||||
continue
|
||||
}
|
||||
if condition >= 6 && condition <= 8 {
|
||||
binding := s.actionMissionCharacters[condition]
|
||||
if binding == 0 {
|
||||
return nil, fmt.Errorf("eventplay: action mission character binding missing")
|
||||
}
|
||||
if character != binding {
|
||||
continue
|
||||
}
|
||||
}
|
||||
earned := false
|
||||
switch condition {
|
||||
case 1:
|
||||
earned = threshold == a.Char
|
||||
case 2:
|
||||
earned = threshold <= math.MaxUint64/1000 && result.Score <= threshold*1000
|
||||
case 3:
|
||||
earned = num(req, 8) <= threshold
|
||||
case 4:
|
||||
earned = num(req, 9) >= threshold
|
||||
case 5:
|
||||
earned = num(req, 10) >= threshold
|
||||
case 6:
|
||||
earned = num(req, 11) >= threshold
|
||||
case 7:
|
||||
earned = num(req, 12) >= threshold
|
||||
case 8:
|
||||
earned = num(req, 13) >= threshold
|
||||
case 9:
|
||||
earned = num(req, 14) >= threshold
|
||||
case 10:
|
||||
earned = num(req, 15) >= threshold
|
||||
case 11:
|
||||
earned = threshold == a.Char && num(req, 16) <= target
|
||||
case 12:
|
||||
earned = num(req, 17) >= threshold
|
||||
default:
|
||||
return nil, fmt.Errorf("eventplay: unsupported action mission condition %d", condition)
|
||||
}
|
||||
if !earned {
|
||||
continue
|
||||
}
|
||||
ledger.Clears[identity] = true
|
||||
out = wire.AppendVarint(out, 2, id)
|
||||
rr, e := gamedata.EventPlayRewards(row, 10, 9, 8)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rewards = append(rewards, rr...)
|
||||
}
|
||||
st.Records[recKey(a.UID, 0, 0, a.Family)] = ledger
|
||||
if len(rewards) > 0 {
|
||||
bundle, err := s.grant(ctx, "eventplay:"+key+":missions", rewards)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = wire.AppendBytes(out, 3, bundle)
|
||||
}
|
||||
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
)
|
||||
|
||||
func (s *Service) AttachArcadeRankings(ranks *ranking.Arcade, profile func(command.Context) (ranking.ArcadeProfile, error)) {
|
||||
s.arcadeRanks, s.arcadeProfile = ranks, profile
|
||||
}
|
||||
|
||||
func (s *Service) AttachRankingGuilds(load func(command.Context, []uint64) (map[uint64][]byte, error)) {
|
||||
s.arcadeGuilds = load
|
||||
}
|
||||
|
||||
func (s *Service) RankRecords() []ranking.ArcadeRecord {
|
||||
return s.arcadeRecords(&s.state)
|
||||
}
|
||||
|
||||
func (s *Service) arcadeRecords(state *snapshot) []ranking.ArcadeRecord {
|
||||
keys := make([]string, 0, len(state.Records))
|
||||
for key := range state.Records {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var records []ranking.ArcadeRecord
|
||||
for _, key := range keys {
|
||||
row := state.Records[key]
|
||||
entry := ranking.ArcadeRecord{ArcadeScope: ranking.ArcadeScope{Family: row.Family, EventUID: row.UID, Stage: row.Stage, Mode: row.Mode}, Score: float64(row.Best), CapturedArea: row.CapturedArea, ClearTime: row.ClearTime, AchievedAt: row.AchievedAt, PlayInfo: row.PlayInfo}
|
||||
switch row.Family {
|
||||
case "Survival":
|
||||
mapRow, err := s.survivalMap(row.Mode, row.Stage)
|
||||
if err != nil || num(mapRow, 11) != 1 {
|
||||
continue
|
||||
}
|
||||
case "PackMan", "Field", "Run":
|
||||
case "Sichuan":
|
||||
if row.Mode != 2 {
|
||||
continue
|
||||
}
|
||||
entry.Score = row.BestScore
|
||||
case "Rhythm":
|
||||
if row.Mode == 0 {
|
||||
continue
|
||||
}
|
||||
case "Hopscotch":
|
||||
if !row.Clears["clear"] {
|
||||
continue
|
||||
}
|
||||
entry.Score = float64(row.ClearTime)
|
||||
default:
|
||||
continue
|
||||
}
|
||||
if entry.Score > 0 {
|
||||
records = append(records, entry)
|
||||
}
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
func (s *Service) arcadeWorldBest(ctx command.Context, uid uint64, state *snapshot, ownerField, nameField, scoreField int) ([]byte, error) {
|
||||
if s.arcadeRanks == nil || s.arcadeProfile == nil {
|
||||
return nil, fmt.Errorf("eventplay: arcade ranking unavailable")
|
||||
}
|
||||
profile, err := s.arcadeProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := s.arcadeRanks.Board(ranking.ArcadeScope{Family: "Sichuan", EventUID: uid}, profile, s.arcadeRecords(state), 1)
|
||||
if len(rows) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
entry := rows[0]
|
||||
out := wire.AppendVarint(nil, ownerField, entry.Profile.Owner)
|
||||
out = wire.AppendString(out, nameField, entry.Profile.Name)
|
||||
return wire.AppendDouble(out, scoreField, entry.Score), nil
|
||||
}
|
||||
|
||||
func (s *Service) arcadeRanking(ctx command.Context, path string, req []byte) ([]byte, error) {
|
||||
if s.arcadeRanks == nil || s.arcadeProfile == nil {
|
||||
return nil, fmt.Errorf("eventplay: arcade ranking unavailable")
|
||||
}
|
||||
profile, err := s.arcadeProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if path == "/MiniGameRanking" || path == "/MiniGameUserRecordInfo" {
|
||||
return s.arcadeSummary(ctx, profile, path == "/MiniGameUserRecordInfo")
|
||||
}
|
||||
f := family(path)
|
||||
calendar, err := s.calendar(num(req, 2), f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scope := ranking.ArcadeScope{Family: f, EventUID: calendar.UID}
|
||||
if f == "Rhythm" || f == "Hopscotch" {
|
||||
scope.Stage = num(req, 3)
|
||||
if f == "Rhythm" {
|
||||
scope.Mode = num(req, 4)
|
||||
if scope.Mode == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
if err := s.validateStage(f, scope.Stage, scope.Mode); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
limit := 100
|
||||
if f == "Sichuan" {
|
||||
for _, row := range s.design.Tables["SichuanDefaultTable"] {
|
||||
limit = int(num(row, 10))
|
||||
break
|
||||
}
|
||||
}
|
||||
rows := s.arcadeRanks.Board(scope, profile, s.RankRecords(), limit)
|
||||
if f == "Sichuan" && s.arcadeGuilds != nil {
|
||||
owners := make([]uint64, 0, len(rows))
|
||||
for _, entry := range rows {
|
||||
owners = append(owners, entry.Profile.Owner)
|
||||
}
|
||||
guilds, err := s.arcadeGuilds(ctx, owners)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range rows {
|
||||
rows[i].Profile.Guild = guilds[rows[i].Profile.Owner]
|
||||
}
|
||||
}
|
||||
ownOnly := strings.Contains(path, "UserRecord")
|
||||
var out []byte
|
||||
for _, entry := range rows {
|
||||
if ownOnly {
|
||||
if entry.Own {
|
||||
return wire.AppendBytes(nil, 1, arcadeRecordWire(entry)), nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
row := arcadeRankWire(entry)
|
||||
if entry.Rank <= uint64(limit) {
|
||||
out = wire.AppendBytes(out, 1, row)
|
||||
}
|
||||
if entry.Own && (f == "Survival" || f == "Rhythm") {
|
||||
out = wire.AppendBytes(out, 2, row)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func arcadeRankWire(entry ranking.ArcadeEntry) []byte {
|
||||
p := entry.Profile
|
||||
if entry.Family == "Sichuan" {
|
||||
out := wire.AppendVarint(nil, 1, p.Owner)
|
||||
out = wire.AppendString(out, 2, p.Name)
|
||||
out = wire.AppendVarint(out, 3, p.XP)
|
||||
out = wire.AppendVarint(out, 4, p.Portrait)
|
||||
out = wire.AppendVarint(out, 5, p.PortraitDesign)
|
||||
if len(p.Guild) > 0 {
|
||||
out = wire.AppendBytes(out, 6, p.Guild)
|
||||
}
|
||||
out = wire.AppendVarint(out, 7, entry.Rank)
|
||||
out = wire.AppendDouble(out, 8, entry.Score)
|
||||
return wire.AppendVarint(out, 9, p.Title)
|
||||
}
|
||||
out := wire.AppendVarint(nil, 1, entry.Rank)
|
||||
out = wire.AppendVarint(out, 2, p.Owner)
|
||||
out = wire.AppendString(out, 3, p.Name)
|
||||
if entry.Family == "Hopscotch" {
|
||||
out = wire.AppendVarint(out, 4, entry.CapturedArea)
|
||||
return wire.AppendVarint(out, 5, entry.ClearTime)
|
||||
}
|
||||
return wire.AppendVarint(out, 4, uint64(entry.Score))
|
||||
}
|
||||
|
||||
func arcadeRecordWire(entry ranking.ArcadeEntry) []byte {
|
||||
switch entry.Family {
|
||||
case "Survival":
|
||||
return wire.AppendDouble(wire.AppendVarint(nil, 1, uint64(entry.Score)), 2, entry.TopPercent)
|
||||
case "Sichuan":
|
||||
return wire.AppendDouble(wire.AppendDouble(nil, 1, entry.Score), 2, entry.TopPercent)
|
||||
case "Rhythm":
|
||||
out := wire.AppendVarint(nil, 1, uint64(entry.Score))
|
||||
out = wire.AppendVarint(out, 2, entry.Stage)
|
||||
return wire.AppendDouble(out, 3, entry.TopPercent)
|
||||
case "Hopscotch":
|
||||
out := wire.AppendVarint(nil, 1, entry.Stage)
|
||||
out = wire.AppendVarint(out, 2, entry.CapturedArea)
|
||||
out = wire.AppendVarint(out, 3, entry.ClearTime)
|
||||
return wire.AppendDouble(out, 4, entry.TopPercent)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func arcadeTopWire(entry ranking.ArcadeEntry) []byte {
|
||||
if entry.Family == "Hopscotch" {
|
||||
out := wire.AppendVarint(nil, 1, entry.Stage)
|
||||
out = wire.AppendString(out, 2, entry.Profile.Name)
|
||||
out = wire.AppendVarint(out, 3, entry.CapturedArea)
|
||||
return wire.AppendVarint(out, 4, entry.ClearTime)
|
||||
}
|
||||
out := wire.AppendString(nil, 1, entry.Profile.Name)
|
||||
if entry.Family == "Sichuan" {
|
||||
return wire.AppendDouble(out, 2, entry.Score)
|
||||
}
|
||||
out = wire.AppendVarint(out, 2, uint64(entry.Score))
|
||||
if entry.Family == "Rhythm" {
|
||||
out = wire.AppendVarint(out, 3, entry.Stage)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) currentRankingCalendars(ctx command.Context) (map[uint64]events.Schedule, error) {
|
||||
now := s.now().UnixMilli()
|
||||
bound := map[uint64]bool{}
|
||||
if s.hubCalendars != nil {
|
||||
body, err := s.miniEventHubs(ctx, wire.AppendVarint(nil, 1, 1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := wire.Walk(body, func(hub wire.Field) error {
|
||||
if hub.Number != 1 || hub.Type != 2 {
|
||||
return nil
|
||||
}
|
||||
return wire.Walk(hub.Value, func(slot wire.Field) error {
|
||||
if slot.Number != 6 || slot.Type != 2 || num(slot.Value, 2) != 6 {
|
||||
return nil
|
||||
}
|
||||
uid := num(slot.Value, 4)
|
||||
active := now >= int64(num(slot.Value, 5)) && now < int64(num(slot.Value, 6))
|
||||
bound[uid] = bound[uid] || active
|
||||
return nil
|
||||
})
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
active := map[uint64]events.Schedule{}
|
||||
for _, schedule := range s.registry.List() {
|
||||
if schedule.Type != 11 || now < schedule.Start || now >= schedule.End {
|
||||
continue
|
||||
}
|
||||
if open, exists := bound[schedule.UID]; exists && !open {
|
||||
continue
|
||||
}
|
||||
active[schedule.UID] = schedule
|
||||
}
|
||||
return active, nil
|
||||
}
|
||||
|
||||
func (s *Service) arcadeSummary(ctx command.Context, profile ranking.ArcadeProfile, ownOnly bool) ([]byte, error) {
|
||||
calendars, err := s.currentRankingCalendars(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
records := s.RankRecords()
|
||||
scopes := s.arcadeRanks.Scopes()
|
||||
for _, record := range records {
|
||||
if !slices.Contains(scopes, record.ArcadeScope) {
|
||||
scopes = append(scopes, record.ArcadeScope)
|
||||
}
|
||||
}
|
||||
type summaryKey struct {
|
||||
family string
|
||||
stage uint64
|
||||
}
|
||||
selected := map[summaryKey]ranking.ArcadeEntry{}
|
||||
for _, scope := range scopes {
|
||||
if scope.Family == "PackMan" || scope.Family == "Field" || scope.Family == "Run" {
|
||||
continue
|
||||
}
|
||||
calendar, open := calendars[scope.EventUID]
|
||||
if !open {
|
||||
continue
|
||||
}
|
||||
if _, err := s.calendar(calendar.UID, scope.Family); err != nil {
|
||||
continue
|
||||
}
|
||||
key := summaryKey{family: scope.Family}
|
||||
if scope.Family == "Rhythm" || scope.Family == "Hopscotch" {
|
||||
key.stage = scope.Stage
|
||||
}
|
||||
for _, row := range s.arcadeRanks.Board(scope, profile, records, 1) {
|
||||
if ownOnly && !row.Own || !ownOnly && row.Rank != 1 {
|
||||
continue
|
||||
}
|
||||
old, found := selected[key]
|
||||
oldCalendar := calendars[old.EventUID]
|
||||
newer := calendar.Start > oldCalendar.Start || calendar.Start == oldCalendar.Start && calendar.UID > oldCalendar.UID
|
||||
if !found || newer || calendar.UID == old.EventUID && scope.Family == "Rhythm" && row.Score > old.Score {
|
||||
selected[key] = row
|
||||
}
|
||||
}
|
||||
}
|
||||
keys := make([]summaryKey, 0, len(selected))
|
||||
for key := range selected {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
slices.SortFunc(keys, func(a, b summaryKey) int {
|
||||
if a.family < b.family {
|
||||
return -1
|
||||
}
|
||||
if a.family > b.family {
|
||||
return 1
|
||||
}
|
||||
if a.stage < b.stage {
|
||||
return -1
|
||||
}
|
||||
if a.stage > b.stage {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
var out []byte
|
||||
for _, key := range keys {
|
||||
entry := selected[key]
|
||||
row := arcadeTopWire(entry)
|
||||
if ownOnly {
|
||||
row = arcadeRecordWire(entry)
|
||||
}
|
||||
field := map[string]int{"Survival": 1, "Sichuan": 2, "Rhythm": 5, "Hopscotch": 6}[key.family]
|
||||
out = wire.AppendBytes(out, field, row)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -16,6 +16,10 @@ type FieldBinding struct {
|
||||
EventType uint64 `json:"event_type"`
|
||||
ContentOpenType uint64 `json:"content_open_type"`
|
||||
}
|
||||
type ActionMissionCharacterBinding struct {
|
||||
ConditionType uint64 `json:"condition_type"`
|
||||
CharacterID uint64 `json:"character_id"`
|
||||
}
|
||||
|
||||
func (s *Service) AttachFieldBindingsFile(path string) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
@@ -23,8 +27,9 @@ func (s *Service) AttachFieldBindingsFile(path string) error {
|
||||
return err
|
||||
}
|
||||
var seed struct {
|
||||
Version string `json:"version"`
|
||||
Bindings []FieldBinding `json:"bindings"`
|
||||
Version string `json:"version"`
|
||||
Bindings []FieldBinding `json:"bindings"`
|
||||
ActionMissionCharacters []ActionMissionCharacterBinding `json:"action_mission_characters"`
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
@@ -47,5 +52,22 @@ func (s *Service) AttachFieldBindingsFile(path string) error {
|
||||
seen[b.PackID] = true
|
||||
}
|
||||
s.fieldBindings = append([]FieldBinding(nil), seed.Bindings...)
|
||||
s.actionMissionCharacters = map[uint64]uint64{}
|
||||
for _, binding := range seed.ActionMissionCharacters {
|
||||
if binding.ConditionType < 6 || binding.ConditionType > 8 || binding.CharacterID == 0 || s.actionMissionCharacters[binding.ConditionType] != 0 {
|
||||
return fmt.Errorf("eventplay: invalid action mission character binding")
|
||||
}
|
||||
row, err := s.design.Row("ActionGameCharTable", 14, binding.CharacterID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if num(row, 16) != 0 {
|
||||
return fmt.Errorf("eventplay: mission character is a monster")
|
||||
}
|
||||
s.actionMissionCharacters[binding.ConditionType] = binding.CharacterID
|
||||
}
|
||||
if len(s.actionMissionCharacters) != 3 {
|
||||
return fmt.Errorf("eventplay: action mission character bindings incomplete")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,368 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func improvesFieldRecord(kind, current, previous uint64) bool {
|
||||
return current > 0 && (previous == 0 || kind == 3 && current < previous || kind != 3 && current > previous)
|
||||
}
|
||||
|
||||
func selectFieldObjects(d *gamedata.EventField) (map[uint64]bool, error) {
|
||||
selected := map[uint64]bool{}
|
||||
groups := map[uint64][]uint64{}
|
||||
for id, object := range d.Objects {
|
||||
if object.RandomGroup == 0 {
|
||||
selected[id] = true
|
||||
} else {
|
||||
groups[object.RandomGroup] = append(groups[object.RandomGroup], id)
|
||||
}
|
||||
}
|
||||
for group, ids := range groups {
|
||||
count, configured := d.RandomCounts[group]
|
||||
if !configured || count > uint64(len(ids)) {
|
||||
return nil, fmt.Errorf("eventplay: field random count outside group %d", group)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
for i := range count {
|
||||
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(ids))-int64(i)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
j := int(i) + int(n.Int64())
|
||||
ids[i], ids[j] = ids[j], ids[i]
|
||||
selected[ids[i]] = true
|
||||
}
|
||||
}
|
||||
for group, count := range d.RandomCounts {
|
||||
if count > uint64(len(groups[group])) {
|
||||
return nil, fmt.Errorf("eventplay: field random group %d unavailable", group)
|
||||
}
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
func (s *Service) fieldRunGame(ctx command.Context, path string, req []byte, st *snapshot, key string) ([]byte, error) {
|
||||
f := family(path)
|
||||
if strings.HasSuffix(path, "Info") {
|
||||
uids, err := list(req, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []byte
|
||||
seen := map[uint64]bool{}
|
||||
for _, uid := range uids {
|
||||
c, err := s.calendar(uid, f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if seen[c.UID] {
|
||||
continue
|
||||
}
|
||||
seen[c.UID] = true
|
||||
game, err := s.design.Row("PackEventMiniGameTable", 8, c.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := playRecord(st, c.UID, c.ID, 0, num(game, 3), f)
|
||||
body := s.recordWire(r)
|
||||
world, err := s.fieldWorldRecord(ctx, r, st)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = wire.AppendBytes(out, 1, append(body, world...))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
uid := num(req, 2)
|
||||
a, active := st.Runs[f]
|
||||
if strings.HasSuffix(path, "End") || path == "/MiniGameFieldScore" {
|
||||
if !active {
|
||||
return nil, fmt.Errorf("eventplay: no active field run")
|
||||
}
|
||||
if path == "/MiniGameFieldScore" && uid != a.UID {
|
||||
return nil, fmt.Errorf("eventplay: field score schedule differs from run")
|
||||
}
|
||||
uid = a.UID
|
||||
}
|
||||
c, err := s.calendar(uid, f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if now := s.now().UnixMilli(); now < c.Start || now >= c.End {
|
||||
return nil, fmt.Errorf("eventplay: season closed")
|
||||
}
|
||||
game, err := s.design.Row("PackEventMiniGameTable", 8, c.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
kind := num(game, 3)
|
||||
r := playRecord(st, c.UID, c.ID, 0, kind, f)
|
||||
if strings.HasSuffix(path, "Start") {
|
||||
a = Run{UID: c.UID, Game: c.ID, Family: f, Mode: kind, Started: uint64(s.now().UnixMilli()), Session: ctx.SessionID}
|
||||
var out []byte
|
||||
if f == "Field" {
|
||||
d, err := s.fieldRules(c.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.FieldObjects, err = selectFieldObjects(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.HP = d.HP
|
||||
ids := make([]uint64, 0, len(a.FieldObjects))
|
||||
for id := range a.FieldObjects {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
for _, id := range ids {
|
||||
out = wire.AppendVarint(out, 1, id)
|
||||
}
|
||||
}
|
||||
st.Runs[f] = a
|
||||
if s.onProgress != nil {
|
||||
if err := s.onProgress(ctx, 343, c.ID, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.onProgress(ctx, 315, c.ID, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if path == "/MiniGameFieldScore" {
|
||||
d, err := s.fieldRules(a.Game)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids, err := list(req, 3)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, fmt.Errorf("eventplay: missing field objects")
|
||||
}
|
||||
if now := uint64(s.now().UnixMilli()); now < a.Started || now-a.Started > d.Limit*1000+5000 {
|
||||
return nil, fmt.Errorf("eventplay: field run time expired")
|
||||
}
|
||||
for _, id := range ids {
|
||||
object, exists := d.Objects[id]
|
||||
if !exists || !a.FieldObjects[id] || object.RandomGroup > 0 && has(a.Objects, id) {
|
||||
return nil, fmt.Errorf("eventplay: field object inactive or already collected")
|
||||
}
|
||||
if object.RandomGroup > 0 {
|
||||
a.Objects = append(a.Objects, id)
|
||||
}
|
||||
switch object.Type {
|
||||
case 1:
|
||||
a.Score = uint64(max(int64(0), int64(a.Score)+object.Point))
|
||||
case 2:
|
||||
a.HP = uint64(max(int64(0), min(int64(d.HP), int64(a.HP)-object.Point)))
|
||||
}
|
||||
if a.Score > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("eventplay: field score exceeds protocol")
|
||||
}
|
||||
}
|
||||
st.Runs[f] = a
|
||||
return wire.AppendVarint(wire.AppendVarint(nil, 1, a.Score), 2, a.HP), nil
|
||||
}
|
||||
if strings.HasSuffix(path, "End") {
|
||||
score := a.Score
|
||||
var history string
|
||||
if f == "Run" {
|
||||
score, history, err = s.runResult(req, a, kind)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if improvesFieldRecord(kind, score, r.Best) {
|
||||
r.Best = score
|
||||
r.PlayInfo = history
|
||||
r.AchievedAt = uint64(s.now().UnixMilli())
|
||||
}
|
||||
bundle, err := s.payFieldRecord(ctx, &r, score, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st.Records[recKey(r.UID, 0, kind, f)] = r
|
||||
delete(st.Runs, f)
|
||||
if f == "Run" {
|
||||
out := wire.AppendVarint(wire.AppendVarint(nil, 1, r.Best), 2, r.Paid)
|
||||
if len(bundle) > 0 {
|
||||
out = wire.AppendBytes(out, 3, bundle)
|
||||
}
|
||||
return wire.AppendVarint(out, 4, boolWire(s.fieldQuickAvailable(r))), nil
|
||||
}
|
||||
out := wire.AppendVarint(nil, 1, r.UID)
|
||||
out = wire.AppendVarint(out, 2, score)
|
||||
out = wire.AppendVarint(out, 3, r.Best)
|
||||
out = wire.AppendVarint(out, 4, r.Paid)
|
||||
if len(bundle) > 0 {
|
||||
out = wire.AppendBytes(out, 5, bundle)
|
||||
}
|
||||
return wire.AppendVarint(out, 6, boolWire(s.fieldQuickAvailable(r))), nil
|
||||
}
|
||||
if strings.HasSuffix(path, "QuickReward") || path == "/MiniGameFieldReward" {
|
||||
if !s.fieldQuickAvailable(r) {
|
||||
return nil, fmt.Errorf("eventplay: no unpaid field reward")
|
||||
}
|
||||
bundle, err := s.payFieldRecord(ctx, &r, r.Best, key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st.Records[recKey(r.UID, 0, kind, f)] = r
|
||||
if strings.HasSuffix(path, "QuickReward") {
|
||||
return wire.AppendBytes(nil, 1, bundle), nil
|
||||
}
|
||||
out := wire.AppendVarint(nil, 1, r.Paid)
|
||||
err = wire.Walk(bundle, func(field wire.Field) error {
|
||||
if field.Number == 1 {
|
||||
if field.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
out = wire.AppendBytes(out, 2, field.Value)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
return nil, fmt.Errorf("eventplay: unsupported field run transition")
|
||||
}
|
||||
|
||||
func (s *Service) payFieldRecord(ctx command.Context, r *record, score uint64, key string) ([]byte, error) {
|
||||
day := uint64(s.now().UnixMilli()) / 86400000
|
||||
if r.Date != day {
|
||||
r.Paid = 0
|
||||
r.Date = day
|
||||
}
|
||||
point, rewards, err := s.scoreRewards(r.Game, score)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !improvesFieldRecord(r.Mode, point, r.Paid) {
|
||||
return nil, nil
|
||||
}
|
||||
_, old, err := s.scoreRewards(r.Game, r.Paid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
difference := rewardDifference(old, rewards)
|
||||
var bundle []byte
|
||||
if len(difference) > 0 {
|
||||
bundle, err = s.grant(ctx, "eventplay:"+key, difference)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
r.Paid = point
|
||||
return bundle, nil
|
||||
}
|
||||
|
||||
func (s *Service) fieldQuickAvailable(r record) bool {
|
||||
if r.Date != uint64(s.now().UnixMilli())/86400000 {
|
||||
r.Paid = 0
|
||||
}
|
||||
point, _, err := s.scoreRewards(r.Game, r.Best)
|
||||
return err == nil && improvesFieldRecord(r.Mode, point, r.Paid)
|
||||
}
|
||||
|
||||
func (s *Service) fieldWorldRecord(ctx command.Context, r record, st *snapshot) ([]byte, error) {
|
||||
if s.arcadeRanks == nil || s.arcadeProfile == nil {
|
||||
return nil, fmt.Errorf("eventplay: arcade ranking unavailable")
|
||||
}
|
||||
profile, err := s.arcadeProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := s.arcadeRanks.Board(ranking.ArcadeScope{Family: r.Family, EventUID: r.UID, Mode: r.Mode}, profile, s.arcadeRecords(st), 1)
|
||||
if len(rows) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
best := rows[0]
|
||||
out := wire.AppendVarint(nil, 5, best.Profile.Owner)
|
||||
out = wire.AppendString(out, 6, best.Profile.Name)
|
||||
out = wire.AppendVarint(out, 7, uint64(best.Score))
|
||||
if best.PlayInfo != "" {
|
||||
out = wire.AppendString(out, 8, best.PlayInfo)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type runTimeline struct {
|
||||
TotalTime float64
|
||||
TimelineDatas []struct {
|
||||
Time float64
|
||||
Behaviour int
|
||||
Position struct{ X, Y, Z float64 }
|
||||
SpeedMagnification float64
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) runResult(req []byte, a Run, kind uint64) (uint64, string, error) {
|
||||
score := num(req, 3)
|
||||
if score > math.MaxInt32 {
|
||||
return 0, "", fmt.Errorf("eventplay: run time exceeds protocol")
|
||||
}
|
||||
if now := uint64(s.now().UnixMilli()); now < a.Started || score > now-a.Started+1000 {
|
||||
return 0, "", fmt.Errorf("eventplay: run time exceeds elapsed time")
|
||||
}
|
||||
raw, _, err := wire.Bytes(req, 4)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
if kind == 4 {
|
||||
d, err := s.fieldRules(a.Game)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
if score > d.Limit*1000 {
|
||||
return 0, "", fmt.Errorf("eventplay: dodge time exceeds limit")
|
||||
}
|
||||
if len(raw) != 0 {
|
||||
return 0, "", fmt.Errorf("eventplay: dodge has no run ghost")
|
||||
}
|
||||
return score, "", nil
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
if num(req, 2) == 0 && score > 0 {
|
||||
return 0, "", fmt.Errorf("eventplay: completed run has no ghost")
|
||||
}
|
||||
return 0, "", nil
|
||||
}
|
||||
if num(req, 2) != 0 {
|
||||
return 0, "", fmt.Errorf("eventplay: abandoned run contains completed ghost")
|
||||
}
|
||||
if len(raw) > 512*1024 {
|
||||
return 0, "", fmt.Errorf("eventplay: run timeline too large")
|
||||
}
|
||||
var timeline runTimeline
|
||||
if err := json.Unmarshal(raw, &timeline); err != nil {
|
||||
return 0, "", fmt.Errorf("eventplay: invalid run timeline: %w", err)
|
||||
}
|
||||
if timeline.TotalTime <= 0 || math.Abs(timeline.TotalTime*1000-float64(score)) > 1000 || len(timeline.TimelineDatas) < 2 || len(timeline.TimelineDatas) > 20000 {
|
||||
return 0, "", fmt.Errorf("eventplay: run timeline time differs from result")
|
||||
}
|
||||
previous := float64(0)
|
||||
for _, sample := range timeline.TimelineDatas {
|
||||
if sample.Time < previous || sample.Time > timeline.TotalTime+0.001 || sample.Behaviour < 0 || sample.Behaviour > 7 || sample.SpeedMagnification < 0 || math.IsNaN(sample.SpeedMagnification) || math.IsInf(sample.SpeedMagnification, 0) {
|
||||
return 0, "", fmt.Errorf("eventplay: invalid run timeline sample")
|
||||
}
|
||||
previous = sample.Time
|
||||
}
|
||||
last := timeline.TimelineDatas[len(timeline.TimelineDatas)-1]
|
||||
if last.Behaviour != 7 || math.Abs(last.Time-timeline.TotalTime) > 0.001 {
|
||||
return 0, "", fmt.Errorf("eventplay: run timeline not completed")
|
||||
}
|
||||
return score, string(raw), nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fieldRunHarness(t *testing.T) *playHarness {
|
||||
t.Helper()
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["PackEventMiniGameTable"] = append(h.design.Tables["PackEventMiniGameTable"], testRow(8, 90, 3, 2, 10, 90), testRow(8, 91, 3, 3, 10, 91), testRow(8, 92, 3, 4, 10, 92))
|
||||
h.design.Tables["FieldMiniGameRewardTable"] = [][]byte{
|
||||
testRow(1, 90, 2, 1, 3, 100, 6, 8, 5, 77, 4, 10), testRow(1, 90, 2, 2, 3, 200, 6, 4, 5, 0, 4, 20),
|
||||
testRow(1, 91, 2, 1, 3, 45, 6, 4, 5, 0, 4, 20), testRow(1, 91, 2, 2, 3, 35, 6, 8, 5, 77, 4, 60), testRow(1, 91, 2, 3, 3, 25, 6, 4, 5, 0, 4, 30),
|
||||
testRow(1, 92, 2, 1, 3, 5, 6, 4, 5, 0, 4, 20), testRow(1, 92, 2, 2, 3, 10, 6, 8, 5, 77, 4, 10),
|
||||
}
|
||||
calendars := h.registry.List()
|
||||
for _, game := range []uint64{90, 91, 92} {
|
||||
calendars = append(calendars, events.Schedule{UID: game + 100, Type: 11, ID: game, Start: h.now.UnixMilli() - 1000, End: h.now.Add(48 * time.Hour).UnixMilli()})
|
||||
}
|
||||
if err := h.registry.Replace(calendars); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.service.fieldRules = func(uint64) (*gamedata.EventField, error) {
|
||||
return &gamedata.EventField{HP: 300, Limit: 3600, RandomCounts: map[uint64]uint64{7: 1}, Objects: map[uint64]gamedata.FieldGameObject{
|
||||
1: {Point: 200, Type: 1}, 2: {Point: -50, Type: 1}, 3: {Point: 100, Type: 2}, 4: {Point: -100, Type: 2}, 5: {Point: 100, Type: 1, RandomGroup: 7}, 6: {Point: 100, Type: 1, RandomGroup: 7},
|
||||
}}, nil
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// RacingHUD applies signed score changes, HP-point capped to starting HP, and
|
||||
// only the start response's enabled objects. EventMiniGameUI's reward guide
|
||||
// accumulates every reached row, rather than replacing one row with another.
|
||||
func TestRacingSelectedObjectsHealthAndCumulativeDailyRewards(t *testing.T) {
|
||||
h := fieldRunHarness(t)
|
||||
start := testRow(1, 1, 2, 190)
|
||||
body := h.call(t, "/MiniGameFieldStart", start)
|
||||
ids, err := list(body, 1)
|
||||
if err != nil || len(ids) != 5 {
|
||||
t.Fatalf("enabled objects: %v %v", ids, err)
|
||||
}
|
||||
if !bytes.Equal(body, h.call(t, "/MiniGameFieldStart", start)) {
|
||||
t.Fatal("start retry resampled objects")
|
||||
}
|
||||
inactive := uint64(5)
|
||||
if has(ids, 5) {
|
||||
inactive = 6
|
||||
}
|
||||
h.reject(t, "/MiniGameFieldScore", testRow(1, 2, 2, 190, 3, inactive))
|
||||
result := h.call(t, "/MiniGameFieldScore", testRow(1, 3, 2, 190, 3, 1, 3, 2, 3, 3))
|
||||
if num(result, 1) != 150 || num(result, 2) != 200 {
|
||||
t.Fatal("signed score or HP damage diverges from RacingHUD")
|
||||
}
|
||||
h.reject(t, "/MiniGameFieldScore", testRow(1, 4, 2, 191, 3, 1))
|
||||
result = h.call(t, "/MiniGameFieldScore", testRow(1, 5, 2, 190, 3, 4))
|
||||
if num(result, 2) != 300 {
|
||||
t.Fatal("healing did not cap at starting health")
|
||||
}
|
||||
end := testRow(1, 6)
|
||||
h.call(t, "/MiniGameFieldEnd", end)
|
||||
if h.balance(t, 8) != 10 || h.balance(t, 4) != 0 {
|
||||
t.Fatal("first daily tier paid wrong inventory")
|
||||
}
|
||||
h.call(t, "/MiniGameFieldEnd", end)
|
||||
if h.balance(t, 8) != 10 {
|
||||
t.Fatal("end retry paid twice")
|
||||
}
|
||||
h.call(t, "/MiniGameFieldStart", testRow(1, 7, 2, 190))
|
||||
h.call(t, "/MiniGameFieldScore", testRow(1, 8, 2, 190, 3, 1, 3, 1))
|
||||
h.call(t, "/MiniGameFieldEnd", testRow(1, 9))
|
||||
if h.balance(t, 8) != 10 || h.balance(t, 4) != 20 {
|
||||
t.Fatal("improved score did not pay exactly the additional tier")
|
||||
}
|
||||
h.reopen(t)
|
||||
h.now = h.now.Add(24 * time.Hour)
|
||||
body = h.call(t, "/MiniGameFieldInfo", testRow(1, 10, 2, 190))
|
||||
info, _, err := wire.Bytes(body, 1)
|
||||
if err != nil || num(info, 3) != 400 || num(info, 2) != 0 || num(info, 4) != 1 {
|
||||
t.Fatal("daily reset lost season best or did not enable quick reward")
|
||||
}
|
||||
h.call(t, "/MiniGameFieldQuickReward", testRow(1, 11, 2, 190))
|
||||
h.reopen(t)
|
||||
h.reject(t, "/MiniGameFieldQuickReward", testRow(1, 12, 2, 190))
|
||||
if h.balance(t, 8) != 20 || h.balance(t, 4) != 40 {
|
||||
t.Fatal("next-day cumulative reward was lost or duplicated across reopening")
|
||||
}
|
||||
}
|
||||
|
||||
func runHistory(seconds float64) string {
|
||||
return fmt.Sprintf(`{"TotalTime":%g,"TimelineDatas":[{"Time":0,"Behaviour":1,"Position":{"x":0,"y":0,"z":0},"SpeedMagnification":1},{"Time":%g,"Behaviour":7,"Position":{"x":1,"y":0,"z":1},"SpeedMagnification":0}]}`, seconds, seconds)
|
||||
}
|
||||
|
||||
// RunHUD reports milliseconds plus RunPlayerController's completed ghost.
|
||||
// The reward guide marks time <= authored seconds as earned for Run, and
|
||||
// time >= authored seconds for Dodge. These exercise settlement and reopening.
|
||||
func TestRunFastestGhostAndDodgeSurvivalRewardDirections(t *testing.T) {
|
||||
h := fieldRunHarness(t)
|
||||
for i, seconds := range []float64{40, 30, 50} {
|
||||
h.call(t, "/MiniGameRunStart", testRow(1, uint64(i*3+1), 2, 191))
|
||||
h.now = h.now.Add(time.Duration(seconds) * time.Second)
|
||||
end := wire.AppendString(testRow(1, uint64(i*3+2), 3, uint64(seconds*1000)), 4, runHistory(seconds))
|
||||
result := h.call(t, "/MiniGameRunEnd", end)
|
||||
if i == 2 && num(result, 1) != 30000 {
|
||||
t.Fatal("slower run replaced fastest completed record")
|
||||
}
|
||||
h.call(t, "/MiniGameRunEnd", end)
|
||||
h.reopen(t)
|
||||
}
|
||||
if h.balance(t, 4) != 20 || h.balance(t, 8) != 60 {
|
||||
t.Fatal("run tiers were not cumulative or repeated/slower runs paid again")
|
||||
}
|
||||
body := h.call(t, "/MiniGameRunInfo", testRow(1, 11, 2, 191))
|
||||
info, _, err := wire.Bytes(body, 1)
|
||||
history, _, historyErr := wire.Bytes(info, 8)
|
||||
if err != nil || historyErr != nil || num(info, 7) != 30000 || string(history) != runHistory(30) {
|
||||
t.Fatal("world ghost differs from the fastest persisted result")
|
||||
}
|
||||
h.call(t, "/MiniGameRunStart", testRow(1, 12, 2, 191))
|
||||
h.now = h.now.Add(time.Second)
|
||||
h.reject(t, "/MiniGameRunEnd", wire.AppendString(testRow(1, 13, 3, 1000), 4, runHistory(40)))
|
||||
h.call(t, "/MiniGameRunEnd", testRow(1, 14, 2, 1, 3, 1000))
|
||||
if h.balance(t, 4) != 20 || h.balance(t, 8) != 60 {
|
||||
t.Fatal("abandoned run granted rewards")
|
||||
}
|
||||
h.service.fieldRules = func(uint64) (*gamedata.EventField, error) { return &gamedata.EventField{Limit: 3600}, nil }
|
||||
for i, seconds := range []uint64{5, 12, 7} {
|
||||
h.call(t, "/MiniGameRunStart", testRow(1, uint64(20+i*3), 2, 192))
|
||||
h.now = h.now.Add(time.Duration(seconds) * time.Second)
|
||||
result := h.call(t, "/MiniGameRunEnd", testRow(1, uint64(21+i*3), 3, seconds*1000))
|
||||
if i == 2 && num(result, 1) != 12000 {
|
||||
t.Fatal("shorter dodge survival replaced best record")
|
||||
}
|
||||
}
|
||||
if h.balance(t, 4) != 40 || h.balance(t, 8) != 70 {
|
||||
t.Fatal("dodge time units or additional-tier payments wrong")
|
||||
}
|
||||
}
|
||||
@@ -29,10 +29,24 @@ func (s *Service) nativeRanking(ctx command.Context, path string, req []byte) ([
|
||||
return nil, fmt.Errorf("eventplay: native ranking unavailable")
|
||||
}
|
||||
uid, monster, stage := num(req, 2), num(req, 3), num(req, 4)
|
||||
if path == "/MiniGameRanking" || path == "/MiniGameUserRecordInfo" {
|
||||
summary := path == "/MiniGameRanking" || path == "/MiniGameUserRecordInfo"
|
||||
current, err := s.currentRankingCalendars(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if summary {
|
||||
uid = 0
|
||||
monster = 0
|
||||
stage = 0
|
||||
} else {
|
||||
calendar, err := s.calendar(uid, "Action")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uid = calendar.UID
|
||||
if !s.validNativeRankScope(uid, monster, stage) {
|
||||
return nil, fmt.Errorf("eventplay: native ranking selection outside event group")
|
||||
}
|
||||
}
|
||||
if stage > 2 {
|
||||
return nil, fmt.Errorf("eventplay: invalid native stage type")
|
||||
@@ -41,19 +55,37 @@ func (s *Service) nativeRanking(ctx command.Context, path string, req []byte) ([
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
type selection struct{ monster, stage uint64 }
|
||||
latest := map[selection]uint64{}
|
||||
if summary {
|
||||
for _, row := range ranks {
|
||||
calendar, active := current[row.EventUID]
|
||||
if !active || !s.validNativeRankScope(row.EventUID, row.Monster, row.StageType) {
|
||||
continue
|
||||
}
|
||||
key := selection{row.Monster, row.StageType}
|
||||
old, exists := latest[key]
|
||||
previous := current[old]
|
||||
if !exists || calendar.Start > previous.Start || calendar.Start == previous.Start && calendar.UID > previous.UID {
|
||||
latest[key] = row.EventUID
|
||||
}
|
||||
}
|
||||
}
|
||||
var out []byte
|
||||
if path == "/MiniGameRanking" || path == "/MiniGameUserRecordInfo" {
|
||||
b := summaryWire(&s.state, path == "/MiniGameUserRecordInfo")
|
||||
if err = wire.Walk(b, func(f wire.Field) error {
|
||||
if f.Number != 3 && f.Number != 4 {
|
||||
out = append(out, b[f.Start:f.End]...)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
out, err = s.arcadeRanking(ctx, path, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, r := range ranks {
|
||||
if summary {
|
||||
if latest[selection{r.Monster, r.StageType}] != r.EventUID {
|
||||
continue
|
||||
}
|
||||
} else if !s.validNativeRankScope(r.EventUID, r.Monster, r.StageType) {
|
||||
continue
|
||||
}
|
||||
if len(r.Members) == 0 || r.Rank == 0 || r.Score <= 0 {
|
||||
continue
|
||||
}
|
||||
@@ -120,6 +152,27 @@ func (s *Service) nativeRanking(ctx command.Context, path string, req []byte) ([
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Service) validNativeRankScope(uid, monster, stage uint64) bool {
|
||||
calendar, err := s.calendar(uid, "Action")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
game, err := s.design.Row("PackEventMiniGameTable", 8, calendar.ID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
action, err := s.design.Row("ActionGameTable", 3, num(game, 4))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, row := range s.design.Rows("ActionGameStageTable", 3, num(action, 4)) {
|
||||
if (monster == 0 || num(row, 1) == monster) && (stage == 0 || num(row, 11) == stage) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func nativeRankMember(u NativeRankMember) []byte {
|
||||
b := wire.AppendVarint(nil, 1, u.OwnerIndex)
|
||||
b = wire.AppendString(b, 2, u.UserID)
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"fmt"
|
||||
"math"
|
||||
)
|
||||
|
||||
func (s *Service) packManRule(mode uint64) ([]byte, error) {
|
||||
if len(s.design.Tables["PackManDefaultTable"]) == 0 {
|
||||
return nil, fmt.Errorf("eventplay: PackMan default missing")
|
||||
}
|
||||
group := num(s.design.Tables["PackManDefaultTable"][0], 15)
|
||||
for _, row := range s.design.Rows("PackManModeTable", 2, group) {
|
||||
if num(row, 5) == mode {
|
||||
return s.design.Row("PackManModeRuleTable", 2, num(row, 4))
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("eventplay: PackMan mode missing")
|
||||
}
|
||||
|
||||
func (s *Service) validatePackManRecord(a Run, progress []byte, stageClear bool) (uint64, error) {
|
||||
if len(progress) == 0 {
|
||||
return 0, fmt.Errorf("eventplay: missing PackMan history")
|
||||
}
|
||||
for field := 1; field <= 6; field++ {
|
||||
value := num(progress, field)
|
||||
if value > math.MaxInt32 || value < num(a.PackRecord, field) {
|
||||
return 0, fmt.Errorf("eventplay: PackMan cumulative history regressed")
|
||||
}
|
||||
}
|
||||
elapsed := num(progress, 1)
|
||||
if now := uint64(s.now().UnixMilli()); now < a.Started || elapsed > (now-a.Started)/1000+1 {
|
||||
return 0, fmt.Errorf("eventplay: PackMan play time exceeds run duration")
|
||||
}
|
||||
expectedEscapes := a.Stage - 1
|
||||
if stageClear {
|
||||
expectedEscapes++
|
||||
}
|
||||
if num(progress, 6) != expectedEscapes {
|
||||
return 0, fmt.Errorf("eventplay: PackMan escape count differs from committed stages")
|
||||
}
|
||||
rule, err := s.packManRule(a.Mode)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if limit := num(rule, 8); limit > 0 && elapsed*1000 > limit+num(rule, 6)*expectedEscapes+1000 {
|
||||
return 0, fmt.Errorf("eventplay: PackMan time limit exceeded")
|
||||
}
|
||||
coinCounts := map[uint64]uint64{}
|
||||
seen := map[string]bool{}
|
||||
lastCoinTime := uint64(0)
|
||||
err = wire.Walk(progress, func(f wire.Field) error {
|
||||
switch f.Number {
|
||||
case 7:
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
typ, x, y, t := num(f.Value, 1), num(f.Value, 2), num(f.Value, 3), num(f.Value, 4)
|
||||
if typ < 1 || typ > 3 || t > elapsed*1000+1000 || t < lastCoinTime {
|
||||
return fmt.Errorf("eventplay: invalid PackMan coin record")
|
||||
}
|
||||
identity := fmt.Sprintf("%d:%d", x, y)
|
||||
if seen[identity] {
|
||||
return fmt.Errorf("eventplay: PackMan coin collected twice")
|
||||
}
|
||||
seen[identity] = true
|
||||
coinCounts[typ]++
|
||||
lastCoinTime = t
|
||||
case 8:
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
row, e := s.design.Row("PackManItemTable", 4, num(f.Value, 2))
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if num(row, 7) != num(f.Value, 1) || num(f.Value, 3) > elapsed*1000+1000 {
|
||||
return fmt.Errorf("eventplay: invalid PackMan item use")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
for typ := uint64(1); typ <= 3; typ++ {
|
||||
if num(progress, int(typ)+1)-num(a.PackRecord, int(typ)+1) != coinCounts[typ] {
|
||||
return 0, fmt.Errorf("eventplay: PackMan coin totals differ from stage history")
|
||||
}
|
||||
}
|
||||
if num(progress, 5) > num(progress, 2)+num(progress, 3)+num(progress, 4) {
|
||||
return 0, fmt.Errorf("eventplay: PackMan chain exceeds coins")
|
||||
}
|
||||
if a.Mode == 1 {
|
||||
if num(progress, 5) != 0 {
|
||||
return 0, fmt.Errorf("eventplay: normal PackMan has no chain score")
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
var score uint64
|
||||
for field := 1; field <= 6; field++ {
|
||||
row, e := s.design.Row("PackManScoreTable", 1, uint64(field))
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
value, unit := num(progress, field), num(row, 2)
|
||||
if unit > 0 && value > (math.MaxInt32-score)/unit {
|
||||
return 0, fmt.Errorf("eventplay: PackMan score overflow")
|
||||
}
|
||||
score += value * unit
|
||||
}
|
||||
return score, nil
|
||||
}
|
||||
|
||||
func (s *Service) endPackMan(ctx command.Context, req []byte, a Run, st *snapshot, key string) ([]byte, error) {
|
||||
endType := num(req, 2)
|
||||
if endType < 1 || endType > 3 {
|
||||
return nil, fmt.Errorf("eventplay: invalid PackMan end type")
|
||||
}
|
||||
if id := num(req, 3); id > 0 {
|
||||
if _, err := s.design.Row("PackManChaserTable", 2, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
rule, err := s.packManRule(a.Mode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if endType == 3 && (num(rule, 4) == 0 || a.Stage != num(rule, 4)) {
|
||||
return nil, fmt.Errorf("eventplay: PackMan final stage not reached")
|
||||
}
|
||||
if endType == 2 && num(rule, 8) == 0 {
|
||||
return nil, fmt.Errorf("eventplay: PackMan mode has no timer")
|
||||
}
|
||||
progress, _, err := wire.Bytes(req, 4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
score, err := s.validatePackManRecord(a, progress, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if score != num(req, 5) {
|
||||
return nil, fmt.Errorf("eventplay: PackMan score differs from configured formula")
|
||||
}
|
||||
if endType == 2 && num(progress, 1)*1000+1000 < num(rule, 8)+num(rule, 6)*(a.Stage-1) {
|
||||
return nil, fmt.Errorf("eventplay: PackMan timer has not expired")
|
||||
}
|
||||
r := playRecord(st, a.UID, a.Game, 0, a.Mode, a.Family)
|
||||
newRecord := a.Mode == 2 && score > r.Best
|
||||
if newRecord {
|
||||
r.Best = score
|
||||
r.AchievedAt = uint64(s.now().UnixMilli())
|
||||
}
|
||||
if endType == 3 {
|
||||
r.Clears["clear"] = true
|
||||
}
|
||||
st.Records[recKey(a.UID, 0, a.Mode, a.Family)] = r
|
||||
if s.onProgress != nil {
|
||||
if err := s.onProgress(ctx, 364, a.Game, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
condition := uint64(360)
|
||||
if a.Mode == 2 {
|
||||
condition = 362
|
||||
}
|
||||
if err := s.onProgress(ctx, condition, a.Game, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if endType == 3 {
|
||||
if err := s.onProgress(ctx, 361, a.Game, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if a.Mode == 2 && endType == 2 {
|
||||
if err := s.onProgress(ctx, 363, a.Game, score); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return wire.AppendVarint(nil, 1, boolWire(newRecord)), nil
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/protocol/staticdata"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
@@ -22,19 +23,33 @@ type Run struct {
|
||||
UID, Game, Stage, Mode, Started, Score, HP uint64
|
||||
Family, Session string
|
||||
Objects, Skills []uint64
|
||||
FieldObjects map[uint64]bool
|
||||
Coin, Exp, Char, MapGroup uint64
|
||||
SkillLevels map[uint64]uint64
|
||||
MaxHP, Rerolls, Level, SkillCredits uint64
|
||||
Offers []uint64
|
||||
LevelExp uint64
|
||||
Killed, Picked, Available map[uint64]uint64
|
||||
Killed, Picked map[uint64]uint64
|
||||
Native *NativeRun `json:"native,omitempty"`
|
||||
LastProgress, OfferNonce uint64
|
||||
Regen, CoinRate, ExpRate float64
|
||||
PackRecord []byte
|
||||
Blocks []byte
|
||||
Boxes, SpecialItems map[uint64]uint64
|
||||
RandomState [16]uint64
|
||||
RandomIndex uint64
|
||||
Drops []survivalDrop
|
||||
}
|
||||
type survivalDrop struct{ ID, Created uint64 }
|
||||
type record struct {
|
||||
UID, Game, Stage, Mode, Best, Paid, Date uint64
|
||||
Family string
|
||||
Clears map[string]bool
|
||||
PendingBundle []byte
|
||||
BestScore float64
|
||||
CapturedArea, ClearTime, AchievedAt uint64
|
||||
BestGrade, BestCombo uint64
|
||||
PlayInfo string
|
||||
}
|
||||
type reply struct{ Request, Body []byte }
|
||||
type snapshot struct {
|
||||
@@ -53,23 +68,27 @@ type Service struct {
|
||||
fieldRules FieldRuleLoader
|
||||
battleChallenges gamedata.EventBattleChallenges
|
||||
|
||||
store stateio.Store
|
||||
registry events.Resolver
|
||||
economy Rewards
|
||||
design *gamedata.EventPlayCatalog
|
||||
state snapshot
|
||||
now func() time.Time
|
||||
rooms RoomRuntime
|
||||
onProgress func(command.Context, uint64, uint64, uint64) error
|
||||
hubCalendars *readonly.Seed
|
||||
fieldBindings []FieldBinding
|
||||
store stateio.Store
|
||||
registry events.Resolver
|
||||
economy Rewards
|
||||
design *gamedata.EventPlayCatalog
|
||||
state snapshot
|
||||
now func() time.Time
|
||||
rooms RoomRuntime
|
||||
arcadeRanks *ranking.Arcade
|
||||
arcadeProfile func(command.Context) (ranking.ArcadeProfile, error)
|
||||
arcadeGuilds func(command.Context, []uint64) (map[uint64][]byte, error)
|
||||
onProgress func(command.Context, uint64, uint64, uint64) error
|
||||
hubCalendars *readonly.Seed
|
||||
fieldBindings []FieldBinding
|
||||
actionMissionCharacters map[uint64]uint64
|
||||
}
|
||||
|
||||
func Open(ctx command.Context, store stateio.Store, design *gamedata.EventPlayCatalog, fieldRules FieldRuleLoader, registry events.Resolver, economy Rewards) (*Service, error) {
|
||||
if store == nil || design == nil || fieldRules == nil || registry == nil || economy == nil {
|
||||
return nil, fmt.Errorf("eventplay: incomplete configuration")
|
||||
}
|
||||
s := &Service{store: store, registry: registry, economy: economy, design: design, fieldRules: fieldRules, now: time.Now, state: snapshot{1, map[string]record{}, map[string]Run{}, map[string]reply{}, map[string]bool{}, map[string]uint64{}}}
|
||||
s := &Service{store: store, registry: registry, economy: economy, design: design, fieldRules: fieldRules, now: time.Now, state: snapshot{2, map[string]record{}, map[string]Run{}, map[string]reply{}, map[string]bool{}, map[string]uint64{}}}
|
||||
raw, e := store.Load(ctx.State, "eventplay")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
@@ -81,18 +100,45 @@ func Open(ctx command.Context, store stateio.Store, design *gamedata.EventPlayCa
|
||||
if e = json.Unmarshal(raw, &s.state); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if s.state.Version != 1 || s.state.Records == nil || s.state.Runs == nil || s.state.Replies == nil || s.state.Stories == nil || s.state.Upgrades == nil {
|
||||
if s.state.Version != 2 || s.state.Records == nil || s.state.Runs == nil || s.state.Replies == nil || s.state.Stories == nil || s.state.Upgrades == nil {
|
||||
return nil, fmt.Errorf("eventplay: incompatible save")
|
||||
}
|
||||
}
|
||||
for _, r := range s.state.Records {
|
||||
if r.UID == 0 || r.Game == 0 || r.Best > math.MaxInt32 || r.Clears == nil {
|
||||
if r.UID == 0 || r.Game == 0 || r.Best > math.MaxInt32 || r.Clears == nil || math.IsNaN(r.BestScore) || math.IsInf(r.BestScore, 0) || r.BestScore < 0 || r.CapturedArea > 100 || r.ClearTime > math.MaxInt32 || r.Best > 0 && r.AchievedAt == 0 {
|
||||
return nil, fmt.Errorf("eventplay: invalid saved record")
|
||||
}
|
||||
if _, e = s.design.Row("PackEventMiniGameTable", 8, r.Game); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
}
|
||||
for key, run := range s.state.Runs {
|
||||
if run.Family == "Battle" {
|
||||
if !strings.HasPrefix(key, "battle:") || len(key) == len("battle:") || run.UID == 0 || run.Game == 0 || run.Stage == 0 || run.Mode != 17 || run.Started == 0 {
|
||||
return nil, fmt.Errorf("eventplay: invalid saved event battle")
|
||||
}
|
||||
c, err := s.registry.Resolve(run.UID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.Type != 17 || c.ID != run.Game {
|
||||
return nil, fmt.Errorf("eventplay: saved event battle schedule differs")
|
||||
}
|
||||
if _, err := s.design.Row("PackEventBattleGroupTable", 3, run.Game); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if key != run.Family || run.UID == 0 || run.Game == 0 || run.Started == 0 || run.Started > math.MaxInt64 {
|
||||
return nil, fmt.Errorf("eventplay: invalid saved run")
|
||||
}
|
||||
if _, err := s.calendar(run.UID, run.Family); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if run.Family == "Survival" && (run.Killed == nil || run.Picked == nil || run.Boxes == nil || run.SpecialItems == nil || run.SkillLevels == nil || run.RandomIndex >= 16 || run.MaxHP == 0) {
|
||||
return nil, fmt.Errorf("eventplay: invalid saved survival progress")
|
||||
}
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
@@ -112,7 +158,7 @@ func (s *Service) grant(ctx command.Context, identity string, rewards []gamedata
|
||||
|
||||
func family(path string) string {
|
||||
p := strings.TrimPrefix(path, "/MiniGame")
|
||||
for _, f := range []string{"Hopscotch", "Survival", "Defense", "Rhythm", "Sichuan", "Action", "Field", "Run"} {
|
||||
for _, f := range []string{"Hopscotch", "Survival", "Defense", "Rhythm", "Sichuan", "Action", "PackMan", "Field", "Run"} {
|
||||
if strings.HasPrefix(p, f) {
|
||||
return f
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -26,6 +26,10 @@ var codes = map[string]int{
|
||||
"/MiniGameHopscotchInfo": 541,
|
||||
"/MiniGameHopscotchRankingInfo": 542,
|
||||
"/MiniGameHopscotchUserRecordInfo": 640,
|
||||
"/MiniGamePackManStart": 647,
|
||||
"/MiniGamePackManStageClear": 648,
|
||||
"/MiniGamePackManEnd": 649,
|
||||
"/MiniGamePackManInfo": 653,
|
||||
"/MiniGameHubInfo": 390,
|
||||
"/MiniGameRhythmInfo": 428,
|
||||
"/MiniGameRhythmPlayEnd": 430,
|
||||
|
||||
@@ -0,0 +1,627 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func playRecord(st *snapshot, uid, game, stage, mode uint64, family string) record {
|
||||
r := st.Records[recKey(uid, stage, mode, family)]
|
||||
if r.Clears == nil {
|
||||
r = record{UID: uid, Game: game, Stage: stage, Mode: mode, Family: family, Clears: map[string]bool{}}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *Service) singlePlayerGame(ctx command.Context, path string, req []byte, st *snapshot, key string) ([]byte, error) {
|
||||
f := family(path)
|
||||
if strings.Contains(path, "Ranking") || strings.Contains(path, "UserRecord") {
|
||||
return s.arcadeRanking(ctx, path, req)
|
||||
}
|
||||
if path == "/MiniGameSichuanInfo" {
|
||||
uids, err := list(req, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(uids) == 0 {
|
||||
uids = []uint64{0}
|
||||
}
|
||||
var out []byte
|
||||
for _, uid := range uids {
|
||||
c, err := s.calendar(uid, f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body := s.sichuanInfo(st, c.UID)
|
||||
world, e := s.arcadeWorldBest(ctx, c.UID, st, 3, 4, 5)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = wire.AppendBytes(out, 1, append(body, world...))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if strings.HasSuffix(path, "Info") {
|
||||
c, err := s.calendar(num(req, 2), f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch f {
|
||||
case "Hopscotch":
|
||||
return s.hopscotchInfo(st, c.UID), nil
|
||||
case "PackMan":
|
||||
return wire.AppendVarint(nil, 1, playRecord(st, c.UID, c.ID, 0, 2, f).Best), nil
|
||||
case "Rhythm":
|
||||
var out, bundle []byte
|
||||
for _, row := range s.design.Tables["RhythmGameMusicTable"] {
|
||||
for mode := range uint64(3) {
|
||||
r := playRecord(st, c.UID, c.ID, num(row, 5), mode, f)
|
||||
out = wire.AppendBytes(out, 1, rhythmRecordWire(r))
|
||||
bundle = append(bundle, r.PendingBundle...)
|
||||
r.PendingBundle = nil
|
||||
st.Records[recKey(r.UID, r.Stage, r.Mode, f)] = r
|
||||
}
|
||||
}
|
||||
if len(bundle) > 0 {
|
||||
out = wire.AppendBytes(out, 2, bundle)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
if strings.HasSuffix(path, "Start") {
|
||||
c, err := s.calendar(num(req, 2), f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if now := s.now().UnixMilli(); now < c.Start || now >= c.End {
|
||||
return nil, fmt.Errorf("eventplay: season closed")
|
||||
}
|
||||
a := Run{UID: c.UID, Game: c.ID, Family: f, Started: uint64(s.now().UnixMilli()), Session: ctx.SessionID, Stage: num(req, 3), Mode: num(req, 4)}
|
||||
switch f {
|
||||
case "Sichuan":
|
||||
a.Stage, a.Mode = num(req, 4), num(req, 3)
|
||||
row, err := s.sichuanStage(a.Mode, a.Stage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !s.sichuanActive(st, a.UID, a.Mode, a.Stage) {
|
||||
return nil, fmt.Errorf("eventplay: Sichuan level locked")
|
||||
}
|
||||
var blocks []byte
|
||||
var total uint64
|
||||
seen := map[uint64]bool{}
|
||||
err = wire.Walk(req, func(field wire.Field) error {
|
||||
if field.Number != 5 {
|
||||
return nil
|
||||
}
|
||||
if field.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
id, count := num(field.Value, 1), num(field.Value, 2)
|
||||
if count == 0 || count > num(row, 8) || count%2 != 0 || id/1000 == 12 || id/1000 == 10 || id == 0 || seen[id] {
|
||||
return fmt.Errorf("eventplay: invalid Sichuan block inventory")
|
||||
}
|
||||
seen[id] = true
|
||||
total += count
|
||||
blocks = wire.AppendBytes(blocks, 1, field.Value)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if total == 0 || total > num(row, 8) {
|
||||
return nil, fmt.Errorf("eventplay: Sichuan block count differs from layout")
|
||||
}
|
||||
a.Blocks = blocks
|
||||
case "Rhythm":
|
||||
a.Mode, a.Char = num(req, 5), num(req, 4)
|
||||
if err := s.validateStage(f, a.Stage, a.Mode); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.design.Row("RhythmGameCharTable", 2, a.Char); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "Hopscotch":
|
||||
a.Mode = 0
|
||||
if err := s.validateStage(f, a.Stage, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "PackMan":
|
||||
a.Mode, a.Stage = num(req, 3), 1
|
||||
if _, err := s.packManRule(a.Mode); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
st.Runs[f] = a
|
||||
if s.onProgress != nil {
|
||||
if err := s.onProgress(ctx, 343, c.ID, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.onProgress(ctx, 315, c.ID, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
a, exists := st.Runs[f]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("eventplay: no active run")
|
||||
}
|
||||
calendar, err := s.calendar(a.UID, f)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if now := s.now().UnixMilli(); now < calendar.Start || now >= calendar.End {
|
||||
return nil, fmt.Errorf("eventplay: season closed")
|
||||
}
|
||||
if path == "/MiniGamePackManStageClear" {
|
||||
if num(req, 2) != a.Stage {
|
||||
return nil, fmt.Errorf("eventplay: PackMan stage out of order")
|
||||
}
|
||||
rule, err := s.packManRule(a.Mode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if max := num(rule, 4); max > 0 && a.Stage >= max {
|
||||
return nil, fmt.Errorf("eventplay: final PackMan stage requires End")
|
||||
}
|
||||
progress, _, err := wire.Bytes(req, 3)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err = s.validatePackManRecord(a, progress, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.PackRecord = append([]byte(nil), progress...)
|
||||
a.Stage++
|
||||
st.Runs[f] = a
|
||||
return nil, nil
|
||||
}
|
||||
if !strings.HasSuffix(path, "End") {
|
||||
return nil, fmt.Errorf("eventplay: unsupported single player transition")
|
||||
}
|
||||
var out []byte
|
||||
switch f {
|
||||
case "Sichuan":
|
||||
out, err = s.endSichuan(ctx, req, a, st, key)
|
||||
case "Hopscotch":
|
||||
out, err = s.endHopscotch(ctx, req, a, st, key)
|
||||
case "PackMan":
|
||||
out, err = s.endPackMan(ctx, req, a, st, key)
|
||||
case "Rhythm":
|
||||
out, err = s.endRhythm(ctx, req, a, st, key)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
delete(st.Runs, f)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Service) sichuanStage(group, id uint64) ([]byte, error) {
|
||||
for _, row := range s.design.Rows("SichuanEventTable", 1, group) {
|
||||
if num(row, 2) == id {
|
||||
return s.design.Row("SichuanStageTable", 2, num(row, 3))
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("eventplay: Sichuan event level missing")
|
||||
}
|
||||
|
||||
func (s *Service) sichuanActive(st *snapshot, uid, group, id uint64) bool {
|
||||
if group == 2 {
|
||||
return true
|
||||
}
|
||||
if group != 1 {
|
||||
return false
|
||||
}
|
||||
for _, row := range s.design.Rows("SichuanEventTable", 1, group) {
|
||||
stage := num(row, 2)
|
||||
if stage < id && !st.Records[recKey(uid, stage, group, "Sichuan")].Clears["clear"] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Service) sichuanInfo(st *snapshot, uid uint64) []byte {
|
||||
out := wire.AppendVarint(nil, 1, uid)
|
||||
best := float64(0)
|
||||
for _, row := range s.design.Tables["SichuanEventTable"] {
|
||||
group, id := num(row, 1), num(row, 2)
|
||||
r := st.Records[recKey(uid, id, group, "Sichuan")]
|
||||
v := wire.AppendVarint(nil, 1, group)
|
||||
v = wire.AppendVarint(v, 2, id)
|
||||
for i := range 3 {
|
||||
if r.Clears[fmt.Sprintf("star:%d", i)] {
|
||||
v = wire.AppendVarint(v, 3, uint64(i))
|
||||
}
|
||||
}
|
||||
out = wire.AppendBytes(out, 2, v)
|
||||
v = wire.AppendVarint(nil, 1, group)
|
||||
v = wire.AppendVarint(v, 2, id)
|
||||
v = wire.AppendVarint(v, 3, 1)
|
||||
out = wire.AppendBytes(out, 8, v)
|
||||
if group == 2 && r.BestScore > 0 && (best == 0 || r.BestScore < best) {
|
||||
best = r.BestScore
|
||||
}
|
||||
}
|
||||
out = wire.AppendDouble(out, 6, best)
|
||||
ledger := st.Records[recKey(uid, 0, 0, "Sichuan")]
|
||||
for _, row := range s.design.Tables["SichuanRewardTable"] {
|
||||
group, id := num(row, 1), num(row, 2)
|
||||
if ledger.Clears[fmt.Sprintf("reward:%d:%d", group, id)] {
|
||||
v := wire.AppendVarint(nil, 1, group)
|
||||
v = wire.AppendVarint(v, 2, id)
|
||||
out = wire.AppendBytes(out, 7, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) endSichuan(ctx command.Context, req []byte, a Run, st *snapshot, key string) ([]byte, error) {
|
||||
encoded := num(req, 3)
|
||||
if encoded < 7 || (encoded-7)%13 != 0 {
|
||||
return nil, fmt.Errorf("eventplay: invalid Sichuan game checksum")
|
||||
}
|
||||
score := (encoded - 7) / 13
|
||||
if score%11 != num(req, 4) || score > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("eventplay: Sichuan checksum mismatch")
|
||||
}
|
||||
row, err := s.sichuanStage(a.Mode, a.Stage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := playRecord(st, a.UID, a.Game, a.Stage, a.Mode, a.Family)
|
||||
clear := num(req, 2) == 0 && num(req, 6) == 0
|
||||
if clear {
|
||||
limits, err := list(row, 3)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(limits) == 0 || score == 0 || score > limits[0] {
|
||||
return nil, fmt.Errorf("eventplay: Sichuan clear time outside limit")
|
||||
}
|
||||
remaining := map[uint64]uint64{}
|
||||
_ = wire.Walk(a.Blocks, func(f wire.Field) error { remaining[num(f.Value, 1)] = num(f.Value, 2); return nil })
|
||||
turn := uint64(0)
|
||||
err = wire.Walk(req, func(f wire.Field) error {
|
||||
if f.Number != 5 {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
if n := num(f.Value, 1); n <= turn {
|
||||
return fmt.Errorf("eventplay: Sichuan turn order invalid")
|
||||
} else {
|
||||
turn = n
|
||||
}
|
||||
ids, e := list(f.Value, 2)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if len(ids) != 2 || ids[0] != ids[1] || remaining[ids[0]] < 2 {
|
||||
return fmt.Errorf("eventplay: Sichuan turn differs from starting inventory")
|
||||
}
|
||||
remaining[ids[0]] -= 2
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, count := range remaining {
|
||||
if count != 0 {
|
||||
return nil, fmt.Errorf("eventplay: Sichuan board not cleared")
|
||||
}
|
||||
}
|
||||
r.Clears["clear"] = true
|
||||
for i, limit := range limits {
|
||||
if score <= limit {
|
||||
r.Clears[fmt.Sprintf("star:%d", i)] = true
|
||||
}
|
||||
}
|
||||
if r.BestScore == 0 || float64(score) < r.BestScore {
|
||||
r.Best = score
|
||||
r.BestScore = float64(score)
|
||||
r.AchievedAt = uint64(s.now().UnixMilli())
|
||||
}
|
||||
}
|
||||
st.Records[recKey(a.UID, a.Stage, a.Mode, a.Family)] = r
|
||||
ledger := playRecord(st, a.UID, a.Game, 0, 0, a.Family)
|
||||
var rewards []gamedata.BattleReward
|
||||
for _, reward := range s.design.Tables["SichuanRewardTable"] {
|
||||
group, id := num(reward, 1), num(reward, 2)
|
||||
count := uint64(0)
|
||||
for _, progress := range st.Records {
|
||||
if progress.UID != a.UID || progress.Family != a.Family || progress.Mode != group {
|
||||
continue
|
||||
}
|
||||
if group == 2 {
|
||||
if progress.Clears["clear"] {
|
||||
count++
|
||||
}
|
||||
} else {
|
||||
for i := range 3 {
|
||||
if progress.Clears[fmt.Sprintf("star:%d", i)] {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
identity := fmt.Sprintf("reward:%d:%d", group, id)
|
||||
if count < num(reward, 3) || ledger.Clears[identity] {
|
||||
continue
|
||||
}
|
||||
rr, e := gamedata.EventPlayRewards(reward, 6, 5, 4)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
rewards = append(rewards, rr...)
|
||||
ledger.Clears[identity] = true
|
||||
}
|
||||
st.Records[recKey(a.UID, 0, 0, a.Family)] = ledger
|
||||
var out []byte
|
||||
if len(rewards) > 0 {
|
||||
bundle, e := s.grant(ctx, "eventplay:"+key, rewards)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = wire.AppendBytes(out, 1, bundle)
|
||||
}
|
||||
if num(req, 6) > 0 {
|
||||
out = wire.AppendVarint(out, 5, 1)
|
||||
}
|
||||
world, e := s.arcadeWorldBest(ctx, a.UID, st, 2, 3, 4)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, world...)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func boolWire(value bool) uint64 {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (s *Service) hopscotchInfo(st *snapshot, uid uint64) []byte {
|
||||
ledger := st.Records[recKey(uid, 0, 0, "Hopscotch")]
|
||||
var out []byte
|
||||
for _, row := range s.design.Tables["HopscotchGalleryTable"] {
|
||||
id := num(row, 4)
|
||||
if ledger.Clears[fmt.Sprintf("gallery:%d", id)] {
|
||||
out = wire.AppendVarint(out, 1, id)
|
||||
}
|
||||
}
|
||||
for _, row := range s.design.Tables["HopscotchStageTable"] {
|
||||
id := num(row, 6)
|
||||
r := st.Records[recKey(uid, id, 0, "Hopscotch")]
|
||||
v := wire.AppendVarint(nil, 1, id)
|
||||
v = wire.AppendVarint(v, 2, boolWire(r.Clears["clear"]))
|
||||
out = wire.AppendBytes(out, 2, v)
|
||||
}
|
||||
for _, row := range s.design.Tables["HopscotchRewardTable"] {
|
||||
id := num(row, 3)
|
||||
if ledger.Clears[fmt.Sprintf("reward:%d", id)] {
|
||||
out = wire.AppendVarint(out, 3, id)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) endHopscotch(ctx command.Context, req []byte, a Run, st *snapshot, key string) ([]byte, error) {
|
||||
if len(s.design.Tables["HopscotchDefaultTable"]) == 0 {
|
||||
return nil, fmt.Errorf("eventplay: Hopscotch default missing")
|
||||
}
|
||||
d := s.design.Tables["HopscotchDefaultTable"][0]
|
||||
area, elapsed := num(req, 2), num(req, 3)
|
||||
if area > 100 || elapsed > math.MaxInt32 || elapsed > num(d, 9)*1000 {
|
||||
return nil, fmt.Errorf("eventplay: invalid Hopscotch result")
|
||||
}
|
||||
row, err := s.design.Row("HopscotchStageTable", 6, a.Stage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := playRecord(st, a.UID, a.Game, a.Stage, 0, a.Family)
|
||||
clear := area >= num(d, 4)
|
||||
r.Clears["play"] = true
|
||||
if clear {
|
||||
r.Clears["clear"] = true
|
||||
}
|
||||
if clear && elapsed > 0 && (r.ClearTime == 0 || elapsed < r.ClearTime) {
|
||||
r.CapturedArea, r.ClearTime, r.Best = area, elapsed, area
|
||||
r.AchievedAt = uint64(s.now().UnixMilli())
|
||||
}
|
||||
if num(req, 4) == 0 && clear {
|
||||
r.Clears["no-continue"] = true
|
||||
}
|
||||
if area == 100 {
|
||||
r.Clears["full"] = true
|
||||
}
|
||||
st.Records[recKey(a.UID, a.Stage, 0, a.Family)] = r
|
||||
ledger := playRecord(st, a.UID, a.Game, 0, 0, a.Family)
|
||||
var out []byte
|
||||
gallery := func(id uint64) {
|
||||
if id > 0 && !ledger.Clears[fmt.Sprintf("gallery:%d", id)] {
|
||||
ledger.Clears[fmt.Sprintf("gallery:%d", id)] = true
|
||||
out = wire.AppendVarint(out, 1, id)
|
||||
}
|
||||
}
|
||||
gallery(num(row, 2))
|
||||
if clear {
|
||||
gallery(num(row, 1))
|
||||
}
|
||||
allPlayed, allCleared := true, true
|
||||
for _, stage := range s.design.Tables["HopscotchStageTable"] {
|
||||
p := st.Records[recKey(a.UID, num(stage, 6), 0, a.Family)]
|
||||
allPlayed = allPlayed && p.Clears["play"]
|
||||
allCleared = allCleared && p.Clears["clear"]
|
||||
}
|
||||
if allPlayed {
|
||||
gallery(num(d, 2))
|
||||
}
|
||||
if allCleared {
|
||||
gallery(num(d, 1))
|
||||
}
|
||||
var rewards []gamedata.BattleReward
|
||||
for _, reward := range s.design.Tables["HopscotchRewardTable"] {
|
||||
id, sub := num(reward, 3), num(reward, 1)
|
||||
p := st.Records[recKey(a.UID, sub, 0, a.Family)]
|
||||
earned := false
|
||||
switch num(reward, 2) {
|
||||
case 1:
|
||||
earned = p.Clears["play"]
|
||||
case 2:
|
||||
earned = p.Clears["clear"]
|
||||
case 3:
|
||||
earned = allPlayed
|
||||
case 4:
|
||||
earned = allCleared
|
||||
case 5:
|
||||
for _, p := range st.Records {
|
||||
if p.UID == a.UID && p.Family == a.Family && p.Clears["no-continue"] {
|
||||
earned = true
|
||||
}
|
||||
}
|
||||
case 6:
|
||||
earned = p.Clears["full"]
|
||||
}
|
||||
identity := fmt.Sprintf("reward:%d", id)
|
||||
if !earned || ledger.Clears[identity] {
|
||||
continue
|
||||
}
|
||||
rr, e := gamedata.EventPlayRewards(reward, 7, 6, 4)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
for _, v := range rr {
|
||||
if v.Type > 0 && v.Count > 0 {
|
||||
rewards = append(rewards, v)
|
||||
}
|
||||
}
|
||||
ledger.Clears[identity] = true
|
||||
out = wire.AppendVarint(out, 3, id)
|
||||
}
|
||||
v := wire.AppendVarint(nil, 1, a.Stage)
|
||||
v = wire.AppendVarint(v, 2, boolWire(r.Clears["clear"]))
|
||||
out = wire.AppendBytes(out, 2, v)
|
||||
if len(rewards) > 0 {
|
||||
bundle, e := s.grant(ctx, "eventplay:"+key, rewards)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = wire.AppendBytes(out, 4, bundle)
|
||||
}
|
||||
st.Records[recKey(a.UID, 0, 0, a.Family)] = ledger
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func rhythmRecordWire(r record) []byte {
|
||||
v := wire.AppendVarint(nil, 1, r.Stage)
|
||||
v = wire.AppendVarint(v, 2, r.Mode)
|
||||
v = wire.AppendVarint(v, 3, r.Best)
|
||||
v = wire.AppendVarint(v, 4, r.BestGrade)
|
||||
return wire.AppendVarint(v, 5, r.BestCombo)
|
||||
}
|
||||
|
||||
func (s *Service) endRhythm(ctx command.Context, req []byte, a Run, st *snapshot, key string) ([]byte, error) {
|
||||
score, err := s.endScore("Rhythm", req, a)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
grade, combo := num(req, 2), num(req, 6)
|
||||
if grade > 6 || combo > 2 {
|
||||
return nil, fmt.Errorf("eventplay: invalid rhythm grade/combo")
|
||||
}
|
||||
counts := map[uint64]uint64{}
|
||||
err = wire.Walk(req, func(f wire.Field) error {
|
||||
if f.Number != 3 {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
typ, count := num(f.Value, 1), num(f.Value, 2)
|
||||
if typ < 1 || typ > 4 || counts[typ] != 0 {
|
||||
return fmt.Errorf("eventplay: invalid rhythm judgment")
|
||||
}
|
||||
counts[typ] = count
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if combo > 0 && (num(req, 7) > 0 || counts[4] > 0) || combo == 2 && counts[2]+counts[3] > 0 {
|
||||
return nil, fmt.Errorf("eventplay: rhythm combo contradicts judgments")
|
||||
}
|
||||
if s.arcadeProfile == nil {
|
||||
return nil, fmt.Errorf("eventplay: rhythm account profile unavailable")
|
||||
}
|
||||
profile, err := s.arcadeProfile(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seed := profile.Owner + score + num(req, 1)
|
||||
for typ, count := range counts {
|
||||
seed += typ * count
|
||||
}
|
||||
random := Run{}
|
||||
for i := range random.RandomState {
|
||||
random.RandomState[i] = seed + uint64(i)*90
|
||||
}
|
||||
checksum := fmt.Sprintf("%d-%d-%d-%d", 11111+survivalRandom(&random, 88888), 11111+survivalRandom(&random, 88888), 11111+survivalRandom(&random, 88888), 11111+survivalRandom(&random, 88888))
|
||||
checksumWire, _, err := wire.Bytes(req, 5)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if string(checksumWire) != checksum {
|
||||
return nil, fmt.Errorf("eventplay: rhythm game checksum mismatch")
|
||||
}
|
||||
r := playRecord(st, a.UID, a.Game, a.Stage, a.Mode, a.Family)
|
||||
if score > r.Best {
|
||||
r.Best = score
|
||||
r.AchievedAt = uint64(s.now().UnixMilli())
|
||||
}
|
||||
if grade > 0 && (r.BestGrade == 0 || grade < r.BestGrade) {
|
||||
r.BestGrade = grade
|
||||
}
|
||||
if combo > r.BestCombo {
|
||||
r.BestCombo = combo
|
||||
}
|
||||
st.Records[recKey(a.UID, a.Stage, a.Mode, a.Family)] = r
|
||||
if s.onProgress != nil {
|
||||
for typ, count := range counts {
|
||||
if count == 0 {
|
||||
continue
|
||||
}
|
||||
if err := s.onProgress(ctx, 49, typ, count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, p := range []struct{ condition, value, count uint64 }{{51, a.Stage, score}, {52, grade, 1}, {53, a.Mode, 1}, {50, combo, 1}} {
|
||||
if p.count == 0 {
|
||||
continue
|
||||
}
|
||||
if err := s.onProgress(ctx, p.condition, p.value, p.count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return wire.AppendBytes(nil, 1, rhythmRecordWire(r)), nil
|
||||
}
|
||||
|
||||
func sortedRecordKeys(st *snapshot) []string {
|
||||
keys := make([]string, 0, len(st.Records))
|
||||
for key := range st.Records {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return keys
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/domain/ranking"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testRow(fields ...uint64) []byte {
|
||||
var out []byte
|
||||
for i := 0; i < len(fields); i += 2 {
|
||||
out = wire.AppendVarint(out, int(fields[i]), fields[i+1])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// The small synthetic designs express workflow rules; they are independent of
|
||||
// the installed season's resource identities and table contents.
|
||||
type playHarness struct {
|
||||
service *Service
|
||||
ctx command.Context
|
||||
design *gamedata.EventPlayCatalog
|
||||
registry *events.Registry
|
||||
now time.Time
|
||||
}
|
||||
|
||||
type testEconomy struct{}
|
||||
|
||||
func (testEconomy) Apply(ctx command.Context, identity string, costs, rewards []gamedata.Reward) ([]byte, error) {
|
||||
if _, found, err := ctx.State.LoadEntry("test-wallet", "grants", identity); err != nil {
|
||||
return nil, err
|
||||
} else if found {
|
||||
return nil, fmt.Errorf("duplicate economy identity")
|
||||
}
|
||||
balances := map[uint64]uint64{}
|
||||
raw, _ := ctx.State.Load("test-wallet")
|
||||
if raw != nil {
|
||||
if err := json.Unmarshal(raw, &balances); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, cost := range costs {
|
||||
if balances[cost.Type] < cost.Count {
|
||||
return nil, fmt.Errorf("insufficient balance")
|
||||
}
|
||||
balances[cost.Type] -= cost.Count
|
||||
}
|
||||
for _, reward := range rewards {
|
||||
balances[reward.Type] += reward.Count
|
||||
}
|
||||
raw, _ = json.Marshal(balances)
|
||||
if err := ctx.State.Save("test-wallet", raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.State.PutEntry("test-wallet", "grants", identity, []byte{1}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return testRow(1, uint64(len(rewards))), nil
|
||||
}
|
||||
|
||||
type emptyRankStore struct{}
|
||||
type emptyRankTx struct{}
|
||||
|
||||
func (emptyRankTx) Get(string, string) ([]byte, bool, error) { return nil, false, nil }
|
||||
func (emptyRankTx) Put(string, string, []byte) error { return nil }
|
||||
func (emptyRankTx) Scan(string, string, string, int) ([]ranking.Entry, error) { return nil, nil }
|
||||
func (emptyRankStore) View(_ context.Context, fn func(ranking.Tx) error) error {
|
||||
return fn(emptyRankTx{})
|
||||
}
|
||||
func (emptyRankStore) Update(_ context.Context, fn func(ranking.Tx) error) error {
|
||||
return fn(emptyRankTx{})
|
||||
}
|
||||
|
||||
func newPlayHarness(t *testing.T) *playHarness {
|
||||
t.Helper()
|
||||
h := &playHarness{ctx: command.Context{Identity: command.Identity{AccountID: "player", SessionID: "first-login"}, State: stateio.NewMemory()}, design: &gamedata.EventPlayCatalog{Tables: map[string][][]byte{}}, registry: events.NewRegistry(), now: time.UnixMilli(1000000000)}
|
||||
h.design.Tables["PackEventMiniGameTable"] = [][]byte{testRow(8, 10, 3, 5, 4, 1), testRow(8, 20, 3, 6), testRow(8, 30, 3, 12), testRow(8, 40, 3, 13), testRow(8, 50, 3, 9)}
|
||||
var schedules []events.Schedule
|
||||
for _, id := range []uint64{10, 20, 30, 40, 50} {
|
||||
schedules = append(schedules, events.Schedule{UID: id + 100, Type: 11, ID: id, Start: h.now.UnixMilli() - 1000, End: h.now.UnixMilli() + 86400000})
|
||||
}
|
||||
if err := h.registry.Replace(schedules); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.design.Tables["FieldMiniGameSurvivalTable"] = [][]byte{testRow(9, 1, 7, 1, 15, 1, 21, 2, 24, 30, 10, 500)}
|
||||
h.design.Tables["FieldMiniGameCharTable"] = [][]byte{wire.AppendDouble(wire.AppendDouble(testRow(11, 1, 13, 1, 20, 100, 19, 2, 3, 1, 2, 1), 8, 1), 10, 1)}
|
||||
h.design.Tables["FieldMiniGameMapGroupTable"] = [][]byte{testRow(1, 1, 2, 1)}
|
||||
h.design.Tables["FieldMiniGameMapTable"] = [][]byte{testRow(2, 1, 3, 1, 4, 1, 9, 1, 6, 50, 8, 43)}
|
||||
h.design.Tables["FieldMiniGameMonsterTable"] = [][]byte{testRow(2, 1, 5, 1, 12, 2, 14, 10, 11, 1, 6, 1)}
|
||||
h.design.Tables["FieldMiniGameSurvivalBoxTable"] = [][]byte{testRow(2, 1, 3, 11, 3, 12)}
|
||||
h.design.Tables["FieldMiniGameSurvivalItemTable"] = [][]byte{testRow(1, 11, 3, 3, 4, 10, 6, 100), testRow(1, 12, 3, 4, 4, 5, 6, 100)}
|
||||
h.design.Tables["FieldMiniGameSkillGroupTable"] = [][]byte{testRow(1, 1, 2, 3, 5, 1, 7, 1), testRow(1, 2, 2, 2, 5, 2), testRow(1, 3, 2, 2, 5, 1, 7, 2)}
|
||||
h.design.Tables["FieldMiniGameSkillTable"] = [][]byte{testRow(7, 1, 8, 1), testRow(7, 1, 8, 2), testRow(7, 1, 8, 3), testRow(7, 2, 8, 1), testRow(7, 2, 8, 2)}
|
||||
h.design.Tables["FieldMiniGameCharLevelTable"] = [][]byte{testRow(1, 1, 2, 1, 3, 10), testRow(1, 1, 2, 2, 3, 20), testRow(1, 1, 2, 3, 3, 50)}
|
||||
h.design.Tables["FieldMiniGameCollectionTable"] = [][]byte{testRow(1, 1, 3, 5), testRow(1, 3, 3, 6, 7, 2)}
|
||||
h.design.Tables["FieldMiniGameUpgradeGroupTable"] = [][]byte{testRow(1, 9, 2, 1)}
|
||||
h.design.Tables["FieldMiniGameUpgradeTable"] = [][]byte{testRow(1, 9, 2, 1), wire.AppendDouble(testRow(1, 9, 2, 2, 3, 10), 4, 20)}
|
||||
h.reopen(t)
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *playHarness) reopen(t *testing.T) {
|
||||
t.Helper()
|
||||
s, err := Open(h.ctx, stateio.RootStore{}, h.design, func(uint64) (*gamedata.EventField, error) { return nil, fmt.Errorf("fixture has no field game") }, h.registry, testEconomy{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.now = func() time.Time { return h.now }
|
||||
s.actionMissionCharacters = map[uint64]uint64{6: 1, 7: 2, 8: 3}
|
||||
ranks, err := ranking.NewArcade(context.Background(), emptyRankStore{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.AttachArcadeRankings(ranks, func(command.Context) (ranking.ArcadeProfile, error) {
|
||||
return ranking.ArcadeProfile{Owner: 7, Name: "player"}, nil
|
||||
})
|
||||
h.service = s
|
||||
}
|
||||
func (h *playHarness) call(t *testing.T, path string, req []byte) []byte {
|
||||
t.Helper()
|
||||
_, out, handled, err := h.service.Handle(h.ctx, path, req)
|
||||
if err != nil || !handled {
|
||||
t.Fatalf("%s failed: %v", path, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func (h *playHarness) reject(t *testing.T, path string, req []byte) {
|
||||
t.Helper()
|
||||
before, _ := h.ctx.State.Load("eventplay")
|
||||
_, _, _, err := h.service.Handle(h.ctx, path, req)
|
||||
if err == nil {
|
||||
t.Fatalf("%s accepted invalid transition", path)
|
||||
}
|
||||
after, _ := h.ctx.State.Load("eventplay")
|
||||
if !bytes.Equal(before, after) {
|
||||
t.Fatalf("%s persisted failed transition", path)
|
||||
}
|
||||
}
|
||||
func (h *playHarness) balance(t *testing.T, typ uint64) uint64 {
|
||||
t.Helper()
|
||||
raw, err := h.ctx.State.Load("test-wallet")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var values map[uint64]uint64
|
||||
if raw != nil {
|
||||
if err := json.Unmarshal(raw, &values); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return values[typ]
|
||||
}
|
||||
|
||||
func TestSurvivalReconnectionProgressRewardAndUpgradeReset(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
start := testRow(1, 1, 2, 110, 3, 1, 4, 1, 5, 1)
|
||||
first := h.call(t, "/MiniGameSurvivalStart", start)
|
||||
h.reopen(t)
|
||||
if !bytes.Equal(first, h.call(t, "/MiniGameSurvivalStart", start)) {
|
||||
t.Fatal("start retry changed persisted seed")
|
||||
}
|
||||
h.ctx.SessionID = "reconnected"
|
||||
h.now = h.now.Add(time.Second)
|
||||
play := testRow(1, 2, 2, 100, 3, 10, 4, 5, 7, 1)
|
||||
play = wire.AppendBytes(play, 6, testRow(1, 1, 2, 1))
|
||||
play = wire.AppendBytes(play, 5, testRow(1, 11, 2, 1))
|
||||
play = wire.AppendBytes(play, 5, testRow(1, 12, 2, 1))
|
||||
h.call(t, "/MiniGameSurvivalPlay", play)
|
||||
h.reject(t, "/MiniGameSurvivalPlay", wire.AppendBytes(testRow(1, 3, 2, 100, 4, 5), 5, testRow(1, 12, 2, 1)))
|
||||
offers := h.call(t, "/MiniGameSurvivalSkillSelectList", testRow(1, 4))
|
||||
ids, _ := list(offers, 2)
|
||||
for _, id := range ids {
|
||||
if id == 3 {
|
||||
t.Fatal("other character's unique weapon was offered")
|
||||
}
|
||||
}
|
||||
h.call(t, "/MiniGameSurvivalSkillUp", testRow(1, 5, 2, ids[0]))
|
||||
end := testRow(1, 6, 3, 1, 4, 1, 5, 5, 6, 10)
|
||||
result := h.call(t, "/MiniGameSurvivalEnd", end)
|
||||
if h.balance(t, 43) != 55 {
|
||||
t.Fatal("first clear and collected coins were not credited")
|
||||
}
|
||||
h.reopen(t)
|
||||
if !bytes.Equal(result, h.call(t, "/MiniGameSurvivalEnd", end)) || h.balance(t, 43) != 55 {
|
||||
t.Fatal("persisted End retry duplicated rewards")
|
||||
}
|
||||
h.reject(t, "/MiniGameSurvivalEnd", testRow(1, 7, 3, 1))
|
||||
h.call(t, "/MiniGameSurvivalCharUpgrade", testRow(1, 8, 2, 9, 3, 2))
|
||||
if h.balance(t, 43) != 45 {
|
||||
t.Fatal("upgrade did not consume currency")
|
||||
}
|
||||
h.call(t, "/MiniGameSurvivalStart", testRow(1, 9, 2, 110, 3, 1, 4, 1, 5, 1))
|
||||
if h.service.state.Runs["Survival"].HP != 120 {
|
||||
t.Fatal("permanent HP upgrade was not applied to new run")
|
||||
}
|
||||
h.call(t, "/MiniGameSurvivalEnd", testRow(1, 10, 2, 1))
|
||||
h.call(t, "/MiniGameSurvivalCharUpgradeReset", testRow(1, 11))
|
||||
if h.balance(t, 43) != 55 {
|
||||
t.Fatal("reset did not refund actual upgrade cost")
|
||||
}
|
||||
h.reopen(t)
|
||||
info := h.call(t, "/MiniGameSurvivalInfo", testRow(1, 12))
|
||||
|
||||
var collections int
|
||||
_ = wire.Walk(info, func(f wire.Field) error {
|
||||
if f.Number == 9 {
|
||||
collections++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if collections != 2 {
|
||||
t.Fatal("collected weapon/item entries were not persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSurvivalWeightedDropsCannotBeCollectedTwiceOrRerolledByRetry(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["FieldMiniGameSurvivalBoxTable"] = [][]byte{testRow(1, 1, 2, 1, 3, 11, 3, 12, 4, 3, 4, 1)}
|
||||
h.call(t, "/MiniGameSurvivalStart", testRow(1, 1, 2, 110, 3, 1, 4, 1, 5, 1))
|
||||
h.now = h.now.Add(time.Second)
|
||||
// A separately evaluated current-client Well512 vector for seed 1,000,000,000
|
||||
// draws 1 modulo 4, selecting the first weighted item and excluding the coin.
|
||||
bad := wire.AppendBytes(wire.AppendBytes(testRow(1, 2, 2, 100, 4, 5, 7, 1), 6, testRow(1, 1, 2, 1)), 5, testRow(1, 12, 2, 1))
|
||||
h.reject(t, "/MiniGameSurvivalPlay", bad)
|
||||
good := wire.AppendBytes(wire.AppendBytes(testRow(1, 2, 2, 100, 3, 10, 7, 1), 6, testRow(1, 1, 2, 1)), 5, testRow(1, 11, 2, 1))
|
||||
out := h.call(t, "/MiniGameSurvivalPlay", good)
|
||||
h.reopen(t)
|
||||
if !bytes.Equal(out, h.call(t, "/MiniGameSurvivalPlay", good)) {
|
||||
t.Fatal("drop retry advanced random state")
|
||||
}
|
||||
h.reject(t, "/MiniGameSurvivalPlay", wire.AppendBytes(testRow(1, 3, 2, 100, 3, 10), 5, testRow(1, 11, 2, 1)))
|
||||
h.call(t, "/MiniGameSurvivalEnd", testRow(1, 4, 2, 1, 3, 1, 4, 1, 6, 10))
|
||||
if h.balance(t, 43) != 0 {
|
||||
t.Fatal("an unselected drop granted currency")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSurvivalInsufficientUpgradePreservesStateAndResources(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.call(t, "/MiniGameSurvivalInfo", testRow(1, 1))
|
||||
h.reject(t, "/MiniGameSurvivalCharUpgrade", testRow(1, 2, 2, 9, 3, 2))
|
||||
h.reopen(t)
|
||||
if h.balance(t, 43) != 0 || len(h.service.state.Upgrades) != 0 {
|
||||
t.Fatal("failed upgrade altered persisted resources")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSichuanStarsUnlockAndFirstClearRewardsSurviveLogin(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["SichuanEventTable"] = [][]byte{testRow(1, 1, 2, 1, 3, 9), testRow(1, 1, 2, 2, 3, 9), testRow(1, 2, 2, 1, 3, 9)}
|
||||
h.design.Tables["SichuanStageTable"] = [][]byte{testRow(2, 9, 8, 6, 3, 300, 3, 200, 3, 100)}
|
||||
h.design.Tables["SichuanRewardTable"] = [][]byte{testRow(1, 1, 2, 1, 3, 3, 4, 2, 5, 1, 6, 27), testRow(1, 2, 2, 1, 3, 1, 4, 1, 5, 2, 6, 27)}
|
||||
start := func(seq, group, stage uint64) []byte {
|
||||
return wire.AppendBytes(testRow(1, seq, 2, 120, 3, group, 4, stage), 5, testRow(1, 1001, 2, 4))
|
||||
}
|
||||
end := func(seq, score uint64) []byte {
|
||||
out := testRow(1, seq, 3, score*13+7, 4, score%11)
|
||||
for i := uint64(1); i <= 2; i++ {
|
||||
out = wire.AppendBytes(out, 5, testRow(1, i, 2, 1001, 2, 1001))
|
||||
}
|
||||
return out
|
||||
}
|
||||
h.reject(t, "/MiniGameSichuanStart", start(1, 1, 2))
|
||||
h.call(t, "/MiniGameSichuanStart", start(2, 1, 1))
|
||||
h.reject(t, "/MiniGameSichuanEnd", testRow(1, 3, 3, 1307, 4, 2))
|
||||
h.call(t, "/MiniGameSichuanEnd", end(4, 90))
|
||||
if h.balance(t, 27) != 2 {
|
||||
t.Fatal("normal accumulated stars did not grant reward")
|
||||
}
|
||||
h.reopen(t)
|
||||
h.ctx.SessionID = "second"
|
||||
h.call(t, "/MiniGameSichuanStart", start(5, 1, 2))
|
||||
h.call(t, "/MiniGameSichuanEnd", end(6, 180))
|
||||
if h.balance(t, 27) != 2 {
|
||||
t.Fatal("normal reward repeated after another level")
|
||||
}
|
||||
h.call(t, "/MiniGameSichuanStart", start(7, 2, 1))
|
||||
response := h.call(t, "/MiniGameSichuanEnd", end(8, 180))
|
||||
if h.balance(t, 27) != 3 {
|
||||
t.Fatal("challenge first clear reward missing")
|
||||
}
|
||||
h.reopen(t)
|
||||
if !bytes.Equal(response, h.call(t, "/MiniGameSichuanEnd", end(8, 180))) || h.balance(t, 27) != 3 {
|
||||
t.Fatal("challenge retry duplicated reward")
|
||||
}
|
||||
h.call(t, "/MiniGameSichuanStart", start(9, 2, 1))
|
||||
h.call(t, "/MiniGameSichuanEnd", end(10, 120))
|
||||
if h.balance(t, 27) != 3 {
|
||||
t.Fatal("improved challenge time repeated furniture reward")
|
||||
}
|
||||
if records := h.service.RankRecords(); len(records) != 1 || records[0].Score != 120 {
|
||||
t.Fatal("challenge did not retain the smaller clear time")
|
||||
}
|
||||
info := h.call(t, "/MiniGameSichuanInfo", testRow(1, 11, 2, 120))
|
||||
schedule, _, _ := wire.Bytes(info, 1)
|
||||
var rewardClaims int
|
||||
_ = wire.Walk(schedule, func(f wire.Field) error {
|
||||
if f.Number == 7 {
|
||||
rewardClaims++
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if rewardClaims != 2 {
|
||||
t.Fatal("claimed star/challenge rewards were not persisted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHopscotchPartialPlayClearFullAndContinueRewardsAreDistinct(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["HopscotchDefaultTable"] = [][]byte{testRow(4, 80, 9, 300, 1, 12, 2, 11)}
|
||||
h.design.Tables["HopscotchStageTable"] = [][]byte{testRow(6, 1, 1, 2, 2, 1), testRow(6, 2, 1, 4, 2, 3)}
|
||||
for _, id := range []uint64{1, 2, 3, 4, 11, 12} {
|
||||
h.design.Tables["HopscotchGalleryTable"] = append(h.design.Tables["HopscotchGalleryTable"], testRow(4, id))
|
||||
}
|
||||
for _, v := range [][3]uint64{{1, 1, 1}, {2, 2, 1}, {3, 6, 1}, {4, 5, 0}, {5, 3, 0}, {6, 4, 0}} {
|
||||
h.design.Tables["HopscotchRewardTable"] = append(h.design.Tables["HopscotchRewardTable"], testRow(3, v[0], 2, v[1], 1, v[2], 7, 25, 6, v[0], 4, 1))
|
||||
}
|
||||
play := func(startSeq, endSeq, stage, area, elapsed, continued uint64) {
|
||||
t.Helper()
|
||||
h.call(t, "/MiniGameHopscotchGameStart", testRow(1, startSeq, 2, 130, 3, stage))
|
||||
h.call(t, "/MiniGameHopscotchGameEnd", testRow(1, endSeq, 2, area, 3, elapsed, 4, continued))
|
||||
}
|
||||
play(1, 2, 1, 40, 5000, 0)
|
||||
if h.balance(t, 25) != 1 || len(h.service.RankRecords()) != 0 {
|
||||
t.Fatal("partial play earned a clear reward or ranked")
|
||||
}
|
||||
play(3, 4, 1, 85, 4000, 1)
|
||||
if h.balance(t, 25) != 2 {
|
||||
t.Fatal("continued clear did not earn only clear reward")
|
||||
}
|
||||
play(5, 6, 1, 100, 3000, 0)
|
||||
if h.balance(t, 25) != 4 {
|
||||
t.Fatal("full completion and any-stage no-continue rewards missing")
|
||||
}
|
||||
h.reopen(t)
|
||||
h.ctx.SessionID = "second"
|
||||
play(7, 8, 1, 100, 4500, 0)
|
||||
if h.balance(t, 25) != 4 {
|
||||
t.Fatal("repeated clear duplicated rewards")
|
||||
}
|
||||
records := h.service.RankRecords()
|
||||
if len(records) != 1 || records[0].ClearTime != 3000 {
|
||||
t.Fatal("slower full clear replaced best time")
|
||||
}
|
||||
play(9, 10, 2, 85, 4000, 1)
|
||||
if h.balance(t, 25) != 6 {
|
||||
t.Fatal("all-stage play/clear rewards missing")
|
||||
}
|
||||
info := h.call(t, "/MiniGameHopscotchInfo", testRow(1, 11, 2, 130))
|
||||
galleries, _ := list(info, 1)
|
||||
if len(galleries) != 6 {
|
||||
t.Fatal("stage and all-stage galleries missing after replay")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPackManCommitsStagesAndChecksScoreAcrossLogin(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["PackManDefaultTable"] = [][]byte{testRow(15, 1)}
|
||||
h.design.Tables["PackManModeTable"] = [][]byte{testRow(2, 1, 5, 1, 4, 1), testRow(2, 1, 5, 2, 4, 2)}
|
||||
h.design.Tables["PackManModeRuleTable"] = [][]byte{testRow(2, 1, 4, 2), testRow(2, 2, 8, 2000, 6, 1000)}
|
||||
for i, unit := range []uint64{1, 1, 10, 20, 1, 20} {
|
||||
h.design.Tables["PackManScoreTable"] = append(h.design.Tables["PackManScoreTable"], testRow(1, uint64(i+1), 2, unit))
|
||||
}
|
||||
history := func(seconds, coins, chain, escapes uint64) []byte {
|
||||
return wire.AppendBytes(testRow(1, seconds, 2, coins, 5, chain, 6, escapes), 7, testRow(1, 1, 2, 1, 3, 1, 4, seconds*1000))
|
||||
}
|
||||
h.call(t, "/MiniGamePackManStart", testRow(1, 1, 2, 140, 3, 1))
|
||||
h.now = h.now.Add(time.Second)
|
||||
h.reject(t, "/MiniGamePackManStageClear", wire.AppendBytes(testRow(1, 2, 2, 2), 3, history(1, 1, 0, 1)))
|
||||
stage := wire.AppendBytes(testRow(1, 3, 2, 1), 3, history(1, 1, 0, 1))
|
||||
h.call(t, "/MiniGamePackManStageClear", stage)
|
||||
h.reopen(t)
|
||||
h.ctx.SessionID = "second"
|
||||
h.now = h.now.Add(time.Second)
|
||||
end := wire.AppendBytes(testRow(1, 4, 2, 3), 4, history(2, 2, 0, 1))
|
||||
h.call(t, "/MiniGamePackManEnd", end)
|
||||
h.call(t, "/MiniGamePackManStart", testRow(1, 5, 2, 140, 3, 2))
|
||||
h.now = h.now.Add(time.Second)
|
||||
h.call(t, "/MiniGamePackManStageClear", wire.AppendBytes(testRow(1, 6, 2, 1), 3, history(1, 1, 1, 1)))
|
||||
h.now = h.now.Add(2 * time.Second)
|
||||
end = wire.AppendBytes(testRow(1, 7, 2, 2, 5, 999), 4, history(3, 2, 2, 1))
|
||||
h.reject(t, "/MiniGamePackManEnd", end)
|
||||
end = wire.AppendBytes(testRow(1, 8, 2, 2, 5, 27), 4, history(3, 2, 2, 1))
|
||||
response := h.call(t, "/MiniGamePackManEnd", end)
|
||||
if num(response, 1) != 1 {
|
||||
t.Fatal("challenge result did not report new record")
|
||||
}
|
||||
h.reopen(t)
|
||||
if !bytes.Equal(response, h.call(t, "/MiniGamePackManEnd", end)) {
|
||||
t.Fatal("PackMan end retry changed new-record result")
|
||||
}
|
||||
info := h.call(t, "/MiniGamePackManInfo", testRow(1, 9, 2, 140))
|
||||
if num(info, 1) != 27 {
|
||||
t.Fatal("PackMan challenge best did not survive login")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRhythmModeRecordsAndClientChecksumPersistIndependently(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["RhythmGameMusicTable"] = [][]byte{testRow(5, 1, 8, 1000, 2, 1000, 1, 1000, 10, 2, 4, 2)}
|
||||
h.design.Tables["RhythmGameCharTable"] = [][]byte{testRow(2, 1)}
|
||||
end := func(seq, score, grade, combo uint64, checksum string, judgments ...[]byte) []byte {
|
||||
out := wire.AppendString(testRow(1, seq, 2, grade, 4, score, 6, combo), 5, checksum)
|
||||
for _, judgment := range judgments {
|
||||
out = wire.AppendBytes(out, 3, judgment)
|
||||
}
|
||||
return out
|
||||
}
|
||||
h.call(t, "/MiniGameRhythmPlayStart", testRow(1, 1, 2, 150, 3, 1, 4, 1, 5, 1))
|
||||
h.reject(t, "/MiniGameRhythmPlayEnd", end(2, 500, 1, 2, "invalid", testRow(1, 1, 2, 2)))
|
||||
// Checksums independently evaluated from the client's Well512 game-id recipe.
|
||||
first := end(2, 500, 1, 2, "46791-73263-83023-36775", testRow(1, 1, 2, 2))
|
||||
response := h.call(t, "/MiniGameRhythmPlayEnd", first)
|
||||
h.reopen(t)
|
||||
if !bytes.Equal(response, h.call(t, "/MiniGameRhythmPlayEnd", first)) {
|
||||
t.Fatal("rhythm retry changed persisted result")
|
||||
}
|
||||
h.call(t, "/MiniGameRhythmPlayStart", testRow(1, 3, 2, 150, 3, 1, 4, 1, 5, 2))
|
||||
h.call(t, "/MiniGameRhythmPlayEnd", end(4, 700, 2, 1, "74755-20195-46291-30923", testRow(1, 1, 2, 1), testRow(1, 2, 2, 1)))
|
||||
h.call(t, "/MiniGameRhythmPlayStart", testRow(1, 5, 2, 150, 3, 1, 4, 1, 5, 0))
|
||||
h.call(t, "/MiniGameRhythmPlayEnd", end(6, 800, 1, 2, "82423-77223-39783-63487", testRow(1, 1, 2, 2)))
|
||||
h.reopen(t)
|
||||
records := h.service.RankRecords()
|
||||
if len(records) != 2 {
|
||||
t.Fatal("normal rhythm ranked or separate difficulties collapsed")
|
||||
}
|
||||
modes := map[uint64]float64{}
|
||||
for _, r := range records {
|
||||
if _, exists := modes[r.Mode]; exists {
|
||||
t.Fatal("duplicate ranked rhythm difficulty")
|
||||
}
|
||||
modes[r.Mode] = r.Score
|
||||
}
|
||||
if len(modes) != 2 || modes[1] != 500 || modes[2] != 700 {
|
||||
t.Fatalf("ranked rhythm difficulties differ: %v", modes)
|
||||
}
|
||||
info := h.call(t, "/MiniGameRhythmInfo", testRow(1, 7, 2, 150))
|
||||
best := map[uint64]uint64{}
|
||||
_ = wire.Walk(info, func(f wire.Field) error {
|
||||
if f.Number == 1 {
|
||||
best[num(f.Value, 2)] = num(f.Value, 3)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if best[0] != 800 || best[1] != 500 || best[2] != 700 {
|
||||
t.Fatal("rhythm info lost per-mode records")
|
||||
}
|
||||
}
|
||||
|
||||
type retainedActionRoom struct {
|
||||
run NativeRun
|
||||
result NativeResult
|
||||
}
|
||||
|
||||
func (r *retainedActionRoom) StartRun(command.Context, string) (NativeRun, error) { return r.run, nil }
|
||||
func (r *retainedActionRoom) Result(command.Context, NativeRun) (NativeResult, error) {
|
||||
return r.result, nil
|
||||
}
|
||||
|
||||
func TestNativeActionMissionsUseRoomClearAndGrantOnlyOnce(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.ctx.Emit = func(command.Event) error { return nil }
|
||||
h.design.Tables["PackEventMiniGameTable"] = append(h.design.Tables["PackEventMiniGameTable"], testRow(8, 60, 3, 8, 4, 1))
|
||||
if err := h.registry.Replace(append(h.registry.List(), events.Schedule{UID: 160, Type: 11, ID: 60, Start: h.now.UnixMilli() - 1000, End: h.now.UnixMilli() + 86400000})); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h.design.Tables["ActionGameDefaultTable"] = [][]byte{testRow(1, 1)}
|
||||
h.design.Tables["ActionGameStageTable"] = [][]byte{testRow(3, 1, 4, 1, 1, 101, 11, 1)}
|
||||
h.design.Tables["ActionGameCharTable"] = [][]byte{testRow(14, 101, 16, 1)}
|
||||
h.design.Tables["ActionGameMissionTable"] = [][]byte{testRow(4, 1, 3, 1, 1, 101, 7, 1, 8, 1, 9, 99, 10, 27), testRow(4, 2, 3, 2, 1, 3, 2, 101, 7, 1, 8, 2, 9, 98, 10, 27), testRow(4, 3, 3, 3, 1, 2, 2, 101, 7, 1), testRow(4, 4, 3, 11, 1, 101, 7, 1), testRow(4, 5, 3, 6, 1, 2, 2, 101, 7, 1, 8, 1, 9, 97, 10, 27)}
|
||||
room := &retainedActionRoom{run: NativeRun{UID: 160, Family: "Action", Group: 1, Stage: 1, Monster: 101, InstanceID: "first-room", GUID: "first-guid", Started: h.now.UnixMilli()}, result: NativeResult{Clear: false, Score: 2000, Evidence: wire.AppendBytes(nil, 2, testRow(1, 7, 2, 2))}}
|
||||
h.service.AttachRooms(room)
|
||||
end := func(seq uint64) []byte {
|
||||
return wire.AppendString(testRow(1, seq, 3, 1, 4, 1, 6, 101, 7, 999999, 22, 1, 8, 1, 11, 2), 2, room.run.GUID)
|
||||
}
|
||||
h.call(t, "/MiniGameActionStart", testRow(1, 1))
|
||||
h.call(t, "/MiniGameActionEnd", end(2))
|
||||
if h.balance(t, 27) != 0 {
|
||||
t.Fatal("submitted clear granted mission after authoritative room failure")
|
||||
}
|
||||
room.run.InstanceID, room.run.GUID = "second-room", "second-guid"
|
||||
room.result.Clear = true
|
||||
h.call(t, "/MiniGameActionStart", testRow(1, 3))
|
||||
response := h.call(t, "/MiniGameActionEnd", end(4))
|
||||
if h.balance(t, 27) != 3 {
|
||||
t.Fatal("authoritative fast clear missions did not grant actual rewards")
|
||||
}
|
||||
if num(response, 1) != 2000 {
|
||||
t.Fatal("HTTP score replaced authoritative room time")
|
||||
}
|
||||
h.reopen(t)
|
||||
h.service.AttachRooms(room)
|
||||
if !bytes.Equal(response, h.call(t, "/MiniGameActionEnd", end(4))) || h.balance(t, 27) != 3 {
|
||||
t.Fatal("native mission retry duplicated reward")
|
||||
}
|
||||
info := h.call(t, "/MiniGameActionInfo", testRow(1, 5, 2, 160))
|
||||
missions, _ := list(info, 3)
|
||||
if len(missions) != 4 {
|
||||
t.Fatal("mission ledger did not survive reopen")
|
||||
}
|
||||
best, _, _ := wire.Bytes(info, 2)
|
||||
if num(best, 1) != 101 || num(best, 2) != 2000 {
|
||||
t.Fatal("Action Info did not key best by monster")
|
||||
}
|
||||
room.run.InstanceID, room.run.GUID = "third-room", "third-guid"
|
||||
room.result.Evidence = wire.AppendBytes(nil, 2, testRow(1, 7, 2, 1))
|
||||
h.call(t, "/MiniGameActionStart", testRow(1, 6))
|
||||
h.call(t, "/MiniGameActionEnd", end(7))
|
||||
if h.balance(t, 27) != 4 {
|
||||
t.Fatal("new room failed to award only the own-character mission")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSurvivalEvolutionRequiresOwnedAbilityAndFallbackUpdatesWallet(t *testing.T) {
|
||||
h := newPlayHarness(t)
|
||||
h.design.Tables["FieldMiniGameSkillGroupTable"][0] = testRow(1, 1, 2, 2, 5, 1, 7, 1, 8, 2)
|
||||
h.design.Tables["FieldMiniGameSkillGroupTable"] = append(h.design.Tables["FieldMiniGameSkillGroupTable"], testRow(1, 8, 2, 1, 4, 2002))
|
||||
h.design.Tables["FieldMiniGameSkillTable"] = append(h.design.Tables["FieldMiniGameSkillTable"], wire.AppendDouble(testRow(7, 8, 8, 1), 17, 40))
|
||||
h.design.Tables["FieldMiniGameSurvivalItemTable"] = append(h.design.Tables["FieldMiniGameSurvivalItemTable"], testRow(1, 13, 3, 5, 4, 1, 6, 100))
|
||||
h.design.Tables["FieldMiniGameSurvivalBoxTable"][0] = testRow(2, 1, 3, 11, 3, 12, 3, 13)
|
||||
h.call(t, "/MiniGameSurvivalStart", testRow(1, 1, 2, 110, 3, 1, 4, 1, 5, 1))
|
||||
h.now = h.now.Add(time.Second)
|
||||
play := testRow(1, 2, 2, 100, 3, 10, 4, 5, 7, 1)
|
||||
for _, id := range []uint64{11, 12, 13} {
|
||||
play = wire.AppendBytes(play, 5, testRow(1, id, 2, 1))
|
||||
}
|
||||
play = wire.AppendBytes(play, 6, testRow(1, 1, 2, 1))
|
||||
h.call(t, "/MiniGameSurvivalPlay", play)
|
||||
offers := h.call(t, "/MiniGameSurvivalSkillSelectList", testRow(1, 3))
|
||||
ids, _ := list(offers, 2)
|
||||
if len(ids) != 1 || ids[0] != 2 {
|
||||
t.Fatal("weapon evolved before its combination ability was acquired")
|
||||
}
|
||||
h.call(t, "/MiniGameSurvivalSkillUp", testRow(1, 4, 2, 2))
|
||||
h.call(t, "/MiniGameSurvivalSkillUp", testRow(1, 5, 3, 13))
|
||||
h.now = h.now.Add(time.Second)
|
||||
play = testRow(1, 6, 2, 100, 3, 30, 4, 15, 7, 1, 7, 1, 7, 1)
|
||||
for _, id := range []uint64{11, 12, 13} {
|
||||
play = wire.AppendBytes(play, 5, testRow(1, id, 2, 3))
|
||||
}
|
||||
play = wire.AppendBytes(play, 6, testRow(1, 1, 2, 3))
|
||||
h.call(t, "/MiniGameSurvivalPlay", play)
|
||||
for seq := uint64(7); seq < 10; seq++ {
|
||||
h.call(t, "/MiniGameSurvivalSkillUp", testRow(1, seq, 3, 13))
|
||||
}
|
||||
if h.service.state.Runs["Survival"].Coin != 100 {
|
||||
t.Fatal("fully upgraded chest did not issue coin fallback")
|
||||
}
|
||||
h.call(t, "/MiniGameSurvivalEnd", testRow(1, 10, 2, 1, 3, 2, 4, 4, 5, 100, 6, 40))
|
||||
if h.balance(t, 43) != 100 {
|
||||
t.Fatal("fallback coins were not credited at End")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,662 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (s *Service) survivalRule(game uint64) ([]byte, error) {
|
||||
row, err := s.design.Row("PackEventMiniGameTable", 8, game)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.design.Row("FieldMiniGameSurvivalTable", 9, num(row, 4))
|
||||
}
|
||||
|
||||
func (s *Service) survivalChar(game, id uint64) ([]byte, error) {
|
||||
rule, err := s.survivalRule(game)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range s.design.Rows("FieldMiniGameCharTable", 11, num(rule, 7)) {
|
||||
if num(row, 13) == id {
|
||||
return row, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("eventplay: survival character outside configured group")
|
||||
}
|
||||
|
||||
func (s *Service) survivalMap(group, id uint64) ([]byte, error) {
|
||||
for _, row := range s.design.Rows("FieldMiniGameMapTable", 2, group) {
|
||||
if num(row, 3) == id {
|
||||
return row, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("eventplay: survival map missing")
|
||||
}
|
||||
|
||||
func survivalCleared(st *snapshot, uid, group, id uint64) bool {
|
||||
for _, r := range st.Records {
|
||||
if r.UID == uid && r.Family == "Survival" && r.Clears[fmt.Sprintf("map:%d:%d", group, id)] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Service) startSurvival(req []byte, a *Run, st *snapshot) error {
|
||||
a.Char, a.MapGroup, a.Mode = num(req, 3), num(req, 4), num(req, 4)
|
||||
rule, err := s.survivalRule(a.Game)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
char, err := s.survivalChar(a.Game, a.Char)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
found := false
|
||||
for _, row := range s.design.Rows("FieldMiniGameMapGroupTable", 1, num(rule, 15)) {
|
||||
if num(row, 2) == a.MapGroup {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return fmt.Errorf("eventplay: survival map group outside season")
|
||||
}
|
||||
mapRow, err := s.survivalMap(a.MapGroup, a.Stage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if num(mapRow, 11) == 0 && (a.MapGroup > 1 && !survivalCleared(st, a.UID, a.MapGroup-1, 1) || a.Stage > 1 && !survivalCleared(st, a.UID, a.MapGroup, a.Stage-1)) {
|
||||
return fmt.Errorf("eventplay: survival map difficulty locked")
|
||||
}
|
||||
a.HP = num(char, 20)
|
||||
a.Rerolls = num(char, 19)
|
||||
a.MaxHP = a.HP
|
||||
a.Level = 1
|
||||
a.CoinRate, a.ExpRate = doubleField(char, 10, 1), doubleField(char, 8, 1)
|
||||
a.Regen = 1
|
||||
for _, group := range s.design.Tables["FieldMiniGameUpgradeGroupTable"] {
|
||||
id := num(group, 1)
|
||||
level := st.Upgrades[fmt.Sprintf("%d:%d", a.UID, id)]
|
||||
if level == 0 {
|
||||
level = 1
|
||||
}
|
||||
for _, row := range s.design.Rows("FieldMiniGameUpgradeTable", 1, id) {
|
||||
if num(row, 2) != level {
|
||||
continue
|
||||
}
|
||||
value := doubleField(row, 4, 0)
|
||||
switch num(group, 2) {
|
||||
case 1:
|
||||
a.HP += uint64(value)
|
||||
case 2:
|
||||
a.Regen += value
|
||||
case 8:
|
||||
a.ExpRate *= value
|
||||
case 9:
|
||||
a.CoinRate *= value
|
||||
case 12:
|
||||
a.Rerolls += uint64(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
a.MaxHP = a.HP
|
||||
a.LastProgress = a.Started
|
||||
a.Killed = map[uint64]uint64{}
|
||||
a.Picked = map[uint64]uint64{}
|
||||
a.Boxes = map[uint64]uint64{}
|
||||
a.SpecialItems = map[uint64]uint64{}
|
||||
a.Skills = []uint64{num(char, 3)}
|
||||
a.SkillLevels = map[uint64]uint64{num(char, 3): 1}
|
||||
for i := range a.RandomState {
|
||||
a.RandomState[i] = seqSeed(a.Started) + uint64(i)*90
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) survivalPassive(a Run, stat uint64) float64 {
|
||||
value := float64(1)
|
||||
for group, level := range a.SkillLevels {
|
||||
for _, row := range s.design.Rows("FieldMiniGameSkillTable", 7, group) {
|
||||
if num(row, 8) == level && num(row, 18) == stat {
|
||||
value = doubleField(row, 17, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func (s *Service) survivalUnlockInfo(st *snapshot, uid uint64) []byte {
|
||||
c, err := s.calendar(uid, "Survival")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
rule, err := s.survivalRule(c.ID)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []byte
|
||||
for _, row := range s.design.Rows("FieldMiniGameCharTable", 11, num(rule, 7)) {
|
||||
out = wire.AppendVarint(out, 2, num(row, 13))
|
||||
}
|
||||
for _, row := range s.design.Rows("FieldMiniGameMapGroupTable", 1, num(rule, 15)) {
|
||||
out = wire.AppendVarint(out, 3, num(row, 2))
|
||||
}
|
||||
ledger := st.Records[recKey(uid, 0, 0, "Survival")]
|
||||
for _, row := range s.design.Tables["FieldMiniGameCollectionTable"] {
|
||||
id := num(row, 3)
|
||||
if ledger.Clears[fmt.Sprintf("collection:%d", id)] {
|
||||
out = wire.AppendBytes(out, 9, wire.AppendVarint(nil, 1, id))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) collectSurvival(st *snapshot, a Run, typ, value uint64) {
|
||||
ledger := playRecord(st, a.UID, a.Game, 0, 0, a.Family)
|
||||
for _, row := range s.design.Tables["FieldMiniGameCollectionTable"] {
|
||||
if num(row, 7) == typ && num(row, 1) == value {
|
||||
ledger.Clears[fmt.Sprintf("collection:%d", num(row, 3))] = true
|
||||
}
|
||||
}
|
||||
st.Records[recKey(a.UID, 0, 0, a.Family)] = ledger
|
||||
}
|
||||
|
||||
func survivalRandom(a *Run, bound uint64) uint64 {
|
||||
index := a.RandomIndex
|
||||
x, y := a.RandomState[index], a.RandomState[(index+13)&15]
|
||||
b := x ^ y ^ (x << 16) ^ (y << 15)
|
||||
c := a.RandomState[(index+9)&15]
|
||||
c ^= c >> 11
|
||||
x = b ^ c
|
||||
a.RandomState[index] = x
|
||||
d := x ^ ((x << 5) & uint64(0xffffffffda442d24))
|
||||
index = (index + 15) & 15
|
||||
x = a.RandomState[index]
|
||||
a.RandomState[index] = x ^ b ^ d ^ (x << 2) ^ (b << 18) ^ (c << 28)
|
||||
a.RandomIndex = index
|
||||
if bound == 0 {
|
||||
bound = 1
|
||||
}
|
||||
return uint64(float32(a.RandomState[index] % bound))
|
||||
}
|
||||
|
||||
func (s *Service) survivalDropBox(a *Run, id uint64) error {
|
||||
row, err := s.design.Row("FieldMiniGameSurvivalBoxTable", 2, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, err := list(row, 3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if num(row, 1) > 0 {
|
||||
ratios, e := list(row, 4)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if len(ratios) != len(items) {
|
||||
return fmt.Errorf("eventplay: malformed survival drop ratios")
|
||||
}
|
||||
var total uint64
|
||||
for _, weight := range ratios {
|
||||
total += weight
|
||||
}
|
||||
if total == 0 {
|
||||
return fmt.Errorf("eventplay: empty survival drop ratios")
|
||||
}
|
||||
draw := survivalRandom(a, total)
|
||||
for i, weight := range ratios {
|
||||
if draw < weight {
|
||||
items = []uint64{items[i]}
|
||||
break
|
||||
}
|
||||
draw -= weight
|
||||
}
|
||||
}
|
||||
for _, item := range items {
|
||||
if item != math.MaxUint64 {
|
||||
a.Drops = append(a.Drops, survivalDrop{item, uint64(s.now().UnixMilli())})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) survivalProgress(req []byte, a *Run) (uint64, uint64, error) {
|
||||
mapRow, err := s.survivalMap(a.MapGroup, a.Stage)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
monsters := s.design.Rows("FieldMiniGameMonsterTable", 2, num(mapRow, 4))
|
||||
elapsed := uint64(0)
|
||||
now := uint64(s.now().UnixMilli())
|
||||
if now > a.Started {
|
||||
elapsed = (now - a.Started) / 1000
|
||||
}
|
||||
err = wire.Walk(req, func(f wire.Field) error {
|
||||
if f.Number != 6 {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
id, count := num(f.Value, 1), num(f.Value, 2)
|
||||
if count == 0 {
|
||||
return fmt.Errorf("eventplay: empty kill count")
|
||||
}
|
||||
var row []byte
|
||||
for _, m := range monsters {
|
||||
if num(m, 5) == id {
|
||||
row = m
|
||||
}
|
||||
}
|
||||
if row == nil {
|
||||
return fmt.Errorf("eventplay: monster outside survival map")
|
||||
}
|
||||
start, perSecond, duration, repeats, gap := num(row, 16), num(row, 12), num(row, 14), num(row, 11), num(row, 15)
|
||||
if elapsed < start {
|
||||
return fmt.Errorf("eventplay: monster not spawned yet")
|
||||
}
|
||||
maxSpawn := uint64(0)
|
||||
if perSecond == 0 {
|
||||
maxSpawn = 1
|
||||
} else {
|
||||
if duration == 0 {
|
||||
duration = 1
|
||||
}
|
||||
if repeats == 0 {
|
||||
repeats = 1
|
||||
}
|
||||
for wave := uint64(0); wave < repeats; wave++ {
|
||||
begins := start + wave*(duration+gap)
|
||||
if elapsed < begins {
|
||||
break
|
||||
}
|
||||
seconds := min(duration, elapsed-begins+1)
|
||||
maxSpawn += seconds * perSecond
|
||||
}
|
||||
}
|
||||
if a.Killed[id] > maxSpawn || count > maxSpawn-a.Killed[id] {
|
||||
return fmt.Errorf("eventplay: kill count exceeds designed spawns")
|
||||
}
|
||||
a.Killed[id] += count
|
||||
boxes, e := list(row, 6)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, box := range boxes {
|
||||
a.Boxes[box] += count
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
boxes, err := list(req, 7)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
for _, id := range boxes {
|
||||
if a.Boxes[id] == 0 {
|
||||
return 0, 0, fmt.Errorf("eventplay: drop box exceeds committed monster deaths")
|
||||
}
|
||||
a.Boxes[id]--
|
||||
if err := s.survivalDropBox(a, id); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
}
|
||||
rule, err := s.survivalRule(a.Game)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
limit := num(rule, 10)
|
||||
if limit > 0 && uint64(len(a.Drops)) > limit {
|
||||
a.Drops = a.Drops[len(a.Drops)-int(limit):]
|
||||
}
|
||||
available := a.Drops[:0]
|
||||
for _, drop := range a.Drops {
|
||||
row, e := s.design.Row("FieldMiniGameSurvivalItemTable", 1, drop.ID)
|
||||
if e != nil {
|
||||
return 0, 0, e
|
||||
}
|
||||
if ttl := num(row, 6); ttl == 0 || now <= drop.Created+ttl*1000 {
|
||||
available = append(available, drop)
|
||||
}
|
||||
}
|
||||
a.Drops = available
|
||||
exp, coin, healing := uint64(0), uint64(0), uint64(0)
|
||||
err = wire.Walk(req, func(f wire.Field) error {
|
||||
if f.Number != 5 {
|
||||
return nil
|
||||
}
|
||||
if f.Type != 2 {
|
||||
return wire.ErrMalformed
|
||||
}
|
||||
id, count := num(f.Value, 1), num(f.Value, 2)
|
||||
if count == 0 || count > math.MaxInt32 {
|
||||
return fmt.Errorf("eventplay: invalid pickup count")
|
||||
}
|
||||
remaining := count
|
||||
kept := a.Drops[:0]
|
||||
for _, drop := range a.Drops {
|
||||
if drop.ID == id && remaining > 0 {
|
||||
remaining--
|
||||
} else {
|
||||
kept = append(kept, drop)
|
||||
}
|
||||
}
|
||||
if remaining > 0 {
|
||||
return fmt.Errorf("eventplay: item count exceeds sampled drops")
|
||||
}
|
||||
a.Drops = kept
|
||||
row, e := s.design.Row("FieldMiniGameSurvivalItemTable", 1, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
value := num(row, 4)
|
||||
if value > math.MaxInt32/count {
|
||||
return fmt.Errorf("eventplay: pickup overflow")
|
||||
}
|
||||
a.Picked[id] += count
|
||||
switch num(row, 3) {
|
||||
case 0:
|
||||
healing += value * count
|
||||
case 3:
|
||||
exp += uint64(math.Floor(float64(value)*math.Round(a.ExpRate*s.survivalPassive(*a, 7)*1000)/1000)) * count
|
||||
case 4:
|
||||
coin += uint64(math.Floor(float64(value)*math.Round(a.CoinRate*s.survivalPassive(*a, 8)*1000)/1000)) * count
|
||||
case 5:
|
||||
a.SpecialItems[id] += count
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
if exp != num(req, 3) || coin != num(req, 4) {
|
||||
return 0, 0, fmt.Errorf("eventplay: survival exp/coin differs from picked items")
|
||||
}
|
||||
regen := uint64(0)
|
||||
if now > a.LastProgress {
|
||||
regen = uint64(math.Floor(a.Regen+s.survivalPassive(*a, 10)-1)) * ((now - a.LastProgress) / 5000)
|
||||
}
|
||||
hp := num(req, 2)
|
||||
if hp > uint64(float64(a.MaxHP)*s.survivalPassive(*a, 1)) || hp > a.HP+healing+regen {
|
||||
return 0, 0, fmt.Errorf("eventplay: invalid survival HP")
|
||||
}
|
||||
a.HP = hp
|
||||
a.LastProgress = now
|
||||
a.Exp += exp
|
||||
a.Coin += coin
|
||||
a.LevelExp += exp
|
||||
if a.Exp > math.MaxInt32 || a.Coin > math.MaxInt32 {
|
||||
return 0, 0, fmt.Errorf("eventplay: survival totals overflow")
|
||||
}
|
||||
char, err := s.survivalChar(a.Game, a.Char)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
for {
|
||||
var levelRow []byte
|
||||
nextExists := false
|
||||
for _, row := range s.design.Rows("FieldMiniGameCharLevelTable", 1, num(char, 2)) {
|
||||
if num(row, 2) == a.Level {
|
||||
levelRow = row
|
||||
}
|
||||
if num(row, 2) == a.Level+1 {
|
||||
nextExists = true
|
||||
}
|
||||
}
|
||||
if !nextExists || num(levelRow, 3) == 0 || a.LevelExp < num(levelRow, 3) {
|
||||
break
|
||||
}
|
||||
a.LevelExp -= num(levelRow, 3)
|
||||
a.Level++
|
||||
a.SkillCredits++
|
||||
}
|
||||
return exp, coin, nil
|
||||
}
|
||||
|
||||
func (s *Service) survivalSkillCandidates(a Run) ([]uint64, error) {
|
||||
rule, err := s.survivalRule(a.Game)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
char, err := s.survivalChar(a.Game, a.Char)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
capacity := num(rule, 21)
|
||||
used := map[uint64]uint64{}
|
||||
for id := range a.SkillLevels {
|
||||
row, e := s.design.Row("FieldMiniGameSkillGroupTable", 1, id)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
used[num(row, 5)]++
|
||||
}
|
||||
var candidates []uint64
|
||||
for _, row := range s.design.Tables["FieldMiniGameSkillGroupTable"] {
|
||||
id, typ := num(row, 1), num(row, 5)
|
||||
if typ != 1 && typ != 2 {
|
||||
continue
|
||||
}
|
||||
if unique := num(row, 7); unique > 0 && unique != num(char, 13) {
|
||||
continue
|
||||
}
|
||||
if a.SkillLevels[id] >= num(row, 2) || a.SkillLevels[id] == 0 && used[typ] >= capacity {
|
||||
continue
|
||||
}
|
||||
if typ == 1 && a.SkillLevels[id]+1 == num(row, 2) && num(row, 8) > 0 && a.SkillLevels[num(row, 8)] == 0 {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, id)
|
||||
}
|
||||
slices.Sort(candidates)
|
||||
return candidates, nil
|
||||
}
|
||||
|
||||
func (s *Service) survivalSelect(a *Run) ([]byte, error) {
|
||||
if a.SkillCredits == 0 {
|
||||
return nil, fmt.Errorf("eventplay: no earned skill selection")
|
||||
}
|
||||
if len(a.Offers) > 0 {
|
||||
if a.Rerolls == 0 {
|
||||
return nil, fmt.Errorf("eventplay: no remaining rerolls")
|
||||
}
|
||||
a.Rerolls--
|
||||
}
|
||||
candidates, err := s.survivalSkillCandidates(*a)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
for _, row := range s.design.Tables["FieldMiniGameSkillGroupTable"] {
|
||||
if num(row, 5) == 0 {
|
||||
candidates = append(candidates, num(row, 1))
|
||||
}
|
||||
}
|
||||
}
|
||||
a.OfferNonce++
|
||||
for i := len(candidates) - 1; i > 0; i-- {
|
||||
hash := sha256.Sum256([]byte(fmt.Sprintf("%d:%d:%d:%d", a.UID, a.Started, a.OfferNonce, i)))
|
||||
j := int(binary.LittleEndian.Uint64(hash[:8]) % uint64(i+1))
|
||||
candidates[i], candidates[j] = candidates[j], candidates[i]
|
||||
}
|
||||
if len(candidates) > 3 {
|
||||
candidates = candidates[:3]
|
||||
}
|
||||
a.Offers = candidates
|
||||
out := wire.AppendVarint(nil, 1, a.Rerolls)
|
||||
for _, id := range a.Offers {
|
||||
out = wire.AppendVarint(out, 2, id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Service) survivalSkillUp(ctx command.Context, req []byte, a *Run, st *snapshot) ([]byte, error) {
|
||||
id, item := num(req, 2), num(req, 3)
|
||||
if item > 0 {
|
||||
row, err := s.design.Row("FieldMiniGameSurvivalItemTable", 1, item)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if id != 0 || num(row, 3) != 5 || a.SpecialItems[item] == 0 {
|
||||
return nil, fmt.Errorf("eventplay: survival skill item not collected")
|
||||
}
|
||||
a.SpecialItems[item]--
|
||||
var out []byte
|
||||
for n := uint64(0); n < num(row, 4); n++ {
|
||||
candidates, err := s.survivalSkillCandidates(*a)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
for _, fallback := range s.design.Tables["FieldMiniGameSkillGroupTable"] {
|
||||
if num(fallback, 5) == 0 {
|
||||
b, e := s.survivalFallback(a, fallback)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, b...)
|
||||
break
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
a.OfferNonce++
|
||||
hash := sha256.Sum256([]byte(fmt.Sprintf("item:%d:%d:%d", a.Started, item, a.OfferNonce)))
|
||||
pick := candidates[int(binary.LittleEndian.Uint64(hash[:8])%uint64(len(candidates)))]
|
||||
a.SkillLevels[pick]++
|
||||
if !has(a.Skills, pick) {
|
||||
a.Skills = append(a.Skills, pick)
|
||||
}
|
||||
v := wire.AppendVarint(nil, 1, pick)
|
||||
v = wire.AppendVarint(v, 2, a.SkillLevels[pick])
|
||||
out = wire.AppendBytes(out, 1, v)
|
||||
s.collectSurvival(st, *a, 1, pick)
|
||||
s.collectSurvival(st, *a, 0, pick)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
if a.SkillCredits == 0 || !has(a.Offers, id) {
|
||||
return nil, fmt.Errorf("eventplay: skill not earned or offered")
|
||||
}
|
||||
group, err := s.design.Row("FieldMiniGameSkillGroupTable", 1, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a.SkillCredits--
|
||||
a.Offers = nil
|
||||
if num(group, 5) == 0 {
|
||||
return s.survivalFallback(a, group)
|
||||
}
|
||||
a.SkillLevels[id]++
|
||||
if !has(a.Skills, id) {
|
||||
a.Skills = append(a.Skills, id)
|
||||
}
|
||||
s.collectSurvival(st, *a, 0, id)
|
||||
s.collectSurvival(st, *a, 1, id)
|
||||
if a.SkillLevels[id] == num(group, 2) && s.onProgress != nil {
|
||||
if err := s.onProgress(ctx, 318, a.Game, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.onProgress(ctx, 321, id, 1); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
v := wire.AppendVarint(nil, 1, id)
|
||||
v = wire.AppendVarint(v, 2, a.SkillLevels[id])
|
||||
return wire.AppendBytes(nil, 1, v), nil
|
||||
}
|
||||
|
||||
func (s *Service) endSurvivalRewards(ctx command.Context, req []byte, a Run, st *snapshot, key string, r *record) ([]byte, error) {
|
||||
if num(req, 5) != a.Coin || num(req, 6) != a.Exp {
|
||||
return nil, fmt.Errorf("eventplay: survival end counters differ from committed progress")
|
||||
}
|
||||
var kills uint64
|
||||
for _, count := range a.Killed {
|
||||
kills += count
|
||||
}
|
||||
if num(req, 4) != kills {
|
||||
return nil, fmt.Errorf("eventplay: survival end kill count differs from committed progress")
|
||||
}
|
||||
mapRow, err := s.survivalMap(a.MapGroup, a.Stage)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var rewards []gamedata.BattleReward
|
||||
clear := num(req, 2) == 0 && num(req, 3) >= num(mapRow, 9)
|
||||
identity := fmt.Sprintf("map:%d:%d", a.MapGroup, a.Stage)
|
||||
if clear && !r.Clears[identity] {
|
||||
rr, err := gamedata.EventPlayRewards(mapRow, 8, 7, 6)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rewards = append(rewards, rr...)
|
||||
r.Clears[identity] = true
|
||||
}
|
||||
if a.Coin > 0 {
|
||||
rewards = append(rewards, gamedata.BattleReward{Type: 43, Count: a.Coin})
|
||||
}
|
||||
var out []byte
|
||||
if len(rewards) > 0 {
|
||||
bundle, err := s.grant(ctx, "eventplay:"+key, rewards)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = wire.AppendBytes(out, 1, bundle)
|
||||
}
|
||||
out = wire.AppendVarint(out, 2, a.Coin)
|
||||
out = wire.AppendVarint(out, 3, a.Exp)
|
||||
for id := range a.SkillLevels {
|
||||
s.collectSurvival(st, a, 0, id)
|
||||
s.collectSurvival(st, a, 1, id)
|
||||
}
|
||||
for id := range a.Picked {
|
||||
row, err := s.design.Row("FieldMiniGameSurvivalItemTable", 1, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.collectSurvival(st, a, 2, num(row, 3))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s *Service) survivalFallback(a *Run, group []byte) ([]byte, error) {
|
||||
var row []byte
|
||||
for _, r := range s.design.Rows("FieldMiniGameSkillTable", 7, num(group, 1)) {
|
||||
if num(r, 8) == 1 {
|
||||
row = r
|
||||
}
|
||||
}
|
||||
if row == nil {
|
||||
return nil, fmt.Errorf("eventplay: fallback skill missing")
|
||||
}
|
||||
valueFloat := doubleField(row, 17, 0)
|
||||
if valueFloat < 0 || valueFloat > math.MaxInt32 {
|
||||
return nil, fmt.Errorf("eventplay: invalid fallback skill value")
|
||||
}
|
||||
value := uint64(valueFloat)
|
||||
if num(group, 4) == 2002 {
|
||||
if a.Coin > math.MaxInt32-value {
|
||||
return nil, fmt.Errorf("eventplay: survival coin overflow")
|
||||
}
|
||||
a.Coin += value
|
||||
return wire.AppendVarint(nil, 2, value), nil
|
||||
}
|
||||
maximum := uint64(float64(a.MaxHP) * s.survivalPassive(*a, 1))
|
||||
heal := uint64(0)
|
||||
if maximum > a.HP {
|
||||
heal = min(value, maximum-a.HP)
|
||||
}
|
||||
a.HP += heal
|
||||
return wire.AppendVarint(nil, 3, heal), nil
|
||||
}
|
||||
@@ -2,19 +2,32 @@ package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"sort"
|
||||
)
|
||||
|
||||
func rewardDifference(old, next []gamedata.BattleReward) []gamedata.BattleReward {
|
||||
paid := map[[2]uint64]uint64{}
|
||||
earned := map[[2]uint64]uint64{}
|
||||
for _, r := range old {
|
||||
paid[[2]uint64{r.Type, r.ID}] += r.Count
|
||||
}
|
||||
var out []gamedata.BattleReward
|
||||
for _, r := range next {
|
||||
n := paid[[2]uint64{r.Type, r.ID}]
|
||||
if r.Count > n {
|
||||
r.Count -= n
|
||||
out = append(out, r)
|
||||
earned[[2]uint64{r.Type, r.ID}] += r.Count
|
||||
}
|
||||
keys := make([][2]uint64, 0, len(earned))
|
||||
for k := range earned {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if keys[i][0] != keys[j][0] {
|
||||
return keys[i][0] < keys[j][0]
|
||||
}
|
||||
return keys[i][1] < keys[j][1]
|
||||
})
|
||||
var out []gamedata.BattleReward
|
||||
for _, k := range keys {
|
||||
if earned[k] > paid[k] {
|
||||
out = append(out, gamedata.BattleReward{Type: k[0], ID: k[1], Count: earned[k] - paid[k]})
|
||||
}
|
||||
}
|
||||
return out
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
package ranking
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"sort"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type ArcadeScope struct {
|
||||
Family string
|
||||
EventUID, Stage, Mode uint64
|
||||
}
|
||||
|
||||
type ArcadeRecord struct {
|
||||
ArcadeScope
|
||||
Score float64
|
||||
CapturedArea, ClearTime uint64
|
||||
AchievedAt uint64
|
||||
PlayInfo string
|
||||
}
|
||||
|
||||
type ArcadeProfile struct {
|
||||
Owner uint64
|
||||
Name string
|
||||
XP, Portrait, PortraitDesign, Title uint64
|
||||
Guild []byte
|
||||
}
|
||||
|
||||
type ArcadePublication struct {
|
||||
Account string
|
||||
Version uint64
|
||||
Profile ArcadeProfile
|
||||
Records []ArcadeRecord
|
||||
}
|
||||
|
||||
type ArcadeEntry struct {
|
||||
ArcadeRecord
|
||||
Profile ArcadeProfile
|
||||
Rank uint64
|
||||
TopPercent float64
|
||||
Own bool
|
||||
}
|
||||
|
||||
type Arcade struct {
|
||||
store Store
|
||||
writer sync.Mutex
|
||||
mu sync.RWMutex
|
||||
players map[uint64]ArcadePublication
|
||||
best map[uint64]map[ArcadeScope]ArcadeEntry
|
||||
boards map[ArcadeScope][]ArcadeEntry
|
||||
}
|
||||
|
||||
func NewArcade(ctx context.Context, store Store) (*Arcade, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("arcade ranking requires persistence")
|
||||
}
|
||||
r := &Arcade{store: store, players: map[uint64]ArcadePublication{}, best: map[uint64]map[ArcadeScope]ArcadeEntry{}, boards: map[ArcadeScope][]ArcadeEntry{}}
|
||||
err := store.View(ctx, func(tx Tx) error {
|
||||
for cursor := ""; ; {
|
||||
rows, err := tx.Scan("arcade.players", "", cursor, 256)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
for _, row := range rows {
|
||||
var publication ArcadePublication
|
||||
if err := json.Unmarshal(row.Value, &publication); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validArcadePublication(publication); err != nil {
|
||||
return err
|
||||
}
|
||||
if row.Key != arcadeOwnerKey(publication.Profile.Owner) || row.Key <= cursor {
|
||||
return errors.New("invalid saved arcade identity")
|
||||
}
|
||||
r.players[publication.Profile.Owner] = publication
|
||||
r.best[publication.Profile.Owner] = arcadeBest(publication)
|
||||
for scope, entry := range r.best[publication.Profile.Owner] {
|
||||
r.boards[scope] = append(r.boards[scope], entry)
|
||||
}
|
||||
cursor = row.Key
|
||||
}
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, board := range r.boards {
|
||||
slices.SortFunc(board, compareArcade)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func arcadeOwnerKey(owner uint64) string { return fmt.Sprintf("%020d", owner) }
|
||||
|
||||
func (r *Arcade) Account(owner uint64) string {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
return r.players[owner].Account
|
||||
}
|
||||
|
||||
func validArcadeRecord(row ArcadeRecord) error {
|
||||
if row.EventUID == 0 || row.EventUID > math.MaxInt32 || row.Stage > math.MaxInt32 || row.Mode > math.MaxInt32 || row.Score <= 0 || row.AchievedAt == 0 || row.AchievedAt > math.MaxInt64 || math.IsNaN(row.Score) || math.IsInf(row.Score, 0) {
|
||||
return errors.New("invalid arcade result")
|
||||
}
|
||||
switch row.Family {
|
||||
case "Survival", "Rhythm", "PackMan", "Field", "Run":
|
||||
if row.Score >= 1<<63 || math.Trunc(row.Score) != row.Score {
|
||||
return errors.New("invalid arcade point")
|
||||
}
|
||||
if row.Family == "Rhythm" && (row.Mode < 1 || row.Mode > 2) {
|
||||
return errors.New("invalid ranked rhythm mode")
|
||||
}
|
||||
if row.Family == "Field" && (row.Mode < 1 || row.Mode > 2) || row.Family == "Run" && (row.Mode < 3 || row.Mode > 4) {
|
||||
return errors.New("invalid field run ranking")
|
||||
}
|
||||
case "Sichuan":
|
||||
if row.Mode != 2 {
|
||||
return errors.New("invalid ranked sichuan mode")
|
||||
}
|
||||
case "Hopscotch":
|
||||
if row.ClearTime == 0 || row.ClearTime > math.MaxInt32 || row.CapturedArea > 100 || row.Score != float64(row.ClearTime) {
|
||||
return errors.New("invalid arcade area record")
|
||||
}
|
||||
default:
|
||||
return errors.New("invalid arcade family")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validArcadePublication(p ArcadePublication) error {
|
||||
if p.Account == "" || p.Profile.Owner == 0 || p.Profile.Owner > math.MaxInt64 || p.Profile.Name == "" || p.Version == 0 {
|
||||
return errors.New("invalid arcade ranking identity")
|
||||
}
|
||||
seen := map[ArcadeScope]bool{}
|
||||
for _, row := range p.Records {
|
||||
if err := validArcadeRecord(row); err != nil {
|
||||
return err
|
||||
}
|
||||
if seen[row.ArcadeScope] {
|
||||
return errors.New("duplicate arcade record")
|
||||
}
|
||||
seen[row.ArcadeScope] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func arcadeBoardScope(scope ArcadeScope) ArcadeScope {
|
||||
if scope.Family == "Survival" || scope.Family == "Sichuan" {
|
||||
scope.Stage, scope.Mode = 0, 0
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
// Sichuan challenge ties retain the first achievement; other ties use stable owner identity.
|
||||
func compareArcade(a, b ArcadeEntry) int {
|
||||
var comparison int
|
||||
if a.Family == "Hopscotch" {
|
||||
comparison = cmpUint(a.ClearTime, b.ClearTime)
|
||||
} else if a.Score < b.Score {
|
||||
comparison = -1
|
||||
} else if a.Score > b.Score {
|
||||
comparison = 1
|
||||
}
|
||||
if a.Family != "Sichuan" && a.Family != "Hopscotch" && (a.Family != "Run" || a.Mode != 3) {
|
||||
comparison = -comparison
|
||||
}
|
||||
if comparison != 0 {
|
||||
return comparison
|
||||
}
|
||||
if a.Family == "Sichuan" {
|
||||
if c := cmpUint(a.AchievedAt, b.AchievedAt); c != 0 {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return cmpUint(a.Profile.Owner, b.Profile.Owner)
|
||||
}
|
||||
|
||||
func cmpUint(a, b uint64) int {
|
||||
if a < b {
|
||||
return -1
|
||||
}
|
||||
if a > b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func arcadeBest(p ArcadePublication) map[ArcadeScope]ArcadeEntry {
|
||||
best := map[ArcadeScope]ArcadeEntry{}
|
||||
for _, record := range p.Records {
|
||||
scope := arcadeBoardScope(record.ArcadeScope)
|
||||
entry := ArcadeEntry{ArcadeRecord: record, Profile: p.Profile}
|
||||
old, exists := best[scope]
|
||||
if !exists || compareArcade(entry, old) < 0 {
|
||||
best[scope] = entry
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
func arcadePosition(board []ArcadeEntry, entry ArcadeEntry) int {
|
||||
return sort.Search(len(board), func(i int) bool { return compareArcade(board[i], entry) >= 0 })
|
||||
}
|
||||
|
||||
func (r *Arcade) apply(p ArcadePublication) {
|
||||
for scope, previous := range r.best[p.Profile.Owner] {
|
||||
board := r.boards[scope]
|
||||
position := arcadePosition(board, previous)
|
||||
if position < len(board) && board[position].Profile.Owner == p.Profile.Owner {
|
||||
r.boards[scope] = slices.Delete(board, position, position+1)
|
||||
}
|
||||
}
|
||||
r.best[p.Profile.Owner] = arcadeBest(p)
|
||||
for scope, entry := range r.best[p.Profile.Owner] {
|
||||
board := r.boards[scope]
|
||||
position := arcadePosition(board, entry)
|
||||
r.boards[scope] = slices.Insert(board, position, entry)
|
||||
}
|
||||
r.players[p.Profile.Owner] = p
|
||||
}
|
||||
|
||||
func (r *Arcade) Publish(ctx context.Context, p ArcadePublication) error {
|
||||
if err := validArcadePublication(p); err != nil {
|
||||
return err
|
||||
}
|
||||
r.writer.Lock()
|
||||
defer r.writer.Unlock()
|
||||
r.mu.RLock()
|
||||
old := r.players[p.Profile.Owner]
|
||||
r.mu.RUnlock()
|
||||
if old.Account != "" && old.Account != p.Account {
|
||||
return errors.New("arcade ranking owner conflict")
|
||||
}
|
||||
if old.Version > p.Version {
|
||||
return nil
|
||||
}
|
||||
if old.Version == p.Version {
|
||||
oldRaw, err := json.Marshal(old)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nextRaw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(oldRaw, nextRaw) {
|
||||
return errors.New("arcade publication version conflict")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
nextRecords := map[ArcadeScope]ArcadeRecord{}
|
||||
for _, row := range p.Records {
|
||||
nextRecords[row.ArcadeScope] = row
|
||||
}
|
||||
for _, previous := range old.Records {
|
||||
next, exists := nextRecords[previous.ArcadeScope]
|
||||
if !exists || compareArcade(ArcadeEntry{ArcadeRecord: next}, ArcadeEntry{ArcadeRecord: previous}) > 0 {
|
||||
return errors.New("arcade publication lost or regressed record")
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var owned ArcadePublication
|
||||
if err := json.Unmarshal(raw, &owned); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.store.Update(ctx, func(tx Tx) error { return tx.Put("arcade.players", arcadeOwnerKey(p.Profile.Owner), raw) }); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.apply(owned)
|
||||
r.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Board overlays the requesting player's committed state while its outbox is pending.
|
||||
func (r *Arcade) Board(scope ArcadeScope, own ArcadeProfile, recent []ArcadeRecord, limit int) []ArcadeEntry {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
scope = arcadeBoardScope(scope)
|
||||
board := r.boards[scope]
|
||||
ownPosition := -1
|
||||
if previous, found := r.best[own.Owner][scope]; found {
|
||||
position := arcadePosition(board, previous)
|
||||
if position < len(board) && board[position].Profile.Owner == own.Owner {
|
||||
ownPosition = position
|
||||
}
|
||||
}
|
||||
var latest ArcadeEntry
|
||||
for _, record := range recent {
|
||||
if arcadeBoardScope(record.ArcadeScope) != scope {
|
||||
continue
|
||||
}
|
||||
entry := ArcadeEntry{ArcadeRecord: record, Profile: own}
|
||||
if latest.Profile.Owner == 0 || compareArcade(entry, latest) < 0 {
|
||||
latest = entry
|
||||
}
|
||||
}
|
||||
count, insertion := len(board), -1
|
||||
if latest.Profile.Owner != 0 {
|
||||
insertion = arcadePosition(board, latest)
|
||||
if ownPosition >= 0 {
|
||||
count--
|
||||
if ownPosition < insertion {
|
||||
insertion--
|
||||
}
|
||||
}
|
||||
count++
|
||||
}
|
||||
entryAt := func(position int) ArcadeEntry {
|
||||
if insertion >= 0 && position == insertion {
|
||||
return latest
|
||||
}
|
||||
index := position
|
||||
if insertion >= 0 {
|
||||
if position > insertion {
|
||||
index--
|
||||
}
|
||||
if ownPosition >= 0 && index >= ownPosition {
|
||||
index++
|
||||
}
|
||||
}
|
||||
return board[index]
|
||||
}
|
||||
placed := func(position int) ArcadeEntry {
|
||||
entry := entryAt(position)
|
||||
entry.Own = own.Owner != 0 && entry.Profile.Owner == own.Owner
|
||||
entry.Profile.Guild = slices.Clone(entry.Profile.Guild)
|
||||
entry.Rank, entry.TopPercent = uint64(position+1), float64(position+1)*100/float64(count)
|
||||
return entry
|
||||
}
|
||||
topCount := min(max(limit, 0), count)
|
||||
out := make([]ArcadeEntry, 0, min(topCount+1, count))
|
||||
for i := range topCount {
|
||||
out = append(out, placed(i))
|
||||
}
|
||||
if insertion >= 0 {
|
||||
ownPosition = insertion
|
||||
}
|
||||
if ownPosition >= topCount {
|
||||
out = append(out, placed(ownPosition))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (r *Arcade) Scopes() []ArcadeScope {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
var scopes []ArcadeScope
|
||||
for scope, rows := range r.boards {
|
||||
if len(rows) > 0 {
|
||||
scopes = append(scopes, scope)
|
||||
}
|
||||
}
|
||||
slices.SortFunc(scopes, func(a, b ArcadeScope) int {
|
||||
if a.Family < b.Family {
|
||||
return -1
|
||||
}
|
||||
if a.Family > b.Family {
|
||||
return 1
|
||||
}
|
||||
if c := cmpUint(a.EventUID, b.EventUID); c != 0 {
|
||||
return c
|
||||
}
|
||||
if c := cmpUint(a.Stage, b.Stage); c != 0 {
|
||||
return c
|
||||
}
|
||||
return cmpUint(a.Mode, b.Mode)
|
||||
})
|
||||
return scopes
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package ranking
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/server/storage/shared"
|
||||
)
|
||||
|
||||
func arcadePublication(account string, owner, version uint64, records ...ArcadeRecord) ArcadePublication {
|
||||
return ArcadePublication{Account: account, Version: version, Profile: ArcadeProfile{Owner: owner, Name: account}, Records: records}
|
||||
}
|
||||
|
||||
func arcadeResult(family string, event, stage, mode uint64, score float64, achieved uint64) ArcadeRecord {
|
||||
return ArcadeRecord{ArcadeScope: ArcadeScope{Family: family, EventUID: event, Stage: stage, Mode: mode}, Score: score, AchievedAt: achieved}
|
||||
}
|
||||
|
||||
func TestArcadePersistentBoardAndPendingOwnImprovement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
directory := t.TempDir()
|
||||
store, err := shared.Open(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ranks, err := NewArcade(ctx, testPVPStore{store})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alice := arcadePublication("alice", 11, 1, arcadeResult("Survival", 7, 1, 0, 50, 100))
|
||||
bob := arcadePublication("bob", 22, 1, arcadeResult("Survival", 7, 2, 0, 100, 101))
|
||||
carol := arcadePublication("carol", 33, 1, arcadeResult("Survival", 7, 3, 0, 150, 102))
|
||||
for _, p := range []ArcadePublication{alice, bob, carol} {
|
||||
if err := ranks.Publish(ctx, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := store.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err = shared.Open(directory)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := store.Close(); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
})
|
||||
ranks, err = NewArcade(ctx, testPVPStore{store})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scope := ArcadeScope{Family: "Survival", EventUID: 7}
|
||||
rows := ranks.Board(scope, alice.Profile, alice.Records, 1)
|
||||
if len(rows) != 2 || rows[0].Profile.Name != "carol" || rows[0].Rank != 1 || rows[1].Profile.Name != "alice" || rows[1].Rank != 3 || rows[1].TopPercent != 100 || !rows[1].Own {
|
||||
t.Fatalf("persisted multiplayer/own board: %+v", rows)
|
||||
}
|
||||
alice.Version = 2
|
||||
alice.Records[0].Score, alice.Records[0].AchievedAt = 200, 200
|
||||
rows = ranks.Board(scope, alice.Profile, alice.Records, 1)
|
||||
if len(rows) != 1 || rows[0].Profile.Name != "alice" || rows[0].Rank != 1 || rows[0].TopPercent != 100.0/3 || !rows[0].Own {
|
||||
t.Fatalf("pending own result not counted once: %+v", rows)
|
||||
}
|
||||
otherView := ranks.Board(scope, bob.Profile, bob.Records, 3)
|
||||
if otherView[0].Profile.Name != "carol" {
|
||||
t.Fatalf("unpublished own overlay escaped to other players: %+v", otherView)
|
||||
}
|
||||
if err := ranks.Publish(ctx, alice); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ranks.Publish(ctx, alice); err != nil {
|
||||
t.Fatal("outbox retry:", err)
|
||||
}
|
||||
if err := ranks.Publish(ctx, arcadePublication("alice", 11, 1, arcadeResult("Survival", 7, 1, 0, 50, 100))); err != nil {
|
||||
t.Fatal("stale outbox retry:", err)
|
||||
}
|
||||
rows = ranks.Board(scope, bob.Profile, bob.Records, 3)
|
||||
if len(rows) != 3 || rows[0].Profile.Name != "alice" || rows[0].Score != 200 || rows[2].Profile.Name != "bob" || rows[2].Rank != 3 {
|
||||
t.Fatalf("published result lost across retries: %+v", rows)
|
||||
}
|
||||
alice.Version = 3
|
||||
alice.Profile.Name, alice.Profile.Title = "Alice renamed", 9
|
||||
if err := ranks.Publish(ctx, alice); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows = ranks.Board(scope, bob.Profile, bob.Records, 3)
|
||||
if rows[0].Profile.Name != "Alice renamed" || rows[0].Profile.Title != 9 || rows[0].Score != 200 {
|
||||
t.Fatalf("profile publication replaced score: %+v", rows)
|
||||
}
|
||||
if foreign := ranks.Board(ArcadeScope{Family: "Survival", EventUID: 8}, alice.Profile, alice.Records, 100); len(foreign) != 0 {
|
||||
t.Fatalf("season leaked: %+v", foreign)
|
||||
}
|
||||
}
|
||||
|
||||
func TestArcadeSichuanFasterTimesAndFirstAchievementTies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ranks, err := NewArcade(ctx, teamTestStore(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alice := arcadePublication("alice", 11, 1, arcadeResult("Sichuan", 7, 1, 2, 12.25, 200))
|
||||
bob := arcadePublication("bob", 22, 1, arcadeResult("Sichuan", 7, 1, 2, 12.25, 100))
|
||||
carol := arcadePublication("carol", 33, 1, arcadeResult("Sichuan", 7, 1, 2, 11.75, 300))
|
||||
for _, p := range []ArcadePublication{alice, bob, carol} {
|
||||
if err := ranks.Publish(ctx, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rows := ranks.Board(ArcadeScope{Family: "Sichuan", EventUID: 7}, alice.Profile, nil, 100)
|
||||
if len(rows) != 3 || rows[0].Profile.Name != "carol" || rows[0].Score != 11.75 || rows[1].Profile.Name != "bob" || rows[2].Profile.Name != "alice" {
|
||||
t.Fatalf("LocalText125517 completion time and first-achievement order: %+v", rows)
|
||||
}
|
||||
regressed := alice
|
||||
regressed.Version = 2
|
||||
regressed.Records = append([]ArcadeRecord(nil), alice.Records...)
|
||||
regressed.Records[0].Score = 13.25
|
||||
if err := ranks.Publish(ctx, regressed); err == nil {
|
||||
t.Fatal("slower challenge replaced saved best")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArcadeRhythmModesStayIndependentAndNormalIsUnranked(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ranks, err := NewArcade(ctx, teamTestStore(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alice := arcadePublication("alice", 11, 1, arcadeResult("Rhythm", 7, 1, 1, 100, 100), arcadeResult("Rhythm", 7, 1, 2, 20, 101))
|
||||
bob := arcadePublication("bob", 22, 1, arcadeResult("Rhythm", 7, 1, 1, 10, 100), arcadeResult("Rhythm", 7, 1, 2, 200, 101))
|
||||
for _, p := range []ArcadePublication{alice, bob} {
|
||||
if err := ranks.Publish(ctx, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for mode, leader := range map[uint64]string{1: "alice", 2: "bob"} {
|
||||
rows := ranks.Board(ArcadeScope{Family: "Rhythm", EventUID: 7, Stage: 1, Mode: mode}, alice.Profile, nil, 100)
|
||||
if len(rows) != 2 || rows[0].Profile.Name != leader {
|
||||
t.Fatalf("rhythm mode %d merged: %+v", mode, rows)
|
||||
}
|
||||
}
|
||||
normal := arcadePublication("normal", 44, 1, arcadeResult("Rhythm", 7, 1, 0, 1000, 100))
|
||||
if err := ranks.Publish(ctx, normal); err == nil {
|
||||
t.Fatal("normal entered leaderboard despite LocalText1500089")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArcadeHopscotchCompletedTimeKeepsCorrespondingArea(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ranks, err := NewArcade(ctx, teamTestStore(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fast := arcadeResult("Hopscotch", 8, 1, 0, 5000, 100)
|
||||
fast.ClearTime, fast.CapturedArea = 5000, 80
|
||||
slow := arcadeResult("Hopscotch", 8, 1, 0, 6000, 101)
|
||||
slow.ClearTime, slow.CapturedArea = 6000, 99
|
||||
if err := ranks.Publish(ctx, arcadePublication("fast", 55, 1, fast)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ranks.Publish(ctx, arcadePublication("slow", 66, 1, slow)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := ranks.Board(fast.ArcadeScope, ArcadeProfile{}, nil, 100)
|
||||
if len(rows) != 2 || rows[0].Profile.Name != "fast" || rows[0].ClearTime != 5000 || rows[0].CapturedArea != 80 {
|
||||
t.Fatalf("hopscotch time replaced by area: %+v", rows)
|
||||
}
|
||||
}
|
||||
|
||||
type arcadeFailingStore struct {
|
||||
Store
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (s *arcadeFailingStore) Update(ctx context.Context, write func(Tx) error) error {
|
||||
return s.Store.Update(ctx, func(tx Tx) error {
|
||||
if err := write(tx); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.fail {
|
||||
return errors.New("injected commit failure")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func TestArcadeFailedPersistenceDoesNotAdvanceProjection(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &arcadeFailingStore{Store: teamTestStore(t)}
|
||||
ranks, err := NewArcade(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
publication := arcadePublication("alice", 11, 1, arcadeResult("PackMan", 9, 1, 1, 500, 100))
|
||||
store.fail = true
|
||||
if err := ranks.Publish(ctx, publication); err == nil {
|
||||
t.Fatal("injected persistence failure ignored")
|
||||
}
|
||||
if rows := ranks.Board(publication.Records[0].ArcadeScope, ArcadeProfile{}, nil, 100); len(rows) != 0 {
|
||||
t.Fatalf("failed write advanced cache: %+v", rows)
|
||||
}
|
||||
reopened, err := NewArcade(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if scopes := reopened.Scopes(); len(scopes) != 0 {
|
||||
t.Fatalf("failed write survived reopen: %+v", scopes)
|
||||
}
|
||||
store.fail = false
|
||||
if err := reopened.Publish(ctx, publication); err != nil {
|
||||
t.Fatal("retry:", err)
|
||||
}
|
||||
if err := reopened.Publish(ctx, publication); err != nil {
|
||||
t.Fatal("duplicate retry:", err)
|
||||
}
|
||||
reloaded, err := NewArcade(ctx, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rows := reloaded.Board(publication.Records[0].ArcadeScope, publication.Profile, nil, 100)
|
||||
if len(rows) != 1 || rows[0].Rank != 1 || rows[0].Score != 500 || !rows[0].Own {
|
||||
t.Fatalf("retry did not publish once: %+v", rows)
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,41 @@ func (o *Owner) LoginInfo(ctx context.Context, account string) (member, base []b
|
||||
return
|
||||
}
|
||||
|
||||
func (o *Owner) GuildBases(ctx context.Context, accounts []string) (map[string][]byte, error) {
|
||||
result := make(map[string][]byte, len(accounts))
|
||||
byGuild := map[uint64][]byte{}
|
||||
err := o.store.View(ctx, func(tx Tx) error {
|
||||
for _, account := range accounts {
|
||||
if _, exists := result[account]; exists {
|
||||
continue
|
||||
}
|
||||
a, err := readAccount(tx, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result[account] = nil
|
||||
if a.GuildID == 0 {
|
||||
continue
|
||||
}
|
||||
base, cached := byGuild[a.GuildID]
|
||||
if !cached {
|
||||
g, err := readGuild(tx, a.GuildID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
base = wire.AppendVarint(nil, 1, g.ID)
|
||||
base = wire.AppendString(base, 2, g.Name)
|
||||
base = wire.AppendVarint(base, 3, g.Icon)
|
||||
base = wire.AppendString(base, 4, g.IconColor)
|
||||
byGuild[a.GuildID] = base
|
||||
}
|
||||
result[account] = base
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
func projectMemberProfiles(tx Tx, g *Guild) error {
|
||||
for account, member := range g.Members {
|
||||
raw, found, err := tx.Get("friend.directory", numberKey(member.OwnerIndex))
|
||||
|
||||
@@ -1,6 +1,24 @@
|
||||
{
|
||||
"version": "2.36.7",
|
||||
"bindings": [
|
||||
{"pack_id": 20000, "event_type": 20, "content_open_type": 20}
|
||||
{
|
||||
"pack_id": 20000,
|
||||
"event_type": 20,
|
||||
"content_open_type": 20
|
||||
}
|
||||
],
|
||||
"action_mission_characters": [
|
||||
{
|
||||
"condition_type": 6,
|
||||
"character_id": 1
|
||||
},
|
||||
{
|
||||
"condition_type": 7,
|
||||
"character_id": 2
|
||||
},
|
||||
{
|
||||
"condition_type": 8,
|
||||
"character_id": 3
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in new issue
Block a user