summaryrefslogtreecommitdiff
path: root/src/systems/fight.rs
blob: 3e1142b6cfe76563f2ac3ea7ceb6272bd68b2b24 (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
75
76
77
78
79
80
81
82
83

use std::collections::HashSet;
use specs::{
	Entities,
	ReadStorage,
	WriteStorage,
	System,
	Join,
	Read
};

use crate::components::{
	Controller,
	Position,
	AttackInbox,
	AttackMessage,
	Fighter,
	Health,
	ControlCooldown,
	Autofight,
	Faction,
	Inventory
};

use crate::controls::{Control};
use crate::resources::{Ground};



pub struct Fight;
impl <'a> System<'a> for Fight {
	type SystemData = (
		Entities<'a>,
		ReadStorage<'a, Controller>,
		ReadStorage<'a, Position>,
		Read<'a, Ground>,
		WriteStorage<'a, AttackInbox>,
		ReadStorage<'a, Fighter>,
		ReadStorage<'a, Health>,
		WriteStorage<'a, ControlCooldown>,
		WriteStorage<'a, Autofight>,
		ReadStorage<'a, Faction>,
		ReadStorage<'a, Inventory>
	);
	
	fn run(&mut self, (entities, controllers, positions, ground, mut attacked, fighters, healths, mut cooldowns, mut autofighters, factions, inventories): Self::SystemData) {
		for (entity, controller, position, fighter) in (&entities, &controllers, &positions, &fighters).join(){
			let mut target = None;
			match &controller.control {
				Control::Attack(directions) => {
					'targets: for direction in directions {
						for ent in ground.cells.get(&(position.pos + direction.to_position())).unwrap_or(&HashSet::new()) {
							if healths.contains(*ent) && *ent != entity && Faction::is_enemy_entity(&factions, entity, *ent) {
								target = Some(*ent);
								break 'targets;
							}
						}
					}
				}
				Control::AttackTarget(t) => {
					if *t == entity { // don't knock yourself out
					} else if let Some(target_position) = positions.get(*t){
						if position.pos.distance_to(target_position.pos) <= fighter.range {
							target = Some(*t);
						}
					}
				}
				_ => {}
			}
			if let Some(ent) = target {
				let mut attack = fighter.attack.clone();
				if let Some(inventory) = inventories.get(entity) {
					attack = attack.apply_bonuses(&inventory.equipment_bonuses());
				}
				AttackInbox::add_message(&mut attacked, ent, AttackMessage{typ: attack, attacker: Some(entity)});
				cooldowns.insert(entity, ControlCooldown{amount: fighter.cooldown}).unwrap();
				if let Some(autofighter) = autofighters.get_mut(entity){
					autofighter.target = Some(ent);
				}
			}
		}
	}
}