use super::rules::Cond;
use super::{Kind, Phrase, Reader, Statement, Target, Tok, Token, is_word, phrase, shown, word_of};
const TRIGGERS: &[(&[&str], &str, &str)] = &[
(
&["asked", "or", "told", "about"],
"AskTellTopic",
"DefaultAskTellTopic",
),
(&["asked", "about"], "AskTopic", "DefaultAskTopic"),
(&["told", "about"], "TellTopic", "DefaultTellTopic"),
(
&["shown", "or", "given"],
"GiveShowTopic",
"DefaultGiveShowTopic",
),
(&["shown"], "ShowTopic", "DefaultShowTopic"),
(&["given"], "GiveTopic", "DefaultGiveTopic"),
];
#[derive(Debug, Clone)]
pub(super) struct Hint {
pub(super) title: String,
pub(super) opens: Vec<(bool, Cond)>,
pub(super) closes: Vec<(bool, Cond)>,
pub(super) steps: Vec<String>,
pub(super) line: u32,
pub(super) order: usize,
}
#[derive(Debug, Clone)]
pub(super) struct WrittenHint {
pub(super) title: String,
pub(super) opens: Option<String>,
pub(super) closes: Option<String>,
pub(super) steps: Vec<String>,
pub(super) line: u32,
pub(super) order: usize,
}
const TALK_FORM: &str = "What a character says is said as \"Greeted, the keeper says: \
\"...\"\", \"Said goodbye to, the keeper says: \"...\"\", \"Asked about the lamp, the keeper says: \"...\"\", or \"Otherwise, the keeper \
says: \"...\"\"; asked, told, asked or told, shown, given, or shown or given about anything \
else, as well.";
const HINT_FORM: &str = "A hint is said as \"The hint \"How do I get in?\" opens when the \
door is seen, and closes when the door is unlocked.\", and what it says after it: \"It says \
\"Is there a key?\", then \"Look in the box.\"\"";
impl Reader {
pub(super) fn talk_sentence(&mut self, line: u32, t: &[Token]) -> bool {
if is_word(t.first(), &["it"])
&& is_word(t.get(1), &["says"])
&& let Some(hint) = self.open_hint
{
self.hint_steps(line, hint, t);
return true;
}
self.open_hint = None;
if is_word(t.first(), &["the"])
&& is_word(t.get(1), &["hint"])
&& matches!(t.get(2).map(|t| &t.tok), Some(Tok::Text(_)))
{
self.hint(line, t);
return true;
}
let first = t.first().and_then(word_of).unwrap_or_default();
if !matches!(
first.as_str(),
"greeted" | "said" | "asked" | "told" | "shown" | "given" | "otherwise"
) || !t.iter().any(|token| is_word(Some(token), &["says"]))
{
return false;
}
self.says(line, t);
true
}
fn says(&mut self, line: u32, t: &[Token]) {
let bad = |reader: &mut Self| {
reader.problem(line, format!("I can't read \"{}\". {TALK_FORM}", shown(t)));
};
let Some(says) = t.iter().position(|token| is_word(Some(token), &["says"])) else {
return bad(self);
};
let text = match &t[says + 1..] {
[
Token {
tok: Tok::Punct(':'),
..
},
Token {
tok: Tok::Text(text),
..
},
] => text.clone(),
_ => return bad(self),
};
let Some(comma) = t[..says]
.iter()
.rposition(|token| matches!(token.tok, Tok::Punct(',')))
else {
return bad(self);
};
let Some(character) = phrase(&t[comma + 1..says]) else {
return bad(self);
};
let Some(character) = self.subject(character) else {
return;
};
let trigger = &t[..comma];
let words: Vec<String> = trigger.iter().filter_map(word_of).collect();
let (class, about) = if words == ["greeted"] {
("HelloTopic", Vec::new())
} else if words == ["said", "goodbye", "to"] {
("ByeTopic", Vec::new())
} else if words == ["otherwise"] {
("DefaultAnyTopic", Vec::new())
} else {
let Some((len, specific, default)) =
TRIGGERS.iter().find_map(|(lead, specific, default)| {
(words.len() > lead.len() && words[..lead.len()] == **lead).then_some((
lead.len(),
*specific,
*default,
))
})
else {
return bad(self);
};
let rest = &trigger[len..];
let rest_words = &words[len..];
if rest_words == ["anything", "else"] {
(default, Vec::new())
} else {
let mut about = Vec::new();
for part in super::split_list(rest).unwrap_or_default() {
about.push(part);
}
if about.is_empty() {
return bad(self);
}
(specific, about)
}
};
self.last_subject = Some(character.clone());
self.add(
line,
Statement::Topic {
character,
class,
about,
text,
},
);
}
fn hint(&mut self, line: u32, t: &[Token]) {
let Some(Tok::Text(title)) = t.get(2).map(|t| t.tok.clone()) else {
return;
};
let mut opens = Vec::new();
let mut closes = Vec::new();
let rest = &t[3..];
let mut parts: Vec<(&str, Vec<Token>)> = Vec::new();
let mut i = 0;
while i < rest.len() {
let word = word_of(&rest[i]).unwrap_or_default();
if matches!(word.as_str(), "opens" | "closes") && is_word(rest.get(i + 1), &["when"]) {
parts.push((if word == "opens" { "opens" } else { "closes" }, Vec::new()));
i += 2;
continue;
}
match parts.last_mut() {
Some((_, tokens)) => tokens.push(rest[i].clone()),
None => {
self.problem(line, format!("I can't read \"{}\". {HINT_FORM}", shown(t)));
return;
}
}
i += 1;
}
for (which, mut tokens) in parts {
while matches!(tokens.last().map(|t| &t.tok), Some(Tok::Punct(',')))
|| is_word(tokens.last(), &["and"])
{
tokens.pop();
if matches!(tokens.last().map(|t| &t.tok), Some(Tok::Punct(','))) {
tokens.pop();
}
}
if tokens.is_empty() {
self.problem(line, format!("I can't read \"{}\". {HINT_FORM}", shown(t)));
return;
}
let mut conds = Vec::new();
for part in split_and(&tokens) {
let Some(cond) = self.condition(line, &part) else {
self.open_hint = Some(usize::MAX);
return;
};
conds.push(cond);
}
if which == "opens" {
opens.extend(conds);
} else {
closes.extend(conds);
}
}
self.hints.push(Hint {
title,
opens,
closes,
steps: Vec::new(),
line,
order: self.sentences,
});
self.open_hint = Some(self.hints.len() - 1);
}
fn hint_steps(&mut self, line: u32, hint: usize, t: &[Token]) {
let mut steps = Vec::new();
let mut ok = true;
for token in &t[2..] {
match &token.tok {
Tok::Text(text) => steps.push(text.clone()),
Tok::Punct(',') => {}
Tok::Word(w) if matches!(w.to_lowercase().as_str(), "then" | "and") => {}
_ => ok = false,
}
}
if !ok || steps.is_empty() {
self.problem(
line,
format!(
"I can't read \"{}\". What a hint says is said as \"It says \"Is there a \
key?\", then \"Look in the box.\"\"",
shown(t)
),
);
return;
}
if hint != usize::MAX {
self.hints[hint].steps.extend(steps);
}
}
pub(super) fn topic(
&mut self,
line: u32,
character: &Phrase,
class: &'static str,
about: &[Phrase],
text: &str,
) {
let Some(c) = self.resolve_obj(character) else {
return;
};
if !matches!(self.objs[c].kind, Kind::Man | Kind::Woman | Kind::Person) {
let name = self.objs[c].called();
self.problem(
line,
format!("\"{name}\" is not a character, so it says nothing: a character is a man, a woman, or a person."),
);
return;
}
let mut matches = Vec::new();
for phrase in about {
match self.resolve(phrase) {
Ok(Target::Obj(i)) => matches.push(self.objs[i].id.clone()),
Ok(_) => {
self.problem(
phrase.line,
format!(
"\"{}\" is not something to talk about: a thing or a topic is.",
phrase.shown()
),
);
return;
}
Err(message) => {
self.problem(phrase.line, message);
return;
}
}
}
let matched = match matches.as_slice() {
[] => None,
[one] => Some(format!("@{one}")),
many => Some(format!("[{}]", many.join(", "))),
};
self.objs[c]
.topics
.push((line, class, matched, text.to_owned()));
}
pub(super) fn write_hints(&mut self) {
let hints = std::mem::take(&mut self.hints);
for hint in hints {
if hint.steps.is_empty() {
self.problem(
hint.line,
"This hint says nothing: say what it says after it, as \"It says \"Is there a key?\", then \"Look in the box.\"\"",
);
continue;
}
let test = |reader: &mut Self, conds: &[(bool, Cond)]| -> Option<Option<String>> {
if conds.is_empty() {
return Some(None);
}
let mut codes = Vec::new();
for (not, cond) in conds {
codes.push(reader.cond_code(*not, cond)?);
}
Some(Some(codes.join(" && ")))
};
let (Some(opens), Some(closes)) = (test(self, &hint.opens), test(self, &hint.closes))
else {
continue;
};
self.written_hints.push(WrittenHint {
title: hint.title,
opens,
closes,
steps: hint.steps,
line: hint.line,
order: hint.order,
});
}
}
pub(super) fn write_hint(&self, out: &mut Vec<(u32, String)>, hint: &WrittenHint, menu: &str) {
let line = hint.line;
out.push((line, format!("Goal '{}'", single_text(&hint.title))));
out.push((line, " [".to_owned()));
let n = hint.steps.len();
for (i, step) in hint.steps.iter().enumerate() {
let comma = if i + 1 < n { "," } else { "" };
out.push((line, format!(" '{}'{comma}", single_text(step))));
}
out.push((line, " ]".to_owned()));
out.push((line, format!(" location = {menu}")));
match &hint.opens {
Some(test) => out.push((line, format!(" openWhenTrue = ({test})"))),
None => out.push((line, " goalState = OpenGoal".to_owned())),
}
if let Some(test) = &hint.closes {
out.push((line, format!(" closeWhenTrue = ({test})")));
}
out.push((line, ";".to_owned()));
}
}
fn single_text(text: &str) -> String {
text.replace('\'', "\\'")
}
fn split_and(tokens: &[Token]) -> Vec<Vec<Token>> {
let mut parts = vec![Vec::new()];
for token in tokens {
if is_word(Some(token), &["and"]) {
parts.push(Vec::new());
} else if let Some(last) = parts.last_mut() {
last.push(token.clone());
}
}
parts
}
#[cfg(test)]
mod tests {
use super::super::translate;
const WORLD: &str = "The Hall is a room. The player is in the Hall.\n\
Bob is a man in the Hall. The lamp is a thing in the Hall.\n\
The storm is a topic. The box is a container in the Hall.\n";
fn hexicon(more: &str) -> String {
let translation = translate(&format!("{WORLD}{more}"));
assert!(
translation.problems.is_empty(),
"problems: {:?}",
translation.problems
);
translation.text()
}
fn has(text: &str, wanted: &str) {
assert!(text.contains(wanted), "no {wanted:?} in:\n{text}");
}
fn problem(more: &str, wanted: &str) {
let found = translate(&format!("{WORLD}{more}")).problems;
assert!(
found.iter().any(|(_, m)| m.contains(wanted)),
"{more:?}: wanted {wanted:?}, found {found:?}"
);
}
#[test]
fn what_a_character_says_becomes_topic_entries_in_it() {
let text = hexicon(
"Greeted, Bob says: \"'Hello.'\"\n\
Asked about the lamp, Bob says: \"'Mine.'\"\n\
Asked about the storm, the lamp, and the box, Bob says: \"'Wet.'\"\n\
Told about the storm, Bob says: \"'I know.'\"\n\
Asked or told about the box, Bob says: \"'Empty.'\"\n\
Shown the lamp, Bob says: \"'Nice.'\"\n\
Given the lamp, Bob says: \"'Thanks.'\"\n\
Shown or given the box, Bob says: \"'No.'\"\n\
Asked about anything else, Bob says: \"'Eh?'\"\n\
Otherwise, Bob says: \"Bob shrugs.\"",
);
has(
&text,
"HelloTopic\n \"<q>Hello.</q> \"\n location = bob\n;",
);
has(
&text,
"AskTopic @lamp\n \"<q>Mine.</q> \"\n location = bob\n;",
);
has(&text, "AskTopic [storm, lamp, box]\n");
has(&text, "TellTopic @storm\n");
has(&text, "AskTellTopic @box\n");
has(&text, "ShowTopic @lamp\n");
has(&text, "GiveTopic @lamp\n");
has(&text, "GiveShowTopic @box\n");
has(&text, "DefaultAskTopic\n \"<q>Eh?</q> \"\n");
has(
&text,
"DefaultAnyTopic\n \"Bob shrugs. \"\n location = bob\n;",
);
}
#[test]
fn a_hint_is_a_goal_that_opens_and_closes() {
let text = hexicon(
"The hint \"Where is the lamp?\" opens when the box is seen and the player \
does not have the lamp, and closes when the player has the lamp. It says \
\"Look around.\", \"It's in the Hall.\", then \"Take it.\"\n\
The hint \"How do I win?\" It says \"You can't.\"",
);
has(
&text,
"hintMenu: TopHintMenu 'Hints';\n\nGoal 'Where is the lamp?'\n [\n \
'Look around.',\n 'It\\'s in the Hall.',\n 'Take it.'\n ]\n \
location = hintMenu\n openWhenTrue = (box.seen && !lamp.isIn(now.player))\n \
closeWhenTrue = (lamp.isIn(now.player))\n;",
);
has(
&text,
"Goal 'How do I win?'\n [\n 'You can\\'t.'\n ]\n location = hintMenu\n goalState = OpenGoal\n;",
);
}
#[test]
fn a_sentence_ends_at_a_quotation_s_end() {
let text = hexicon("Greeted, Bob says: \"'Hello.'\"\nThe cup is a thing in the Hall.");
has(&text, "cup: Thing 'cup'");
}
#[test]
fn problems_with_talk_and_hints() {
problem("Greeted, the lamp says: \"Hi.\"", "is not a character");
problem(
"Asked about the sea, Bob says: \"Hm.\"",
"Nothing in the story is called",
);
problem("Asked about, Bob says: \"Hm.\"", "I can\u{2019}t read");
problem("Greeted, Bob says \"Hi.\"", "I can\u{2019}t read");
problem(
"The hint \"Help?\" opens when the lamp is shiny. It says \"No.\"",
"\u{201c}shiny\u{201d} is not something I know",
);
problem(
"The hint \"Help?\" opens when the lamp is seen.",
"This hint says nothing",
);
problem(
"The hint \"Help?\" It says nothing useful.",
"What a hint says is said as",
);
}
}