Files
pokerfreak/src/wire/respond.rs
T

59 lines
2.5 KiB
Rust

use super::decode::decode;
use super::decode_extras::extras;
use super::encode::{encode, encode_evs, encode_value};
use super::reads::reads;
use crate::engine::decide::{decide, decide_with};
use crate::engine::double_board::decide_double;
use crate::engine::run_twice::{run_twice, RunTwice};
use crate::fault::Fault;
use crate::game::{Decision, Spot};
use crate::guard::enforce::enforce;
use crate::guard::validate::check;
use crate::json::{parse, render, Value};
type Answer = (Decision, Option<(RunTwice, String)>, Option<Value>, Option<Value>);
fn pipeline(line: &str) -> Result<Answer, Fault> {
let value = parse(line)?;
let spot: Spot = check(decode(&value)?)?;
let extras = extras(&value)?;
let decision = match &extras.board_double {
Some(second) => decide_double(&spot, second),
None => match &extras.tournament {
Some(lage) => decide_with(&spot, Some(lage)),
None => enforce(&spot, decide(&spot)),
},
};
// Chip EVs only mean what they say on one board in cash: a double board or a tournament prices otherwise.
let plain = extras.board_double.is_none() && extras.tournament.is_none();
let evs = (extras.want_evs && plain).then(|| encode_evs(&decision)).flatten();
let rit = extras.rit_offered.then(|| run_twice(&spot, &decision));
Ok((decision, rit, reads(&value, &spot.villains), evs))
}
/// One request line in, one response line out (without trailing newline). Never panics.
/// With `ritOffered` the answer carries `rit` and `ritReason` after the contract keys; with
/// villain profiles it carries `reads` (wire::reads).
pub fn respond(line: &str) -> String {
match pipeline(line) {
Ok((decision, None, None, None)) => encode(&decision),
Ok((decision, rit, gelesen, evs)) => {
let Value::Object(mut felder) = encode_value(&decision) else {
return encode(&decision);
};
if let Some((answer, reason)) = rit {
felder.push(("rit".to_string(), Value::String(answer.name().to_string())));
felder.push(("ritReason".to_string(), Value::String(reason)));
}
if let Some(r) = gelesen {
felder.push(("reads".to_string(), r));
}
if let Some(e) = evs {
felder.push(("evs".to_string(), e));
}
render(&Value::Object(felder))
}
Err(fault) => encode(&Decision::abstain(format!("invalid request: {fault}"))),
}
}