summaryrefslogtreecommitdiff
path: root/src/systems/attacking.rs
blob: 43186959498a67b1c500b9f59bc46486cadc9345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74


use rand::Rng;
use specs::{
	ReadStorage,
	WriteStorage,
	Write,
	System,
	Entities,
	Join
};

use crate::{
	components::{Health, AttackInbox, AttackType, Dead, Position, Autofight},
	resources::NewEntities,
	Template,
	util
};


pub struct Attacking;
impl <'a> System<'a> for Attacking {
	type SystemData = (
		Entities<'a>,
		WriteStorage<'a, AttackInbox>,
		WriteStorage<'a, Health>,
		WriteStorage<'a, Dead>,
		ReadStorage<'a, Position>,
		Write<'a, NewEntities>,
		WriteStorage<'a, Autofight>
	);
	fn run(&mut self, (entities, mut attackeds, mut healths, mut deads, positions, mut new, mut autofighters): Self::SystemData) {
		
		for (entity, attacked, autofighter) in (&entities, &attackeds, &mut autofighters).join() {
			for attack in &attacked.messages {
				if attack.typ.is_hostile() {
					if let Some(attacker) = attack.attacker {
						if healths.contains(attacker) && attacker != entity {
							autofighter.target = Some(attacker);
						}
					}
				}
			}
		}
		for (ent, health, attacked) in (&entities, &mut healths, &mut attackeds).join() {
			let mut wounded = false;
			for attack in attacked.messages.drain(..) {
				match attack.typ {
					AttackType::Attack(strength) => {
						let damage = rand::thread_rng().gen_range(0, strength+1);
						health.health -= damage;
						if damage > 0 {
							wounded = true;
						}
					}
					AttackType::Heal(healthdiff) => {
						health.health += healthdiff;
					}
				}
			}
			health.health = util::clamp(health.health, 0, health.maxhealth);
			if health.health == 0 {
				deads.insert(ent, Dead).unwrap();
			}
			if let Some(position) = positions.get(ent){
				if wounded {
					new.create(position.pos, Template::empty("wound")).unwrap();
				}
			}
		}
		attackeds.clear();
	}
}