-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnet.rs
More file actions
216 lines (189 loc) · 5.71 KB
/
Copy pathnet.rs
File metadata and controls
216 lines (189 loc) · 5.71 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
use serde::{Deserialize, Serialize};
use crate::{Action, GameOutcome, GameState, Team};
pub type UserId = u32;
pub type ChallengeId = u32;
pub type GameId = u32;
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct User {
pub id: UserId,
pub name: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Challenge {
pub id: ChallengeId,
pub source: User,
pub target: User,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
pub enum Player {
Human { id: UserId, name: String },
Bot { name: String },
}
impl Player {
#[must_use]
pub fn human(user: User) -> Self {
Self::Human {
id: user.id,
name: user.name,
}
}
#[must_use]
pub fn bot(name: impl Into<String>) -> Self {
Self::Bot { name: name.into() }
}
#[must_use]
pub fn name(&self) -> &str {
match self {
Self::Human { name, .. } | Self::Bot { name } => name,
}
}
#[must_use]
pub const fn user_id(&self) -> Option<UserId> {
match self {
Self::Human { id, .. } => Some(*id),
Self::Bot { .. } => None,
}
}
#[must_use]
pub const fn is_bot(&self) -> bool {
matches!(self, Self::Bot { .. })
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BotEvaluation {
/// Score in centibots from White's perspective: +100 is about one bot for White.
pub white_score: i32,
/// Forced mate distance in moves by the winning side, positive for White and negative for Black.
#[serde(default)]
pub mate_in: Option<i16>,
}
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BotEvaluations {
pub white: Option<BotEvaluation>,
pub black: Option<BotEvaluation>,
}
impl BotEvaluations {
#[must_use]
pub const fn get(&self, team: Team) -> Option<BotEvaluation> {
match team {
Team::White => self.white,
Team::Black => self.black,
}
}
pub fn set(&mut self, team: Team, evaluation: BotEvaluation) {
match team {
Team::White => self.white = Some(evaluation),
Team::Black => self.black = Some(evaluation),
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Game {
pub id: GameId,
pub revision: u32,
pub white: Player,
pub black: Player,
pub bot_evaluations: BotEvaluations,
pub state: GameState,
pub outcome: Option<GameOutcome>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum ClientMessage {
Handshake { name: String },
SendChallenge { target_id: UserId },
AcceptChallenge { challenge_id: ChallengeId },
StartBotMatch,
LeaveGame { game_id: GameId },
GameAction { action: Action },
Quit,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum ServerMessage {
Welcome {
user_id: UserId,
},
Lobby {
users: Vec<User>,
challenges: Vec<Challenge>,
},
Game {
game: Game,
},
BotThinking {
game_id: GameId,
team: crate::Team,
budget_ms: u64,
},
Error {
message: String,
},
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Pos;
#[test]
fn client_messages_are_readable_tagged_json() {
let message = ClientMessage::GameAction {
action: Action::move_bots(Pos::new(0, 1), Pos::new(0, 2), 1),
};
let json = serde_json::to_value(&message).unwrap();
assert_eq!(json["type"], "gameAction");
assert_eq!(json["action"]["source"]["x"], 0);
assert_eq!(json["action"]["target"]["y"], 2);
assert_eq!(json["action"]["count"], 1);
assert_eq!(
serde_json::from_value::<ClientMessage>(json).unwrap(),
message
);
}
#[test]
fn lobby_messages_use_named_fields_instead_of_tuple_data() {
let message = ServerMessage::Lobby {
users: vec![User {
id: 7,
name: "Ada".into(),
}],
challenges: Vec::new(),
};
let json = serde_json::to_value(&message).unwrap();
assert_eq!(json["type"], "lobby");
assert_eq!(json["users"][0]["name"], "Ada");
assert!(json.get("data").is_none());
}
#[test]
fn bot_match_messages_and_players_have_explicit_types() {
let start = serde_json::to_value(ClientMessage::StartBotMatch).unwrap();
assert_eq!(start, serde_json::json!({ "type": "startBotMatch" }));
let player = Player::bot("Atlas");
let json = serde_json::to_value(&player).unwrap();
assert_eq!(json, serde_json::json!({ "kind": "bot", "name": "Atlas" }));
assert!(player.is_bot());
assert_eq!(player.user_id(), None);
let evaluation = BotEvaluations {
white: Some(BotEvaluation {
white_score: 100,
mate_in: None,
}),
black: Some(BotEvaluation {
white_score: -999_985,
mate_in: Some(-8),
}),
};
assert_eq!(
serde_json::to_value(evaluation).unwrap(),
serde_json::json!({
"white": { "whiteScore": 100, "mateIn": null },
"black": { "whiteScore": -999985, "mateIn": -8 }
})
);
}
}