Skip to content

Commit

Permalink
feat(component): Add damage component to player
Browse files Browse the repository at this point in the history
We can now specify the amount of damage that the hero can inflict.
  • Loading branch information
yngtdd committed Apr 10, 2022
1 parent baff974 commit 356113d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
1 change: 1 addition & 0 deletions src/spawner/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub fn spawn_player(ecs: &mut World, pos: Point) {
max: 15,
},
FieldOfView::new(8),
Damage(1),
));
}

Expand Down
29 changes: 23 additions & 6 deletions src/systems/combat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,49 @@ use crate::prelude::*;
#[read_component(WantsToAttack)]
#[read_component(Player)]
#[write_component(Health)]
#[read_component(Damage)]
#[read_component(Carried)]
pub fn combat(ecs: &mut SubWorld, commands: &mut CommandBuffer) {
let mut attackers = <(Entity, &WantsToAttack)>::query();

let victims: Vec<(Entity, Entity)> = attackers
let victims: Vec<(Entity, Entity, Entity)> = attackers
.iter(ecs)
.map(|(entity, attack)| (*entity, attack.victim))
.map(|(entity, attack)| (*entity, attack.attacker, attack.victim))
.collect();

victims.iter().for_each(|(message, victim)| {
victims.iter().for_each(|(message, attacker, victim)| {
let is_player = ecs
.entry_ref(*victim)
.unwrap()
.get_component::<Player>()
.is_ok();

let base_damage = if let Ok(v) = ecs.entry_ref(*attacker) {
if let Ok(dmg) = v.get_component::<Damage>() {
dmg.0
} else {
0
}
} else {
0
};

let weapon_damage: i32 = <(&Carried, &Damage)>::query().iter(ecs)
.filter(|(carried, _)| carried.0 == *attacker)
.map(|(_, dmg)| dmg.0)
.sum();

let final_damage = base_damage + weapon_damage;

if let Ok(mut health) = ecs
.entry_mut(*victim)
.unwrap()
.get_component_mut::<Health>()
{
println!("Health before attack: {}", health.current);
health.current -= 1;
health.current -= final_damage;
if health.current < 1 && !is_player {
commands.remove(*victim);
}
println!("Health after attack: {}", health.current);
}
commands.remove(*message);
});
Expand Down

0 comments on commit 356113d

Please sign in to comment.