Skip to content

Commit

Permalink
refactor: spawn and terminate bots
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan1993spb committed Jan 16, 2024
1 parent 1766da2 commit 0ff06ce
Showing 1 changed file with 28 additions and 24 deletions.
52 changes: 28 additions & 24 deletions internal/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down

0 comments on commit 0ff06ce

Please sign in to comment.