player.rs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. extern crate rltk;
  2. use rltk::{VirtualKeyCode, Rltk, Point};
  3. extern crate specs;
  4. use specs::prelude::*;
  5. use std::cmp::{max, min};
  6. use super::{Position, Player, Viewshed, State, Map, RunState, CombatStats, WantsToMelee};
  7. pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
  8. let mut positions = ecs.write_storage::<Position>();
  9. let players = ecs.read_storage::<Player>();
  10. let mut viewsheds = ecs.write_storage::<Viewshed>();
  11. let entities = ecs.entities();
  12. let combat_stats = ecs.read_storage::<CombatStats>();
  13. let map = ecs.fetch::<Map>();
  14. let mut wants_to_melee = ecs.write_storage::<WantsToMelee>();
  15. for (entity, _player, pos, viewshed) in (&entities, &players, &mut positions, &mut viewsheds).join() {
  16. let destination_idx = map.xy_idx(pos.x + delta_x, pos.y + delta_y);
  17. for potential_target in map.tile_content[destination_idx].iter() {
  18. let target = combat_stats.get(*potential_target);
  19. if let Some(_target) = target {
  20. wants_to_melee.insert(entity, WantsToMelee{ target: *potential_target }).expect("Add target failed");
  21. return;
  22. }
  23. }
  24. if !map.blocked[destination_idx] {
  25. pos.x = min(79 , max(0, pos.x + delta_x));
  26. pos.y = min(49, max(0, pos.y + delta_y));
  27. viewshed.dirty = true;
  28. let mut ppos = ecs.write_resource::<Point>();
  29. ppos.x = pos.x;
  30. ppos.y = pos.y;
  31. }
  32. }
  33. }
  34. pub fn player_input(gs: &mut State, ctx: &mut Rltk) -> RunState {
  35. // Player movement
  36. match ctx.key {
  37. None => { return RunState::AwaitingInput } // Nothing happened
  38. Some(key) => match key {
  39. VirtualKeyCode::Left |
  40. VirtualKeyCode::Numpad4 |
  41. VirtualKeyCode::H => try_move_player(-1, 0, &mut gs.ecs),
  42. VirtualKeyCode::Right |
  43. VirtualKeyCode::Numpad6 |
  44. VirtualKeyCode::L => try_move_player(1, 0, &mut gs.ecs),
  45. VirtualKeyCode::Up |
  46. VirtualKeyCode::Numpad8 |
  47. VirtualKeyCode::K => try_move_player(0, -1, &mut gs.ecs),
  48. VirtualKeyCode::Down |
  49. VirtualKeyCode::Numpad2 |
  50. VirtualKeyCode::J => try_move_player(0, 1, &mut gs.ecs),
  51. // Diagonals
  52. VirtualKeyCode::Numpad9 |
  53. VirtualKeyCode::U => try_move_player(1, -1, &mut gs.ecs),
  54. VirtualKeyCode::Numpad7 |
  55. VirtualKeyCode::Y => try_move_player(-1, -1, &mut gs.ecs),
  56. VirtualKeyCode::Numpad3 |
  57. VirtualKeyCode::N => try_move_player(1, 1, &mut gs.ecs),
  58. VirtualKeyCode::Numpad1 |
  59. VirtualKeyCode::B => try_move_player(-1, 1, &mut gs.ecs),
  60. _ => { return RunState::AwaitingInput }
  61. },
  62. }
  63. RunState::PlayerTurn
  64. }