628fefc92e90629c715f19f58af90e6d5245ecbb
[entelect-challenge-tower-defence.git] / src / engine / bitwise_engine.rs
1 use engine::command::{Command, BuildingType};
2 use engine::geometry::Point;
3 use engine::constants::*;
4 use engine::status::GameStatus;
5
6 use arrayvec::ArrayVec;
7
8 const LEFT_COL_MASK: u64 = 0x0101_0101_0101_0101;
9 const RIGHT_COL_MASK: u64 = 0x8080_8080_8080_8080;
10
11 #[derive(Debug, Clone, PartialEq, Eq)]
12 pub struct BitwiseGameState {
13     pub status: GameStatus,
14     pub player: Player,
15     pub opponent: Player,
16     pub round: u16
17 }
18
19 #[derive(Debug, Clone, PartialEq, Eq)]
20 pub struct Player {
21     pub energy: u16,
22     pub health: u8,
23     pub unconstructed: ArrayVec<[UnconstructedBuilding; MAX_CONCURRENT_CONSTRUCTION]>,
24     pub buildings: [u64; DEFENCE_HEALTH],
25     pub occupied: u64,
26     
27     pub energy_towers: u64,
28
29     pub missile_towers: [u64; MISSILE_COOLDOWN_STATES],
30     pub firing_tower: usize,
31     
32     pub missiles: [(u64, u64); MISSILE_MAX_SINGLE_CELL],
33     pub tesla_cooldowns: ArrayVec<[TeslaCooldown; TESLA_MAX]>,
34
35     pub iron_curtain_available: bool,
36     pub iron_curtain_remaining: u8,
37 }
38
39 #[derive(Debug, Clone, PartialEq, Eq)]
40 pub struct UnconstructedBuilding {
41     pub pos: Point,
42     pub construction_time_left: u8,
43     pub building_type: BuildingType
44 }
45
46 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
47 pub struct TeslaCooldown {
48     pub pos: Point,
49     pub cooldown: u8,
50     pub age: u16
51 }
52
53
54 impl BitwiseGameState {
55     pub fn simulate(&mut self, player_command: Command, opponent_command: Command) -> GameStatus {
56         BitwiseGameState::perform_command(&mut self.player, player_command);
57         BitwiseGameState::perform_command(&mut self.opponent, opponent_command);
58
59         BitwiseGameState::update_construction(&mut self.player);
60         BitwiseGameState::update_construction(&mut self.opponent);
61
62         BitwiseGameState::add_missiles(&mut self.player);
63         BitwiseGameState::add_missiles(&mut self.opponent);
64
65         BitwiseGameState::fire_teslas(&mut self.player, &mut self.opponent);
66
67         BitwiseGameState::move_and_collide_missiles(&mut self.player, &mut self.opponent.missiles);
68         BitwiseGameState::move_and_collide_missiles(&mut self.opponent, &mut self.player.missiles);
69
70         BitwiseGameState::add_energy(&mut self.player);
71         BitwiseGameState::add_energy(&mut self.opponent);
72
73         BitwiseGameState::update_iron_curtain(&mut self.player, self.round);
74         BitwiseGameState::update_iron_curtain(&mut self.opponent, self.round);
75
76         self.round += 1;
77
78         self.update_status();
79         self.status
80     }
81 }
82
83 fn find_bit_index_from_rank(occupied: u64, i: u64) -> u8 {
84     // Adapted from https://graphics.stanford.edu/~seander/bithacks.html#SelectPosFromMSBRank
85     let v = !occupied;
86     
87     let mut r = u64::from(v.count_ones()) - i;
88
89     let a: u64 =  v - ((v >> 1) & (!0u64/3));
90     let b: u64 = (a & (!0u64/5)) + ((a >> 2) & (!0u64/5));
91     let c: u64 = (b + (b >> 4)) & (!0u64/0x11);
92     let d: u64 = (c + (c >> 8)) & (!0u64/0x101);
93     let mut t: u64 = (d >> 32) + (d >> 48);
94
95     let mut s: u64 = 64;
96     s -= (t.wrapping_sub(r) & 256) >> 3; r -= t & (t.wrapping_sub(r) >> 8);
97     t  = (d >> (s - 16)) & 0xff;
98     s -= (t.wrapping_sub(r) & 256) >> 4; r -= t & (t.wrapping_sub(r) >> 8);
99     t  = (c >> (s - 8)) & 0xf;
100     s -= (t.wrapping_sub(r) & 256) >> 5; r -= t & (t.wrapping_sub(r) >> 8);
101     t  = (b >> (s - 4)) & 0x7;
102     s -= (t.wrapping_sub(r) & 256) >> 6; r -= t & (t.wrapping_sub(r) >> 8);
103     t  = (a >> (s - 2)) & 0x3;
104     s -= (t.wrapping_sub(r) & 256) >> 7; r -= t & (t.wrapping_sub(r) >> 8);
105     t  = (v >> (s - 1)) & 0x1;
106     s -= (t.wrapping_sub(r) & 256) >> 8;
107     s = 65 - s;
108
109     64 - s as u8
110 }
111
112 impl BitwiseGameState {
113     pub fn new(
114         player: Player, opponent: Player,
115         round: u16
116     ) -> BitwiseGameState {
117         BitwiseGameState {
118             status: GameStatus::Continue,
119             player, opponent,
120             round
121         }
122     }
123
124     /**
125      * This is to make things more comparable when writing tests, not
126      * for actual use in the engine.
127      */
128     #[cfg(debug_assertions)]
129     pub fn sort(&mut self) {
130         for i in 0..MISSILE_MAX_SINGLE_CELL {
131             for j in i+1..MISSILE_MAX_SINGLE_CELL {
132                 let move_down1 = !self.player.missiles[i].0 & self.player.missiles[j].0;
133                 self.player.missiles[i].0 |= move_down1;
134                 self.player.missiles[j].0 &= !move_down1;
135
136                 let move_down2 = !self.player.missiles[i].1 & self.player.missiles[j].1;
137                 self.player.missiles[i].1 |= move_down2;
138                 self.player.missiles[j].1 &= !move_down2;
139
140                 let move_down3 = !self.opponent.missiles[i].0 & self.opponent.missiles[j].0;
141                 self.opponent.missiles[i].0 |= move_down3;
142                 self.opponent.missiles[j].0 &= !move_down3;
143
144                 let move_down4 = !self.opponent.missiles[i].1 & self.opponent.missiles[j].1;
145                 self.opponent.missiles[i].1 |= move_down4;
146                 self.opponent.missiles[j].1 &= !move_down4;
147             }
148         }
149
150         self.player.unconstructed.sort_by_key(|b| b.pos);
151         self.opponent.unconstructed.sort_by_key(|b| b.pos);
152
153         self.player.tesla_cooldowns.sort_by_key(|b| b.pos);
154         self.opponent.tesla_cooldowns.sort_by_key(|b| b.pos);
155
156
157         while self.player.firing_tower > 0 {
158             self.player.firing_tower -= 1;
159             let zero = self.player.missile_towers[0];
160             for i in 1..self.player.missile_towers.len() {
161                 self.player.missile_towers[i-1] = self.player.missile_towers[i];
162             }
163             let end = self.player.missile_towers.len()-1;
164             self.player.missile_towers[end] = zero;
165         }
166         while self.opponent.firing_tower > 0 {
167             self.opponent.firing_tower -= 1;
168             let zero = self.opponent.missile_towers[0];
169             for i in 1..self.opponent.missile_towers.len() {
170                 self.opponent.missile_towers[i-1] = self.opponent.missile_towers[i];
171             }
172             let end = self.opponent.missile_towers.len()-1;
173             self.opponent.missile_towers[end] = zero;
174         }
175     }
176
177     #[cfg(debug_assertions)]
178     pub fn sorted(&self) -> BitwiseGameState {
179         let mut res = self.clone();
180         res.sort();
181         res
182     }
183
184     fn perform_command(player: &mut Player, command: Command) {
185         match command {
186             Command::Nothing => {},
187             Command::Build(p, b) => {
188                 let bitfield = p.to_either_bitfield();
189
190                 let price = match b {
191                     BuildingType::Attack => MISSILE_PRICE,
192                     BuildingType::Defence => DEFENCE_PRICE,
193                     BuildingType::Energy => ENERGY_PRICE,
194                     BuildingType::Tesla => TESLA_PRICE,
195                 };
196                 let construction_time = match b {
197                     BuildingType::Attack => MISSILE_CONSTRUCTION_TIME,
198                     BuildingType::Defence => DEFENCE_CONSTRUCTION_TIME,
199                     BuildingType::Energy => ENERGY_CONSTRUCTION_TIME,
200                     BuildingType::Tesla => TESLA_CONSTRUCTION_TIME,
201                 };
202
203                 // This is used internally. I should not be making
204                 // invalid moves!
205                 debug_assert!(player.buildings[0] & bitfield == 0);
206                 debug_assert!(p.x() < FULL_MAP_WIDTH && p.y() < MAP_HEIGHT);
207                 debug_assert!(player.energy >= price);
208                 debug_assert!(b != BuildingType::Tesla ||
209                               player.count_teslas() < TESLA_MAX);
210
211                 player.energy -= price;
212                 player.unconstructed.push(UnconstructedBuilding {
213                     pos: p,
214                     construction_time_left: construction_time,
215                     building_type: b
216                 });
217                 player.occupied |= bitfield;
218             },
219             Command::Deconstruct(p) => {
220                 let unconstructed_to_remove_index = player.unconstructed.iter().position(|ref b| b.pos == p);
221                 let deconstruct_mask = !(p.to_either_bitfield() & player.buildings[0]);
222                 
223                 debug_assert!(deconstruct_mask != 0 || unconstructed_to_remove_index.is_some());
224                 
225                 if let Some(i) = unconstructed_to_remove_index {
226                     player.unconstructed.swap_remove(i);
227                 }
228                 
229                 player.energy += DECONSTRUCT_ENERGY;
230                 
231                 for tier in 0..player.buildings.len() {
232                     player.buildings[tier] &= deconstruct_mask;
233                 }
234                 player.energy_towers &= deconstruct_mask;
235                 for tier in 0..player.missile_towers.len() {
236                     player.missile_towers[tier] &= deconstruct_mask;
237                 }
238                 player.tesla_cooldowns.retain(|t| t.pos != p);
239                 player.occupied &= deconstruct_mask;
240             },
241             Command::IronCurtain => {
242                 debug_assert!(player.iron_curtain_available);
243                 debug_assert!(player.energy >= IRON_CURTAIN_PRICE);
244
245                 player.energy -= IRON_CURTAIN_PRICE;
246                 player.iron_curtain_available = false;
247                 player.iron_curtain_remaining = IRON_CURTAIN_DURATION;
248             }
249         }
250     }
251
252     fn update_construction(player: &mut Player) {
253         let mut buildings_len = player.unconstructed.len();
254         for i in (0..buildings_len).rev() {
255             if player.unconstructed[i].construction_time_left == 0 {
256                 let building_type = player.unconstructed[i].building_type;
257                 let health = if building_type == BuildingType::Defence { DEFENCE_HEALTH } else { 1 };
258                 
259                 let pos = player.unconstructed[i].pos;
260                 let bitfield = pos.to_either_bitfield();
261                 
262                 for health_tier in 0..health {
263                     player.buildings[health_tier] |= bitfield;
264                 }
265                 if building_type == BuildingType::Energy {
266                     player.energy_towers |= bitfield;
267                 }
268                 if building_type == BuildingType::Attack {
269                     player.missile_towers[player.firing_tower] |= bitfield;
270                 }
271                 if building_type == BuildingType::Tesla {
272                     player.tesla_cooldowns.push(TeslaCooldown { 
273                         pos,
274                         cooldown: 0,
275                         age: 0
276                     });
277                 }
278                 
279                 buildings_len -= 1;
280                 player.unconstructed.swap(i, buildings_len);
281             } else {
282                 player.unconstructed[i].construction_time_left -= 1
283             }
284         }
285         player.unconstructed.truncate(buildings_len);
286     }
287
288     fn update_iron_curtain(player: &mut Player, round: u16) {
289         if round != 0 && round % IRON_CURTAIN_UNLOCK_INTERVAL == 0 {
290             player.iron_curtain_available = true;
291         }
292         player.iron_curtain_remaining = player.iron_curtain_remaining.saturating_sub(1);
293     }
294     
295     fn fire_teslas(player: &mut Player, opponent: &mut Player) {
296         BitwiseGameState::fire_single_players_teslas_without_cleanup(player, opponent);
297         BitwiseGameState::fire_single_players_teslas_without_cleanup(opponent, player);
298
299         BitwiseGameState::update_tesla_activity(player);
300         BitwiseGameState::update_tesla_activity(opponent);
301     }
302
303     fn fire_single_players_teslas_without_cleanup(player: &mut Player, opponent: &mut Player) {
304         player.tesla_cooldowns.sort_unstable_by(|a, b| b.age.cmp(&a.age));
305         for tesla in player.tesla_cooldowns.iter_mut() {
306             tesla.age += 1;
307             if tesla.cooldown > 0 {
308                 tesla.cooldown -= 1;
309             } else if player.energy >= TESLA_FIRING_ENERGY && opponent.iron_curtain_remaining > 0 {
310                 player.energy -= TESLA_FIRING_ENERGY;
311                 tesla.cooldown = TESLA_COOLDOWN;
312             } else if player.energy >= TESLA_FIRING_ENERGY {
313                 player.energy -= TESLA_FIRING_ENERGY;
314                 tesla.cooldown = TESLA_COOLDOWN;
315
316                 if tesla.pos.to_either_bitfield() & RIGHT_COL_MASK != 0 {
317                     opponent.health = opponent.health.saturating_sub(TESLA_DAMAGE);
318                 }
319
320                 let x = tesla.pos.x();
321                 let y = tesla.pos.y();
322                 let missed_cells = (u32::from(SINGLE_MAP_WIDTH - x)).saturating_sub(2);
323                 
324                 let top_row = y.saturating_sub(1);
325                 let top_row_mask = 255u64 << (top_row * SINGLE_MAP_WIDTH);
326                 let mut destroy_mask = top_row_mask.wrapping_shl(missed_cells) & top_row_mask;
327
328                 let mut hits = 0;
329                 for _ in 0..(if y == 0 || y == MAP_HEIGHT-1 { 2 } else { 3 }) {
330                     hits |= destroy_mask & opponent.buildings[0];
331                     destroy_mask &= !hits;
332                     destroy_mask <<= SINGLE_MAP_WIDTH;
333                 }
334                 BitwiseGameState::destroy_buildings(opponent, hits);
335             }
336         }
337     }
338
339     fn add_missiles(player: &mut Player) {
340         let mut missiles = player.missile_towers[player.firing_tower];
341         for mut tier in &mut player.missiles {
342             let setting = !tier.0 & missiles;
343             tier.0 |= setting;
344             missiles &= !setting;
345         }
346         player.firing_tower = (player.firing_tower + 1) % MISSILE_COOLDOWN_STATES;
347     }
348
349     fn move_and_collide_missiles(opponent: &mut Player, player_missiles: &mut [(u64, u64); MISSILE_MAX_SINGLE_CELL]) {
350         let mut destroyed = 0;
351         let mut damaging = 0;
352         for _ in 0..MISSILE_SPEED {
353             for missile in player_missiles.iter_mut() {
354                 let swapping_sides = if opponent.iron_curtain_remaining > 0 { 0 } else { missile.0 & RIGHT_COL_MASK };
355                 let about_to_hit_opponent = missile.1 & LEFT_COL_MASK;
356
357                 missile.0 = (missile.0 & !RIGHT_COL_MASK) << 1;
358                 missile.1 = ((missile.1 & !LEFT_COL_MASK) >> 1) | swapping_sides;
359
360                 damaging = (damaging << 1) | about_to_hit_opponent;
361
362                 let mut hits = 0;
363                 for health_tier in (0..DEFENCE_HEALTH).rev() {
364                     hits = opponent.buildings[health_tier] & missile.1;
365                     missile.1 &= !hits;
366                     opponent.buildings[health_tier] &= !hits;
367                 }
368                 destroyed |= hits;
369             }
370         }
371         let damage = damaging.count_ones() as u8 * MISSILE_DAMAGE;
372         opponent.health = opponent.health.saturating_sub(damage);
373
374         BitwiseGameState::destroy_buildings(opponent, destroyed);
375         BitwiseGameState::update_tesla_activity(opponent);
376     }
377
378     fn destroy_buildings(buildings: &mut Player, hit_mask: u64) {
379         let deconstruct_mask = !hit_mask;
380         
381         buildings.energy_towers &= deconstruct_mask;
382         for tier in &mut buildings.missile_towers {
383             *tier &= deconstruct_mask;
384         }
385         for tier in &mut buildings.buildings {
386             *tier &= deconstruct_mask;
387         }
388         buildings.occupied &= deconstruct_mask;
389     }
390
391     fn update_tesla_activity(buildings: &mut Player) {
392         let occupied = buildings.occupied;
393         buildings.tesla_cooldowns.retain(|t| (t.pos.to_either_bitfield() & occupied) != 0);
394     }
395     
396     
397     fn add_energy(player: &mut Player) {
398         player.energy += player.energy_generated();
399     }
400
401     fn update_status(&mut self) {
402         let player_dead = self.player.health == 0;
403         let opponent_dead = self.opponent.health == 0;
404         self.status = match (player_dead, opponent_dead) {
405             (true, true) => GameStatus::Draw,
406             (false, true) => GameStatus::PlayerWon,
407             (true, false) => GameStatus::OpponentWon,
408             (false, false) => GameStatus::Continue,
409         };
410     }
411
412 }
413
414 impl Player {
415     pub fn count_teslas(&self) -> usize {
416         self.tesla_cooldowns.len()
417             + self.unconstructed.iter().filter(|t| t.building_type == BuildingType::Tesla).count()
418     }
419
420     pub fn empty() -> Player {
421         Player {
422             health: 0,
423             energy: 0,
424             unconstructed: ArrayVec::new(),
425             buildings: [0; DEFENCE_HEALTH],
426             occupied: 0,
427             energy_towers: 0,
428             missile_towers: [0; MISSILE_COOLDOWN_STATES],
429             firing_tower: 0,
430             missiles: [(0,0); MISSILE_MAX_SINGLE_CELL],
431             tesla_cooldowns: ArrayVec::new(),
432             iron_curtain_available: false,
433             iron_curtain_remaining: 0,
434         }
435     }
436
437     pub fn energy_generated(&self) -> u16 {
438         ENERGY_GENERATED_BASE + self.energy_towers.count_ones() as u16 * ENERGY_GENERATED_TOWER
439     }
440
441     pub fn has_max_teslas(&self) -> bool {
442         self.count_teslas() >= TESLA_MAX
443     }
444
445     pub fn can_build_iron_curtain(&self) -> bool {
446         self.iron_curtain_available && self.iron_curtain_remaining == 0 && self.energy >= IRON_CURTAIN_PRICE
447     }
448
449     pub fn unoccupied_cell_count(&self) -> usize { self.occupied.count_zeros() as usize }
450     pub fn location_of_unoccupied_cell(&self, i: usize) -> Point  {
451         let bit = find_bit_index_from_rank(self.occupied, i as u64);
452         let point = Point { index: bit };
453         debug_assert!(point.to_either_bitfield() & self.occupied == 0);
454         point
455     }
456 }