forked from bones-ai/rust-drive-ai
-
Notifications
You must be signed in to change notification settings - Fork 7
/
enemy.cairo
589 lines (518 loc) · 19.7 KB
/
enemy.cairo
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use array::{ArrayTrait, SpanTrait};
use cubit::types::vec2::Vec2;
use cubit::types::fixed::FixedTrait;
use drive_ai::racer::{CAR_HEIGHT as CAR_HEIGHT_SCALED, CAR_WIDTH as CAR_WIDTH_SCALED};
/// Number of enemies to spawn.
const ENEMIES_NB: u8 = 10;
/// Height of the grid.
const GRID_HEIGHT: u128 = 1000;
// Width of the grid.
const GRID_WIDTH: u128 = 400;
const HALF_GRID_WIDTH: u128 = 200;
const CAR_HEIGHT: u128 = 32;
const CAR_WIDTH: u128 = 16;
const CAR_VELOCITY: u128 = 50;
#[derive(Component, Serde, SerdeLen, Drop, Copy)]
struct Position {
// Current vehicle position
x: u128,
y: u128,
}
trait PositionTrait {
// Returns the vertices of the enemy at given position
fn vertices(self: @Position) -> Span<Vec2>; // Position has unscaled members
fn vertices_scaled(self: @Position) -> Span<Vec2>; // Position has scaled members
}
impl PostionImpl of PositionTrait {
fn vertices(self: @Position) -> Span<Vec2> {
let mut vertices = ArrayTrait::new();
vertices
.append(
Vec2 {
x: FixedTrait::new_unscaled(*self.x + CAR_WIDTH, false),
y: FixedTrait::new_unscaled(*self.y + CAR_HEIGHT, false)
}
);
let x1 = if *self.x < CAR_WIDTH {
FixedTrait::new_unscaled(0, false)
} else {
FixedTrait::new_unscaled(*self.x - CAR_WIDTH, false)
};
let y1 = if *self.y < CAR_HEIGHT {
FixedTrait::new_unscaled(0, false)
} else {
FixedTrait::new_unscaled(*self.y - CAR_HEIGHT, false)
};
vertices.append(Vec2 { x: x1, y: FixedTrait::new_unscaled(*self.y + CAR_HEIGHT, false) });
vertices.append(Vec2 { x: x1, y: y1 });
vertices.append(Vec2 { x: FixedTrait::new_unscaled(*self.x + CAR_WIDTH, false), y: y1 });
vertices.span()
}
fn vertices_scaled(self: @Position) -> Span<Vec2> {
let mut vertices = ArrayTrait::new();
vertices
.append(
Vec2 {
x: FixedTrait::new(*self.x + CAR_WIDTH_SCALED, false),
y: FixedTrait::new(*self.y + CAR_HEIGHT_SCALED, false)
}
);
let x1 = if *self.x < CAR_WIDTH_SCALED {
FixedTrait::new(0, false)
} else {
FixedTrait::new(*self.x - CAR_WIDTH_SCALED, false)
};
let y1 = if *self.y < CAR_HEIGHT_SCALED {
FixedTrait::new(0, false)
} else {
FixedTrait::new(*self.y - CAR_HEIGHT_SCALED, false)
};
vertices.append(Vec2 { x: x1, y: FixedTrait::new(*self.y + CAR_HEIGHT_SCALED, false) });
vertices.append(Vec2 { x: x1, y: y1 });
vertices.append(Vec2 { x: FixedTrait::new(*self.x + CAR_WIDTH_SCALED, false), y: y1 });
vertices.span()
}
}
#[system]
mod spawn_enemies {
use integer::{u256_safe_divmod, u256_as_non_zero};
use traits::{Into, TryInto};
use dojo::world::Context;
use drive_ai::Vehicle;
use super::{Position, ENEMIES_NB, GRID_HEIGHT, GRID_WIDTH, CAR_WIDTH};
/// Spawn [`ENEMIES_NB`] enemies. Each enemy has its own x range that corresponds to:
/// [`GRID_WIDTH`] * car_nb / [`ENEMIES_NB`] to [`GRID_WIDTH`] * (car_nb + 1) / [`ENEMIES_NB`]
/// So they don't spawn on top of each other.
/// The initial Y position is determined by model * car_nb / [GRID_HEIGHT] % GRID_HEIGHT
/// This division is a felt division so that cars don't spawn in diagonal and are well spread out
///
/// # Arguments
///
/// * `ctx` - Context of the game.
/// * `model` - The AI model id to namespace the games.
fn execute(ctx: Context, model: felt252) {
let mut i: usize = 0;
// Get the grid height as [`NonZero<felt252>`] for later div.
let grid_height: felt252 = GRID_HEIGHT.into();
// GRID_HEIGHT is a constant not set to 0 so it can't panic.
let grid_height: NonZero<felt252> = grid_height.try_into().unwrap();
// Get the grid height as [`NonZero<u256>`] for later div.
// GRID_HEIGHT is a constant not set to 0 so it can't panic.
let big_grid_height: NonZero<u256> = u256 {
low: GRID_HEIGHT.into(), high: 0_u128
}.try_into().unwrap();
// ENEMIES_NB is a constant not set to 0 so it can't panic.
let x_range: u128 = GRID_WIDTH.into() / ENEMIES_NB.into() - 2 * CAR_WIDTH.into();
loop {
if i == ENEMIES_NB.into() {
break ();
}
let numerator: felt252 = model.into() + i.into();
// This value gives us a """random""" value to better spread the enemies on the grid at init.
let base_value = felt252_div(numerator, grid_height);
// Resize the value so it fits in the x range given for enemies so they don't overlap.
let (_, x_rem) = u256_safe_divmod(base_value.into(), u256_as_non_zero(x_range.into()));
// Resize the value so it fits in the grid height.
let (_, y_rem) = u256_safe_divmod(base_value.into(), big_grid_height);
// Spawn the enemy.
set !(
ctx.world,
(model, i).into(),
(Position {
x: x_rem.low + CAR_WIDTH + (2 * CAR_WIDTH + x_range) * i.into(), y: y_rem.low
})
);
i += 1;
}
}
}
#[cfg(test)]
mod tests_spawn {
use array::{Array, ArrayTrait};
use traits::Into;
use dojo::test_utils::spawn_test_world;
use dojo::world::IWorldDispatcherTrait;
use super::{Position, ENEMIES_NB};
#[test]
#[available_gas(20000000000)]
fn test_spawn() {
// Get required component.
let mut components = ArrayTrait::new();
components.append(drive_ai::vehicle::vehicle::TEST_CLASS_HASH);
// Get required system.
let mut systems = ArrayTrait::new();
systems.append(super::spawn_enemies::TEST_CLASS_HASH);
// Get test world.
let world = spawn_test_world(components, systems);
let caller = starknet::contract_address_const::<0x0>();
// The execute method from the spawn system expects a Vehicle array
// formatted as a felt252 array to spawn the enemies
let mut calldata: Array<felt252> = ArrayTrait::new();
// Model.
calldata.append(1);
world.execute('spawn_enemies'.into(), calldata.span());
let mut i: usize = 0;
let players: usize = ENEMIES_NB.into();
let mut expected_coordinates: Array<felt252> = ArrayTrait::new();
// 10 enemies on 400 width grid so each enemy has a 40 x range - the width
// of the car it's a range of 8
// 16 <= x <= 24
expected_coordinates.append(18);
expected_coordinates.append(618);
// 54 <= x <= 62
expected_coordinates.append(60);
expected_coordinates.append(236);
// 96 <= x <= 104
expected_coordinates.append(102);
expected_coordinates.append(854);
// 136 <= x <= 144
expected_coordinates.append(136);
expected_coordinates.append(472);
// 176 <= x <= 184
expected_coordinates.append(178);
expected_coordinates.append(90);
// 216 <= x <= 224
expected_coordinates.append(220);
expected_coordinates.append(708);
// 256 <= x <= 264
expected_coordinates.append(262);
expected_coordinates.append(326);
// 296 <= x <= 204
expected_coordinates.append(296);
expected_coordinates.append(944);
// 336 <= x <= 344
expected_coordinates.append(338);
expected_coordinates.append(562);
// 376 <= x <= 388
expected_coordinates.append(380);
expected_coordinates.append(180);
loop {
if i == players {
break ();
}
// We set the model to 1 earlier.
let position = world
.entity('Position'.into(), (1, i).into(), 0, dojo::SerdeLen::<Position>::len());
assert(*position[0] == *(@expected_coordinates)[2 * i], 'Wrong position x');
assert(*position[1] == *(@expected_coordinates)[2 * i + 1], 'Wrong position y');
i += 1;
}
}
}
#[system]
mod move_enemies {
use integer::{u256_safe_divmod, u256_as_non_zero};
use traits::{TryInto, Into};
use dojo::world::Context;
use super::{Position, CAR_HEIGHT, CAR_VELOCITY, ENEMIES_NB, GRID_HEIGHT, GRID_WIDTH, CAR_WIDTH};
/// Executes a tick for the enemies.
/// During a tick the enemies will need to be moved/respawned if they go out of the grid.
///
/// # Arguments
///
/// * `ctx` - Context of the game.
/// * `model` - The AI model id to namespace the games.
fn execute(ctx: Context, model: felt252) {
// Iterate through the enemies and move them. If the are out of the grid respawn them at
// the top of the grid
let mut i: u8 = 0;
loop {
if i == ENEMIES_NB {
break ();
}
let key = (model, i).into();
let position = get !(ctx.world, key, Position);
let position = move(position, CAR_HEIGHT, CAR_VELOCITY, i.into());
set !(ctx.world, key, (Position { x: position.x, y: position.y }));
i += 1;
}
}
/// Enemy
/// +---+
/// | | ^
/// | x | | 2 * length
/// | | v
/// +---+
/// <-->
/// 2 * width
/// We respawn the enemy if the front of the car has disappeared from the grid <=> center.y + length <= 0.
/// As we need to make this smooth for the ui we'll respawn the car at the top of the
/// grid - distance traveled during the tick.
/// Ex: If the center of the enemy is at the position init = (16, 25) and its speed is 50 points/tick
/// We'll respawn the car at (16, TOP_GRID - (speed - init.y) + length).
/// We also change the x coordinate of the enemy otherwise the racer would just drive straight forward.
///
/// # Arguments
///
/// * `position`- The initial position of the enemy to move.
/// * `height` - The height of the enemy.
/// * `velocity` - The velocity of the enemy to move.
/// * `enemy_nb` - The enemy id that we want to move.
///
/// # Returns
///
/// * [`Position`] - The updated position of the enemy after being moved.
#[inline(always)]
fn move(position: Position, height: u128, velocity: u128, enemy_nb: u128) -> Position {
let y = position.y;
let x = position.x;
// Get the grid width as [`NonZero<felt252>`] for later div.
let grid_width: felt252 = GRID_WIDTH.into();
// GRID_WIDTH is a constant not set to 0 so it can't panic.
let grid_width: NonZero<felt252> = grid_width.try_into().unwrap();
// ENEMIES_NB is a constant not set to 0 so it can't panic.
let x_range: u128 = GRID_WIDTH.into() / ENEMIES_NB.into() - 2 * CAR_WIDTH.into();
let base_value = felt252_div(x.into(), grid_width);
let (_, x_rem) = u256_safe_divmod(base_value.into(), u256_as_non_zero(x_range.into()));
let new_y = if y <= velocity + height {
GRID_HEIGHT + y + height - velocity
} else {
y - velocity
};
Position {
x: x_rem.low + CAR_WIDTH + (2 * CAR_WIDTH + x_range) * enemy_nb.into(), y: new_y
}
}
}
#[cfg(test)]
mod tests_move {
use array::{Array, ArrayTrait};
use traits::Into;
use dojo::test_utils::spawn_test_world;
use dojo::world::IWorldDispatcherTrait;
use super::move_enemies::move;
use super::{ENEMIES_NB, Position};
use debug::PrintTrait;
#[test]
#[available_gas(2000000)]
fn test_move_respawns_on_top() {
let x = 16;
let y = 25;
let height = 10;
let velocity = 50;
let position = Position { x: x, y: y };
// We change the x coordinate otherwise the racer would have to drive straight forward to win.
let expected_x = 21;
// Top of the grid - (velocity - remaining bottom grid) + enemy height
// 1000 - (50 - 25) + 10 = 985
let expected_y = 985;
let got_position = move(position, height, velocity, 0);
assert(got_position.x == expected_x, 'Wrong position x');
assert(got_position.y == expected_y, 'Wrong position y');
}
#[test]
#[available_gas(2000000)]
fn test_move_without_respawn() {
let x = 16;
let y = 980;
let height = 10;
let velocity = 50;
let position = Position { x: x, y: y };
// We change the x coordinate otherwise the racer would have to drive straight forward to win.
let expected_x = 61;
// y - speed
// 980 - 50 = 930
let expected_y = 930;
let got_position = move(position, height, velocity, 1);
assert(got_position.x == expected_x, 'Wrong position x');
assert(got_position.y == expected_y, 'Wrong position y');
}
#[test]
#[available_gas(20000000000)]
fn test_move_through_execute() {
// Get required component.
let mut components = ArrayTrait::new();
components.append(drive_ai::vehicle::vehicle::TEST_CLASS_HASH);
// Get required system.
let mut systems = ArrayTrait::new();
systems.append(super::spawn_enemies::TEST_CLASS_HASH);
systems.append(super::move_enemies::TEST_CLASS_HASH);
// Get test world.
let world = spawn_test_world(components, systems);
let caller = starknet::contract_address_const::<0x0>();
// The execute method from the spawn system expects a Vehicle array
// formatted as a felt252 array to spawn the enemies
let mut calldata: Array<felt252> = ArrayTrait::new();
// Model.
calldata.append(1);
world.execute('spawn_enemies'.into(), calldata.span());
world.execute('move_enemies'.into(), calldata.span());
world.execute('move_enemies'.into(), calldata.span());
let mut i: usize = 0;
let players: usize = ENEMIES_NB.into();
let mut expected_coordinates: Array<felt252> = ArrayTrait::new();
// 10 enemies on 400 width grid so each enemy has a 40 x range - the width
// of the car it's a range of 8
// 16 <= x <= 24
expected_coordinates.append(23);
// spawn_y - 50 = 618 - 50
expected_coordinates.append(518);
// 54 <= x <= 62
expected_coordinates.append(58);
// spawn_y - 50 = 236 - 50
expected_coordinates.append(136);
// 96 <= x <= 104
expected_coordinates.append(103);
// spawn_y - 50 = 854 - 50
expected_coordinates.append(754);
// 136 <= x <= 144
expected_coordinates.append(138);
// spawn_y - 50 = 472 - 50
expected_coordinates.append(372);
// 176 <= x <= 184
expected_coordinates.append(183);
// spawn_y - 50 = 90 - 50
expected_coordinates.append(1022);
// 216 <= x <= 224
expected_coordinates.append(219);
// spawn_y - 50 = 708 - 50
expected_coordinates.append(608);
// 256 <= x <= 264
expected_coordinates.append(260);
// spawn_y - 50 = 326 - 50
expected_coordinates.append(226);
// 296 <= x <= 304
expected_coordinates.append(299);
// spawn_y - 50 = 944 - 50
expected_coordinates.append(844);
// 336 <= x <= 344
expected_coordinates.append(342);
// spawn_y - 50 = 562 - 50
expected_coordinates.append(462);
// 376 <= x <= 388
expected_coordinates.append(379);
// spawn_y - 50 = 180 - 50
expected_coordinates.append(80);
loop {
if i == players {
break ();
}
// We set the model to 1 earlier.
let position = world
.entity('Position'.into(), (1, i).into(), 0, dojo::SerdeLen::<Position>::len());
assert(*position[0] == *(@expected_coordinates)[2 * i], 'Wrong position x');
assert(*position[1] == *(@expected_coordinates)[2 * i + 1], 'Wrong position y');
i += 1;
}
}
}
#[cfg(test)]
mod tests {
use array::{ArrayTrait, SpanTrait};
use traits::Into;
use debug::PrintTrait;
use cubit::types::vec2::{Vec2, Vec2Trait};
use cubit::types::fixed::{Fixed, FixedTrait, FixedPrint};
use cubit::test::helpers::assert_precise;
use drive_ai::racer::{CAR_HEIGHT as CAR_HEIGHT_SCALED, CAR_WIDTH as CAR_WIDTH_SCALED};
use super::{Position, PositionTrait};
const ONE_HUNDRED: u128 = 1844674407370955161600;
#[test]
#[available_gas(2000000)]
fn test_vertices() {
let position = Position { x: 100, y: 100 };
let vertices = position.vertices();
assert_precise(
*vertices.at(0).x,
(ONE_HUNDRED + CAR_WIDTH_SCALED).into(),
'invalid vertex_0',
Option::None(())
);
assert_precise(
*vertices.at(0).y,
(ONE_HUNDRED + CAR_HEIGHT_SCALED).into(),
'invalid vertex_0',
Option::None(())
);
assert_precise(
*vertices.at(1).x,
(ONE_HUNDRED - CAR_WIDTH_SCALED).into(),
'invalid vertex_1',
Option::None(())
);
assert_precise(
*vertices.at(1).y,
(ONE_HUNDRED + CAR_HEIGHT_SCALED).into(),
'invalid vertex_1',
Option::None(())
);
assert_precise(
*vertices.at(2).x,
(ONE_HUNDRED - CAR_WIDTH_SCALED).into(),
'invalid vertex_x2',
Option::None(())
);
assert_precise(
*vertices.at(2).y,
(ONE_HUNDRED - CAR_HEIGHT_SCALED).into(),
'invalid vertex_y2',
Option::None(())
);
assert_precise(
*vertices.at(3).x,
(ONE_HUNDRED + CAR_WIDTH_SCALED).into(),
'invalid vertex_3',
Option::None(())
);
assert_precise(
*vertices.at(3).y,
(ONE_HUNDRED - CAR_HEIGHT_SCALED).into(),
'invalid vertex_3',
Option::None(())
);
}
#[test]
#[available_gas(2000000)]
fn test_vertices_scaled() {
let position = Position { x: ONE_HUNDRED, y: ONE_HUNDRED };
let vertices = position.vertices_scaled();
assert_precise(
*vertices.at(0).x,
(ONE_HUNDRED + CAR_WIDTH_SCALED).into(),
'invalid vertex_0',
Option::None(())
);
assert_precise(
*vertices.at(0).y,
(ONE_HUNDRED + CAR_HEIGHT_SCALED).into(),
'invalid vertex_0',
Option::None(())
);
assert_precise(
*vertices.at(1).x,
(ONE_HUNDRED - CAR_WIDTH_SCALED).into(),
'invalid vertex_1',
Option::None(())
);
assert_precise(
*vertices.at(1).y,
(ONE_HUNDRED + CAR_HEIGHT_SCALED).into(),
'invalid vertex_1',
Option::None(())
);
assert_precise(
*vertices.at(2).x,
(ONE_HUNDRED - CAR_WIDTH_SCALED).into(),
'invalid vertex_x2',
Option::None(())
);
assert_precise(
*vertices.at(2).y,
(ONE_HUNDRED - CAR_HEIGHT_SCALED).into(),
'invalid vertex_y2',
Option::None(())
);
assert_precise(
*vertices.at(3).x,
(ONE_HUNDRED + CAR_WIDTH_SCALED).into(),
'invalid vertex_3',
Option::None(())
);
assert_precise(
*vertices.at(3).y,
(ONE_HUNDRED - CAR_HEIGHT_SCALED).into(),
'invalid vertex_3',
Option::None(())
);
}
}