8627a00860f77bf4d3fe1f48c84ebebca87ef1d3
[entelect-challenge-tower-defence.git] / src / strategy / monte_carlo.rs
1 use engine::command::*;
2 use engine::status::GameStatus;
3 use engine::bitwise_engine::{Player, BitwiseGameState};
4 use engine::constants::*;
5 use engine::geometry::*;
6
7 use std::fmt;
8
9 use rand::{Rng, XorShiftRng, SeedableRng};
10
11 use arrayvec::ArrayVec;
12
13 const MAX_MOVES: u16 = 400;
14 const INIT_SEED: [u8;16] = [0x7b, 0x6a, 0xe1, 0xf4, 0x41, 0x3c, 0xe9, 0x0f, 0x67, 0x81, 0x67, 0x99, 0x77, 0x0a, 0x6b, 0xda];
15
16 use time::{Duration, PreciseTime};
17
18 #[cfg(not(feature = "single-threaded"))]
19 use rayon::prelude::*;
20
21 #[cfg(feature = "energy-cutoff")] pub const ENERGY_PRODUCTION_CUTOFF: u16 = 50;
22 #[cfg(feature = "energy-cutoff")] pub const ENERGY_STORAGE_CUTOFF: u16 = 120;
23
24 pub fn choose_move(state: &BitwiseGameState, start_time: PreciseTime, max_time: Duration) -> Command {
25     let mut command_scores = CommandScore::init_command_scores(state);
26
27     let command = {
28         let best_command_score = simulate_options_to_timeout(&mut command_scores, state, start_time, max_time);
29         match best_command_score {
30             Some(best) if !best.starts_with_nothing => best.command,
31             _ => Command::Nothing
32         }
33     };
34
35     #[cfg(feature = "benchmarking")]
36     {
37         let total_iterations: u32 = command_scores.iter().map(|c| c.attempts).sum();
38         println!("Iterations: {}", total_iterations);
39     }
40     #[cfg(feature = "debug-decisions")]
41     {
42         debug_print_choices("ENERGY", &command_scores, |score| match score.command {
43             Command::Build(p, BuildingType::Energy) => Some((p, score.win_ratio())),
44             _ => None
45         });
46         debug_print_choices("ATTACK", &command_scores, |score| match score.command {
47             Command::Build(p, BuildingType::Attack) => Some((p, score.win_ratio())),
48             _ => None
49         });
50         debug_print_choices("DEFENCE", &command_scores, |score| match score.command {
51             Command::Build(p, BuildingType::Defence) => Some((p, score.win_ratio())),
52             _ => None
53         });
54         debug_print_choices("TESLA", &command_scores, |score| match score.command {
55             Command::Build(p, BuildingType::Tesla) => Some((p, score.win_ratio())),
56             _ => None
57         });
58         
59         println!("NOTHING");
60         println!("{}", command_scores.iter().find(|c| c.command == Command::Nothing).map(|s| s.win_ratio()).unwrap_or(0));
61         println!();
62
63         println!("IRON CURTAIN");
64         println!("{}", command_scores.iter().find(|c| c.command == Command::IronCurtain).map(|s| s.win_ratio()).unwrap_or(0));
65         println!();
66     }
67
68     command
69 }
70
71 #[cfg(feature = "debug-decisions")]
72 fn debug_print_choices<F: FnMut(&CommandScore) -> Option<(Point, i32)>>(label: &str, command_scores: &[CommandScore], extractor: F) {
73     println!("#+NAME: {}", label);
74     println!("#+PLOT: type:3d with:pm3d");
75     let relevant_moves: Vec<(Point, i32)>  = command_scores.iter()
76         .filter_map(extractor)
77         .collect();
78     for y in 0..MAP_HEIGHT {
79         for x in 0..SINGLE_MAP_WIDTH {
80             let point = Point::new(x, y);
81             let score = relevant_moves.iter().find(|(p, _)| *p == point);
82             print!(" | {}", score.map(|(_,s)| s).cloned().unwrap_or(0));
83         }
84         println!(" |");
85     }
86     println!();
87 }
88
89 #[cfg(not(feature = "discard-poor-performers"))]
90 fn simulate_options_to_timeout<'a>(command_scores: &'a mut Vec<CommandScore>, state: &BitwiseGameState, start_time: PreciseTime, max_time: Duration) -> Option<&'a CommandScore> {
91     loop {
92         simulate_all_options_once(command_scores, state);
93         if start_time.to(PreciseTime::now()) > max_time {
94             break;
95         }
96     }
97     command_scores.iter().max_by_key(|&c| c.win_ratio())
98 }
99
100 #[cfg(feature = "discard-poor-performers")]
101 fn simulate_options_to_timeout<'a>(command_scores: &'a mut Vec<CommandScore>, state: &BitwiseGameState, start_time: PreciseTime, max_time: Duration) -> Option<&'a CommandScore> {
102     use std::cmp;
103     let min_options = cmp::min(command_scores.len(), 5);
104     
105     let maxes = [max_time / 4, max_time / 2, max_time * 3 / 4, max_time];
106     for (i, &max) in maxes.iter().enumerate() {
107         let new_length = cmp::max(min_options, command_scores.len() / (2usize.pow(i as u32)));
108         let active_scores = &mut command_scores[0..new_length];
109         loop {
110             simulate_all_options_once(active_scores, state);
111             if start_time.to(PreciseTime::now()) > max {
112                 break;
113             }
114         }
115         active_scores.sort_unstable_by_key(|c| -c.win_ratio());
116     }
117     command_scores.first()
118 }
119
120 #[cfg(feature = "single-threaded")]
121 fn simulate_all_options_once(command_scores: &mut[CommandScore], state: &BitwiseGameState) {
122     command_scores.iter_mut()
123         .for_each(|score| {
124             let mut rng = XorShiftRng::from_seed(score.next_seed);
125             simulate_to_endstate(score, state, &mut rng);
126         });
127 }
128
129 #[cfg(not(feature = "single-threaded"))]
130 fn simulate_all_options_once(command_scores: &mut[CommandScore], state: &BitwiseGameState) {
131     command_scores.par_iter_mut()
132         .for_each(|score| {
133             let mut rng = XorShiftRng::from_seed(score.next_seed);
134             simulate_to_endstate(score, state, &mut rng);
135         });
136 }
137
138 fn simulate_to_endstate<R: Rng>(command_score: &mut CommandScore, state: &BitwiseGameState, rng: &mut R) {
139     let mut state_mut = state.clone();
140     
141     let mut status = GameStatus::Continue; //state_mut.simulate(command_score.command, opponent_first);
142     let mut first_move_made = false;
143     
144     for _ in 0..MAX_MOVES {
145         if status != GameStatus::Continue {
146             break;
147         }
148
149         let player_command = if first_move_made {
150             random_move(&state_mut.player, &state_mut.opponent, rng)
151         } else {
152             let do_nothing = command_score.command.cant_build_yet(state_mut.player.energy);
153             first_move_made = !do_nothing;
154             if do_nothing { Command::Nothing } else { command_score.command }
155         };
156         let opponent_command = random_move(&state_mut.opponent, &state_mut.player, rng);
157         status = state_mut.simulate(player_command, opponent_command);
158     }
159
160     let mut next_seed: [u8;16] = [0; 16];
161     rng.fill_bytes(&mut next_seed);
162     match status {
163         GameStatus::PlayerWon => command_score.add_victory(state_mut.player.count_towers() as i32 - state_mut.opponent.count_towers() as i32, next_seed),
164         GameStatus::OpponentWon => command_score.add_defeat(state_mut.opponent.count_towers() as i32 - state_mut.player.count_towers() as i32, next_seed),
165         GameStatus::Continue => command_score.add_stalemate(next_seed),
166         GameStatus::Draw => command_score.add_draw(next_seed)
167     }
168 }
169
170 #[cfg(feature = "heuristic-random")]
171 fn random_move<R: Rng>(player: &Player, opponent: &Player, rng: &mut R) -> Command {
172     lazy_static! {
173         static ref MOVES: [Command; NUMBER_OF_POSSIBLE_MOVES] = {
174             let mut m = [Command::Nothing; NUMBER_OF_POSSIBLE_MOVES];
175             m[1] = Command::IronCurtain;
176             let mut i = 2;
177             for b in &[BuildingType::Energy, BuildingType::Defence, BuildingType::Attack, BuildingType::Tesla] {
178                 for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
179                 let point = Point::new_index(p);
180                     m[i] = Command::Build(point, *b);
181                     i += 1;
182                 }
183             }
184             m
185         };
186     }
187
188     let mut cdf_other = [0; 2];
189     let mut cdf_energy = [0; NUMBER_OF_MAP_POSITIONS];
190     let mut cdf_defence = [0; NUMBER_OF_MAP_POSITIONS];
191     let mut cdf_attack = [0; NUMBER_OF_MAP_POSITIONS];
192     let mut cdf_tesla = [0; NUMBER_OF_MAP_POSITIONS];
193
194     let mut opponent_energy_per_row = [0; MAP_HEIGHT as usize];
195     let mut opponent_attack_per_row = [0; MAP_HEIGHT as usize];
196     let mut opponent_towers_per_row = [0; MAP_HEIGHT as usize];
197     let mut player_attack_per_row = [0; MAP_HEIGHT as usize];
198     for y in 0..MAP_HEIGHT {
199         opponent_energy_per_row[y as usize] = opponent.count_energy_towers_in_row(y);
200         opponent_attack_per_row[y as usize] = opponent.count_attack_towers_in_row(y);
201         opponent_towers_per_row[y as usize] = opponent.count_towers_in_row(y);
202         player_attack_per_row[y as usize] = player.count_attack_towers_in_row(y);
203     }
204     
205
206     let mut other_end: u16 = 0;
207     // Nothing
208     {
209         let weight = 1;
210         other_end += weight;
211         cdf_other[0] = other_end;
212     }
213     
214     // Iron Curtain
215     {
216         let weight = if player.can_build_iron_curtain() && player.energy >= IRON_CURTAIN_PRICE {
217             30
218         } else {
219             0
220         };
221         other_end += weight;
222         cdf_other[1] = other_end;
223     }
224
225     // Energy
226     let mut energy_end: u16 = other_end;
227     let needs_energy = player.energy_generated() <= ENERGY_PRODUCTION_CUTOFF ||
228         player.energy <= ENERGY_STORAGE_CUTOFF;
229     if needs_energy && player.energy >= ENERGY_PRICE {
230         for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
231             let point = Point::new_index(p);
232             let weight = if player.occupied & point.to_either_bitfield() != 0 {
233                 0
234             } else {
235                 2
236             };
237
238             energy_end += weight;
239             cdf_energy[p as usize] = energy_end;
240         }
241     }
242
243     // Defence
244     let mut defence_end: u16 = energy_end;
245     if player.energy >= DEFENCE_PRICE {
246         for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
247             let point = Point::new_index(p);
248             let weight = if player.occupied & point.to_either_bitfield() != 0 {
249                 0
250             } else {
251                 //TODO: Favour the front and rows with something to defend
252                 opponent_attack_per_row[usize::from(point.y())]
253             };
254
255             defence_end += weight;
256             cdf_defence[p as usize] = defence_end;
257         }
258     }
259
260     // Attack
261     let mut attack_end: u16 = defence_end;
262     if player.energy >= MISSILE_PRICE {
263         for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
264             let point = Point::new_index(p);
265             let weight = if player.occupied & point.to_either_bitfield() != 0 {
266                 0
267             } else {
268                 // TODO: take into account opponent attacks and defence in row?
269                 let y = usize::from(point.y());
270                 8 + opponent_energy_per_row[y] + opponent_towers_per_row[y] - player_attack_per_row[y]
271             };
272
273             attack_end += weight;
274             cdf_attack[p as usize] = attack_end;
275         }
276     }
277
278     // Tesla
279     let mut tesla_end: u16 = attack_end;
280     let cant_tesla = player.has_max_teslas() || player.energy < TESLA_PRICE;
281     if !cant_tesla {
282         for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
283             let point = Point::new_index(p);
284             let weight = if (player.occupied & point.to_either_bitfield() != 0) || point.y() < 7 {
285                 0
286             } else {
287                 2
288             };
289
290             tesla_end += weight;
291             cdf_tesla[p as usize] = tesla_end;
292         }
293     }
294
295     let cumulative_distribution = tesla_end;
296
297     if cumulative_distribution == 0 {
298         return Command::Nothing;
299     }
300
301     let choice = rng.gen_range(0, cumulative_distribution);
302
303     let index = match choice {
304         c if c < other_end => cdf_other.iter().position(|&c| c > choice).expect("Random number has exceeded cumulative distribution"),
305         c if c < energy_end => 2 + cdf_energy.iter().position(|&c| c > choice).expect("Random number has exceeded cumulative distribution"),
306         c if c < defence_end => 2 + NUMBER_OF_MAP_POSITIONS + cdf_defence.iter().position(|&c| c > choice).expect("Random number has exceeded cumulative distribution"),
307         c if c < attack_end => 2 + 2 * NUMBER_OF_MAP_POSITIONS + cdf_attack.iter().position(|&c| c > choice).expect("Random number has exceeded cumulative distribution"),
308         _ => 2 + 3 * NUMBER_OF_MAP_POSITIONS + cdf_tesla.iter().position(|&c| c > choice).expect("Random number has exceeded cumulative distribution"),
309     };
310
311     MOVES[index]
312 }
313
314 #[cfg(not(feature = "heuristic-random"))]
315 fn random_move<R: Rng>(player: &Player, _opponent: &Player, rng: &mut R) -> Command {
316     let free_positions_count = player.unoccupied_cell_count();
317
318     let open_building_spot = free_positions_count > 0;
319
320     let all_buildings = sensible_buildings(player, open_building_spot);
321
322     let iron_curtain_count = if player.can_build_iron_curtain() && player.energy >= IRON_CURTAIN_PRICE { 1 } else { 0 };
323     let nothing_count = 1;
324
325     let building_choice_index = rng.gen_range(0, all_buildings.len() + nothing_count + iron_curtain_count);
326
327     if building_choice_index < all_buildings.len() {
328         let position_choice = rng.gen_range(0, free_positions_count);
329         Command::Build(
330             player.location_of_unoccupied_cell(position_choice),
331             all_buildings[building_choice_index]
332         )
333     }
334     else if building_choice_index == all_buildings.len() {
335         Command::Nothing        
336     } else {
337         Command::IronCurtain
338     }
339 }
340
341 #[derive(Debug)]
342 struct CommandScore {
343     command: Command,
344     starts_with_nothing: bool,
345     victory_score: i32,
346     victories: u32,
347     defeat_score: i32,
348     defeats: u32,
349     draws: u32,
350     stalemates: u32,
351     attempts: u32,
352     next_seed: [u8; 16]
353 }
354
355 impl CommandScore {
356     fn new(command: Command, starts_with_nothing: bool) -> CommandScore {
357         CommandScore {
358             command, starts_with_nothing,
359             victory_score: 0,
360             victories: 0,
361             defeat_score: 0,
362             defeats: 0,
363             draws: 0,
364             stalemates: 0,
365             attempts: 0,
366             next_seed: INIT_SEED
367         }
368     }
369
370     fn add_victory(&mut self, weight: i32, next_seed: [u8; 16]) {
371         self.victory_score += weight;
372         self.victories += 1;
373         self.attempts += 1;
374         self.next_seed = next_seed;
375     }
376
377     fn add_defeat(&mut self, weight: i32, next_seed: [u8; 16]) {
378         self.defeat_score += weight;
379         self.defeats += 1;
380         self.attempts += 1;
381         self.next_seed = next_seed;
382     }
383
384     fn add_draw(&mut self, next_seed: [u8; 16]) {
385         self.draws += 1;
386         self.attempts += 1;
387         self.next_seed = next_seed;
388     }
389
390     fn add_stalemate(&mut self, next_seed: [u8; 16]) {
391         self.stalemates += 1;
392         self.attempts += 1;
393         self.next_seed = next_seed;
394     }
395
396     fn win_ratio(&self) -> i32 {
397         (self.victory_score - self.defeat_score) * 10000 / (self.attempts as i32)
398     }
399
400     fn init_command_scores(state: &BitwiseGameState) -> Vec<CommandScore> {
401         let unoccupied_cells_count = state.player.unoccupied_cell_count();
402         let unoccupied_cells = (0..unoccupied_cells_count)
403             .map(|i| state.player.location_of_unoccupied_cell(i));
404         let energy_generated = state.player.energy_generated();
405
406         let mut all_buildings: ArrayVec<[BuildingType; NUMBER_OF_BUILDING_TYPES]> = ArrayVec::new();
407         if DEFENCE_PRICE <= state.player.energy {
408             all_buildings.push(BuildingType::Defence);
409         }
410         if MISSILE_PRICE <= state.player.energy {
411             all_buildings.push(BuildingType::Attack);
412         }
413         if ENERGY_PRICE <= state.player.energy {
414             all_buildings.push(BuildingType::Energy);
415         }
416         if !state.player.has_max_teslas() && (TESLA_PRICE.saturating_sub(state.player.energy) / energy_generated < 4) {
417             all_buildings.push(BuildingType::Tesla);
418         }
419         
420         let building_command_count = unoccupied_cells.len()*all_buildings.len();
421
422         let mut commands = Vec::with_capacity(building_command_count + 1);
423         let time_to_curtain_energy = (IRON_CURTAIN_PRICE.saturating_sub(state.player.energy) / energy_generated) as u8;
424         
425         if time_to_curtain_energy < 4 && state.player.can_build_iron_curtain_in(state.round, time_to_curtain_energy) {
426             commands.push(CommandScore::new(Command::IronCurtain, state.player.energy < IRON_CURTAIN_PRICE));
427         }
428
429         for position in unoccupied_cells {
430             for &building in &all_buildings {
431                 commands.push(CommandScore::new(Command::Build(position, building), building.cant_build_yet(state.player.energy)));
432             }
433         }
434
435         commands
436     }
437 }
438
439 impl fmt::Display for CommandScore {
440     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441         write!(f, "{},{}", self.command, self.win_ratio())
442     }
443 }
444
445 #[cfg(not(feature = "energy-cutoff"))]
446 fn sensible_buildings(player: &Player, open_building_spot: bool) -> ArrayVec<[BuildingType; NUMBER_OF_BUILDING_TYPES]> {
447     let mut result = ArrayVec::new();
448     if !open_building_spot {
449         return result;
450     }
451
452     if DEFENCE_PRICE <= player.energy {
453         result.push(BuildingType::Defence);
454     }
455     if MISSILE_PRICE <= player.energy {
456         result.push(BuildingType::Attack);
457     }
458     if ENERGY_PRICE <= player.energy {
459         result.push(BuildingType::Energy);
460     }
461     if TESLA_PRICE <= player.energy && !player.has_max_teslas() {
462         result.push(BuildingType::Tesla);
463     }
464
465     result
466 }
467
468 #[cfg(feature = "energy-cutoff")]
469 fn sensible_buildings(player: &Player, open_building_spot: bool) -> ArrayVec<[BuildingType; NUMBER_OF_BUILDING_TYPES]> {
470     let mut result = ArrayVec::new();
471     if !open_building_spot {
472         return result;
473     }
474
475     let needs_energy = player.energy_generated() <= ENERGY_PRODUCTION_CUTOFF ||
476         player.energy <= ENERGY_STORAGE_CUTOFF;
477
478     if DEFENCE_PRICE <= player.energy {
479         result.push(BuildingType::Defence);
480     }
481     if MISSILE_PRICE <= player.energy {
482         result.push(BuildingType::Attack);
483     }
484     if ENERGY_PRICE <= player.energy && needs_energy {
485         result.push(BuildingType::Energy);
486     }
487     if TESLA_PRICE <= player.energy && !player.has_max_teslas() {
488         result.push(BuildingType::Tesla);
489     }
490     
491     result
492 }
493