roguelike-game/src/player.rs

74 lines
2.5 KiB
Rust
Raw Normal View History

2021-10-26 14:23:08 -04:00
use super::{Map, Player, Position, State, TileType, Viewshed};
2021-10-26 15:43:59 -04:00
use crate::RunState;
use rltk::{Point, Rltk, VirtualKeyCode};
2021-10-22 10:05:06 -04:00
use specs::prelude::*;
2021-10-25 15:26:39 -04:00
use std::cmp::{max, min};
2021-10-22 10:05:06 -04:00
pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
let mut positions = ecs.write_storage::<Position>();
let mut players = ecs.write_storage::<Player>();
2021-10-26 14:23:08 -04:00
let mut viewsheds = ecs.write_storage::<Viewshed>();
2021-10-25 14:23:19 -04:00
let map = ecs.fetch::<Map>();
2021-10-22 10:05:06 -04:00
2021-10-26 14:23:08 -04:00
for (_player, pos, viewshed) in (&mut players, &mut positions, &mut viewsheds).join() {
2021-10-25 14:23:19 -04:00
let destination_idx = map.xy_idx(pos.x + delta_x, pos.y + delta_y);
2021-10-29 11:11:17 -04:00
if !map.blocked[destination_idx] {
2021-10-22 10:05:06 -04:00
pos.x = min(79, max(0, pos.x + delta_x));
pos.y = min(49, max(0, pos.y + delta_y));
2021-10-26 14:23:08 -04:00
2021-10-26 15:43:59 -04:00
let mut ppos = ecs.write_resource::<Point>();
ppos.x = pos.x;
ppos.y = pos.y;
2021-10-26 14:23:08 -04:00
viewshed.dirty = true;
2021-10-22 10:05:06 -04:00
}
}
}
2021-10-26 15:43:59 -04:00
pub fn player_input(gs: &mut State, ctx: &mut Rltk) -> RunState {
2021-10-22 10:05:06 -04:00
// Player movement
match ctx.key {
2021-10-26 15:43:59 -04:00
None => return RunState::Paused, // Nothing happened
2021-10-22 10:05:06 -04:00
Some(key) => match key {
2021-10-29 11:11:17 -04:00
VirtualKeyCode::Left
| VirtualKeyCode::Numpad4
| VirtualKeyCode::H
| VirtualKeyCode::A => try_move_player(-1, 0, &mut gs.ecs),
2021-10-22 14:50:04 -04:00
2021-10-29 11:11:17 -04:00
VirtualKeyCode::Right
| VirtualKeyCode::Numpad6
| VirtualKeyCode::L
| VirtualKeyCode::D => try_move_player(1, 0, &mut gs.ecs),
2021-10-22 14:50:04 -04:00
2021-10-29 11:11:17 -04:00
VirtualKeyCode::Up
| VirtualKeyCode::Numpad8
| VirtualKeyCode::K
| VirtualKeyCode::W => try_move_player(0, -1, &mut gs.ecs),
VirtualKeyCode::Down
| VirtualKeyCode::Numpad2
| VirtualKeyCode::J
| VirtualKeyCode::S
| VirtualKeyCode::X => try_move_player(0, 1, &mut gs.ecs),
2021-10-22 14:50:04 -04:00
2021-10-29 11:11:17 -04:00
// Diagonals
VirtualKeyCode::Numpad9 | VirtualKeyCode::Y | VirtualKeyCode::E => {
try_move_player(1, -1, &mut gs.ecs)
}
VirtualKeyCode::Numpad7 | VirtualKeyCode::U | VirtualKeyCode::Q => {
try_move_player(-1, -1, &mut gs.ecs)
}
VirtualKeyCode::Numpad3 | VirtualKeyCode::N | VirtualKeyCode::C => {
try_move_player(1, 1, &mut gs.ecs)
}
VirtualKeyCode::Numpad1 | VirtualKeyCode::B | VirtualKeyCode::Z => {
try_move_player(-1, 1, &mut gs.ecs)
2021-10-25 15:26:39 -04:00
}
2021-10-22 14:50:04 -04:00
2021-10-26 15:43:59 -04:00
_ => return RunState::Paused,
2021-10-22 10:05:06 -04:00
},
}
2021-10-26 15:43:59 -04:00
RunState::Running
2021-10-25 15:26:39 -04:00
}