terminal_graphics_interactive 0.2.0

Keyboard and mouse input for terminal_graphics: build interactive terminal games, art and animations. Almost no unsafe.
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
//! Scenes: the stack of screens a game is made of, and the one update path
//! that both the real loop and the headless runner use.

use super::{Context, Keys, PlayerId, Screen};
use crate::Pointer;
use std::time::Duration;

/// One update is 1/60 of a second.
pub(crate) const STEP: Duration = Duration::from_nanos(16_666_667);

/// One update in seconds, as `Context::dt`.
pub(crate) const DT: f32 = 1.0 / 60.0;

/// A screen of your game: it updates, and it draws itself.
///
/// Both methods have defaults, so a screen can be only a `draw` or only an
/// `update`. Implement it on a struct that holds the game's state.
///
/// ```
/// use terminal_graphics_interactive::game::*;
///
/// struct Counter { count: u32 }
/// impl Game for Counter {
///     fn update(&mut self, ctx: &mut Context<'_>) -> Next {
///         if ctx.keys.held(KeyCode::Right) {
///             self.count += 1;
///         }
///         Next::stay()
///     }
///     fn draw(&self, screen: &mut Screen) {
///         screen.text(0, 0, &format!("count {}", self.count), Colour::White);
///     }
/// }
/// ```
pub trait Game {
    /// Runs once per update (60 times a second). Change the state here and
    /// return what should happen next.
    fn update(&mut self, _ctx: &mut Context<'_>) -> Next {
        Next::Stay
    }

    /// Draws the current state. It takes `&self`, so drawing cannot change the
    /// game. Clear the screen first if the background should be plain.
    fn draw(&self, _screen: &mut Screen) {}
}

/// What happens after a game's `update`. Build one with the constructors:
/// [`Next::stay`], [`Next::switch`], [`Next::push`], [`Next::pop`] and
/// [`Next::quit`].
///
/// ```
/// use terminal_graphics_interactive::game::*;
///
/// struct Shop;
/// impl Game for Shop {
///     fn update(&mut self, ctx: &mut Context<'_>) -> Next {
///         if ctx.keys.pressed(KeyCode::Esc) {
///             Next::pop() // leave the shop
///         } else {
///             Next::stay()
///         }
///     }
/// }
///
/// let mut game = Headless::new(Shop);
/// game.tap(KeyCode::Esc);
/// assert!(game.quit());
/// ```
pub enum Next {
    /// Keep the current scene.
    Stay,
    /// Replace the current scene with this one.
    Switch(Box<dyn Game>),
    /// Put this scene on top; the one below is kept and paused.
    Push(Box<dyn Game>),
    /// Remove the current scene and go back to the one below.
    Pop,
    /// End the game.
    Quit,
}

impl Next {
    /// Keep the current scene as it is. This is what `update` returns on most
    /// updates.
    ///
    /// ```
    /// use terminal_graphics_interactive::game::*;
    ///
    /// struct Still;
    /// impl Game for Still {
    ///     fn update(&mut self, _ctx: &mut Context<'_>) -> Next {
    ///         Next::stay()
    ///     }
    /// }
    ///
    /// let mut game = Headless::new(Still);
    /// game.step(60);
    /// assert!(!game.quit());
    /// ```
    pub fn stay() -> Next {
        Next::Stay
    }

    /// Replace the current scene with `game`.
    ///
    /// ```
    /// use terminal_graphics_interactive::game::*;
    ///
    /// struct Menu;
    /// struct Play;
    /// impl Game for Menu {
    ///     fn update(&mut self, ctx: &mut Context<'_>) -> Next {
    ///         if ctx.keys.pressed(KeyCode::Enter) { Next::switch(Play) } else { Next::stay() }
    ///     }
    /// }
    /// impl Game for Play {}
    ///
    /// let mut game = Headless::new(Menu);
    /// game.tap(KeyCode::Enter);
    /// assert!(!game.quit());
    /// ```
    pub fn switch(game: impl Game + 'static) -> Next {
        Next::Switch(Box::new(game))
    }

    /// Put `game` on top of the current scene. The scene below is kept and
    /// does not update until `Next::pop()` brings it back to the top.
    ///
    /// ```
    /// use terminal_graphics_interactive::game::*;
    ///
    /// struct Play;
    /// struct Pause;
    /// impl Game for Play {
    ///     fn update(&mut self, ctx: &mut Context<'_>) -> Next {
    ///         if ctx.keys.pressed(KeyCode::Esc) { Next::push(Pause) } else { Next::stay() }
    ///     }
    /// }
    /// impl Game for Pause {
    ///     fn update(&mut self, ctx: &mut Context<'_>) -> Next {
    ///         if ctx.keys.pressed(KeyCode::Esc) { Next::pop() } else { Next::stay() }
    ///     }
    /// }
    ///
    /// let mut game = Headless::new(Play);
    /// game.tap(KeyCode::Esc); // pause
    /// game.tap(KeyCode::Esc); // resume
    /// assert!(!game.quit());
    /// ```
    pub fn push(game: impl Game + 'static) -> Next {
        Next::Push(Box::new(game))
    }

    /// Remove the current scene and go back to the one below. Popping the
    /// last scene ends the game.
    ///
    /// ```
    /// use terminal_graphics_interactive::game::*;
    ///
    /// struct Done;
    /// impl Game for Done {
    ///     fn update(&mut self, _ctx: &mut Context<'_>) -> Next {
    ///         Next::pop()
    ///     }
    /// }
    ///
    /// let mut game = Headless::new(Done);
    /// game.step(1);
    /// assert!(game.quit());
    /// ```
    pub fn pop() -> Next {
        Next::Pop
    }

    /// End the game now, whatever scenes are on the stack.
    ///
    /// ```
    /// use terminal_graphics_interactive::game::*;
    ///
    /// struct Exit;
    /// impl Game for Exit {
    ///     fn update(&mut self, _ctx: &mut Context<'_>) -> Next {
    ///         Next::quit()
    ///     }
    /// }
    ///
    /// let mut game = Headless::new(Exit);
    /// game.step(5);
    /// assert!(game.quit());
    /// assert_eq!(game.tick(), 1, "no updates run after quitting");
    /// ```
    pub fn quit() -> Next {
        Next::Quit
    }
}

/// The stack of scenes. The top scene is the one that updates.
pub(crate) struct Scenes {
    stack: Vec<Box<dyn Game>>,
}

impl Scenes {
    /// A stack holding just `first`.
    pub(crate) fn new(first: Box<dyn Game>) -> Scenes {
        Scenes { stack: vec![first] }
    }

    /// How many scenes are on the stack.
    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        self.stack.len()
    }

    /// Whether the stack is empty, which means the game has ended.
    pub(crate) fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }

    /// Carries out what a scene asked for.
    pub(crate) fn apply(&mut self, next: Next) {
        match next {
            Next::Switch(game) => {
                if let Some(top) = self.stack.last_mut() {
                    *top = game;
                } else {
                    self.stack.push(game);
                }
            }
            Next::Push(game) => self.stack.push(game),
            Next::Pop => {
                self.stack.pop();
            }
            Next::Quit => self.stack.clear(),
            Next::Stay => {}
        }
    }

    /// Draws every scene, bottom to top, so a pause screen pushed over the
    /// game is drawn on top of it. Then finishes the frame, so the pixels
    /// drawn by any scene show above the text and the sprites of all of them.
    pub(crate) fn draw(&self, screen: &mut Screen, tick: u64) {
        screen.set_clock(tick as f32 * DT, tick);
        for scene in &self.stack {
            scene.draw(screen);
        }
        screen.finish_frame();
    }

    /// Runs one update of the top scene and applies what it returns.
    /// Returns `false` once no scenes are left. This is the one update path,
    /// used by both the real loop and [`Headless`](super::Headless).
    pub(crate) fn step(
        &mut self,
        keys: &mut Keys,
        pointer: &mut Pointer,
        tick: u64,
        size: (u32, u32),
        seed: u64,
    ) -> bool {
        keys.tick(time_of(tick));
        let next = match self.stack.last_mut() {
            Some(top) => {
                let mut ctx = Context {
                    keys: &*keys,
                    pointer: &*pointer,
                    dt: DT,
                    tick,
                    size,
                    seed,
                    players: 1,
                    me: PlayerId(0),
                };
                top.update(&mut ctx)
            }
            None => return false,
        };
        self.apply(next);
        keys.end_tick();
        pointer.end_frame();
        !self.is_empty()
    }
}

/// The game time of update `tick`, for timing key events.
pub(crate) fn time_of(tick: u64) -> Duration {
    Duration::from_nanos((STEP.as_nanos() as u64).saturating_mul(tick))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;
    use terminal_graphics::Colour;

    type Log = Rc<RefCell<Vec<&'static str>>>;

    /// A scene that records its name whenever it is updated.
    struct Probe {
        name: &'static str,
        log: Log,
    }

    impl Probe {
        fn boxed(name: &'static str, log: &Log) -> Box<dyn Game> {
            Box::new(Probe {
                name,
                log: Rc::clone(log),
            })
        }
    }

    impl Game for Probe {
        fn update(&mut self, _ctx: &mut Context<'_>) -> Next {
            self.log.borrow_mut().push(self.name);
            Next::Stay
        }
    }

    fn one_update(scenes: &mut Scenes) -> bool {
        scenes.step(&mut Keys::new(), &mut Pointer::default(), 0, (10, 5), 1)
    }

    fn take(log: &Log) -> Vec<&'static str> {
        std::mem::take(&mut *log.borrow_mut())
    }

    #[test]
    fn the_frame_is_finished_after_every_scene_draws_so_pixels_show_above_text() {
        struct Floor;
        impl Game for Floor {
            fn draw(&self, screen: &mut Screen) {
                screen.pixel(0, 0, Colour::Red);
            }
        }
        struct Words;
        impl Game for Words {
            fn draw(&self, screen: &mut Screen) {
                screen.text(0, 0, "xy", Colour::White);
            }
        }
        let mut scenes = Scenes::new(Box::new(Floor));
        scenes.apply(Next::push(Words));
        let mut screen = Screen::new(2, 1);
        screen.clear(Colour::Blue);
        scenes.draw(&mut screen, 0);
        let cell = screen.display().pixel(0, 0).unwrap();
        assert_eq!(cell.character(), '\u{2580}', "the pixel is above the text");
        assert_eq!(screen.display().pixel(1, 0).unwrap().character(), 'y');
    }

    #[test]
    fn switch_replaces_the_top_scene() {
        let log: Log = Rc::default();
        let mut scenes = Scenes::new(Probe::boxed("menu", &log));
        scenes.apply(Next::switch(Probe {
            name: "play",
            log: Rc::clone(&log),
        }));
        assert_eq!(scenes.len(), 1);
        one_update(&mut scenes);
        assert_eq!(take(&log), vec!["play"]);
    }

    #[test]
    fn push_keeps_the_scene_below_and_only_the_top_updates() {
        let log: Log = Rc::default();
        let mut scenes = Scenes::new(Probe::boxed("play", &log));
        scenes.apply(Next::push(Probe {
            name: "pause",
            log: Rc::clone(&log),
        }));
        assert_eq!(scenes.len(), 2);
        one_update(&mut scenes);
        assert_eq!(take(&log), vec!["pause"], "play is paused, not updated");
    }

    #[test]
    fn pop_returns_to_the_scene_below() {
        let log: Log = Rc::default();
        let mut scenes = Scenes::new(Probe::boxed("play", &log));
        scenes.apply(Next::push(Probe {
            name: "pause",
            log: Rc::clone(&log),
        }));
        scenes.apply(Next::pop());
        assert_eq!(scenes.len(), 1);
        one_update(&mut scenes);
        assert_eq!(take(&log), vec!["play"]);
    }

    /// A scene that always asks to be popped.
    struct Leave;

    impl Game for Leave {
        fn update(&mut self, _ctx: &mut Context<'_>) -> Next {
            Next::pop()
        }
    }

    #[test]
    fn popping_the_last_scene_ends_the_game() {
        let mut scenes = Scenes::new(Box::new(Leave));
        assert!(!one_update(&mut scenes), "step reports the game is over");
        assert!(scenes.is_empty());
    }

    #[test]
    fn quit_empties_the_whole_stack() {
        let log: Log = Rc::default();
        let mut scenes = Scenes::new(Probe::boxed("play", &log));
        scenes.apply(Next::push(Probe {
            name: "pause",
            log: Rc::clone(&log),
        }));
        scenes.apply(Next::quit());
        assert!(scenes.is_empty());
    }

    /// A scene that records its name whenever it is drawn.
    struct Painter {
        name: &'static str,
        log: Log,
    }

    impl Game for Painter {
        fn draw(&self, _screen: &mut Screen) {
            self.log.borrow_mut().push(self.name);
        }
    }

    #[test]
    fn draw_calls_every_scene_from_the_bottom_up() {
        let log: Log = Rc::default();
        let mut scenes = Scenes::new(Box::new(Painter {
            name: "play",
            log: Rc::clone(&log),
        }));
        scenes.apply(Next::push(Painter {
            name: "pause",
            log: Rc::clone(&log),
        }));
        scenes.draw(&mut Screen::new(4, 2), 0);
        assert_eq!(take(&log), vec!["play", "pause"]);
    }

    /// A scene that remembers the clock it was drawn with.
    struct ClockSeen(Rc<Cell<(f32, u64)>>);

    impl Game for ClockSeen {
        fn draw(&self, screen: &mut Screen) {
            self.0.set((screen.time(), screen.tick()));
        }
    }

    #[test]
    fn draw_sets_the_screen_clock_from_the_tick() {
        let seen = Rc::new(Cell::new((0.0, 0)));
        let scenes = Scenes::new(Box::new(ClockSeen(Rc::clone(&seen))));
        scenes.draw(&mut Screen::new(4, 2), 90);
        let (time, tick) = seen.get();
        assert_eq!(tick, 90);
        assert!((time - 1.5).abs() < 1e-5, "time {time}");
    }
}