summaryrefslogtreecommitdiff
path: root/src/controls.rs
blob: 63f418aec647712af08bbbe1892b9d7d5bf8fe39 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106


use serde_json::{Value, json};
use specs::Entity;
use crate::{PlayerId, Pos};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
	North,
	South,
	East,
	West,
	None
}

impl Direction {
	fn from_json(val: &Value) -> Option<Direction>{
		match val {
			Value::String(txt) => match txt.as_str() {
				"north" => Some(Direction::North),
				"south" => Some(Direction::South),
				"east" => Some(Direction::East),
				"west"=> Some(Direction::West),
				"" => Some(Direction::None),
				_ => None
			}
			Value::Null => Some(Direction::None),
			_ => None
		}
	}
	
	pub fn to_position(&self) -> Pos {
		match self {
			Direction::North => Pos::new(0, -1),
			Direction::South => Pos::new(0, 1),
			Direction::East => Pos::new(1, 0),
			Direction::West => Pos::new(-1, 0),
			Direction::None => Pos::new(0, 0)
		}
	}
}

#[derive(Debug, Clone)]
pub enum Control {
	Move(Direction),
	Take(Option<usize>),
	Drop(usize),
	Use(usize),
	Attack(Vec<Direction>),
	AttackTarget(Entity),
	Interact(Vec<Direction>)
}


impl Control {
	pub fn from_json(val: &Value) -> Option<Control>{
		if let Value::String(control_type) = val.get(0)? {
			match control_type.as_str() {
				"move" => match Direction::from_json(val.get(1)?) {
					Some(dir) => Some(Control::Move(dir)),
					None => None
				},
				"take" => Some(Control::Take(val.get(1).unwrap_or(&json!(0)).as_u64().map(|idx| idx as usize))),
				"drop" => Some(Control::Drop(val.get(1)?.as_u64().unwrap_or(0) as usize)),
				"use" => Some({
					let arr = val.as_array()?;
					let mut rank = 0;
					if arr.len() == 3 {
						if arr[1].as_str()? != "inventory" {
							return None;
						}
						rank = arr[2].as_u64()?;
					} else if arr.len() == 2 {
						rank = arr[1].as_u64()?;
					} else if arr.len() > 1 {
						return None;
					}
					Control::Use(rank as usize)
				}),
				"attack" => Some(Control::Attack({
					let mut directions = Vec::new();
					for dir in val.get(1)?.as_array()? {
						directions.push(Direction::from_json(dir)?);
					}
					directions
				})),
				"interact" => Some(Control::Interact({
					let mut directions = Vec::new();
					for dir in val.get(1)?.as_array()? {
						directions.push(Direction::from_json(dir)?);
					}
					directions
				})),
				_ => None
			}
		} else {None}
	}
}

#[derive(Debug, Clone)]
pub enum Action {
	Join(PlayerId),
	Leave(PlayerId),
	Input(PlayerId, Control)
}