Skip to content

Commit

Permalink
make stats handler event based for the pause and ensure the game memo…
Browse files Browse the repository at this point in the history
…ry is restored when closing koolo window, properly stopping the bot
  • Loading branch information
hectorgimenez committed Mar 27, 2024
1 parent 751a15f commit 234760b
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 23 deletions.
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
![Koolo](images/you_died.png)
<h1 align="center">Koolo</h1>
<p align="center">
<img src="assets/koolo.webp" alt="Koolo" width="150">
</p>
<h3 align="center">Koolo</h3>

---

Expand Down
8 changes: 4 additions & 4 deletions cmd/koolo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ func main() {

winproc.SetProcessDpiAware.Call() // Set DPI awareness to be able to read the correct scale and show the window correctly

eventListener := event.NewListener(logger)
manager := koolo.NewSupervisorManager(logger, eventListener)

g.Go(func() error {
displayScale := config.GetCurrentDisplayScale()
w, err := gowebview.New(&gowebview.Config{URL: "http://localhost:8087", WindowConfig: &gowebview.WindowConfig{
Expand All @@ -56,12 +59,11 @@ func main() {
w.Run()

cancel()
manager.StopAll()
os.Exit(0)
return nil
})

eventListener := event.NewListener(logger)

// Discord Bot initialization
if config.Koolo.Discord.Enabled {
discordBot, err := discord.NewBot(config.Koolo.Discord.Token, config.Koolo.Discord.ChannelID)
Expand Down Expand Up @@ -90,8 +92,6 @@ func main() {
})
}

manager := koolo.NewSupervisorManager(logger, eventListener)

g.Go(func() error {
srv := server.New(logger, manager)
return srv.Listen(8087)
Expand Down
16 changes: 10 additions & 6 deletions internal/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type Bot struct {
logger *slog.Logger
hm health.Manager
ab *action.Builder
container container.Container
c container.Container
paused bool
supervisorName string
}
Expand All @@ -37,7 +37,7 @@ func NewBot(
logger: logger,
hm: hm,
ab: ab,
container: container,
c: container,
supervisorName: supervisorName,
}
}
Expand Down Expand Up @@ -80,7 +80,7 @@ func (b *Bot) Run(ctx context.Context, firstRun bool, runs []run.Run) (err error
time.Sleep(time.Millisecond*10 - time.Since(loopTime))
}

d := b.container.Reader.GetData(false)
d := b.c.Reader.GetData(false)

// Skip running stuff if loading screen is present
if d.OpenMenus.LoadingScreen {
Expand Down Expand Up @@ -108,13 +108,13 @@ func (b *Bot) Run(ctx context.Context, firstRun bool, runs []run.Run) (err error
}

// TODO: Maybe add some kind of "on every iteration action", something that can be executed/skipped on every iteration
if b.ab.IsRebuffRequired(d) && (buffAct == nil || buffAct.Steps == nil || buffAct.Steps[len(buffAct.Steps)-1].Status(d, b.container) == step.StatusCompleted) {
if b.ab.IsRebuffRequired(d) && (buffAct == nil || buffAct.Steps == nil || buffAct.Steps[len(buffAct.Steps)-1].Status(d, b.c) == step.StatusCompleted) {
buffAct = b.ab.BuffIfRequired(d)
actions = append([]action.Action{buffAct}, actions...)
}

for k, act := range actions {
err := act.NextStep(d, b.container)
err := act.NextStep(d, b.c)
loopTime = time.Now()
if errors.Is(err, action.ErrNoMoreSteps) {
if len(actions)-1 == k {
Expand All @@ -129,7 +129,7 @@ func (b *Bot) Run(ctx context.Context, firstRun bool, runs []run.Run) (err error
break
}
if errors.Is(err, action.ErrCanBeSkipped) {
event.Send(event.RunFinished(event.WithScreenshot(b.supervisorName, err.Error(), b.container.Reader.Screenshot()), r.Name(), event.FinishedError))
event.Send(event.RunFinished(event.WithScreenshot(b.supervisorName, err.Error(), b.c.Reader.Screenshot()), r.Name(), event.FinishedError))
b.logger.Warn("error occurred on action that can be skipped, game will continue", slog.Any("error", err))
act.Skip()
break
Expand Down Expand Up @@ -186,9 +186,13 @@ func (b *Bot) postRunActions(currentRun int, runs []run.Run) []action.Action {
func (b *Bot) TogglePause() {
if b.paused {
b.logger.Info("Resuming...")
b.c.Injector.Load()
event.Send(event.GamePaused(event.Text(b.supervisorName, "Game resumed"), false))
b.paused = false
} else {
b.logger.Info("Pausing...")
b.c.Injector.RestoreMemory()
event.Send(event.GamePaused(event.Text(b.supervisorName, "Game paused"), true))
b.paused = true
}
}
12 changes: 12 additions & 0 deletions internal/event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,15 @@ func CompanionLeaderAttack(be BaseEvent, targetUnitID data.UnitID) CompanionLead
TargetUnitID: targetUnitID,
}
}

type GamePausedEvent struct {
BaseEvent
Paused bool
}

func GamePaused(be BaseEvent, paused bool) GamePausedEvent {
return GamePausedEvent{
BaseEvent: be,
Paused: paused,
}
}
6 changes: 6 additions & 0 deletions internal/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ func (mng *SupervisorManager) Start(supervisorName string) error {
return supervisor.Start()
}

func (mng *SupervisorManager) StopAll() {
for _, s := range mng.supervisors {
s.Stop()
}
}

func (mng *SupervisorManager) Stop(supervisor string) {
s, found := mng.supervisors[supervisor]
if found {
Expand Down
10 changes: 6 additions & 4 deletions internal/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,12 @@ func (h *StatsHandler) Handle(_ context.Context, e event.Event) error {
Name: evt.RunName,
StartedAt: evt.OccurredAt(),
})
case event.GamePausedEvent:
if evt.Paused {
h.stats.SupervisorStatus = Paused
} else {
h.stats.SupervisorStatus = InGame
}
case event.RunFinishedEvent:
h.stats.Games[len(h.stats.Games)-1].Runs[len(h.stats.Games[len(h.stats.Games)-1].Runs)-1].FinishedAt = evt.OccurredAt()
h.stats.Games[len(h.stats.Games)-1].Runs[len(h.stats.Games[len(h.stats.Games)-1].Runs)-1].Reason = evt.Reason
Expand All @@ -79,10 +85,6 @@ func (h *StatsHandler) Handle(_ context.Context, e event.Event) error {
return nil
}

func (h *StatsHandler) SetStatus(status SupervisorStatus) {
h.stats.SupervisorStatus = status
}

func (h *StatsHandler) updateGameStatsFile() {
if _, err := os.Stat("stats"); os.IsNotExist(err) {
err = os.MkdirAll("stats", os.ModePerm)
Expand Down
7 changes: 0 additions & 7 deletions internal/supervisor.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,6 @@ func (s *baseSupervisor) Stats() Stats {

func (s *baseSupervisor) TogglePause() {
s.bot.TogglePause()
if s.bot.paused {
s.statsHandler.SetStatus(Paused)
s.c.Injector.RestoreMemory()
} else {
s.statsHandler.SetStatus(InGame)
s.c.Injector.Load()
}
}

func (s *baseSupervisor) Stop() {
Expand Down

0 comments on commit 234760b

Please sign in to comment.