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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
|
//! The `pos` module contains structures for representation an
//! entity or objects position and facing direction inside the
//! dungeon grid.
use strum::IntoEnumIterator;
use strum_macros::EnumIter;
use rand::{
Rng,
distr::{Distribution, StandardUniform},
};
use std::{
fmt::Display,
ops::{AddAssign, SubAssign},
};
use crate::{MAP_SIZE_USIZE, map::MAP_SIZE};
macro_rules! downcast {
($usize:expr, $type:ty) => {
if $usize > <$type>::MAX as usize {
None
} else {
#[expect(clippy::cast_possible_truncation)]
Some($usize as $type)
}
};
}
#[macro_export]
macro_rules! const_pos {
($x:expr, $y:expr) => {{
const CONST_POS: Pos = Pos::new_unchecked($x, $y);
CONST_POS
}};
}
/// The `Direction` type represents a direction an entity
/// or any position object is facing inside the dungeon map.
/// Since the dungeon lives on a grid, there are only four
/// possible directions.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnumIter)]
pub enum Direction {
North,
South,
East,
West,
}
impl Direction {
/// Returns an iterator over all possible directions
pub fn values() -> impl Iterator<Item = Self> {
Self::iter()
}
pub fn get_random_dir() -> Self {
rand::random()
}
}
impl Display for Direction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::North => write!(f, "NORTH"),
Self::South => write!(f, "SOUTH"),
Self::East => write!(f, "EAST"),
Self::West => write!(f, "WEST"),
}
}
}
impl Distribution<Direction> for StandardUniform {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Direction {
// match rng.gen_range(0, 3) { // rand 0.5, 0.6, 0.7
match rng.random_range(0..=3) {
0 => Direction::North,
1 => Direction::East,
2 => Direction::South,
_ => Direction::West,
}
}
}
/// The `Pos` type represents a 2D position inside the dungeon grid.
///
/// The max size for the dungeon map is set by the `MAP_SIZE` constant
/// and therefore the x and y positions can be between 0 and `MAP_SIZE - 1`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Pos(u16, u16);
impl Pos {
/// Creates a new position from a given x and y position.
///
/// Returns `None` if the position goes out of the map.
///
/// # Examples
///
/// ```
/// use dungeon::Pos;
///
/// let pos = Pos::new(0,0);
/// assert!(pos.is_some());
/// ```
///
/// ```
/// use dungeon::{Pos, MAP_SIZE};
///
/// let pos = Pos::new(MAP_SIZE, MAP_SIZE);
/// assert!(pos.is_none())
/// ```
#[must_use]
pub const fn new(x: u16, y: u16) -> Option<Self> {
if x >= MAP_SIZE || y >= MAP_SIZE {
None
} else {
Some(Self(x, y))
}
}
/// Creates a new position from a given x and y position.
///
/// Bounds checks are asserted at runtime and will panic if out of bounds.
///
/// # Examples
///
/// ```
/// use dungeon::Pos;
///
/// let pos = Pos::new_unchecked(1, 1);
/// assert_eq!(pos.xy(), (1,1));
/// ```
#[must_use]
pub const fn new_unchecked(x: u16, y: u16) -> Self {
assert!(x < MAP_SIZE, "Positions must be smaller then MAP_SIZE");
assert!(y < MAP_SIZE, "Positions must be smaller then MAP_SIZE");
Self(x, y)
}
/// Returns the x and y positions of `Pos`.
///
/// # Examples
///
/// ```
/// use dungeon::Pos;
///
/// let pos = Pos::new(5,7).unwrap();
/// let (x,y) = pos.xy();
/// assert_eq!(x, 5);
/// assert_eq!(y, 7);
/// ```
#[must_use]
pub const fn xy(self) -> (u16, u16) {
(self.0, self.1)
}
/// Returns the x component of `Pos`
///
/// # Examples
///
/// ```
/// use dungeon::Pos;
///
/// let pos = Pos::new(5,7).unwrap();
/// assert_eq!(pos.x(), 5);
/// ```
#[must_use]
pub const fn x(&self) -> u16 {
self.0
}
/// Returns the y component of `Pos`
///
/// # Examples
///
/// ```
/// use dungeon::Pos;
///
/// let pos = Pos::new(5,7).unwrap();
/// assert_eq!(pos.y(), 7);
/// ```
#[must_use]
pub const fn y(&self) -> u16 {
self.1
}
/// Converts the x and y positions into an index of a continous list.
///
/// # Examples
///
/// ```
/// use dungeon::{Pos, MAP_SIZE_USIZE};
///
/// let pos = Pos::new(1,2).unwrap();
/// let idx = pos.idx();
/// assert_eq!(idx, 1 + 2 * MAP_SIZE_USIZE);
/// ```
#[must_use]
pub const fn idx(self) -> usize {
let (x, y) = (self.x() as usize, self.y() as usize);
x + y * MAP_SIZE_USIZE
}
/// Converse an index into a possible x and y position
///
/// # Examples
///
/// ```
/// use dungeon::{Pos, MAP_SIZE_USIZE};
///
/// let idx_pos = Pos::from_idx(MAP_SIZE_USIZE);
/// let pos = Pos::new(0, 1);
///
/// assert_eq!(idx_pos, pos);
/// ```
///
/// ```
/// use dungeon::{Pos, MAP_SIZE_USIZE};
///
/// let idx_pos = Pos::from_idx(MAP_SIZE_USIZE * 70 + 1);
/// let pos = Pos::new(70, 1);
///
/// assert_eq!(idx_pos, pos);
/// ```
#[must_use]
pub const fn from_idx(idx: usize) -> Option<Self> {
let x = downcast!(idx % MAP_SIZE_USIZE, u16);
let y = downcast!(idx / MAP_SIZE_USIZE, u16);
match (x, y) {
(Some(a), Some(b)) => Self::new(a, b),
_ => None,
}
}
/// Steps `Pos` one space in the `Direction` `dir`.
///
/// Returns `None` if the position goes out of the map.
///
/// # Examples
///
/// ```
/// use dungeon::{Direction, Pos};
///
/// let pos = Pos::new(0, 1).unwrap();
/// let new_pos = pos.step(Direction::North);
/// assert_eq!(new_pos, Pos::new(0, 0));
/// ```
///
/// ```
/// use dungeon::{Direction, Pos};
///
/// let pos = Pos::new(0, 1).unwrap();
/// let new_pos = pos.step(Direction::West);
/// assert!(new_pos.is_none());
/// ```
#[must_use]
pub const fn step(self, dir: Direction) -> Option<Self> {
self.step_by(dir, 1)
}
/// Steps `Pos` a given ammount in the `Direction` `dir`.
///
/// Returns `None` if the position goes out of the map.
///
/// # Examples
///
/// ```
/// use dungeon::{Direction, Pos};
///
/// let pos = Pos::new(0, 1).unwrap();
/// let new_pos = pos.step_by(Direction::South, 3);
/// assert_eq!(new_pos, Pos::new(0, 4));
/// ```
///
/// ```
/// use dungeon::{Direction, Pos};
///
/// let pos = Pos::new(1, 1).unwrap();
/// let new_pos = pos.step_by(Direction::West, 2);
/// assert!(new_pos.is_none());
/// ```
#[must_use]
pub const fn step_by(self, dir: Direction, amt: u16) -> Option<Self> {
let (x, y) = self.xy();
if amt > MAP_SIZE {
return None;
}
match dir {
Direction::North if y >= amt => Self::new(x, y - amt),
Direction::South => Self::new(x, y + amt),
Direction::East => Self::new(x + amt, y),
Direction::West if x >= amt => Self::new(x - amt, y),
_ => None,
}
}
/// Computes the absolute difference between to positions
///
/// Both values are gurenteed to be less than MAP_SIZE
///
/// # Examples
///
/// ```
/// use dungeon::Pos;
///
/// let pos1 = Pos::new(2,7).unwrap();
/// let pos2 = Pos::new(1,17).unwrap();
/// let diff = pos1.abs_diff(pos2);
/// assert_eq!(diff.xy(), (1, 10));
/// ```
///
#[must_use]
pub const fn abs_diff(self, other: Self) -> Self {
let x = self.0.abs_diff(other.0);
let y = self.1.abs_diff(other.1);
Self(x, y)
}
/// Returns the manhattan distance between `self` and `other`
pub fn manhattan(self, other: Self) -> u16 {
let abs_diff = Self::abs_diff(self, other);
abs_diff.0 + abs_diff.1
}
/// Returns of the given position is on the border of the map
///
/// ```
/// use dungeon::{Pos, MAP_SIZE};
///
/// // Assuming MAP_SIZE is at least 2
///
/// let pos1 = Pos::new(0, MAP_SIZE - 1).unwrap();
/// let pos2 = Pos::new(1, MAP_SIZE - 2).unwrap();
/// let pos3 = Pos::new(MAP_SIZE - 1, MAP_SIZE - 1).unwrap();
/// let pos4 = Pos::new(MAP_SIZE - 1, MAP_SIZE - 1).unwrap();
/// let pos5 = Pos::new(MAP_SIZE - 1, 0).unwrap();
///
/// assert!(pos1.is_border());
/// assert!(!pos2.is_border());
/// assert!(pos3.is_border());
/// assert!(pos4.is_border());
/// assert!(pos5.is_border());
/// ```
#[must_use]
pub const fn is_border(&self) -> bool {
self.0 == 0 || self.0 == MAP_SIZE - 1 || self.1 == 0 || self.1 == MAP_SIZE - 1
}
/// Returns the cardinal neighbors of this positions
pub fn neighbors(&self) -> impl Iterator<Item = Self> {
Direction::values().filter_map(|dir| self.step(dir))
}
/// Returns an iterator over all possible `Pos`
pub fn values() -> impl Iterator<Item = Self> {
(0..MAP_SIZE).flat_map(|y| (0..MAP_SIZE).filter_map(move |x| Self::new(x, y)))
}
}
impl Default for Pos {
/// Returns a default postion at the origin (0,0)
///
/// ```
/// use dungeon::Pos;
///
/// let pos = Pos::default();
///
/// assert_eq!(pos.xy(), (0, 0));
/// ```
///
fn default() -> Self {
const_pos!(0, 0)
}
}
impl TryFrom<usize> for Pos {
type Error = ();
fn try_from(value: usize) -> Result<Self, Self::Error> {
Self::from_idx(value).ok_or(())
}
}
/// The `FPos` type represents a floating 2D (temp) position.
///
/// This position is not gurenteed to be inside the dungeon grid. FPos exists to
/// tween between two different `Pos`. All bounds checks should be done in `Pos` before updating
/// the underlying Floating Position.
#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)]
pub struct FPos(f32, f32);
impl FPos {
/// Creates a new position from a given floating x and y position.
///
/// Returns `None` if the position goes out of the map.
///
/// # Examples
///
/// ```
/// use dungeon::FPos;
///
/// let fpos = FPos::new(5.4,6.7);
/// ```
#[must_use]
pub const fn new(x: f32, y: f32) -> Self {
Self(x, y)
}
/// Creates a new `FPos` using the checked/fixed `Pos`.
///
/// # Examples
///
/// ```
/// use dungeon::{Pos, FPos};
///
/// let pos = Pos::new(1, 1).unwrap();
/// let fpos = FPos::from_pos(pos);
/// ```
#[must_use]
pub const fn from_pos(pos: Pos) -> Self {
let (x, y) = pos.xy();
Self(x as f32, y as f32)
}
/// Returns the x and y positions of `FPos`.
///
/// # Examples
///
/// ```
/// use dungeon::FPos;
///
/// let fpos = FPos::new(5.0,7.2);
/// let (x,y) = fpos.xy();
/// assert_eq!(x, 5.0);
/// assert_eq!(y, 7.2);
/// ```
#[must_use]
pub const fn xy(self) -> (f32, f32) {
(self.0, self.1)
}
/// Returns the x component of `FPos`
///
/// # Examples
///
/// ```
/// use dungeon::FPos;
///
/// let fpos = FPos::new(5.0,7.2);
/// assert_eq!(fpos.x(), 5.0);
/// ```
#[must_use]
pub const fn x(&self) -> f32 {
self.0
}
/// Returns the y component of `FPos`
///
/// # Examples
///
/// ```
/// use dungeon::FPos;
///
/// let fpos = FPos::new(5.0,7.2);
/// assert_eq!(fpos.y(), 7.2);
/// ```
#[must_use]
pub const fn y(&self) -> f32 {
self.1
}
/// Steps `FPos` a given floating amount in the `Direction` `dir`.
///
/// Returns `None` if the floating position wraps.
///
/// # Examples
///
/// ```
/// use dungeon::{Direction, FPos};
///
/// let fpos = FPos::new(0.0, 1.0);
/// let new_fpos = fpos.step_by(Direction::North, 0.3);
/// assert!(new_fpos.is_some());
/// ```
///
/// ```
/// use dungeon::{Direction, FPos};
///
/// let fpos = FPos::new(0.0, 0.0);
/// let new_fpos = fpos.step_by(Direction::North, 5.0);
/// assert!(new_fpos.is_none());
/// ```
#[must_use]
pub fn step_by(self, dir: Direction, amt: f32) -> Option<Self> {
use Direction as D;
let (mut x, mut y) = self.xy();
match dir {
D::North if y >= amt => y.sub_assign(amt),
D::South => y.add_assign(amt),
D::East => x.add_assign(amt),
D::West if x >= amt => x.sub_assign(amt),
_ => return None,
};
Some(Self(x, y))
}
/// Computes the absolute difference between to positions
///
/// # Examples
///
/// ```
/// use dungeon::FPos;
///
/// let fpos1 = FPos::new(1.0,0.0);
/// let fpos2 = FPos::new(0.0,1.0);
/// let diff = fpos1.abs_diff(fpos2);
/// assert_eq!(diff.xy(), (1.0, 1.0));
/// ```
///
#[must_use]
pub fn abs_diff(self, other: Self) -> Self {
let x = (self.0 - other.0).abs();
let y = (self.1 - other.1).abs();
Self(x, y)
}
pub fn manhattan(self, other: Self) -> f32 {
let abs_diff = Self::abs_diff(self, other);
abs_diff.0 + abs_diff.1
}
}
impl Default for FPos {
/// Returns a default postion at the origin (0,0)
///
/// ```
/// use dungeon::FPos;
///
/// let fpos = FPos::default();
///
/// assert_eq!(fpos.xy(), (0.0, 0.0));
/// ```
///
fn default() -> Self {
Self::new(0.0, 0.0)
}
}
impl From<Pos> for FPos {
fn from(value: Pos) -> Self {
Self::from_pos(value)
}
}
|