Commit f39978e6 authored by Mathieu NIVOLIEZ's avatar Mathieu NIVOLIEZ

Working on the "Dealing Damage" chapter. Made the melee combat system.

Also update the rltk to version 7.
parent c3e0f6e7
Pipeline #784 passed with stage
in 22 minutes and 59 seconds
This diff is collapsed.
......@@ -7,6 +7,6 @@ edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rltk = "0.6.0"
specs = "0.15.1"
rltk = "0.7.0"
specs = "0.16.1"
specs-derive = "0.4.0"
......@@ -11,3 +11,4 @@ Little Rogue Like made in Rust using the [guide](http://bfnightly.bracketproduct
- [A more interesting map](http://bfnightly.bracketproductions.com/rustbook/chapter_4.html)
- [Field of view](http://bfnightly.bracketproductions.com/rustbook/chapter_5.html)
- [Monster](http://bfnightly.bracketproductions.com/rustbook/chapter_6.html)
- [Dealing damage](http://bfnightly.bracketproductions.com/rustbook/chapter_7.html)
use rltk::RGB;
extern crate specs;
use specs::prelude::*;
extern crate rltk;
extern crate specs_derive;
use rltk::RGB;
#[derive(Component)]
pub struct Position {
......@@ -31,3 +34,24 @@ pub struct Viewshed {
pub range: i32,
pub dirty: bool,
}
#[derive(Component, Debug)]
pub struct BlocksTile {}
#[derive(Component, Debug)]
pub struct CombatStats {
pub max_hp: i32,
pub hp: i32,
pub defense: i32,
pub power: i32,
}
#[derive(Component, Debug, Clone)]
pub struct WantsToMelee {
pub target: Entity,
}
#[derive(Component, Debug)]
pub struct SufferDamage {
pub amount: i32,
}
// Only useful if compile to wasm
rltk::add_wasm_support!();
extern crate rltk;
use rltk::{Console, GameState, Point, Rltk, RGB};
extern crate specs;
use specs::prelude::*;
#[macro_use]
extern crate specs_derive;
......@@ -18,6 +20,10 @@ mod visibility_system;
use visibility_system::VisibilitySystem;
mod monster_ai_system;
use monster_ai_system::MonsterAI;
mod map_indexing_system;
use map_indexing_system::MapIndexingSystem;
mod melee_combat_system;
use melee_combat_system::MeleeCombatSystem;
#[derive(PartialEq, Copy, Clone)]
pub enum RunState {
......@@ -37,6 +43,10 @@ impl State {
vis.run_now(&self.ecs);
let mut mob = MonsterAI {};
mob.run_now(&self.ecs);
let mut mapindex = MapIndexingSystem {};
mapindex.run_now(&self.ecs);
let mut meleecombat = MeleeCombatSystem {};
meleecombat.run_now(&self.ecs);
self.ecs.maintain();
}
}
......@@ -72,8 +82,12 @@ impl GameState for State {
// Entry point
fn main() {
use rltk::RltkBuilder;
// Init renderer
let context = Rltk::init_simple8x8(80, 50, "Hello Rust World", "resources");
let context = RltkBuilder::simple80x50()
.with_title("Hello Rust World")
.build();
// Init global state with an ecs world
let mut gs = State {
......@@ -88,6 +102,10 @@ fn main() {
gs.ecs.register::<Monster>();
gs.ecs.register::<Name>();
gs.ecs.register::<Viewshed>();
gs.ecs.register::<BlocksTile>();
gs.ecs.register::<CombatStats>();
gs.ecs.register::<WantsToMelee>();
gs.ecs.register::<SufferDamage>();
let map = Map::new_map_rooms_and_corridors();
let (player_x, player_y) = map.rooms[0].center();
......@@ -114,7 +132,7 @@ fn main() {
.create_entity()
.with(Position { x, y })
.with(Renderable {
glyph: glyph,
glyph,
fg: RGB::named(rltk::RED),
bg: RGB::named(rltk::BLACK),
})
......@@ -127,6 +145,13 @@ fn main() {
.with(Name {
name: format!("{} #{}", &name, i),
})
.with(BlocksTile {})
.with(CombatStats {
max_hp: 16,
hp: 16,
defense: 1,
power: 4,
})
.build();
}
gs.ecs.insert(map);
......@@ -153,6 +178,12 @@ fn main() {
.with(Name {
name: "Player".to_string(),
})
.with(CombatStats {
max_hp: 30,
hp: 30,
defense: 2,
power: 5,
})
.build();
// Run the game
......
use super::{Player, Rect, Viewshed};
use super::Rect;
use rltk::{Algorithm2D, BaseMap, Console, Point, RandomNumberGenerator, Rltk, RGB};
use specs::prelude::*;
use std::cmp::{max, min};
......@@ -16,6 +16,8 @@ pub struct Map {
pub height: i32,
pub revealed_tiles: Vec<bool>,
pub visible_tiles: Vec<bool>,
pub blocked: Vec<bool>,
pub tile_content: Vec<Vec<Entity>>,
}
impl Map {
......@@ -50,6 +52,18 @@ impl Map {
}
}
pub fn populate_blocked(&mut self) {
for (i, tile) in self.tiles.iter_mut().enumerate() {
self.blocked[i] = *tile == TileType::Wall;
}
}
pub fn clear_content_index(&mut self) {
for content in self.tile_content.iter_mut() {
content.clear();
}
}
pub fn new_map_rooms_and_corridors() -> Map {
let mut map = Map {
tiles: vec![TileType::Wall; 80 * 50],
......@@ -58,6 +72,8 @@ impl Map {
height: 50,
revealed_tiles: vec![false; 80 * 50],
visible_tiles: vec![false; 80 * 50],
blocked: vec![false; 80 * 50],
tile_content: vec![Vec::new(); 80 * 50],
};
const MAX_ROOMS: i32 = 30;
......@@ -98,6 +114,14 @@ impl Map {
map
}
fn is_exit_valid(&self, x: i32, y: i32) -> bool {
if x < 1 || x > self.width - 1 || y < 1 || y > self.height - 1 {
return false;
}
let idx = self.xy_idx(x, y);
!self.blocked[idx]
}
}
impl Algorithm2D for Map {
......@@ -110,6 +134,43 @@ impl BaseMap for Map {
fn is_opaque(&self, idx: usize) -> bool {
self.tiles[idx] == TileType::Wall
}
fn get_available_exits(&self, idx: usize) -> Vec<(usize, f32)> {
let mut exits: Vec<(usize, f32)> = Vec::new();
let x = idx as i32 % self.width;
let y = idx as i32 / self.width;
let w = self.width as usize;
// Cardinal directions
if self.is_exit_valid(x - 1, y) {
exits.push((idx - 1, 1.0))
};
if self.is_exit_valid(x + 1, y) {
exits.push((idx + 1, 1.0))
};
if self.is_exit_valid(x, y - 1) {
exits.push((idx - w, 1.0))
};
if self.is_exit_valid(x, y + 1) {
exits.push((idx + w, 1.0))
};
// Diagonals
if self.is_exit_valid(x - 1, y - 1) {
exits.push(((idx - w) - 1, 1.45));
}
if self.is_exit_valid(x + 1, y - 1) {
exits.push(((idx - w) + 1, 1.45));
}
if self.is_exit_valid(x - 1, y + 1) {
exits.push(((idx + w) - 1, 1.45));
}
if self.is_exit_valid(x + 1, y + 1) {
exits.push(((idx + w) + 1, 1.45));
}
exits
}
}
pub fn draw_map(ecs: &World, ctx: &mut Rltk) {
......
extern crate specs;
use super::{BlocksTile, Map, Position};
use specs::prelude::*;
pub struct MapIndexingSystem {}
impl<'a> System<'a> for MapIndexingSystem {
type SystemData = (
WriteExpect<'a, Map>,
ReadStorage<'a, Position>,
ReadStorage<'a, BlocksTile>,
Entities<'a>,
);
fn run(&mut self, data: Self::SystemData) {
let (mut map, position, blockers, entities) = data;
map.populate_blocked();
map.clear_content_index();
for (entity, position) in (&entities, &position).join() {
let idx = map.xy_idx(position.x, position.y);
let _p: Option<&BlocksTile> = blockers.get(entity);
if let Some(_p) = _p {
map.blocked[idx] = true;
}
map.tile_content[idx].push(entity);
}
}
}
extern crate specs;
use super::{CombatStats, Name, SufferDamage, WantsToMelee};
use rltk::console;
use specs::prelude::*;
pub struct MeleeCombatSystem {}
impl<'a> System<'a> for MeleeCombatSystem {
type SystemData = (
Entities<'a>,
WriteStorage<'a, WantsToMelee>,
ReadStorage<'a, Name>,
ReadStorage<'a, CombatStats>,
WriteStorage<'a, SufferDamage>,
);
fn run(&mut self, data: Self::SystemData) {
let (entities, mut wants_melee, names, combat_stats, mut inflict_damage) = data;
for (_entity, wants_melee, name, stats) in
(&entities, &wants_melee, &names, &combat_stats).join()
{
if stats.hp > 0 {
let target_stats = combat_stats.get(wants_melee.target).unwrap();
if target_stats.hp > 0 {
let target_name = names.get(wants_melee.target).unwrap();
let damage = i32::max(0, stats.power - target_stats.defense);
if damage == 0 {
console::log(&format!(
"{} is unable to hurt {}",
&name.name, &target_name.name
));
} else {
console::log(&format!(
"{} hits {}, for {} hp.",
&name.name, &target_name.name, damage
));
inflict_damage
.insert(wants_melee.target, SufferDamage { amount: damage })
.expect("Unable to do damage");
}
}
}
}
wants_melee.clear();
}
}
extern crate specs;
use super::{Monster, Name, Viewshed};
use super::{Map, Monster, Name, Position, Viewshed};
use specs::prelude::*;
extern crate rltk;
use rltk::{console, Point};
......@@ -7,19 +7,40 @@ use rltk::{console, Point};
pub struct MonsterAI {}
impl<'a> System<'a> for MonsterAI {
#[allow(clippy::type_complexity)]
type SystemData = (
WriteExpect<'a, Map>,
ReadExpect<'a, Point>,
ReadStorage<'a, Viewshed>,
WriteStorage<'a, Viewshed>,
ReadStorage<'a, Monster>,
ReadStorage<'a, Name>,
WriteStorage<'a, Position>,
);
fn run(&mut self, data: Self::SystemData) {
let (player_pos, viewshed, monster, name) = data;
let (map, player_pos, mut viewshed, monster, name, mut position) = data;
for (viewshed, _monster, name) in (&viewshed, &monster, &name).join() {
for (mut viewshed, _monster, name, mut pos) in
(&mut viewshed, &monster, &name, &mut position).join()
{
let distance =
rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
if distance < 1.5 {
// Attack goes here
console::log(&format!("{} shouts insults", name.name));
return;
}
if viewshed.visible_tiles.contains(&*player_pos) {
console::log(format!("{} shouts insults", name.name));
let path = rltk::a_star_search(
map.xy_idx(pos.x, pos.y) as i32,
map.xy_idx(player_pos.x, player_pos.y) as i32,
&*map,
);
if path.success && path.steps.len() > 1 {
pos.x = path.steps[1] as i32 % map.width;
pos.y = path.steps[1] as i32 / map.width;
viewshed.dirty = true;
}
}
}
}
......
use super::{Map, Player, Position, RunState, State, TileType, Viewshed};
use rltk::{Rltk, VirtualKeyCode, Point};
use super::{CombatStats, Map, Player, Position, RunState, State, Viewshed, WantsToMelee};
use rltk::{Point, Rltk, VirtualKeyCode};
use specs::prelude::*;
use std::cmp::{max, min};
......@@ -8,16 +8,36 @@ pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
let mut players = ecs.write_storage::<Player>();
let mut viewsheds = ecs.write_storage::<Viewshed>();
let mut ppos = ecs.write_resource::<Point>();
let entities = ecs.entities();
let combat_stats = ecs.read_storage::<CombatStats>();
let map = ecs.fetch::<Map>();
let mut wants_to_melee = ecs.write_storage::<WantsToMelee>();
for (_player, pos, viewshed) in (&mut players, &mut positions, &mut viewsheds).join() {
for (entity, _player, pos, viewshed) in
(&entities, &mut players, &mut positions, &mut viewsheds).join()
{
let destination_idx = map.xy_idx(pos.x + delta_x, pos.y + delta_y);
if map.tiles[destination_idx] != TileType::Wall {
for potential_target in map.tile_content[destination_idx].iter() {
let target = combat_stats.get(*potential_target);
if let Some(_target) = target {
wants_to_melee
.insert(
entity,
WantsToMelee {
target: *potential_target,
},
)
.expect("Add target failed.");
return;
}
}
if !map.blocked[destination_idx] {
pos.x = min(79, max(0, pos.x + delta_x));
pos.y = min(49, max(0, pos.y + delta_y));
viewshed.dirty = true;
ppos.x = pos.x;
ppos.y = pos.y;
}
......@@ -27,20 +47,33 @@ pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
pub fn player_input(gs: &mut State, ctx: &mut Rltk) -> RunState {
// Player movement
match ctx.key {
None => return RunState::Paused,
None => return RunState::Paused, // Nothing happened
Some(key) => match key {
VirtualKeyCode::Left => try_move_player(-1, 0, &mut gs.ecs),
VirtualKeyCode::Numpad4 => try_move_player(-1, 0, &mut gs.ecs),
VirtualKeyCode::H => try_move_player(-1, 0, &mut gs.ecs),
VirtualKeyCode::Right => try_move_player(1, 0, &mut gs.ecs),
VirtualKeyCode::Numpad6 => try_move_player(1, 0, &mut gs.ecs),
VirtualKeyCode::L => try_move_player(1, 0, &mut gs.ecs),
VirtualKeyCode::Up => try_move_player(0, -1, &mut gs.ecs),
VirtualKeyCode::Numpad8 => try_move_player(0, -1, &mut gs.ecs),
VirtualKeyCode::K => try_move_player(0, -1, &mut gs.ecs),
VirtualKeyCode::Down => try_move_player(0, 1, &mut gs.ecs),
VirtualKeyCode::Numpad2 => try_move_player(0, 1, &mut gs.ecs),
VirtualKeyCode::J => try_move_player(0, 1, &mut gs.ecs),
VirtualKeyCode::Left | VirtualKeyCode::Numpad4 | VirtualKeyCode::H => {
try_move_player(-1, 0, &mut gs.ecs)
}
VirtualKeyCode::Right | VirtualKeyCode::Numpad6 | VirtualKeyCode::L => {
try_move_player(1, 0, &mut gs.ecs)
}
VirtualKeyCode::Up | VirtualKeyCode::Numpad8 | VirtualKeyCode::K => {
try_move_player(0, -1, &mut gs.ecs)
}
VirtualKeyCode::Down | VirtualKeyCode::Numpad2 | VirtualKeyCode::J => {
try_move_player(0, 1, &mut gs.ecs)
}
// Diagonals
VirtualKeyCode::Numpad9 | VirtualKeyCode::Y => try_move_player(1, -1, &mut gs.ecs),
VirtualKeyCode::Numpad7 | VirtualKeyCode::U => try_move_player(-1, -1, &mut gs.ecs),
VirtualKeyCode::Numpad3 | VirtualKeyCode::N => try_move_player(1, 1, &mut gs.ecs),
VirtualKeyCode::Numpad1 | VirtualKeyCode::B => try_move_player(-1, 1, &mut gs.ecs),
_ => return RunState::Paused,
},
}
......
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment