SHARE
TWEET

Input handler

a guest Nov 7th, 2018 48 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extern crate tcod;
  2.  
  3. use tcod::input::Key;
  4. use tcod::input::KeyCode::*;
  5. use self::tcod::console::Root;
  6. use ::actors::Object;
  7.  
  8. pub enum PlayerAction<'a> {
  9.    TookTurn,
  10.    Moved(MoveCommand<'a>),
  11.     DidntTakeTurn,
  12.     Exit,
  13. }
  14.  
  15. trait Executes {
  16.     fn execute(self);
  17. }
  18.  
  19. pub struct MoveCommand<'a> {
  20.    pub entity: Option<&'a mut Object>,
  21.     dx: i32,
  22.     dy: i32
  23. }
  24. impl<'a> MoveCommand<'a> {
  25.     pub fn new(dx: i32, dy: i32) -> MoveCommand<'a> {
  26.        MoveCommand {
  27.            entity: None,
  28.            dx, dy
  29.        }
  30.    }
  31. }
  32. impl<'a> Executes for MoveCommand<'a> {
  33.    fn execute(self) {
  34.        if let Some(entity) = self.entity {
  35.            entity.move_by(self.dx, self.dy)
  36.        };
  37.    }
  38. }
  39.  
  40. pub fn handle_keys<'a>(root: &mut Root) -> PlayerAction {
  41.     let key = root.wait_for_keypress(true);
  42.  
  43.     match key {
  44.         Key { code: Enter, alt: true, .. } => {
  45.             let fullscreen = root.is_fullscreen();
  46.             root.set_fullscreen(!fullscreen);
  47.             PlayerAction::DidntTakeTurn
  48.         },
  49.         Key { code: Escape, .. } => {
  50.             PlayerAction::Exit
  51.         },
  52.         Key { code: Up, .. } => {
  53.             PlayerAction::Moved(MoveCommand::new(0, -1))
  54.         }
  55.         Key { code: Down, .. } => {
  56.             PlayerAction::Moved(MoveCommand::new(0, 1))
  57.         }
  58.         Key { code: Left, .. } => {
  59.             PlayerAction::Moved(MoveCommand::new(-1, 0))
  60.         }
  61.         Key { code: Right, .. } => {
  62.             PlayerAction::Moved(MoveCommand::new(1, 0))
  63.         }
  64.         _ => {
  65.             PlayerAction::DidntTakeTurn
  66.         }
  67.     }
  68. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top