use std::path::Path;
use std::process::ExitCode;
fn title_of(name: &str) -> String {
let words: Vec<String> = name
.split(['-', '_', ' '])
.filter(|word| !word.is_empty())
.map(|word| {
let mut chars = word.chars();
chars.next().map_or_else(String::new, |first| {
first.to_uppercase().chain(chars).collect()
})
})
.collect();
if words.is_empty() {
"My Game".to_owned()
} else {
words.join(" ")
}
}
fn toml_string(text: &str) -> String {
format!("\"{}\"", text.replace('\\', "\\\\").replace('"', "\\\""))
}
fn source_string(text: &str) -> String {
format!("'{}'", text.replace('\\', "\\\\").replace('\'', "\\'"))
}
fn libraries(choices: bool) -> &'static str {
if choices {
"[\"system\", { name = \"hexad\", include = [\"extensions/hypothetical\", \"extensions/choices\"] }]"
} else {
"[\"system\", \"hexad\"]"
}
}
fn manifest(title: &str, image: &str, choices: bool) -> String {
format!(
"# {title}, a game for Hexicon.\n\
\n\
[game]\n\
name = {}\n\
libraries = {}\n\
sources = [\"start\"]\n\
image = {}\n\
\n\
[defines]\n\
LANGUAGE = \"english\"\n",
toml_string(title),
libraries(choices),
toml_string(image)
)
}
fn start(title: &str, ifid: &str, choices: bool) -> String {
if choices {
return start_choices(title, ifid);
}
format!(
"// Where {title} begins.\n\
\n\
import hexad;\n\
\n\
// The story: what it is called, who wrote it, and who the player\n\
// is as it begins.\n\
story: Story\n\
\x20 IFID = '{ifid}'\n\
\x20 name = {}\n\
\x20 byline = 'by the author'\n\
\x20 version = '1'\n\
\n\
\x20 protagonist = me\n\
;\n\
\n\
// The first room, and what is in it.\n\
startRoom: Room 'Start Room'\n\
\x20 \"This is where the game begins. \"\n\
;\n\
\n\
+ note: Thing 'note'\n\
\x20 \"It says: <q>Welcome to <<story.name>>.</q> \"\n\
;\n\
\n\
// The player, who starts in the room.\n\
+ me: Player 'you'\n\
;\n",
source_string(title)
)
}
fn start_choices(title: &str, ifid: &str) -> String {
format!(
"// Where {title} begins.\n\
\n\
import hexad;\n\
\n\
// The story: what it is called, who wrote it, and who the player\n\
// is as it begins. It is played by choosing.\n\
story: Story\n\
\x20 IFID = '{ifid}'\n\
\x20 name = {}\n\
\x20 byline = 'by the author'\n\
\x20 version = '1'\n\
\n\
\x20 protagonist = me\n\
\x20 choiceGame = true\n\
;\n\
\n\
// The first room, and what is in it.\n\
startRoom: Room 'Start Room'\n\
\x20 \"This is where the game begins. \"\n\
;\n\
\n\
+ note: Thing 'note'\n\
\x20 \"A folded note. \"\n\
\x20 readDesc = \"It says: <q>Welcome to <<story.name>>.</q> \"\n\
;\n\
\n\
// The player, who starts in the room.\n\
+ me: Player 'you'\n\
;\n\
\n\
// What can be done in the room: its own choices, and then its\n\
// exits, which it lists by itself.\n\
startMoment: RoomMoment @startRoom;\n\
\n\
+ ActionChoice 'Read the note' action = Read dobj = note;\n",
source_string(title)
)
}
pub(crate) fn create(folder: &Path, choices: bool) -> Result<(String, String), String> {
let shown = folder.display();
if folder.exists()
&& std::fs::read_dir(folder)
.map(|mut entries| entries.next().is_some())
.unwrap_or(true)
{
return Err(format!(
"{shown}: already exists and is not empty; start a game in a new folder"
));
}
let name = folder
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let title = title_of(&name);
let image = format!("{}.hxg", if name.is_empty() { "game" } else { &name });
std::fs::create_dir_all(folder).map_err(|e| format!("{shown}: {e}"))?;
for (file, text) in [
("hexicon.toml", manifest(&title, &image, choices)),
(
"start.hxn",
start(&title, &hexicon_compiler::ifid::new(), choices),
),
] {
let path = folder.join(file);
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
}
Ok((title, image))
}
pub(crate) fn run(args: &[&str], usage: &str) -> ExitCode {
let (folder, choices) = match args {
[folder] => (folder, false),
["--choices", folder] => (folder, true),
_ => {
eprint!("{usage}");
return ExitCode::from(2);
}
};
match create(Path::new(folder), choices) {
Ok((title, image)) => {
println!(
"Started {title} in {folder}: hexicon.toml and start.hxn.\n\
To build it and play it:\n\
\n\
\x20 cd {folder}\n\
\x20 hexicon build\n\
\x20 hexicon run {image}"
);
ExitCode::SUCCESS
}
Err(message) => {
eprintln!("hexicon: {message}");
ExitCode::FAILURE
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_title_comes_from_the_folders_name() {
assert_eq!(title_of("my-game"), "My Game");
assert_eq!(title_of("the_lost_key"), "The Lost Key");
assert_eq!(title_of("Cave"), "Cave");
assert_eq!(title_of(""), "My Game");
}
#[test]
fn a_new_game_builds_as_it_is() {
let folder = std::env::temp_dir().join(format!("hexicon-new-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&folder);
let game = folder.join("my-game");
let (title, image) = create(&game, false).unwrap();
assert_eq!((title.as_str(), image.as_str()), ("My Game", "my-game.hxg"));
assert!(create(&game, false).is_err());
let game_dir = game.to_string_lossy().into_owned();
let out = game.join(&image).to_string_lossy().into_owned();
let _ = crate::build::run(&["-f", &game_dir, "-o", &out], "");
let built = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
let _ = std::fs::remove_dir_all(&folder);
assert!(built > 0, "no image was built");
}
#[test]
fn a_new_choice_game_builds_as_it_is() {
let folder =
std::env::temp_dir().join(format!("hexicon-new-choices-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&folder);
let game = folder.join("the-choice");
let (_, image) = create(&game, true).unwrap();
let manifest = std::fs::read_to_string(game.join("hexicon.toml")).unwrap();
assert!(manifest.contains("extensions/choices"));
let source = std::fs::read_to_string(game.join("start.hxn")).unwrap();
assert!(source.contains("choiceGame = true"));
let game_dir = game.to_string_lossy().into_owned();
let out = game.join(&image).to_string_lossy().into_owned();
let _ = crate::build::run(&["-f", &game_dir, "-o", &out], "");
let built = std::fs::metadata(&out).map(|meta| meta.len()).unwrap_or(0);
let _ = std::fs::remove_dir_all(&folder);
assert!(built > 0, "no image was built");
}
}