use super::rules::{Cond, Effect, action_of};
use super::{Phrase, Reader, Tok, Token, double, is_word, list_of, phrase, shown, word_of};
#[derive(Debug, Clone, PartialEq)]
pub(super) enum Leads {
To(String),
End,
Stay,
}
#[derive(Debug, Clone)]
pub(super) struct ChoiceRead {
pub(super) label: String,
pub(super) leads: Leads,
pub(super) response: Option<String>,
pub(super) effects: Vec<(u32, Effect)>,
pub(super) offered: Vec<(bool, Cond)>,
pub(super) again: bool,
pub(super) words: Vec<String>,
pub(super) line: u32,
pub(super) broken: bool,
pub(super) action: Option<ActionPick>,
}
#[derive(Debug, Clone)]
pub(super) struct ActionPick {
pub(super) action: &'static str,
pub(super) dobj: Phrase,
pub(super) iobj: Option<Phrase>,
}
const TWO_OBJECTS: &[(&str, &str, &str)] = &[
("unlocking", "with", "UnlockWith"),
("locking", "with", "LockWith"),
("putting", "in", "PutIn"),
("putting", "on", "PutOn"),
("giving", "to", "GiveTo"),
("showing", "to", "ShowTo"),
];
#[derive(Debug, Clone)]
pub(super) struct Moment {
pub(super) name: String,
pub(super) text: String,
pub(super) begins_in: Option<Phrase>,
pub(super) prompt: Option<(u32, String)>,
pub(super) allows_commands: Option<u32>,
pub(super) on_end: Option<(u32, String)>,
pub(super) choices: Vec<ChoiceRead>,
pub(super) room: Option<Phrase>,
pub(super) room_id: Option<String>,
pub(super) id: String,
pub(super) line: u32,
pub(super) order: usize,
}
const MOMENT_FORM: &str = "A moment is said as \"The moment \"the plank snaps\" is \"A plank \
snaps under your foot.\"\", and its choices after it: \"The choice \"Grab the satchel\" leads \
to \"swaying\": \"You catch it.\"\"";
const CHOICE_FORM: &str = "A choice says where it goes, and what it shows: \"The choice \
\"Grab the satchel\" leads to \"swaying\": \"...\"\", \"... ends the moment: \"...\"\", or \
\"... stays in the moment: \"...\"\".";
impl Reader {
pub(super) fn choice_sentence(&mut self, line: u32, t: &[Token]) -> bool {
let text_at = |n: usize| match t.get(n).map(|t| &t.tok) {
Some(Tok::Text(text)) => Some(text.clone()),
_ => None,
};
if is_word(t.first(), &["the"])
&& is_word(t.get(1), &["moment"])
&& text_at(2).is_some()
&& is_word(t.get(3), &["is"])
{
self.moment(line, t);
return true;
}
if is_word(t.first(), &["the"])
&& is_word(t.get(1), &["choice"])
&& text_at(2).is_some()
&& is_word(t.get(3), &["is"])
&& is_word(t.get(4), &["in"])
{
self.room_choice(line, t);
return true;
}
if let Some(is) = t.iter().position(|token| is_word(Some(token), &["is"]))
&& is_word(t.get(is + 1), &["a"])
&& is_word(t.get(is + 2), &["choice"])
{
let words: Vec<String> = t[..is].iter().map_while(word_of).collect();
if action_of(&words).is_some()
|| TWO_OBJECTS
.iter()
.any(|(g, _, _)| words.first().is_some_and(|w| w == g))
{
self.action_choice(line, t, is);
return true;
}
}
let Some(m) = self.open_moment else {
if is_word(t.first(), &["the"])
&& is_word(t.get(1), &["choice"])
&& text_at(2).is_some()
{
self.problem(
line,
format!("A choice is in a moment, and comes after one. {MOMENT_FORM}"),
);
return true;
}
return false;
};
let failed = m == usize::MAX;
if is_word(t.first(), &["the"]) && is_word(t.get(1), &["choice"]) && text_at(2).is_some() {
if !failed {
self.choice(line, m, t);
}
return true;
}
let words: Vec<String> = t.iter().map_while(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
let about_moment = matches!(
w.as_slice(),
["it", "begins", ..]
| ["its", "prompt", ..]
| ["it", "allows", ..]
| ["when", "it", "ends", ..]
);
if about_moment && !failed && self.moments[m].room.is_some() {
self.problem(
line,
"A room's moment is what can be done in the room: it begins whenever the \
player is there, with the room's prompt.",
);
return true;
}
if about_moment {
if !failed {
self.moment_detail(line, m, t);
}
return true;
}
if let Some(c) = self.open_choice {
let about_choice = matches!(
w.as_slice(),
["it", "is", "offered", ..]
| ["it", "can", "be", "chosen", ..]
| ["it", "is", "also", "chosen", ..]
);
if about_choice {
if !failed {
self.choice_detail(line, m, c, t);
}
return true;
}
if let Some(result) = self.effect(t) {
if !failed {
let choice = &mut self.moments[m].choices[c];
match result {
Ok(effect) => choice.effects.push((line, effect)),
Err(message) => {
choice.broken = true;
self.problem(line, message);
}
}
}
return true;
}
}
self.open_moment = None;
self.open_choice = None;
false
}
fn moment(&mut self, line: u32, t: &[Token]) {
self.open_choice = None;
let (
Some(Tok::Text(name)),
[
Token {
tok: Tok::Text(text),
..
},
],
) = (t.get(2).map(|t| t.tok.clone()), &t[4..])
else {
self.problem(
line,
format!("I can't read \"{}\". {MOMENT_FORM}", shown(t)),
);
self.open_moment = Some(usize::MAX);
return;
};
if let Some(other) = self.moments.iter().find(|m| m.name == name) {
let first = other.line;
self.problem(
line,
format!("There is already a moment called \"{name}\", on line {first}."),
);
self.open_moment = Some(usize::MAX);
return;
}
self.moments.push(Moment {
name,
text: text.clone(),
begins_in: None,
prompt: None,
allows_commands: None,
on_end: None,
choices: Vec::new(),
room: None,
room_id: None,
id: String::new(),
line,
order: self.sentences,
});
self.open_moment = Some(self.moments.len() - 1);
}
fn moment_detail(&mut self, line: u32, m: usize, t: &[Token]) {
let words: Vec<String> = t.iter().filter_map(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
let last_text = match t.last().map(|t| &t.tok) {
Some(Tok::Text(text)) => Some(text.clone()),
_ => None,
};
let bad = |reader: &mut Self| {
reader.problem(
line,
format!(
"I can't read \"{}\". Of a moment, what can be said is when it begins (\"It \
begins the first time the player comes to the Hall.\"), its prompt (\"Its \
prompt is \"Which way? >\".\"), that it allows commands (\"It allows \
commands.\"), and what it shows when it ends (\"When it ends: \"...\"\").",
shown(t)
),
);
};
match w.as_slice() {
[
"it",
"begins",
"the",
"first",
"time",
"the",
"player",
"comes",
"to",
..,
] => match phrase(&t[9..]) {
Some(room) => self.moments[m].begins_in = Some(room),
None => bad(self),
},
["its", "prompt", "is"] if t.len() == 4 && last_text.is_some() => {
self.moments[m].prompt = last_text.map(|p| (line, p));
}
["it", "allows", "commands"] if t.len() == 3 => {
self.moments[m].allows_commands = Some(line);
}
["it", "allows", "commands", "and", "when", "it", "ends"]
if last_text.is_some()
&& matches!(t.get(3).map(|t| &t.tok), Some(Tok::Punct(',')))
&& matches!(t.get(t.len() - 2).map(|t| &t.tok), Some(Tok::Punct(':'))) =>
{
self.moments[m].allows_commands = Some(line);
self.moments[m].on_end = last_text.map(|e| (line, e));
}
["when", "it", "ends"]
if t.len() == 5 && matches!(t[3].tok, Tok::Punct(':')) && last_text.is_some() =>
{
self.moments[m].on_end = last_text.map(|e| (line, e));
}
_ => bad(self),
}
}
fn choice(&mut self, line: u32, m: usize, t: &[Token]) {
let Tok::Text(label) = &t[2].tok else { return };
let colon = t
.iter()
.position(|token| matches!(token.tok, Tok::Punct(':')))
.unwrap_or(t.len());
let how = &t[3..colon];
let words: Vec<String> = how.iter().filter_map(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
let leads = match (w.as_slice(), how) {
(
["leads", "to"],
[
_,
_,
Token {
tok: Tok::Text(to), ..
},
],
) => Some(Leads::To(to.clone())),
(["ends", "the", "moment"], _) if how.len() == 3 => Some(Leads::End),
(["stays", "in", "the", "moment"], _) if how.len() == 4 => Some(Leads::Stay),
_ => None,
};
let response = match &t[colon.min(t.len())..] {
[] => Some(None),
[
Token {
tok: Tok::Punct(':'),
..
},
Token {
tok: Tok::Text(text),
..
},
] => Some(Some(text.clone())),
_ => None,
};
let (Some(leads), Some(response)) = (leads, response) else {
self.problem(
line,
format!("I can't read \"{}\". {CHOICE_FORM}", shown(t)),
);
self.open_choice = None;
return;
};
let moment = &mut self.moments[m];
if let Some(other) = moment.choices.iter().find(|c| c.label == *label) {
let first = other.line;
self.problem(
line,
format!("This moment already has a choice \"{label}\", on line {first}."),
);
self.open_choice = None;
return;
}
moment.choices.push(ChoiceRead {
label: label.clone(),
leads,
response,
effects: Vec::new(),
offered: Vec::new(),
again: false,
words: Vec::new(),
line,
broken: false,
action: None,
});
self.open_choice = Some(moment.choices.len() - 1);
}
fn choice_detail(&mut self, line: u32, m: usize, c: usize, t: &[Token]) {
let words: Vec<String> = t.iter().map_while(word_of).collect();
let w: Vec<&str> = words.iter().map(String::as_str).collect();
match w.as_slice() {
["it", "is", "offered", "when", ..] => {
let mut conds = Vec::new();
for part in super::rules::split_words_and(&t[4..]) {
match self.condition(line, &part) {
Some(cond) => conds.push(cond),
None => {
self.moments[m].choices[c].broken = true;
return;
}
}
}
self.moments[m].choices[c].offered.extend(conds);
}
["it", "can", "be", "chosen", "again"] if t.len() == 5 => {
self.moments[m].choices[c].again = true;
}
["it", "is", "also", "chosen", "by"] => {
let mut texts = Vec::new();
let mut ok = true;
for token in &t[5..] {
match &token.tok {
Tok::Text(text) => texts.push(text.to_lowercase()),
Tok::Punct(',') => {}
Tok::Word(w)
if w.eq_ignore_ascii_case("and") || w.eq_ignore_ascii_case("or") => {}
_ => ok = false,
}
}
if ok && !texts.is_empty() {
self.moments[m].choices[c].words.extend(texts);
} else {
self.problem(
line,
format!(
"I can't read \"{}\". Other words for a choice are said as \"It is \
also chosen by \"help\" and \"shout\".\"",
shown(t)
),
);
}
}
_ => self.problem(
line,
format!(
"I can't read \"{}\". Of a choice, what can be said is when it is offered \
(\"It is offered when the player has the key.\"), that it can be chosen \
again, and other words for it (\"It is also chosen by \"help\".\").",
shown(t)
),
),
}
}
fn room_moment(&mut self, room: &Phrase, line: u32) -> usize {
let key = room.bare();
if let Some(m) = self
.moments
.iter()
.position(|m| m.room.as_ref().is_some_and(|r| r.bare() == key))
{
return m;
}
self.moments.push(Moment {
name: room.shown(),
text: String::new(),
begins_in: None,
prompt: None,
allows_commands: None,
on_end: None,
choices: Vec::new(),
room: Some(room.clone()),
room_id: None,
id: String::new(),
line,
order: self.sentences,
});
self.moments.len() - 1
}
fn room_choice(&mut self, line: u32, t: &[Token]) {
let Tok::Text(label) = &t[2].tok else { return };
let colon = t
.iter()
.position(|token| matches!(token.tok, Tok::Punct(':')))
.unwrap_or(t.len());
let room = phrase(&t[5..colon]);
let response = match &t[colon..] {
[] => Some(None),
[
Token {
tok: Tok::Punct(':'),
..
},
Token {
tok: Tok::Text(text),
..
},
] => Some(Some(text.clone())),
_ => None,
};
let (Some(room), Some(response)) = (room, response) else {
self.problem(
line,
format!(
"I can't read \"{}\". A choice in a room is said as \"The choice \"Listen \
at the stairs\" is in the Hall: \"Something creaks above.\"\"",
shown(t)
),
);
self.open_moment = Some(usize::MAX);
return;
};
let m = self.room_moment(&room, line);
self.moments[m].choices.push(ChoiceRead {
label: label.clone(),
leads: Leads::Stay,
response,
effects: Vec::new(),
offered: Vec::new(),
again: false,
words: Vec::new(),
line,
broken: false,
action: None,
});
self.open_moment = Some(m);
self.open_choice = Some(self.moments[m].choices.len() - 1);
}
fn action_choice(&mut self, line: u32, t: &[Token], is: usize) {
self.open_moment = None;
self.open_choice = None;
let bad = |reader: &mut Self| {
reader.problem(
line,
format!(
"I can't read \"{}\". A command offered as a choice is said as \"Taking \
the lamp is a choice in the Hall: \"Take the lamp\".\", or, offered \
wherever the lamp is, \"Lighting the lamp is a choice: \"Light the \
lamp\".\"",
shown(t)
),
);
};
let what = &t[..is];
let words: Vec<String> = what.iter().filter_map(word_of).collect();
let two = TWO_OBJECTS.iter().find(|(gerund, prep, _)| {
words.first().is_some_and(|w| w == gerund) && words.iter().any(|w| w == prep)
});
let pick = match two {
Some((_, prep, action)) => {
let at = what
.iter()
.position(|token| is_word(Some(token), &[prep]))
.unwrap_or(0);
match (phrase(&what[1..at]), phrase(&what[at + 1..])) {
(Some(dobj), Some(iobj)) => Some(ActionPick {
action,
dobj,
iobj: Some(iobj),
}),
_ => None,
}
}
None => action_of(&words).and_then(|(len, actions)| {
phrase(&what[len..]).map(|dobj| ActionPick {
action: actions[0],
dobj,
iobj: None,
})
}),
};
let Some(pick) = pick else {
return bad(self);
};
let rest = &t[is + 3..];
let colon = rest
.iter()
.position(|token| matches!(token.tok, Tok::Punct(':')));
let (place, label) = match (colon, rest.last().map(|t| &t.tok)) {
(Some(c), Some(Tok::Text(label))) if c + 2 == rest.len() => {
let place = &rest[..c];
if place.is_empty() {
(None, label.clone())
} else if is_word(place.first(), &["in"]) {
match phrase(&place[1..]) {
Some(room) => (Some(room), label.clone()),
None => return bad(self),
}
} else {
return bad(self);
}
}
_ => return bad(self),
};
let choice = ChoiceRead {
label,
leads: Leads::Stay,
response: None,
effects: Vec::new(),
offered: Vec::new(),
again: false,
words: Vec::new(),
line,
broken: false,
action: Some(pick),
};
match place {
Some(room) => {
let m = self.room_moment(&room, line);
self.moments[m].choices.push(choice);
}
None => self.thing_choices.push((self.sentences, choice)),
}
}
pub(super) fn name_moments(&mut self) {
for m in 0..self.moments.len() {
if let Some(room) = self.moments[m].room.clone() {
let id = match self.resolve_room(&room) {
Some(r) => {
let base = format!("{}Moment", self.objs[r].id);
let mut id = base.clone();
let mut n = 2;
while self.used_ids.contains(&id) {
id = format!("{base}{n}");
n += 1;
}
self.used_ids.push(id.clone());
self.moments[m].room_id = Some(self.objs[r].id.clone());
id
}
None => String::new(),
};
self.moments[m].id = id;
continue;
}
let mut words: Vec<String> = self.moments[m]
.name
.split_whitespace()
.map(str::to_lowercase)
.collect();
if words.len() > 1 && matches!(words[0].as_str(), "the" | "a" | "an") {
words.remove(0);
}
let id = self.fresh_id(&words);
self.moments[m].id = id;
}
}
pub(super) fn moment_id(&mut self, line: u32, name: &str) -> Option<String> {
if let Some(m) = self.moments.iter().find(|m| m.name == name) {
return Some(m.id.clone());
}
let names: Vec<String> = self
.moments
.iter()
.map(|m| format!("\"{}\"", m.name))
.collect();
let names: Vec<&str> = names.iter().map(String::as_str).collect();
self.problem(
line,
if names.is_empty() {
format!("There is no moment called \"{name}\".")
} else {
format!(
"There is no moment called \"{name}\". The moments are {}.",
list_of(&names, "and")
)
},
);
None
}
pub(super) fn write_moments(&mut self) {
let moments = self.moments.clone();
for moment in &moments {
let mut out: Vec<(u32, String)> = Vec::new();
let line = moment.line;
if moment.room.is_some() {
let Some(room) = &moment.room_id else {
continue;
};
out.push((line, format!("{}: RoomMoment @{room};", moment.id)));
for choice in moment.choices.iter().filter(|c| !c.broken) {
self.write_choice(&mut out, choice, &moment.id, None);
}
self.written_moments.push((moment.order, out));
continue;
}
out.push((line, format!("{}: ChoiceMoment", moment.id)));
out.push((line, format!(" \"{} \"", double(&moment.text))));
if let Some((l, prompt)) = &moment.prompt {
out.push((
*l,
format!(" choicePrompt = '{}'", prompt.replace('\'', "\\'")),
));
}
if let Some(l) = moment.allows_commands {
out.push((l, " allowCommands = true".to_owned()));
}
if let Some((l, text)) = &moment.on_end {
out.push((
*l,
format!(" onEnd() {{ \"<.p>{}<.p>\"; }}", double(text)),
));
}
out.push((line, ";".to_owned()));
if let Some(room) = &moment.begins_in
&& let Some(r) = self.resolve_room(room)
{
self.objs[r].begins.push((room.line, moment.id.clone()));
}
for choice in moment.choices.iter().filter(|c| !c.broken) {
self.write_choice(&mut out, choice, &moment.id, None);
}
self.written_moments.push((moment.order, out));
}
let things = std::mem::take(&mut self.thing_choices);
for (order, choice) in &things {
let Some(pick) = &choice.action else { continue };
let Some(i) = self.resolve_obj(&pick.dobj) else {
continue;
};
if matches!(self.objs[i].kind, super::Kind::Room | super::Kind::Topic) {
let name = self.objs[i].called();
self.problem(
choice.line,
format!("\"{name}\" can't have choices of its own: a thing can."),
);
continue;
}
let id = self.objs[i].id.clone();
let mut out = Vec::new();
self.write_choice(&mut out, choice, &id, Some(i));
self.written_moments.push((*order, out));
}
}
fn write_choice(
&mut self,
out: &mut Vec<(u32, String)>,
choice: &ChoiceRead,
moment: &str,
own: Option<usize>,
) {
let line = choice.line;
if let Some(pick) = &choice.action {
out.push((
line,
format!("ActionChoice '{}'", choice.label.replace('\'', "\\'")),
));
out.push((line, format!(" location = {moment}")));
out.push((line, format!(" action = {}", pick.action)));
let dobj = self.resolve_obj(&pick.dobj);
if let Some(d) = dobj
&& own != Some(d)
{
out.push((line, format!(" dobj = {}", self.objs[d].id)));
}
if let Some(iobj) = &pick.iobj
&& let Some(i) = self.resolve_obj(iobj)
{
out.push((line, format!(" iobj = {}", self.objs[i].id)));
}
out.push((line, ";".to_owned()));
return;
}
let leads = match &choice.leads {
Leads::To(name) => match self.moment_id(line, name) {
Some(id) => format!(" ->{id}"),
None => return,
},
Leads::End => " ->nil".to_owned(),
Leads::Stay => String::new(),
};
out.push((
line,
format!("Choice '{}'{leads}", choice.label.replace('\'', "\\'")),
));
if let Some(response) = &choice.response {
out.push((line, format!(" \"{} \"", double(response))));
}
out.push((line, format!(" location = {moment}")));
if !choice.offered.is_empty() {
let mut tests = Vec::new();
for (not, cond) in &choice.offered {
if let Some(code) = self.cond_code(*not, cond) {
tests.push(code);
}
}
out.push((line, format!(" isAvailable = ({})", tests.join(" && "))));
}
if choice.again {
out.push((line, " isOnce = nil".to_owned()));
}
if !choice.words.is_empty() {
let words: Vec<String> = choice
.words
.iter()
.map(|w| format!("'{}'", w.replace('\'', "\\'")))
.collect();
out.push((line, format!(" words = [{}]", words.join(", "))));
}
if !choice.effects.is_empty() {
let mut body = Vec::new();
for (l, effect) in &choice.effects {
self.scoring_line = *l;
if let Some(code) = self.effect_code(effect) {
body.push((*l, code));
}
}
if let [(l, code)] = body.as_slice() {
out.push((*l, format!(" effect() {{ {code} }}")));
} else {
out.push((line, " effect()".to_owned()));
out.push((line, " {".to_owned()));
for (l, code) in body {
out.push((l, format!(" {code}")));
}
out.push((line, " }".to_owned()));
}
}
out.push((line, ";".to_owned()));
}
pub(super) fn begins_members(&self, i: usize) -> Vec<(u32, String)> {
let begins = &self.objs[i].begins;
let Some((first, _)) = begins.first() else {
return Vec::new();
};
let mut out = vec![
(*first, " afterTravel(traveler, connector)".to_owned()),
(*first, " {".to_owned()),
(*first, " inherited(traveler, connector);".to_owned()),
];
for (line, id) in begins {
out.push((
*line,
format!(" if (traveler == now.player && {id}.timesBegun == 0)"),
));
out.push((*line, format!(" {id}.begin();")));
}
out.push((*first, " }".to_owned()));
out
}
}
#[cfg(test)]
mod tests {
use super::super::translate;
const WORLD: &str = "The Hall is a room. The Yard is a room north of the Hall.\n\
The player is in the Hall. The key is a thing 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 a_moment_and_its_choices() {
let text = hexicon(
"The moment \"the door creaks\" is \"The door creaks.\"\n\
It begins the first time the player comes to the Yard.\n\
Its prompt is \"Well? >\".\n\
It allows commands, and when it ends: \"Quiet again.\"\n\
The choice \"Listen\" leads to \"silence\": \"You listen.\"\n\
The choice \"Run\" ends the moment: \"You run.\" Now the key is nowhere. It \
scores a point: \"running\".\n\
The choice \"Wait\" stays in the moment: \"You wait.\"\n\
It is offered when the player has the key. It can be chosen again.\n\
It is also chosen by \"hold\" and \"stay\".\n\
The moment \"silence\" is \"Nothing.\"\n\
The choice \"Go on\" ends the moment.",
);
has(
&text,
"doorCreaks: ChoiceMoment\n \"The door creaks. \"\n choicePrompt = 'Well? >'\n \
allowCommands = true\n onEnd() { \"<.p>Quiet again.<.p>\"; }\n;\n\
Choice 'Listen' ->silence\n \"You listen. \"\n location = doorCreaks\n;\n\
Choice 'Run' ->nil\n \"You run. \"\n location = doorCreaks\n effect()\n {\n \
key.moveInto(nil);\n running.awardPointsOnce();\n }\n;\n\
Choice 'Wait'\n \"You wait. \"\n location = doorCreaks\n \
isAvailable = (key.isIn(now.player))\n isOnce = nil\n words = ['hold', 'stay']\n;",
);
has(&text, "Choice 'Go on' ->nil\n location = silence\n;");
has(
&text,
"yard: Room 'Yard'\n south = hall\n afterTravel(traveler, connector)\n {\n \
inherited(traveler, connector);\n if (traveler == now.player && \
doorCreaks.timesBegun == 0)\n doorCreaks.begin();\n }\n;",
);
}
#[test]
fn a_rule_begins_a_moment_and_a_test_checks_it() {
let text = hexicon(
"The moment \"choosing\" is \"Choose.\"\nThe choice \"Done\" ends the moment.\n\
After taking the key: the moment \"choosing\" begins.\n\
The test \"choosing\".\n\
Type \"take key\": the moment \"choosing\" is current.\n\
Type \"done\": no moment is current.",
);
has(&text, " choosing.begin();\n");
has(&text, " expect = (choiceManager.current == choosing)\n");
has(&text, " expect = (choiceManager.current == nil)\n");
}
#[test]
fn what_the_player_carries() {
let text = hexicon("The lamp is a thing. The player carries the lamp.");
has(&text, "lamp: Thing 'lamp'\n location = me\n;");
}
#[test]
fn problems_with_moments_and_choices() {
problem(
"The choice \"Go\" ends the moment.",
"A choice is in a moment",
);
problem(
"The moment \"m\" is \"M.\"\nThe choice \"Go\": \"Off.\"",
"A choice says where it goes",
);
problem(
"The moment \"m\" is \"M.\"\nThe choice \"Go\" leads to \"n\".",
"There is no moment called \u{201c}n\u{201d}",
);
problem(
"The moment \"m\" is \"M.\"\nThe moment \"m\" is \"N.\"",
"There is already a moment called",
);
problem(
"The moment \"m\" is \"M.\"\nIt begins when it likes.",
"Of a moment, what can be said",
);
problem(
"The moment \"m\" is \"M.\"\nThe choice \"Go\" ends the moment.\nIt is offered when \
the key is shiny.",
"\u{201c}shiny\u{201d} is not something I know",
);
problem(
"After taking the key: the moment \"x\" begins.",
"There is no moment called",
);
problem("The player carries the Hall.", "can\u{2019}t carry");
}
}
#[cfg(test)]
mod more_tests {
use super::super::{translate, translate_all};
const WORLD: &str = "The Hall is a room. The player is in the Hall.\n\
The lamp is a lightable thing in the Hall.\n\
The box is an openable container in the Hall.\n\
The key is a key in the Hall. It unlocks the box.\n\
Bob is a man 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 a_room_s_moment_and_its_choices() {
let text = hexicon(
"Taking the lamp is a choice in the Hall: \"Take the lamp\".\n\
Unlocking the box with the key is a choice in the Hall: \"Unlock the box\".\n\
Putting the key in the box is a choice in the Hall: \"Hide the key\".\n\
The choice \"Listen\" is in the Hall: \"Nothing.\" It can be chosen again.",
);
has(
&text,
"hallMoment: RoomMoment @hall;\n\
ActionChoice 'Take the lamp'\n location = hallMoment\n action = Take\n dobj = lamp\n;\n\
ActionChoice 'Unlock the box'\n location = hallMoment\n action = UnlockWith\n \
dobj = box\n iobj = key\n;\n\
ActionChoice 'Hide the key'\n location = hallMoment\n action = PutIn\n \
dobj = key\n iobj = box\n;\n\
Choice 'Listen'\n \"Nothing. \"\n location = hallMoment\n isOnce = nil\n;",
);
}
#[test]
fn a_thing_s_own_choices() {
let text = hexicon(
"Lighting the lamp is a choice: \"Light the lamp\".\n\
Talking to Bob is a choice: \"Talk to Bob\".",
);
has(
&text,
"ActionChoice 'Light the lamp'\n location = lamp\n action = Light\n;",
);
has(
&text,
"ActionChoice 'Talk to Bob'\n location = bob\n action = TalkTo\n;",
);
}
#[test]
fn a_story_told_in_choices_and_saying_goodbye() {
let text = hexicon(
"The story is \"Choosing\".\nThe story is told in choices.\n\
Said goodbye to, Bob says: \"'Bye.'\"",
);
has(&text, " protagonist = me\n choiceGame = true\n;");
has(
&text,
"ByeTopic\n \"<q>Bye.</q> \"\n location = bob\n;",
);
let translations = translate_all(&[
("start.hxe", &format!("{WORLD}The story is \"Choosing\".")),
("only.hxe", "The story is told in choices alone."),
]);
assert!(translations.iter().all(|t| t.problems.is_empty()));
assert!(translations[0].text().contains(" choicesOnly = true\n"));
}
#[test]
fn problems_with_room_and_action_choices() {
problem(
"Taking the lamp is a choice in the Hall.",
"A command offered as a choice is said as",
);
problem(
"Taking the lamp is a choice in the Cellar: \"Take it\".",
"Nothing in the story is called \u{201c}the Cellar\u{201d}",
);
problem(
"The choice \"Wait\" is in the Hall: \"Hm.\"\nIts prompt is \"? >\".",
"A room\u{2019}s moment is what can be done in the room",
);
problem(
"Taking the Hall is a choice: \"Take it\".",
"can\u{2019}t have choices of its own",
);
}
}