epkard 0.1.1

A generalized framework for creating branching narratives
Documentation
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#![deny(missing_docs)]
#![deny(unsafe_code)]

/*!

Epkard is a generalized framework for creating branching narratives.

[Examples](https://github.com/kaikalii/epkard/tree/master/examples)
*/

mod paragraphs;
pub use paragraphs::*;
mod frontend;
pub use frontend::*;

use std::{
    collections::HashMap,
    error::Error,
    fmt::{self, Display, Formatter},
    fs, io,
    ops::{Deref, DerefMut},
    path::Path,
    sync::Arc,
};

use serde::{de::DeserializeOwned, Serialize};
pub use serde_derive::{Deserialize, Serialize};

/// An item that may be owned mutably borrowed
enum MayBor<'a, T> {
    Owned(T),
    Borrowed(&'a mut T),
}

impl<'a, T> Deref for MayBor<'a, T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        use MayBor::*;
        match self {
            Owned(x) => x,
            Borrowed(x) => x,
        }
    }
}

impl<'a, T> DerefMut for MayBor<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        use MayBor::*;
        match self {
            Owned(x) => x,
            Borrowed(x) => x,
        }
    }
}

/// An error used by the [`Runtime`](struct.Runtime.html)
#[derive(Debug)]
pub enum RuntimeError {
    /// An IO error
    IO(io::Error),
    /// A [`serde_yaml`](https://docs.rs/serde_yaml) error
    Serialize(serde_yaml::Error),
}

impl From<io::Error> for RuntimeError {
    fn from(e: io::Error) -> Self {
        RuntimeError::IO(e)
    }
}

impl From<serde_yaml::Error> for RuntimeError {
    fn from(e: serde_yaml::Error) -> Self {
        RuntimeError::Serialize(e)
    }
}

impl Display for RuntimeError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        use RuntimeError::*;
        match self {
            IO(e) => write!(f, "{}", e),
            Serialize(e) => write!(f, "{}", e),
        }
    }
}

impl Error for RuntimeError {}

/// A `Result` type used by the [`Runtime`](struct.Runtime.html)
pub type RuntimeResult<T> = Result<T, RuntimeError>;

/// A type for non-continuous narrative flow.
///
/// These normally only need to be explicitly used as the return type
/// for [`Runtime`](struct.Runtime.html) commands added via
/// [`RunBuilder::command`](struct.RunBuilder.html#method.command).
///
/// This serves as the error type for [`ControlResult`](type.ControlResult.html).
pub enum Interrupt<N> {
    /// Exit the program
    Exit,
    /// Skip the rest of the current [`Node`](trait.Node.html)
    ///
    /// This is normally used after loading a save file.
    Skip,
    /// Continue the current [`Node`](trait.Node.html)
    ///
    /// This picks up where the node left off.
    Continue,
    /// Jump to a [`Node`](trait.Node.html)
    Jump(N),
}

pub use Interrupt::*;

/// A type for controlling narrative flow for non-node types
pub type ControlResult<T, N> = Result<T, Interrupt<N>>;

/// A type for controlling narrative flow of nodes
pub type Control<N> = ControlResult<N, N>;

/// Get a next [`ControlResult`](type.ControlResult.html) with the given [`Node`](trait.Node.html)
pub fn next<T, N>(data: T) -> ControlResult<T, N> {
    Ok(data)
}

/// Get an exit [`ControlResult`](type.ControlResult.html)
pub fn exit<T, N>() -> ControlResult<T, N> {
    Err(Exit)
}

/**

A story node in a narrative.

In a branching narrative, a node is a place where the
story can split into different branches.

While [`Node`](trait.Node.html)s themselves should be transient and not hold
too much data, they have an associated state that can be
mutated.
*/
pub trait Node: Clone {
    /// The state that the node transforms
    type State;
    /// Handle the node to transforms the state and determine the next node
    ///
    /// The state can be access by [`deref`](struct.Runtime.html#impl-Deref)ing the [`Runtime`](struct.Runtime.html).
    fn next<F>(self, rt: &mut Runtime<Self, F>) -> Control<Self>
    where
        F: Frontend;
}

/// Wraps the basic state with extra information and functionality
pub struct Runtime<'a, N, F = CliFrontend>
where
    N: Node,
    F: Frontend,
{
    curr_node: N,
    state: MayBor<'a, N::State>,
    frontend: MayBor<'a, F>,
    commands: HashMap<String, Arc<Box<CommandFn<N, F>>>>,
}

impl<'a, N, F> Runtime<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    fn borrow_state_frontend<G>(&mut self, f: G)
    where
        G: FnOnce(&mut N::State, &mut F),
    {
        f(&mut *self.state, &mut self.frontend)
    }
    /// Push a [`Node`](trait.Node.html) onto the stack using its default
    pub fn push<M>(&mut self) -> Interrupt<N>
    where
        M: Node<State = N::State> + Default,
    {
        self.borrow_state_frontend(|state, frontend| {
            run(M::default(), state, frontend);
        });
        Continue
    }
    /// Push a [`Node`](trait.Node.html) onto the stack
    pub fn push_node<M>(&mut self, node: M) -> Interrupt<N>
    where
        M: Node<State = N::State>,
    {
        self.borrow_state_frontend(|state, frontend| {
            run(node, state, frontend);
        });
        Continue
    }
    /// Save the [`Runtime`](struct.Runtime.html) to the given path
    pub fn save<P: AsRef<Path>>(&self, path: P) -> RuntimeResult<()>
    where
        N: Serialize,
        N::State: Serialize,
    {
        fs::write(
            path,
            &serde_yaml::to_vec(&(&self.curr_node, self.state.deref()))?,
        )?;
        Ok(())
    }
    /// Load the [`Runtime`](struct.Runtime.html) from the given path
    pub fn load<P: AsRef<Path>>(&mut self, path: P) -> RuntimeResult<()>
    where
        N: DeserializeOwned,
        N::State: DeserializeOwned,
    {
        let (curr_node, state): (N, N::State) = serde_yaml::from_slice(&fs::read(path)?)?;
        self.curr_node = curr_node;
        self.state = MayBor::Owned(state);
        Ok(())
    }
    #[must_use]
    fn prompt_intercept(&mut self) -> ControlResult<String, N> {
        loop {
            let input = self.input();
            match input.as_str().trim() {
                "quit" => break exit(),
                s => {
                    if let Some(f) = self.commands.get(s).cloned() {
                        match f(self) {
                            Continue => {}
                            e => break Err(e),
                        }
                    } else {
                        break next(s.to_string());
                    }
                }
            }
        }
    }
    /// Prompt the user to enter text
    #[must_use]
    pub fn prompt<S: Display>(&mut self, prompt: S) -> ControlResult<String, N> {
        loop {
            self.println(&prompt);
            let input = self.prompt_intercept()?;
            if !input.is_empty() {
                break next(input);
            }
        }
    }
    /// Wait for the user to continue
    #[must_use]
    pub fn wait(&mut self) -> ControlResult<(), N> {
        self.prompt_intercept()?;
        next(())
    }
    /// Prompt the user with multiple choices
    #[must_use]
    pub fn multiple_choice<M, C>(&mut self, message: M, choices: &[C]) -> ControlResult<usize, N>
    where
        M: Display,
        C: Display,
    {
        loop {
            self.println(&message);
            for (i, choice) in choices.iter().enumerate() {
                self.println(format!("{}) {}", i + 1, choice));
            }
            let resp = self.prompt_intercept()?;
            match resp.parse::<usize>() {
                Ok(num) if num > 0 && num <= choices.len() => break next(num - 1),
                Err(_) => {
                    if let Some(i) = choices
                        .iter()
                        .position(|c| c.to_string().to_lowercase() == resp.to_lowercase())
                    {
                        break next(i);
                    } else {
                        self.println("Invalid choice")
                    }
                }
                _ => self.println("Invalid choice"),
            }
        }
    }
    /// Prompt the user with custom-named multiple choices
    #[must_use]
    pub fn multiple_choice_named<M, S, C, I>(
        &mut self,
        message: M,
        choices: I,
    ) -> ControlResult<C, N>
    where
        M: Display,
        S: Display,
        I: IntoIterator<Item = (S, C)>,
    {
        let mut choices: Vec<(S, C)> = choices.into_iter().collect();
        loop {
            self.println(&message);
            for (i, (text, _)) in choices.iter().enumerate() {
                self.println(format!("{}) {}", i + 1, text));
            }
            let resp = self.prompt_intercept()?;
            match resp.parse::<usize>() {
                Ok(num) if num > 0 && num <= choices.len() => {
                    break next(choices.remove(num - 1).1)
                }
                _ => self.println("Invalid choice"),
            }
        }
    }
}

impl<'a, N, F> Deref for Runtime<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    type Target = N::State;
    fn deref(&self) -> &Self::Target {
        &self.state
    }
}

impl<'a, N, F> DerefMut for Runtime<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.state
    }
}

impl<'a, N, F> AsRef<N::State> for Runtime<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    fn as_ref(&self) -> &N::State {
        &self.state
    }
}

impl<'a, N, F> AsMut<N::State> for Runtime<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    fn as_mut(&mut self) -> &mut N::State {
        &mut self.state
    }
}

/// Trait for listing command names
pub trait CommandNames {
    /// Get a command name vector
    fn commands(&self) -> Vec<String>;
}

impl CommandNames for &str {
    fn commands(&self) -> Vec<String> {
        self.split_whitespace()
            .flat_map(|s| s.split(','))
            .flat_map(|s| s.split('|'))
            .filter(|s| !s.is_empty())
            .map(Into::into)
            .collect()
    }
}

impl CommandNames for String {
    fn commands(&self) -> Vec<String> {
        self.as_str().commands()
    }
}

/// The signature of a command function
type CommandFn<N, F> = dyn Fn(&mut Runtime<N, F>) -> Interrupt<N>;

/// A builder that runs the narrative when it is dropped
pub struct RunBuilder<'a, N, F = CliFrontend>
where
    N: Node,
    F: Frontend,
{
    commands: HashMap<String, Arc<Box<CommandFn<N, F>>>>,
    state: Option<MayBor<'a, N::State>>,
    start_node: Option<N>,
    frontend: Option<MayBor<'a, F>>,
}

impl<'a, N, F> RunBuilder<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    /// Add a global command to the [`Runtime`](struct.Runtime.html)
    ///
    /// Global commands can always be entered by the user.
    ///
    /// Some examples of global commands might be:
    /// * save
    /// * inventory / inv
    /// * look around
    pub fn command<C, G>(mut self, names: C, command: G) -> Self
    where
        C: CommandNames,
        G: Fn(&mut Runtime<N, F>) -> Interrupt<N> + 'static,
    {
        let names = names.commands();
        let command: Arc<Box<CommandFn<N, F>>> = Arc::new(Box::new(command));
        for name in names {
            self.commands.insert(name.to_string(), Arc::clone(&command));
        }
        self
    }
}

impl<'a, N, F> Drop for RunBuilder<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    fn drop(&mut self) {
        let mut runtime = Runtime {
            state: self.state.take().expect("RunBuilder state is empty"),
            curr_node: self
                .start_node
                .take()
                .expect("RunBuilder start node is empty"),
            commands: self.commands.drain().collect(),
            frontend: self.frontend.take().expect("RunBuilder frontend is empty"),
        };
        loop {
            match runtime.curr_node.clone().next(&mut runtime) {
                Ok(node) | Err(Jump(node)) => runtime.curr_node = node,
                Err(Exit) => break,
                Err(Skip) | Err(Continue) => {}
            }
        }
    }
}

/// Run the narrative starting at the given [`Node`](trait.Node.html) and state
pub fn run<'a, N, F>(start: N, state: &'a mut N::State, frontend: &'a mut F) -> RunBuilder<'a, N, F>
where
    N: Node,
    F: Frontend,
{
    RunBuilder {
        commands: HashMap::new(),
        state: Some(MayBor::Borrowed(state)),
        start_node: Some(start),
        frontend: Some(MayBor::Borrowed(frontend)),
    }
}

/// Run the narrative starting at the default [`Node`](trait.Node.html) and state
pub fn run_default<'a, N, F>() -> RunBuilder<'a, N, F>
where
    N: Node + Default,
    N::State: Default,
    F: Frontend + Default,
{
    RunBuilder {
        commands: HashMap::new(),
        state: Some(MayBor::Owned(N::State::default())),
        start_node: Some(N::default()),
        frontend: Some(MayBor::Owned(F::default())),
    }
}