Spaces:
Paused
Paused
File size: 16,028 Bytes
ae9764e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | /// Hierarchical debug output for ability evaluation.
/// Every line shows WHAT is being checked, WHAT the expected value is,
/// and WHAT the actual game state value is β all in one self-contained line.
use crate::ability::enums::ConditionType;
use crate::card::{Ability, AbilityEffect, Condition};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Mutex;
/// Toggle all ability debug output (eprintln! + rule_log buffer) at runtime.
/// Default OFF in production, ON in tests via test helpers.
pub static ABILITY_DEBUG: AtomicBool = AtomicBool::new(false);
/// Toggle structured verdict items in the in-game rule log.
/// Default OFF β set via RABUKA_RULE_LOG env var or set_rule_log_verbose().
/// This is SEPARATE from ABILITY_DEBUG: ABILITY_DEBUG controls terminal/eprintln
/// output (causes lag), while this controls in-game structured log items only.
pub static RULE_LOG_VERBOSE: AtomicBool = AtomicBool::new(false);
/// Enable/disable ability debug.
pub fn set_debug(enabled: bool) {
ABILITY_DEBUG.store(enabled, Ordering::SeqCst);
}
/// Enable/disable structured verdict items in in-game rule log.
pub fn set_rule_log_verbose(enabled: bool) {
RULE_LOG_VERBOSE.store(enabled, Ordering::SeqCst);
}
// Global buffer to collect debug logs between game state updates
static ABILITY_LOG_BUFFER: Mutex<Vec<String>> = Mutex::new(Vec::new());
// Persisted set of (card_no, full_text) for every ability activated across all test runs.
// Used to generate the coverage report (which abilities are tested vs untested).
static COVERAGE_LOG: Mutex<Vec<(String, String)>> = Mutex::new(Vec::new());
pub struct AbDebug {
indent: usize,
}
impl Default for AbDebug {
fn default() -> Self {
Self::new()
}
}
impl AbDebug {
pub fn new() -> Self {
AbDebug { indent: 0 }
}
pub fn flush_to_rule_log(rule_log: &mut Vec<String>) {
if let Ok(mut buffer) = ABILITY_LOG_BUFFER.lock() {
rule_log.extend(buffer.drain(..));
}
}
pub fn flush_to_structured_log(structured_log: &mut Vec<crate::types::LogEntry>, turn: u32) {
if let Ok(mut buffer) = ABILITY_LOG_BUFFER.lock() {
for line in buffer.drain(..) {
structured_log.push(crate::types::LogEntry {
text: line,
turn,
player_label: String::new(),
source_card_id: None,
source_card_name: None,
category: "debug".to_string(),
metadata: None,
});
}
}
}
pub fn p(&mut self, tag: &str, msg: impl std::fmt::Display) {
if !ABILITY_DEBUG.load(Ordering::Relaxed) {
return;
}
let pad = " ".repeat(self.indent);
let log_entry = format!("[AB]{pad}{tag} {msg}");
eprintln!("{}", log_entry);
log::debug!("{}", log_entry);
if let Ok(mut buffer) = ABILITY_LOG_BUFFER.lock() {
buffer.push(log_entry);
}
}
pub fn ability(&mut self, card_name: &str, card_no: &str, card_id: &str, ability: &Ability) {
self.p("ABILITY", format_args!("\"{}\" ({})", card_name, card_id));
self.indent += 1;
let trigger_str = ability.triggers.as_deref().unwrap_or("none");
let limit_str = ability
.use_limit
.map(|l| format!("{}/turn", l))
.unwrap_or_default();
self.p("TRIGGER", format_args!("{} {}", trigger_str, limit_str));
if !ability.full_text.is_empty() {
self.p("TEXT", &ability.full_text);
}
// Record coverage: (card_no, full_text) for untested-ability reporting
if ABILITY_DEBUG.load(Ordering::Relaxed) && !ability.full_text.is_empty() {
if let Ok(mut cov) = COVERAGE_LOG.lock() {
cov.push((card_no.to_string(), ability.full_text.clone()));
}
}
if let Some(ref cost) = ability.cost {
self.print_cost(cost, "");
}
}
pub fn condition(&mut self, cond: &Condition, actual: u32, threshold: u32, passed: bool) {
let ct = cond.condition_type;
let loc = cond.location.as_deref().unwrap_or("");
let tgt = cond.target.as_deref().unwrap_or("");
let gn = cond
.group_names
.as_ref()
.map(|g| format!("{:?}", g))
.unwrap_or_default();
let op = cond.operator.as_deref().unwrap_or(">=");
let pass = if passed { "PASS" } else { "FAIL" };
let (ct_label, detail): (&str, String) = match ct {
Some(ConditionType::Compound) => (
"compound",
format!(
"{} sub-conditions",
cond.conditions.as_ref().map(|c| c.len()).unwrap_or(0)
),
),
Some(ConditionType::CardCountCondition) => ("card_count_condition", {
let mut parts = vec![format!(
"{}{} {}{}",
op,
threshold,
cond.unit.as_deref().unwrap_or("x"),
loc
)];
if !tgt.is_empty() {
parts.push(tgt.to_string());
}
if !gn.is_empty() {
parts.push(format!("group={}", gn));
}
parts.push(format!("actual={}", actual));
parts.push(pass.to_string());
parts.join(" ")
}),
Some(ConditionType::LocationCondition) => ("location_condition", {
let extras = if cond.distinct.as_ref().is_some_and(|d| d.is_distinct()) {
" distinct=names"
} else {
""
};
format!(
"{}{} @{}.{}{} β actual={} {}",
op, threshold, loc, tgt, extras, actual, pass
)
}),
Some(ConditionType::ComparisonCondition) => ("comparison_condition", {
let rt = cond.resource_type.as_deref().unwrap_or("?");
format!(
"{}{} {}{} β actual={} {}",
op, threshold, rt, loc, actual, pass
)
}),
Some(ConditionType::AppearanceCondition) => ("appearance_condition", {
let areas = if cond.all_areas.unwrap_or(false) {
" all_areas"
} else {
""
};
format!(
"check presence{}{} β {}",
areas,
if cond.baton_touch_trigger.unwrap_or(false) {
" baton_touch"
} else {
""
},
pass
)
}),
Some(ConditionType::MovementCondition) => (
"movement_condition",
format!(
"movement={}{} β {}",
cond.movement.as_deref().unwrap_or("?"),
loc,
pass
),
),
Some(ConditionType::OrCondition) => (
"or_condition",
format!(
"{} sub-conditions (any)",
cond.conditions.as_ref().map(|c| c.len()).unwrap_or(0)
),
),
Some(ConditionType::OtherwiseCondition) => {
("otherwise_condition", format!("else branch β {}", pass))
}
_ => {
let label = ct.map(|c| c.to_str()).unwrap_or("?");
(label, format!("... {}", pass))
}
};
self.p("COND", format_args!("{:20} {}", ct_label, detail));
}
pub fn cost_pay(&mut self, cost: &AbilityEffect, ok: bool) {
let ct = if cost.action.is_empty() {
"custom"
} else {
cost.action.as_str()
};
let msg = match ct {
"pay_energy" => format!(
"pay {} E{}",
cost.energy_count.unwrap_or(1),
if cost.optional.unwrap_or(false) {
" (optional)"
} else {
""
}
),
"move_cards" => format!(
"move {} from {} to {} (src: {})",
cost.count.unwrap_or(1),
cost.source.as_deref().unwrap_or("?"),
cost.destination.as_deref().unwrap_or("?"),
trunc(&cost.text, 40)
),
"change_state" => format!(
"set {} β {}",
cost.source.as_deref().unwrap_or("self"),
cost.state_change.as_deref().unwrap_or("?")
),
"sequential_cost" => format!(
"compound ({} sub-costs)",
cost.compound.actions.as_ref().map(|c| c.len()).unwrap_or(0)
),
"reveal" => format!(
"reveal {} from {}",
cost.count.unwrap_or(1),
cost.source.as_deref().unwrap_or("?")
),
_ => format!("{}: {}", ct, trunc(&cost.text, 40)),
};
let status = if ok { "OK" } else { "FAIL" };
self.p("COST", format_args!("{} β {}", msg, status));
}
pub fn effect(&mut self, effect: &AbilityEffect) {
let a = &effect.action;
let msg = match a.as_str() {
"sequential" => format!(
"multi-step ({} sub-actions)",
effect
.compound
.actions
.as_ref()
.map(|v| v.len())
.unwrap_or(0)
),
"draw_card" => format!(
"draw {} card(s){}",
effect.count.unwrap_or(1),
if effect.optional.unwrap_or(false) {
" (optional)"
} else {
""
}
),
"move_cards" => format!(
"move {} from {} β {} (type: {})",
effect.count.unwrap_or(1),
effect.source.as_deref().unwrap_or("?"),
effect.destination.as_deref().unwrap_or("?"),
effect.card_type.as_deref().unwrap_or("card")
),
"gain_resource" => format!(
"gain {} {}{}",
effect.count.unwrap_or(1),
effect.resource.as_deref().unwrap_or("?"),
effect
.duration
.as_deref()
.map(|d| format!(" for {}", d))
.unwrap_or_default()
),
"modify_score" => format!(
"score {}{}",
effect.operation.as_deref().unwrap_or("add"),
effect.value.map(|v| format!(" {}", v)).unwrap_or_default()
),
"change_state" => format!(
"change state β {}",
effect.state_change.as_deref().unwrap_or("?")
),
"select" => format!(
"select {} {} from {}{}",
effect.count.unwrap_or(1),
effect.card_type.as_deref().unwrap_or("card"),
effect.source.as_deref().unwrap_or("?"),
if effect.optional.unwrap_or(false) {
" (optional)"
} else {
""
}
),
"look_and_select" => "look + select from deck".to_string(),
"pay_energy" => format!(
"pay {} E{}",
effect.count.unwrap_or(1),
if effect.optional.unwrap_or(false) {
" (optional)"
} else {
""
}
),
"reveal" => format!("reveal {}", effect.source.as_deref().unwrap_or("?")),
"position_change" => "position change".to_string(),
"gain_ability" => "gain ability".to_string(),
"do_nothing" => String::new(),
_ => format!("{}: {}", a, trunc(&effect.text, 50)),
};
if !msg.is_empty() {
self.p("EFFECT", format_args!("{}", msg));
}
if let Some(ref cond) = effect.condition {
self.p(
"COND",
format_args!("(gated by: {})", trunc(&cond.text, 60)),
);
}
}
pub fn print_cost(&mut self, cost: &AbilityEffect, prefix: &str) {
let ct = if cost.action.is_empty() {
"?"
} else {
cost.action.as_str()
};
let msg = match ct {
"pay_energy" => format!(
"pay {} E{}",
cost.energy_count.unwrap_or(1),
if cost.optional.unwrap_or(false) {
" (optional)"
} else {
""
}
),
"move_cards" => format!(
"{} β {} ({} {})",
cost.source.as_deref().unwrap_or("?"),
cost.destination.as_deref().unwrap_or("?"),
cost.count.unwrap_or(1),
cost.card_type.as_deref().unwrap_or("card")
),
"change_state" => format!("set self β {}", cost.state_change.as_deref().unwrap_or("?")),
"reveal" => format!(
"reveal {} {}",
cost.count.unwrap_or(1),
cost.card_type.as_deref().unwrap_or("card")
),
"sequential_cost" => format!(
"compound ({} sub-costs)",
cost.compound.actions.as_ref().map(|c| c.len()).unwrap_or(0)
),
"choice_condition" => "choice between costs".to_string(),
_ => ct.to_string(),
};
self.p("COST", format_args!("{}{}", prefix, msg));
}
}
/// Return a deduplicated list of (card_no, full_text) for every ability activated.
pub fn get_coverage_data() -> Vec<(String, String)> {
let mut seen = std::collections::HashSet::new();
let mut result = Vec::new();
if let Ok(cov) = COVERAGE_LOG.lock() {
for (card_no, text) in cov.iter() {
let key = format!("{}|{}", card_no, text);
if seen.insert(key) {
result.push((card_no.clone(), text.clone()));
}
}
}
result.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
result
}
/// Write coverage data to a JSON file at the given path.
/// Format: `{"covered": [{"card_no": "...", "full_text": "..."}, ...]}`
pub fn write_coverage_json(path: &str) -> Result<(), std::io::Error> {
let data = get_coverage_data();
let mut entries: Vec<serde_json::Value> = Vec::new();
for (card_no, text) in &data {
entries.push(serde_json::json!({
"card_no": card_no,
"full_text": text,
}));
}
let output = serde_json::json!({ "covered": entries });
let file = std::fs::File::create(path)?;
let writer = std::io::BufWriter::new(file);
serde_json::to_writer_pretty(writer, &output)?;
log::debug!(
"Coverage data written to {} ({} unique abilities)",
path,
entries.len()
);
Ok(())
}
fn trunc(s: &str, max: usize) -> String {
let chars: Vec<char> = s.chars().collect();
if chars.len() <= max {
s.to_string()
} else {
format!("{}...", chars[..max].iter().collect::<String>())
}
}
|