summaryrefslogtreecommitdiff
path: root/src/systems/interact.rs
blob: b932fd5d31d8ab150aa9988a36540d512c1b392c (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

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

use crate::components::{
	Controller,
	Position,
	ControlCooldown,
	Interactable,
	Dead,
	Removed,
	Sound,
	Ear
};

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



pub struct Interact;
impl <'a> System<'a> for Interact {
	type SystemData = (
		Entities<'a>,
		ReadStorage<'a, Controller>,
		ReadStorage<'a, Position>,
		Read<'a, Ground>,
		WriteStorage<'a, ControlCooldown>,
		ReadStorage<'a, Interactable>,
		WriteStorage<'a, Dead>,
		WriteStorage<'a, Removed>,
		Write<'a, NewEntities>,
		WriteStorage<'a, Ear>
	);
	
	fn run(&mut self, (entities, controllers, positions, ground, mut cooldowns, interactables, mut deads, mut removeds, mut new, mut ears): Self::SystemData) {
		for (entity, controller, position) in (&entities, &controllers, &positions).join(){
			let mut target = None;
			match &controller.control {
				Control::Interact(directions) => {
					'targets: for direction in directions {
						let pos = position.pos + direction.to_position();
						for ent in ground.cells.get(&pos).unwrap_or(&HashSet::new()) {
							if let Some(interactable) = interactables.get(*ent) {
								target = Some((*ent, interactable, pos));
								break 'targets;
							}
						}
					}
				}
				_ => {}
			}
			if let Some((ent, interactable, pos)) = target {
				match interactable {
					Interactable::Harvest => {
						deads.insert(ent, Dead).unwrap();
					}
					Interactable::Change(into) => {
						new.create(pos, into).unwrap();
						removeds.insert(ent, Removed).unwrap();
					}
					Interactable::Say(text) => {
						if let Some(ear) = ears.get_mut(entity) {
							ear.sounds.push(Sound{source: None, text: text.clone()});
						}
					}
				}
				cooldowns.insert(entity, ControlCooldown{amount: 2}).unwrap();
			}
		}
	}
}