Implement character death handling and periodic checks: Add logic to process characters with health <= 0 in EventsWorker and UserCharacterWorker, including immediate death handling during health updates and a scheduled death check every 12 hours. Introduce a new SQL query to retrieve characters with zero health.

This commit is contained in:
Torsten Schulz (local)
2026-02-02 08:05:12 +01:00
parent 972ef2b714
commit 340c658ad1
3 changed files with 80 additions and 0 deletions

View File

@@ -9,6 +9,7 @@ use std::time::{Duration, Instant};
use super::base::{BaseWorker, Worker, WorkerState};
use crate::worker::sql::{
QUERY_GET_CHARACTERS_ZERO_HEALTH,
QUERY_GET_USERS_TO_UPDATE,
QUERY_UPDATE_CHARACTERS_HEALTH,
QUERY_UPDATE_MOOD,
@@ -59,6 +60,7 @@ pub struct UserCharacterWorker {
last_hourly_run: Option<Instant>,
last_pregnancy_run: Option<Instant>,
last_mood_run: Option<Instant>,
last_death_check_run: Option<Instant>,
}
// SQL moved to `src/worker/sql.rs`
@@ -76,6 +78,7 @@ impl UserCharacterWorker {
last_hourly_run: None,
last_pregnancy_run: None,
last_mood_run: None,
last_death_check_run: None,
}
}
@@ -83,6 +86,7 @@ impl UserCharacterWorker {
self.base.set_current_step("UserCharacterWorker iteration");
self.maybe_run_hourly_tasks();
self.maybe_run_death_check();
self.maybe_run_mood_updates();
self.maybe_run_daily_pregnancies();
@@ -116,6 +120,51 @@ impl UserCharacterWorker {
self.last_hourly_run = Some(now);
}
/// Alle 12 Stunden: Charaktere mit health <= 0 finden und Tod verarbeiten
fn maybe_run_death_check(&mut self) {
const DEATH_CHECK_INTERVAL_SECS: u64 = 12 * 3600;
let now = Instant::now();
let should_run = match self.last_death_check_run {
None => true,
Some(last) => now.saturating_duration_since(last) >= Duration::from_secs(DEATH_CHECK_INTERVAL_SECS),
};
if !should_run {
return;
}
if let Err(err) = self.process_zero_health_deaths() {
eprintln!("[UserCharacterWorker] Fehler bei Tod-Prüfung (health <= 0): {err}");
}
self.last_death_check_run = Some(now);
}
fn process_zero_health_deaths(&mut self) -> Result<(), DbError> {
let ids: Vec<i32> = {
let mut conn = self
.base
.pool
.get()
.map_err(|e| DbError::new(format!("DB-Verbindung fehlgeschlagen: {e}")))?;
conn.prepare("get_characters_zero_health", QUERY_GET_CHARACTERS_ZERO_HEALTH)?;
let rows = conn.execute("get_characters_zero_health", &[])?;
rows.into_iter()
.filter_map(|r| r.get("id").and_then(|v| v.parse::<i32>().ok()))
.collect()
};
for character_id in ids {
if let Err(e) = self.handle_character_death(character_id) {
eprintln!("[UserCharacterWorker] handle_character_death für Charakter {}: {e}", character_id);
}
}
Ok(())
}
fn run_hourly_tasks(&mut self) -> Result<(), DbError> {
self.process_character_events()?;
self.handle_credits()?;