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