From 3af3657c7a50449841f274e82b8a112c29627d1b Mon Sep 17 00:00:00 2001 From: Grail Finder Date: Fri, 4 Jul 2025 21:35:59 +0300 Subject: [PATCH] Fix: timer --- handlers/game.go | 2 +- handlers/timer.go | 20 +++++++++++--------- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/handlers/game.go b/handlers/game.go index ae0a25b..939b79a 100644 --- a/handlers/game.go +++ b/handlers/game.go @@ -337,7 +337,7 @@ func HandleGiveClue(w http.ResponseWriter, r *http.Request) { fi.Room.ThisTurnLimit = 9 } fi.Room.OpenedThisTurn = 0 - StartTurnTimer(fi.Room.ID, time.Duration(fi.Room.Settings.RoundTime)*time.Second) + StartTurnTimer(fi.Room.ID, fi.Room.Settings.RoundTime) log.Debug("given clue", "clue", clue, "limit", fi.Room.ThisTurnLimit) notify(models.NotifyBacklogPrefix+fi.Room.ID, clue+num) notifyBotIfNeeded(fi.Room) diff --git a/handlers/timer.go b/handlers/timer.go index 9040184..1f09d31 100644 --- a/handlers/timer.go +++ b/handlers/timer.go @@ -2,7 +2,9 @@ package handlers import ( "context" + "fmt" "gralias/models" + "log/slog" "strconv" "sync" "time" @@ -18,29 +20,29 @@ var ( mu sync.Mutex ) -func StartTurnTimer(roomID string, duration time.Duration) { +func StartTurnTimer(roomID string, timeLeft uint32) { mu.Lock() defer mu.Unlock() if _, exists := timers[roomID]; exists { + slog.Debug("trying to launch already running timer", "room_id", roomID) return // Timer already running } ticker := time.NewTicker(1 * time.Second) done := make(chan bool) timers[roomID] = &roomTimer{ticker: ticker, done: done} go func() { - room, err := repo.RoomGetByID(context.Background(), roomID) - if err != nil { - log.Error("failed to get room by id", "error", err) - StopTurnTimer(roomID) - return - } - timeLeft := room.Settings.RoundTime for { select { case <-done: return case <-ticker.C: if timeLeft <= 0 { + room, err := repo.RoomGetByID(context.Background(), roomID) + if err != nil { + log.Error("failed to get room by id", "error", err) + StopTurnTimer(roomID) + return + } log.Info("turn time is over", "room_id", roomID) room.ChangeTurn() room.MimeDone = false @@ -53,7 +55,7 @@ func StartTurnTimer(roomID string, duration time.Duration) { return } timeLeft-- - notify(models.NotifyRoomUpdatePrefix+roomID, "") + notify(models.NotifyTurnTimerPrefix+roomID, fmt.Sprintf("%d", timeLeft)) } } }()