nightrunner_lib 0.4.0

A parser library for making text adventure games
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
471
472
//! This library is a text-adventure game engine that can be used to create
//! text based adventure games. It is designed to be used with a front-end
//! which can be written in any language. Implementing this library in a
//! language is a matter of writing a front-end an passing string data to
//! the library for parsing.
//!
//! The configuration of the game is done in the `Config` struct
//! and can be initialized both with YAML files and serialized
//! JSON data, so it is perfect for both web and desktop games.
//!
//! The `parse_input` and `parse_input_json` functions are the only
//! functions that need to be called by the front-end, but the library
//! exposes some of the internal structs and functions to help developers
//! understand how the library works, and to allow a little bit of flexibility
//! in how the library is used.
//!
//! # Example:
//! ```rust
//! use nightrunner_lib::{NightRunner, NightRunnerBuilder, ParsingResult};
//! use nightrunner_lib::util::test_helpers::mock_json_data;
//! let data = mock_json_data();
//! let mut nr = NightRunnerBuilder::new().with_json_data(&data).build().unwrap();
//! let result = nr.parse_input("look");
//! let json_result = nr.json_parse_input("look");
//! assert!(result.is_ok());
//! assert_eq!(result.unwrap(),
//!     ParsingResult::Look(
//!         "first room\n\nHere you see: \nan item1\nan item2\nsubject1".to_string()
//!     )
//! );
//! assert_eq!(json_result,
//!     r#"{"messageType":"look","data":"first room\n\nHere you see: \nan item1\nan item2\nsubject1"}"#.to_string()
//! );
//! ```
//!
//! for examples of valid YAML and JSON data, see the documentation for
//! the `config` module.
#![warn(missing_docs)]
use config::{Config, State};
use parser::interpreter::EventMessage;
use serde::{Deserialize, Serialize};
use std::{
    error::Error,
    fmt::{self, Display, Formatter},
};
extern crate console_error_panic_hook;
use util::parse_room_text;
/// Module containing the configuration code for this
/// library.
pub mod config;
/// The parser module contains a single function that
/// parses the input string and returns a `ParsingResult`.
pub mod parser;
/// Helper functions.
pub mod util;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;

/// We use a type alias to make error handling easier.
pub type NRResult<T> = Result<T, Box<dyn Error>>;

/// This is the result of the parsing of the input.
/// Each variant contains the output for the game and
/// should be used by a front-end to display to the user.
#[derive(Debug, PartialEq, Serialize, Deserialize, Clone)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "messageType", content = "data")]
pub enum ParsingResult {
    /// Returned when the player sends a command corresponding
    /// to a verb that has VerbFunction::Help as its verb_function.
    /// The value is a string generated by the library displaying
    /// general commands as well as verbs available in the game.
    Help(String),
    /// Returned when the player sends a command for looking at the
    /// room, an item, or a subject. The value will be the message
    /// returned from the parser with the description associated with
    /// the room, item, or subject.
    Look(String),
    /// Returned when the player receives a new item, either by picking
    /// it up or by receiving it as the result of an event.
    NewItem(String),
    /// Returned when the player loses an item, either by dropping it
    /// or by losing it as the result of an event.
    DropItem(String),
    /// Returned when the player issues a command with a verb that
    /// has VerbFunction::Inventory as its verb_function. The value is
    /// a string containing each item in the player's inventory.
    Inventory(String),
    /// Returned when the player issues a command that interacts with
    /// a subject without a current event associated with it. The value
    /// is the default text for the subject.
    SubjectNoEvent(String),
    /// Returned when an event is triggered by the player's command. The
    /// returned struct contains the text to be displayed to the player.
    EventSuccess(EventMessage),
    /// Returned when the player issues a command with a verb that has
    /// VerbFunction::Quit as its verb_function. This variant is used
    /// to indicate to the front-end that the game should be quit.
    /// Implementation of how to quit the game is left to the front-end.
    Quit,
}

impl Display for ParsingResult {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            ParsingResult::Help(msg) => write!(f, "{}", msg),
            ParsingResult::Look(msg) => write!(f, "{}", msg),
            ParsingResult::NewItem(msg) => write!(f, "{}", msg),
            ParsingResult::DropItem(msg) => write!(f, "{}", msg),
            ParsingResult::Inventory(msg) => write!(f, "{}", msg),
            ParsingResult::SubjectNoEvent(msg) => write!(f, "{}", msg),
            ParsingResult::EventSuccess(event_msg) => {
                let EventMessage {
                    message,
                    message_parts,
                    templated_words: _,
                } = event_msg;
                write!(f, "{}", message)?;
                for part in message_parts.values() {
                    write!(f, "{}", part)?;
                }
                Ok(())
            }
            ParsingResult::Quit => write!(f, "Quitting game"),
        }
    }
}

/// This is the main struct for this library
/// and represents the game. It holds the state
/// internally and passes it to the parser for
/// processing along with the provided input.
#[wasm_bindgen]
#[derive(Debug, PartialEq)]
pub struct NightRunner {
    state: State,
    previous_states: Vec<State>,
    future_states: Vec<State>,
}

/// Describes where the game configuration should be
/// loaded from. The actual parsing is deferred until
/// [`NightRunnerBuilder::build`] so that any error in
/// the configuration is surfaced from a single fallible
/// call rather than panicking while building.
#[derive(Debug, PartialEq, Eq)]
enum ConfigSource {
    Default,
    Path(String),
    Json(String),
}

/// You can use this to build a NightRunner
/// strut. While you can build the NightRunner
/// struct directly, using this builder is a
/// little more convenient.
///
/// # Examples:
/// ```rust
/// use nightrunner_lib::NightRunnerBuilder;
/// use nightrunner_lib::util::test_helpers::mock_json_data;
/// let data = mock_json_data();
/// let path_to_yaml = "fixtures/";
/// let nr1 = NightRunnerBuilder::new().with_json_data(&data);
/// let nr2 = NightRunnerBuilder::new().with_path_for_config(path_to_yaml);
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct NightRunnerBuilder {
    source: ConfigSource,
}
impl NightRunnerBuilder {
    /// Creates a new empty NightRunnerBuilder
    /// which contains an empty Config struct.
    pub fn new() -> NightRunnerBuilder {
        NightRunnerBuilder {
            source: ConfigSource::Default,
        }
    }
    /// Creates a new NightRunnerBuilder with YAML
    /// data from files in the specified path.
    pub fn with_path_for_config(mut self, path: &str) -> NightRunnerBuilder {
        self.source = ConfigSource::Path(path.to_string());
        self
    }
    /// Creates a new NightRunnerBuilder with JSON
    /// data serialized to a string. This data should
    /// contain the configuration for the whole game.
    pub fn with_json_data(mut self, data: &str) -> NightRunnerBuilder {
        self.source = ConfigSource::Json(data.to_string());
        self
    }
    /// Creates a new NightRunner struct. This will fail
    /// if the config is invalid or missing.
    pub fn build(self) -> NRResult<NightRunner> {
        let config = match self.source {
            ConfigSource::Default => Config::default(),
            ConfigSource::Path(path) => Config::from_path(&path)?,
            ConfigSource::Json(data) => Config::from_json(&data)?,
        };
        let state = State::init(config);
        Ok(NightRunner {
            state,
            previous_states: vec![],
            future_states: vec![],
        })
    }
}

impl Default for NightRunnerBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(not(target_arch = "wasm32"))]
/// # Nightrunner Rust Library
///
/// Use this implementation when using this library
/// in a Rust application.
impl NightRunner {
    /// This is the main function that executes the game. Pass
    /// the input string to this function and it will return
    /// a result that can be used on the front-end to display
    /// the game to the user.
    pub fn parse_input(&mut self, input: &str) -> NRResult<ParsingResult> {
        let (new_state, parsing_result) = parser::parse(&self.state, input)?;
        self.previous_states.push(self.state.clone());
        self.state = new_state;
        Ok(parsing_result)
    }
    /// This is the main function that executes the game. Pass
    /// the input string to this function and it will return
    /// a result that can be used on the front-end to display
    /// the game to the user.
    /// Unlike the `parse_input` function, this function will
    /// return the result in JSON format. This is useful for
    /// front-ends that can't integrate with a rust library.
    pub fn json_parse_input(&mut self, input: &str) -> String {
        let result = parser::parse(&self.state, input);
        match result {
            Ok((new_state, ok)) => {
                self.previous_states.push(self.state.clone());
                self.state = new_state;
                serde_json::to_string(&ok)
                    .unwrap_or_else(|_| r#"{"error":"failed to serialize result"}"#.to_string())
            }
            Err(err) => {
                let message = serde_json::to_string(&err.to_string())
                    .unwrap_or_else(|_| "\"an unknown error occurred\"".to_string());
                format!("{{\"error\":{}}}", message)
            }
        }
    }
    /// Rewinds the game state to the previous state.
    /// This is useful for undoing actions in the game.
    /// The state is saved in a stack, so you can rewind
    /// multiple times.
    pub fn rewind_state(&mut self) -> NRResult<ParsingResult> {
        if let Some(state) = self.previous_states.pop() {
            self.future_states.push(self.state.clone());
            self.state = state;
            Ok(ParsingResult::Look("Rewound to previous state".to_string()))
        } else {
            Err("No previous state to rewind to".into())
        }
    }
    /// Fast forwards the game state to the next state.
    /// This is useful for redoing actions in the game.
    /// The state is saved in a stack, so you can fast
    /// forward multiple times.
    pub fn fast_forward_state(&mut self) -> NRResult<ParsingResult> {
        if let Some(state) = self.future_states.pop() {
            self.previous_states.push(self.state.clone());
            self.state = state;
            Ok(ParsingResult::Look(
                "Fast forwarded to next state".to_string(),
            ))
        } else {
            Err("No future state to fast forward to".into())
        }
    }
    /// Returns the string with the game intro text. This can
    /// be used to display the game intro to the user, but isn't
    /// required.
    pub fn game_intro(&self) -> String {
        self.state.config.intro.clone()
    }
    /// Returns the text for the very first room of the game.
    ///
    /// Since there is no input to parse when the game starts,
    /// this function should be used to retrieve that text instead.
    pub fn first_room_text(&self) -> NRResult<EventMessage> {
        let narrative_id = self
            .state
            .rooms
            .first()
            .ok_or(parser::errors::NoRoom)?
            .narrative;
        let narrative_text = self
            .state
            .config
            .narratives
            .iter()
            .find(|n| n.id == narrative_id)
            .ok_or(parser::errors::InvalidNarrative)?
            .text
            .clone();
        let event_message = parse_room_text(&self.state, narrative_text, "".to_string(), None)?;
        Ok(event_message)
    }
}

#[cfg(any(target_arch = "wasm32", doc))]
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "messageType", content = "data")]
#[serde(rename_all = "snake_case")]
/// When compiling for the web, this struct is used to
/// serialize the game state to JSON. `messageType` is
/// the type of the message returned by the library to
/// indicate which action was processed by the parser.
pub enum JsMessage {
    /// Returned when the player sends a command corresponding
    /// to a verb that has VerbFunction::Help as its verb_function.
    /// The value is a string generated by the library displaying
    /// general commands as well as verbs available in the game.
    Help(String),
    /// Returned when the player sends a command for looking at the
    /// room, an item, or a subject. The value will be the message
    /// returned from the parser with the description associated with
    /// the room, item, or subject.
    Look(String),
    /// Returned when the player receives a new item, either by picking
    /// it up or by receiving it as the result of an event.
    NewItem(String),
    /// Returned when the player loses an item, either by dropping it
    /// or by losing it as the result of an event.
    DropItem(String),
    /// Returned when the player issues a command with a verb that
    /// has VerbFunction::Inventory as its verb_function. The value is
    /// a string containing each item in the player's inventory.
    Inventory(String),
    /// Returned when the player issues a command that interacts with
    /// a subject without a current event associated with it. The value
    /// is the default text for the subject.
    SubjectNoEvent(String),
    /// Returned when an event is triggered by the player's command. The
    /// returned struct contains the text to be displayed to the player.
    EventSuccess(EventMessage),
    /// Returned when a parser result isn't applicable to the wasm library
    NoOp,
}

#[cfg(any(target_arch = "wasm32", doc))]
#[wasm_bindgen]
/// # Nightrunner Wasm Library
///
/// Use this implementation when using this library
/// in a WebAssembly browser application. This is the
/// implementation exposed when compiling with `--target=wasm32-unknown-unknown`.
impl NightRunner {
    /// When using the wasm library we won't have access to the
    /// builder patter, so the constructor needs to receive the
    /// configuration for games as a parameter.
    ///
    /// config should be a JSON string.
    #[wasm_bindgen(constructor)]
    pub fn new(config: &str) -> Result<NightRunner, JsError> {
        console_error_panic_hook::set_once();
        let config = Config::from_json(config).map_err(|e| JsError::new(&e.to_string()))?;
        let state = State::init(config);
        Ok(NightRunner {
            state,
            previous_states: vec![],
            future_states: vec![],
        })
    }
    /// This is the main function that executes the game. Pass
    /// the input string to this function and it will return
    /// a result that can be used on the front-end to display
    /// the game to the user.
    /// Unlike the non-wasm version, this function will return
    /// the result in JSON format. The conversion of the result
    /// to JSON is done by the `JsValue::from_serde` function from
    /// wasm_bindgen.
    pub fn parse(&mut self, input: &str) -> Result<JsValue, JsError> {
        let result = parser::parse(&self.state, input);
        match result {
            Ok((new_state, ok)) => {
                self.previous_states.push(self.state.clone());
                self.state = new_state;
                let message = match ok {
                    ParsingResult::Look(msg) => JsMessage::Look(msg),
                    ParsingResult::Help(msg) => JsMessage::Help(msg),
                    ParsingResult::NewItem(msg) => JsMessage::NewItem(msg),
                    ParsingResult::DropItem(msg) => JsMessage::DropItem(msg),
                    ParsingResult::Inventory(msg) => JsMessage::Inventory(msg),
                    ParsingResult::SubjectNoEvent(msg) => JsMessage::SubjectNoEvent(msg),
                    ParsingResult::EventSuccess(event_msg) => JsMessage::EventSuccess(event_msg),
                    ParsingResult::Quit => JsMessage::NoOp,
                };
                Ok(serde_wasm_bindgen::to_value(&message)?)
            }
            Err(err) => Err(JsError::new(&err.to_string())),
        }
    }

    /// Rewinds the game state to the previous state.
    /// This is useful for undoing actions in the game.
    /// The state is saved in a stack, so you can rewind
    /// multiple times.
    pub fn rewind_state(&mut self) -> Result<JsValue, JsError> {
        match self.previous_states.pop() {
            Some(state) => {
                self.future_states.push(self.state.clone());
                self.state = state;
                Ok(serde_wasm_bindgen::to_value(&JsMessage::Look(
                    "Rewound to previous state".to_string(),
                ))?)
            }
            None => Err(JsError::new("No previous state to rewind to")),
        }
    }

    /// Fast forwards the game state to the next state.
    /// This is useful for redoing actions in the game.
    /// The state is saved in a stack, so you can fast
    /// forward multiple times.
    pub fn fast_forward_state(&mut self) -> Result<JsValue, JsError> {
        match self.future_states.pop() {
            Some(state) => {
                self.previous_states.push(self.state.clone());
                self.state = state;
                Ok(serde_wasm_bindgen::to_value(&JsMessage::Look(
                    "Fast forwarded to next state".to_string(),
                ))?)
            }
            None => Err(JsError::new("No future state to fast forward to")),
        }
    }

    /// Returns the string with the game intro text. This can
    /// be used to display the game intro to the user, but isn't
    /// required.
    #[wasm_bindgen]
    pub fn game_intro(&self) -> String {
        self.state.config.intro.clone()
    }
    /// Returns the text for the very first room of the game.
    ///
    /// Since there is no input to parse when the game starts,
    /// this function should be used to retrieve that text instead.
    pub fn first_room_text(&self) -> Result<JsValue, JsError> {
        let narrative_id = self
            .state
            .rooms
            .first()
            .ok_or_else(|| JsError::new("There are no rooms in the game."))?
            .narrative;
        let narrative_text = self
            .state
            .config
            .narratives
            .iter()
            .find(|n| n.id == narrative_id)
            .ok_or_else(|| JsError::new(&parser::errors::InvalidNarrative.to_string()))?
            .text
            .clone();
        let event_message = parse_room_text(&self.state, narrative_text, "".to_string(), None)
            .map_err(|e| JsError::new(&e.to_string()))?;
        Ok(serde_wasm_bindgen::to_value(&event_message)?)
    }
}