-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtilemap.rs
405 lines (356 loc) · 13.4 KB
/
tilemap.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
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
pub use common_types::Vector2;
pub use tile::Tile;
mod common_types;
mod tile;
// -------------------------------------------------------------------------------------------------
// Definition
// -------------------------------------------------------------------------------------------------
/// # Description
/// Small enum that helps identify the result of the private [`Tilemap::build_row()`] method.
enum DrawLineState {
/// # Description
/// Identifies that after the execution of the [`Tilemap::build_row()`] new line should be started.
NewLine,
/// # Description
/// Identifies that after the execution of the the [`Tilemap::build_row()`] index is till pointing
/// tp the same line.
/// # Value
/// * `usize` - Index at which [`Tilemap::build_row()`] stopped. Build process should be continued
/// from this position.
SameLine(usize)
}
/// # Description
/// Object that describes and stores 2d tilemap. Provides to means to add/delete/modify tiles in it.
/// Also provides method to create string representation of the tilemap.
///
/// # Example
/// ```rust
/// // Create new tilemap
/// let mut tilemap = char_tilemap::Tilemap::new('-');
///
/// // Add new tile
/// match tilemap.add_tile(char_tilemap::Vector2::ZERO, 'O') {
/// Ok(_) => (),
/// Err(msg) => println!("{msg}")
/// }
///
/// // Update tile
/// match tilemap.update_tile(char_tilemap::Vector2::ZERO, 'X') {
/// Ok(_) => (),
/// Err(msg) => println!("{msg}")
/// }
///
/// // Build tilemap
/// let tilemap_as_string = tilemap.build();
///
/// // Remove tile
/// match tilemap.remove_tile(char_tilemap::Vector2::ZERO) {
/// Ok(_) => (),
/// Err(msg) => println!("{msg}")
/// }
/// ```
#[derive(Debug)]
pub struct Tilemap {
/// # Description
/// Value of the empty tile that will be used during the build process of the tile map in
/// [`Tilemap::build()`] method.
pub empty_tile: char,
/// # Description
/// Size of the tilemap. Depends on the positions of tile that are stored within.
/// Always equals to the furthest coordinates of tiles on X and Y axes.
size: Vector2,
/// # Description
/// Stores all tiles of this tilemap. They are sorted so it would be much easier to build
/// tilemap to a string representation.
tiles: sorted_vec::SortedSet<Tile>
}
// -------------------------------------------------------------------------------------------------
// Implementation
// -------------------------------------------------------------------------------------------------
impl Tilemap {
/// # Description
/// Creates hew [`Tilemap`] with specified empty tile value.
///
/// # Arguments
/// * `empty_tile: char` - Value that will be used for empty tiles during the build of the [`Tilemap`].
///
/// # Return
/// New instance of the [`Tilemap`].
///
/// # Example
/// ```rust
/// let mut tilemap = char_tilemap::Tilemap::new('-');
/// ```
pub fn new(empty_tile: char) -> Tilemap {
return Tilemap {
empty_tile,
size: Vector2::new(0, 0),
tiles: sorted_vec::SortedSet::new(),
}
}
/// # Description
/// Returns size of the [`Tilemap`].
///
/// # Return
/// [`Vector2`] that stores size of the [`Tilemap`].
///
/// # Example
/// ```rust
/// let mut tilemap = char_tilemap::Tilemap::new('-');
/// assert_eq!(tilemap.size(), char_tilemap::Vector2::ZERO);
/// ```
pub fn size(&self) -> Vector2 {
return self.size;
}
/// # Description
/// Adds a new [`Tile`] at the specified position and with specified value.
///
/// # Arguments
/// * `position: Vector2` - Position represented as [`Vector2`] of a new [`Tile`].
/// * `value: char` - Value as [`char`] of a new [`Tile`].
///
/// # Return
/// * [`Ok`] will be returned in case of successful addition of a new [`Tile`].
/// * [`Err`] will be returned if tile at the specified position already exists. Contains error message.
///
/// # Example
/// ```rust
/// let mut tilemap = char_tilemap::Tilemap::new('-');
/// match tilemap.add_tile(char_tilemap::Vector2::ZERO, 'O') {
/// Ok(_) => (),
/// Err(msg) => println!("{msg}")
/// }
/// ```
pub fn add_tile(&mut self, position: Vector2, value: char) -> Result<(), String> {
let new_tile = Tile { position, value };
if !self.tiles.contains(&new_tile)
{
self.tiles.push(new_tile);
self.size.x = std::cmp::max(self.size.x, position.x + 1);
self.size.y = std::cmp::max(self.size.y, position.y + 1);
return Ok(());
}
return Err(format!("Failed to add new tile at {position} with value \'{value}\'"));
}
/// # Description
/// Removes [`Tile`] at the specified position if it exists.
///
/// # Arguments
/// * `position: Vector2` - Position represented as [`Vector2`] at which [`Tile`] should be removed.
///
/// # Return
/// * [`Ok`] if at the specified position [`Tile`] did exist and was removed.
/// * [`Err`] if at the specified position [`Tile`] did not exist. Contains error message.
///
/// # Example
/// ```rust
/// let mut tilemap = char_tilemap::Tilemap::new('-');
/// match tilemap.remove_tile(char_tilemap::Vector2::ZERO) {
/// Ok(_) => (),
/// Err(msg) => println!("{msg}")
/// }
/// ```
pub fn remove_tile(&mut self, position: Vector2) -> Result<(), String> {
if let Some(index) = self.tiles.iter().position(|tile| tile.position == position) {
self.tiles.remove_index(index);
return Ok(());
}
return Err(format!("There is no tile at the position {position}"));
}
/// # Description
/// Updates [`Tile`] at the specified position if it exists with new value.
///
/// # Arguments
/// * `position: Vector2` - Position represented as [`Vector2`] at which [`Tile`] should be updated.
/// * `new_value: char` - New value that will be assigned to the [`Tile`] at the specified position.
///
/// # Return
/// * [`Ok`] if at the specified position [`Tile`] did exist and was updated.
/// * [`Err`] if at the specified position [`Tile`] did not exist. Contains error message.
///
/// # Example
/// ```rust
/// let mut tilemap = char_tilemap::Tilemap::new('-');
/// match tilemap.update_tile(char_tilemap::Vector2::ZERO, 'X') {
/// Ok(_) => (),
/// Err(msg) => println!("{msg}")
/// }
/// ```
pub fn update_tile(&mut self, position: Vector2, new_value: char) -> Result<(), String> {
if let Some(_) = self.tiles.iter().find(|tile| tile.position == position) {
self.tiles.replace(Tile { position, value: new_value });
return Ok(());
}
return Err(format!("There is no tile at the position {position}"));
}
/// # Description
/// Builds [`Tilemap`] into the string representation. X = 0 is a top row, Y = 0 is a left column.
///
/// # Return
/// A new [`String`] that contains representation of a [`Tilemap`].
///
/// # Example
/// ```rust
/// let mut tilemap = char_tilemap::Tilemap::new('-');
/// let tilemap_as_string = tilemap.build();
/// ```
pub fn build(&self) -> String {
let mut result = String::new();
let mut x = 0;
let mut y = 0;
// Draw all stored tile
for (_, tile) in self.tiles.iter().enumerate() {
// If current tile is on different row, draw empty rows until we reach required one
while y < tile.position.y {
match self.build_row(x, self.size.x, &mut result) {
DrawLineState::SameLine(new_position) => x = new_position,
DrawLineState::NewLine => {
x = 0;
y += 1;
result.push('\n');
},
}
}
// Draw current line until tile
match self.build_row(x, tile.position.x, &mut result) {
DrawLineState::SameLine(new_position) => x = new_position,
DrawLineState::NewLine => panic!("This branch should not be executed!")
}
// Draw tile
result.push(tile.value);
x += 1;
}
// If all tiles were drawn but we did not reach the end of the row, draw it
if x < self.size.x {
self.build_row(x, self.size.x, &mut result);
}
return result;
}
/// # Description
/// Builds a row to the specified [`String`] with empty character from `start_position` to
/// `end_position` using [`Tilemap::empty_tile`].
///
/// # Arguments
/// * `mut start_position: usize` - Start position of the row.
/// It is mutable since it will be used to determine current position of the built row.
/// * `end_position: usize` - Final position of the row. Tile at this position will not be built.
/// * `result: &mut String` - [`String`], to which row will be built.
///
/// # Return
/// * [`DrawLineState::NewLine`] in case if end of the row was reached.
/// * [`DrawLineState::SameLine`] in case of end of the row was not reached.
/// It will contain end position.
fn build_row(&self, mut start_position: usize, end_position: usize, result: &mut String) -> DrawLineState {
while start_position < end_position {
result.push(self.empty_tile);
start_position += 1;
}
return if start_position == self.size.x { DrawLineState::NewLine }
else { DrawLineState::SameLine(start_position) };
}
}
// -------------------------------------------------------------------------------------------------
// Tests
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::{Tilemap, Vector2};
const EMPTY_TILE_CHAR: char = '-';
const NUMBER_OF_TILES: usize = 5;
const TILE_VALUE: char = 'O';
fn build_test_tilemap(tilemap: &mut Tilemap) {
for i in 0..NUMBER_OF_TILES {
match tilemap.add_tile(Vector2::new(i, i), TILE_VALUE) {
Ok(_) => assert!(true),
Err(_) => assert!(false)
}
}
assert_eq!(tilemap.size(), Vector2::new(NUMBER_OF_TILES, NUMBER_OF_TILES));
}
#[test]
fn new() {
let tilemap = Tilemap::new(EMPTY_TILE_CHAR);
assert_eq!(tilemap.empty_tile, EMPTY_TILE_CHAR);
}
#[test]
fn size() {
let tilemap = Tilemap::new(EMPTY_TILE_CHAR);
assert_eq!(tilemap.size(), Vector2::ZERO);
}
#[test]
fn add_tile() {
let mut tilemap = Tilemap::new(EMPTY_TILE_CHAR);
match tilemap.add_tile(Vector2::ZERO, 'O') {
Ok(_) => assert!(true),
Err(_) => assert!(false)
}
assert_eq!(tilemap.size, Vector2::ONE);
match tilemap.add_tile(Vector2::ZERO, 'O') {
Ok(_) => assert!(false),
Err(_) => assert!(true)
}
assert_eq!(tilemap.size, Vector2::ONE);
}
#[test]
fn remove_tile() {
let mut tilemap = Tilemap::new(EMPTY_TILE_CHAR);
match tilemap.add_tile(Vector2::ZERO, 'O') {
Ok(_) => assert!(true),
Err(_) => assert!(false)
}
assert_eq!(tilemap.size, Vector2::ONE);
match tilemap.remove_tile(Vector2::ZERO) {
Ok(_) => assert!(true),
Err(_) => assert!(false)
}
match tilemap.remove_tile(Vector2::ZERO) {
Ok(_) => assert!(false),
Err(_) => assert!(true)
}
}
#[test]
fn update_tile() {
let mut tilemap = Tilemap::new(EMPTY_TILE_CHAR);
match tilemap.add_tile(Vector2::ZERO, 'O') {
Ok(_) => assert!(true),
Err(_) => assert!(false)
}
assert_eq!(tilemap.size, Vector2::ONE);
match tilemap.update_tile(Vector2::ZERO, '>') {
Ok(_) => assert!(true),
Err(_) => assert!(false)
}
match tilemap.update_tile(Vector2::ONE, '>') {
Ok(_) => assert!(false),
Err(_) => assert!(true)
}
}
#[test]
fn build_row() {
let mut result = String::new();
let mut tilemap = Tilemap::new(EMPTY_TILE_CHAR);
build_test_tilemap(&mut tilemap);
match tilemap.build_row(0, NUMBER_OF_TILES, &mut result) {
crate::tilemap::DrawLineState::NewLine => assert!(true),
crate::tilemap::DrawLineState::SameLine(_) => assert!(false)
}
let mut ideal_result = String::new();
ideal_result.push_str(String::from_utf8(vec![EMPTY_TILE_CHAR as u8; NUMBER_OF_TILES]).unwrap().as_str());
assert_eq!(result, ideal_result);
}
#[test]
fn build() {
let mut tilemap = Tilemap::new(EMPTY_TILE_CHAR);
build_test_tilemap(&mut tilemap);
let mut ideal_result = String::new();
for i in 0..NUMBER_OF_TILES {
ideal_result.push_str(String::from_utf8(vec![EMPTY_TILE_CHAR as u8; i]).unwrap().as_str());
ideal_result.push(TILE_VALUE);
ideal_result.push_str(String::from_utf8(vec![EMPTY_TILE_CHAR as u8; NUMBER_OF_TILES - i - 1]).unwrap().as_str());
if i < NUMBER_OF_TILES - 1 {
ideal_result.push('\n');
}
}
assert_eq!(tilemap.build(), ideal_result);
}
}