From 0ff06cefba2cee3f7fb5708ff2c5d6b278e393fc Mon Sep 17 00:00:00 2001 From: Ivan Pushkin Date: Tue, 16 Jan 2024 02:18:43 +0100 Subject: [PATCH] refactor: spawn and terminate bots --- internal/core/core.go | 52 +++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/internal/core/core.go b/internal/core/core.go index 0d3e276..b65afe0 100644 --- a/internal/core/core.go +++ b/internal/core/core.go @@ -218,37 +218,41 @@ func stateBotsNumber(state map[int]int) (number int) { } func (c *Core) unsafeApplyDiff(ctx context.Context, d map[int]int) { - // TODO: Refactor this disaster method. - for gameId, bots := range d { if bots > 0 { - c.wg.Add(bots) + c.unsafeSpawn(ctx, gameId, bots) + } else { + c.unsafeTerminate(ctx, gameId, -bots) + } + } +} - for i := 0; i < bots; i++ { - // Initialize new bot - bot := c.factory.New(gameId) +func (c *Core) unsafeSpawn(ctx context.Context, gameId, bots int) { + c.wg.Add(bots) - // Start bot - go func(gameId int) { - defer c.wg.Done() + for i := 0; i < bots; i++ { + // Initialize new bot + bot := c.factory.New(gameId) - bot.Run(utils.WithField(ctx, "game", gameId)) - }(gameId) + // Start bot + go func(gameId int) { + defer c.wg.Done() - // This is only okay because we are in the mutex lock: - // bot termination will not be called simultaneously. - c.bots[gameId] = append(c.bots[gameId], bot) - } - } else { - for i := 0; i < -bots; i++ { - c.bots[gameId][0].Stop() - c.bots[gameId] = c.bots[gameId][1:] + bot.Run(utils.WithField(ctx, "game", gameId)) + }(gameId) - if len(c.bots[gameId]) == 0 { - delete(c.bots, gameId) - } - } - } + c.bots[gameId] = append(c.bots[gameId], bot) + } +} + +func (c *Core) unsafeTerminate(ctx context.Context, gameId, bots int) { + for i := 0; i < bots && len(c.bots[gameId]) > 0; i++ { + c.bots[gameId][0].Stop() + c.bots[gameId] = c.bots[gameId][1:] + } + + if len(c.bots[gameId]) == 0 { + delete(c.bots, gameId) } }