Files
galaxy-game/game/internal/controller/generate_turn.go
T
Ilia Denisov 601970b028
Tests · Go / test (push) Successful in 2m27s
Tests · UI / test (push) Waiting to run
Tests · Integration / integration (pull_request) Successful in 1m45s
Tests · Go / test (pull_request) Successful in 3m13s
Tests · UI / test (pull_request) Successful in 3m8s
refactor(game): lock-free storage, remove /command, flatten engine wrapper
Three-stage refactor of the game-engine plumbing (game logic untouched):

Stage 1 — lock-free persistence + admin serialisation. Remove the file
lock from repo/fs (the .lock file, the Read/Write-vs-*Safe duality and the
dead ReadSafe polling) and replace the two-step rename with a single atomic
rename so concurrent reads are torn-free without a lock. Serialise the
state-mutating admin writers (init/turn/banish) with one shared router
LimitMiddleware, rewritten to block on the request context instead of a
racy shared 100ms timer.

Stage 2 — remove the obsolete immediate-command path end to end. Players
submit through PUT /api/v1/order; the legacy PUT /api/v1/command path is
deleted across game (route, handler, 24 command factories, Ctrl), backend
(Commands handler/route, engineclient.ExecuteCommands), gateway (dispatch +
executeUserGamesCommand + routing entry), the FlatBuffers/model contract
(UserGamesCommand[Response]) and transcoder, plus every affected
OpenAPI/README/FUNCTIONAL/ARCHITECTURE doc. The integration proxy test is
converted to the order path.

Stage 3 — flatten the REST->engine wrapper. Replace the executor adapter,
the controller package functions and RepoController with one concrete
controller.Service; drop the single-implementation Repo and Storage
interfaces (repo.Repo / fs.FS are now concrete). Handlers depend on a thin
handler.Engine seam and own the domain->REST projection; storage is
resolved once at startup instead of per request.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-05-30 13:37:07 +02:00

141 lines
5.1 KiB
Go

package controller
import (
"maps"
"slices"
"galaxy/model/report"
"galaxy/game/internal/model/game"
"github.com/google/uuid"
)
func (c *Controller) MakeTurn() error {
if err := c.applyOrders(c.Cache.g.Turn); err != nil {
return err
}
// Next turn
c.Cache.g.Turn += 1
c.Cache.g.Stage = 0
// 01. Вышедшие расы удаляются из списка участвующих рас перед началом просчета очередного хода
c.Cache.TurnWipeExtinctRaces()
// 02. Товары загружаются на корабли, находящиеся в начале грузовых маршрутов, и корабли входят в гиперпространство (но ещё не полетели)
c.Cache.SendRoutedGroups()
// 03. Корабли, где это возможно, объединяются в группы.
c.Cache.TurnMergeEqualShipGroups()
// 04. Враждующие корабли вступают в схватку.
battles := ProduceBattles(c.Cache)
// 05. Корабли пролетают сквозь гиперпространство.
c.Cache.MoveShipGroups()
// 06. Корабли, где это возможно, объединяются в группы.
c.Cache.TurnMergeEqualShipGroups()
// 07. Враждующие корабли снова вступают в схватку (это происходит после выхода из гиперпространства).
battles = append(battles, ProduceBattles(c.Cache)...)
// 08. Корабли бомбят вражеские планеты.
bombings := c.Cache.ProduceBombings()
// 09. На планетах строятся корабли.
// 10. Корабли, где это возможно, объединяются в группы.
// 11. На планетах производится промышленность, добывается сырье, разрабатываются новые технологии.
// 12. Увеличивается население планет.
c.Cache.TurnPlanetProductions()
// 13. Товары выгружаются в конце грузовых маршрутов.
// 14. Выгруженные колонисты увеличивают население планеты (если население планеты ниже её размера).
// 15. Накопленная и выгруженная промышленность увеличивает производственный уровень планеты (если производственный уровень планеты ниже уровня населения).
c.Cache.TurnUnloadEnroutedGroups()
// 16. Происходит отмена маршрутов, выходящих за зону полета кораблей.
c.Cache.RemoveUnreachableRoutes()
// 17. Происходит голосование.
winners := c.Cache.TurnCalculateVotes()
c.Cache.TurnAcceptWinners(winners)
/*** Last steps ***/
// Store bombings
bombingReport := make([]*report.Bombing, len(bombings))
if len(bombings) > 0 {
if err := c.repo.SaveBombings(c.Cache.g.Turn, bombings); err != nil {
return err
}
for i := range bombings {
bombingReport[i].Planet = bombings[i].Planet
bombingReport[i].PlanetOwnedID = bombings[i].PlanetOwnedID
bombingReport[i].Number = bombings[i].Number
bombingReport[i].Owner = bombings[i].Owner
bombingReport[i].Attacker = bombings[i].Attacker
bombingReport[i].Production = bombings[i].Production
bombingReport[i].Industry = report.F(bombings[i].Industry.F())
bombingReport[i].Population = report.F(bombings[i].Population.F())
bombingReport[i].Colonists = report.F(bombings[i].Colonists.F())
bombingReport[i].Capital = report.F(bombings[i].Capital.F())
bombingReport[i].Material = report.F(bombings[i].Material.F())
bombingReport[i].AttackPower = report.F(bombings[i].AttackPower.F())
bombingReport[i].Wiped = bombings[i].Wiped
}
}
// Store battles
battleReport := make([]*report.BattleReport, len(battles))
if len(battles) > 0 {
battleMeta := make([]game.BattleMeta, len(battles))
for i := range battles {
b := battles[i]
observers := make(map[uuid.UUID]bool)
for sgi := range b.ObserverGroups {
observers[c.Cache.ShipGroup(sgi).OwnerID] = true
}
battleMeta[i] = game.BattleMeta{
Turn: c.Cache.g.Turn,
Planet: b.Planet,
BattleID: b.ID,
ObserverIDs: slices.Collect(maps.Keys(observers)),
}
report := TransformBattle(c.Cache, b)
if err := c.repo.SaveBattle(c.Cache.g.Turn, report, &battleMeta[i]); err != nil {
return err
}
battleReport[i] = report
}
}
// Remove killed ship groups
c.Cache.DeleteKilledShipGroups()
// Store game state for the new turn and 'current' state as well
if err := c.repo.SaveNewTurn(c.Cache.g.Turn, c.Cache.g); err != nil {
return err
}
for rep := range c.Cache.Report(c.Cache.g.Turn, battleReport, bombingReport) {
if err := c.repo.SaveReport(c.Cache.g.Turn, rep); err != nil {
return err
}
}
for i := range c.Cache.g.Race {
if c.Cache.g.Race[i].Extinct {
continue
}
c.Cache.g.Race[i].TTL -= 1
}
// [ ] monitor memory consumption at this point?
return nil
}