-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathenv.rs
339 lines (302 loc) · 8.72 KB
/
env.rs
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/// # Battlesnake API Types:
///
/// This module contains the types for (de)serializing the battlesnake game
/// requests.
///
/// See: https://docs.battlesnake.com/api
use serde::{Deserialize, Serialize};
use std::fmt::{self, Debug};
use std::mem::size_of;
use std::ops::{Add, Neg, Sub};
pub const API_VERSION: &str = "1";
pub const HAZARD_DAMAGE: u8 = 15;
/// Position in the a 2D grid.
#[derive(Serialize, Deserialize, Default, Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Vec2D {
pub x: i16,
pub y: i16,
}
const _: () = assert!(size_of::<Vec2D>() == 4);
#[inline(always)]
pub fn v2(x: i16, y: i16) -> Vec2D {
Vec2D::new(x, y)
}
impl Vec2D {
pub fn new(x: i16, y: i16) -> Vec2D {
Vec2D { x, y }
}
pub fn apply(self, d: Direction) -> Vec2D {
self + d.into()
}
/// Returns the manhattan distance to (0,0)
pub fn manhattan(self) -> u64 {
self.x.unsigned_abs() as u64 + self.y.unsigned_abs() as u64
}
/// Returns whether the vector is inside a rectangle from (0,0) to (width-1,height-1)
pub fn within(self, width: usize, height: usize) -> bool {
self.x >= 0 && self.x < width as _ && self.y >= 0 && self.y < height as _
}
}
impl From<(i16, i16)> for Vec2D {
fn from(val: (i16, i16)) -> Self {
Vec2D::new(val.0, val.1)
}
}
impl From<(usize, usize)> for Vec2D {
fn from(val: (usize, usize)) -> Self {
Vec2D::new(val.0 as _, val.1 as _)
}
}
impl From<Direction> for Vec2D {
fn from(d: Direction) -> Self {
match d {
Direction::Up => Vec2D::new(0, 1),
Direction::Right => Vec2D::new(1, 0),
Direction::Down => Vec2D::new(0, -1),
Direction::Left => Vec2D::new(-1, 0),
}
}
}
impl Add for Vec2D {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
x: self.x + other.x,
y: self.y + other.y,
}
}
}
impl Sub for Vec2D {
type Output = Self;
fn sub(self, other: Self) -> Self {
Self {
x: self.x - other.x,
y: self.y - other.y,
}
}
}
impl Neg for Vec2D {
type Output = Self;
fn neg(self) -> Self::Output {
Self {
x: -self.x,
y: -self.y,
}
}
}
/// The Direction is returned as part of a `MoveResponse`.
///
/// The Y-Axis is positive in the up direction, and X-Axis is positive to the right.
#[derive(Serialize, Debug, Default, Clone, Copy, Hash, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
/// Positive Y
#[default]
Up,
/// Positive X
Right,
/// Negative Y
Down,
/// Negative X
Left,
}
impl fmt::Display for Direction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
<Self as Debug>::fmt(self, f)
}
}
impl Direction {
pub fn all() -> [Self; 4] {
[Self::Up, Self::Right, Self::Down, Self::Left]
}
/// Returns the invert direction (eg. Left for Right)
pub fn invert(&self) -> Self {
match self {
Self::Up => Self::Down,
Self::Right => Self::Left,
Self::Down => Self::Up,
Self::Left => Self::Right,
}
}
}
impl From<Vec2D> for Direction {
fn from(p: Vec2D) -> Self {
if p.x < 0 {
Self::Left
} else if p.x > 0 {
Self::Right
} else if p.y < 0 {
Self::Down
} else {
Self::Up
}
}
}
impl From<u8> for Direction {
fn from(v: u8) -> Self {
match v {
0 => Self::Up,
1 => Self::Right,
2 => Self::Down,
3 => Self::Left,
_ => unreachable!(),
}
}
}
/// Game Object describing the game being played.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct GameData {
/// A unique identifier for this Game.
pub id: String,
/// Information about the ruleset being used to run this game.
#[serde(default)]
pub ruleset: Ruleset,
/// How much time your snake has to respond to requests for this Game in milliseconds.
pub timeout: u64,
/// The source of this game. (tournament, league, arena, challenge, custom)
#[serde(default)]
pub source: String,
}
/// Information about the ruleset being used to run this game.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Ruleset {
/// Name of the ruleset being used to run this game.
/// Example: "standard"
pub name: String,
/// The release version of the Rules module used in this game.
/// Example: "version": "v1.2.3"
#[serde(default)]
pub version: String,
#[serde(default)]
pub settings: Settings,
}
/// A collection of specific settings being used by the current game
/// that control how the rules are applied.
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct Settings {
/// Percentage chance of spawning a new food every round.
pub food_spawn_chance: usize,
/// Minimum food to keep on the board every turn.
pub minimum_food: usize,
/// Health damage a snake will take when ending its turn in a hazard.
/// This stacks on top of the regular 1 damage a snake takes per turn.
#[serde(alias = "hazardDamagePerTurn")]
pub hazard_damage: usize,
pub royale: Royale,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct Royale {
/// In Royale mode, the number of turns between generating new hazards (shrinking the safe board space).
#[serde(alias = "shrinkEveryNTurns")]
pub shrink: usize,
}
/// Object describing a snake.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Battlesnake {
pub id: String,
pub name: String,
pub health: u8,
/// head to tail
pub body: Vec<Vec2D>,
#[serde(default)]
pub shout: String,
}
impl PartialEq for Battlesnake {
fn eq(&self, rhs: &Self) -> bool {
self.id == rhs.id
}
}
/// The game board is represented by a standard 2D grid, oriented with (0,0) in the bottom left.
/// The Y-Axis is positive in the up direction, and X-Axis is positive to the right.
///
/// Thus a board with width `w` and hight `h` is represented as shown below.
/// ```txt
/// ( 0,h-1) (w-1,h-1)
/// ^ .
/// | .
/// ( 0, 0) -> (w-1, 0)
/// ```
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Board {
/// The number of rows in the y-axis of the game board.
pub height: usize,
/// The number of columns in the x-axis of the game board.
pub width: usize,
/// Array of coordinates representing food locations on the game board.
pub food: Vec<Vec2D>,
/// Array of coordinates representing hazardous locations on the game board.
/// These will only appear in some game modes.
pub hazards: Vec<Vec2D>,
/// Array of [Battlesnake] Objects representing all Battlesnakes remaining on
/// the game board (including yourself if you haven't been eliminated).
pub snakes: Vec<Battlesnake>,
}
/// The game data that is send on the `start`, `move` and `end` requests.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct GameRequest {
/// [Game](GameData) Object describing the game being played.
pub game: GameData,
/// Turn number for this move.
pub turn: usize,
/// [Board] Object describing the game board on this turn.
pub board: Board,
/// Battlesnake Object describing your Battlesnake.
pub you: Battlesnake,
}
impl fmt::Display for GameRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"t={} {}-{} ({})",
self.turn, self.game.source, self.game.ruleset.name, self.game.id
)
}
}
/// This response configures the battlesnake and its appearance.
#[derive(Serialize, Debug)]
pub struct IndexResponse<'a> {
pub apiversion: &'a str,
pub author: &'a str,
pub color: &'a str,
pub head: &'a str,
pub tail: &'a str,
pub version: &'a str,
}
impl<'a> IndexResponse<'a> {
pub fn new(
apiversion: &'a str,
author: &'a str,
color: &'a str,
head: &'a str,
tail: &'a str,
version: &'a str,
) -> Self {
Self {
apiversion,
author,
color,
head,
tail,
version,
}
}
}
/// Game response with the direction in which a snake has decided to move.
#[derive(Serialize, Debug, Default)]
#[must_use]
pub struct MoveResponse {
pub r#move: Direction,
pub shout: String,
}
impl MoveResponse {
pub fn new(r#move: Direction) -> Self {
Self {
r#move,
shout: String::new(),
}
}
pub fn shout(r#move: Direction, shout: String) -> Self {
Self { r#move, shout }
}
}