4ebe90c84a926c663f8c6534ef00c3646c1d622a
[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(command_scores: &'a mut Vec<CommandScore>, settings: &GameSettings, state: &BitwiseGameState, start_time: PreciseTime, max_time: Duration) -> Option<&'a CommandScore> {
91     loop {
92         simulate_all_options_once(command_scores, settings, 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, 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, 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(next_seed),
164         GameStatus::OpponentWon => command_score.add_defeat(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, _state: &BitwiseGameState, 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].iter() {
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 = [0; NUMBER_OF_POSSIBLE_MOVES];
189     let mut cumulative_distribution: u32 = 0;
190     let mut i = 0;
191
192     // Nothing
193     {
194         let weight = 0;
195         cumulative_distribution += weight;
196         cdf[i] = cumulative_distribution;
197         i += 1;
198     }
199     
200     // Iron Curtain
201     {
202         let weight = if player.can_build_iron_curtain() && player.energy >= IRON_CURTAIN_PRICE {
203             20
204         } else {
205             0
206         };
207         cumulative_distribution += weight;
208         cdf[i] = cumulative_distribution;
209         i += 1;
210     }
211
212     // Energy
213     for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
214         let point = Point::new_index(p);
215         let weight = if player.energy < ENERGY_PRICE || player.occupied & point.to_either_bitfield() != 0 {
216             0
217         } else {
218             //TODO: This needs to be more complex
219             1
220         };
221
222         cumulative_distribution += weight;
223         cdf[i] = cumulative_distribution;
224         i += 1;
225     }
226
227     // Defence
228     for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
229         let point = Point::new_index(p);
230         let weight = if player.energy < DEFENCE_PRICE || player.occupied & point.to_either_bitfield() != 0 {
231             0
232         } else {
233             //TODO: This needs to be more complex
234             1
235         };
236
237         cumulative_distribution += weight;
238         cdf[i] = cumulative_distribution;
239         i += 1;
240     }
241
242     // Attack
243     for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
244         let point = Point::new_index(p);
245         let weight = if  player.energy < MISSILE_PRICE || player.occupied & point.to_either_bitfield() != 0 {
246             0
247         } else {
248             //TODO: This needs to be more complex
249             1
250         };
251
252         cumulative_distribution += weight;
253         cdf[i] = cumulative_distribution;
254         i += 1;
255     }
256
257     // Tesla
258     let cant_tesla = player.has_max_teslas() || player.energy < TESLA_PRICE;
259     for p in 0..NUMBER_OF_MAP_POSITIONS as u8 {
260         let point = Point::new_index(p);
261         let weight = if cant_tesla || player.occupied & point.to_either_bitfield() != 0 {
262             0
263         } else {
264             //TODO: This needs to be more complex
265             1
266         };
267
268         cumulative_distribution += weight;
269         cdf[i] = cumulative_distribution;
270         i += 1;
271     }
272
273     assert_eq!(MOVES.len(), i);
274
275     if cumulative_distribution == 0 {
276         return Command::Nothing;
277     }
278
279     let choice = rng.gen_range(0, cumulative_distribution);
280
281     // find maximum index where choice <= cdf[index]
282     let index = cdf.iter().position(|&c| c > choice).expect("Random number has exceeded cumulative distribution");
283     
284     /*
285     let mut min_index = 0;
286     let mut max_index = cdf.len();
287
288     while max_index - min_index > 1 {
289         let mid = (min_index + max_index) / 2;
290         if cdf[mid] > choice {
291             max_index = mid+1;
292         } else {
293             min_index = mid;
294         }
295     }
296     let index = min_index;
297      */
298     
299     MOVES[index].clone()
300 }
301
302 #[cfg(not(feature = "heuristic-random"))]
303 fn random_move<R: Rng>(player: &Player, _state: &BitwiseGameState, rng: &mut R) -> Command {
304     let free_positions_count = player.unoccupied_cell_count();
305
306     let open_building_spot = free_positions_count > 0;
307
308     let all_buildings = sensible_buildings(player, open_building_spot);
309
310     let iron_curtain_count = if player.can_build_iron_curtain() && player.energy >= IRON_CURTAIN_PRICE { 1 } else { 0 };
311     let nothing_count = 1;
312
313     let building_choice_index = rng.gen_range(0, all_buildings.len() + nothing_count + iron_curtain_count);
314
315     if building_choice_index < all_buildings.len() {
316         let position_choice = rng.gen_range(0, free_positions_count);
317         Command::Build(
318             player.location_of_unoccupied_cell(position_choice),
319             all_buildings[building_choice_index]
320         )
321     }
322     else if building_choice_index == all_buildings.len() {
323         Command::Nothing        
324     } else {
325         Command::IronCurtain
326     }
327 }
328
329 #[derive(Debug)]
330 struct CommandScore {
331     command: Command,
332     starts_with_nothing: bool,
333     victories: u32,
334     defeats: u32,
335     draws: u32,
336     stalemates: u32,
337     attempts: u32,
338     next_seed: [u8; 16]
339 }
340
341 impl CommandScore {
342     fn new(command: Command, starts_with_nothing: bool) -> CommandScore {
343         CommandScore {
344             command, starts_with_nothing,
345             victories: 0,
346             defeats: 0,
347             draws: 0,
348             stalemates: 0,
349             attempts: 0,
350             next_seed: INIT_SEED
351         }
352     }
353
354     fn add_victory(&mut self, next_seed: [u8; 16]) {
355         self.victories += 1;
356         self.attempts += 1;
357         self.next_seed = next_seed;
358     }
359
360     fn add_defeat(&mut self, next_seed: [u8; 16]) {
361         self.defeats += 1;
362         self.attempts += 1;
363         self.next_seed = next_seed;
364     }
365
366     fn add_draw(&mut self, next_seed: [u8; 16]) {
367         self.draws += 1;
368         self.attempts += 1;
369         self.next_seed = next_seed;
370     }
371
372     fn add_stalemate(&mut self, next_seed: [u8; 16]) {
373         self.stalemates += 1;
374         self.attempts += 1;
375         self.next_seed = next_seed;
376     }
377
378     fn win_ratio(&self) -> i32 {
379         (self.victories as i32 - self.defeats as i32) * 10000 / (self.attempts as i32)
380     }
381
382     fn init_command_scores(state: &BitwiseGameState) -> Vec<CommandScore> {
383         let unoccupied_cells_count = state.player.unoccupied_cell_count();
384         let unoccupied_cells = (0..unoccupied_cells_count)
385             .map(|i| state.player.location_of_unoccupied_cell(i));
386         let energy_generated = state.player.energy_generated();
387
388         let mut all_buildings: ArrayVec<[BuildingType; NUMBER_OF_BUILDING_TYPES]> = ArrayVec::new();
389         if DEFENCE_PRICE <= state.player.energy {
390             all_buildings.push(BuildingType::Defence);
391         }
392         if MISSILE_PRICE <= state.player.energy {
393             all_buildings.push(BuildingType::Attack);
394         }
395         if ENERGY_PRICE <= state.player.energy {
396             all_buildings.push(BuildingType::Energy);
397         }
398         if !state.player.has_max_teslas() && (TESLA_PRICE.saturating_sub(state.player.energy) / energy_generated < 4) {
399             all_buildings.push(BuildingType::Tesla);
400         }
401         
402         let building_command_count = unoccupied_cells.len()*all_buildings.len();
403         
404         let mut commands = Vec::with_capacity(building_command_count + 1);
405         if state.player.can_build_iron_curtain() && IRON_CURTAIN_PRICE.saturating_sub(state.player.energy) / energy_generated < 4 {
406             commands.push(CommandScore::new(Command::IronCurtain, state.player.energy < IRON_CURTAIN_PRICE));
407         }
408
409         for position in unoccupied_cells {
410             for &building in &all_buildings {
411                 commands.push(CommandScore::new(Command::Build(position, building), building.cant_build_yet(state.player.energy)));
412             }
413         }
414
415         commands
416     }
417 }
418
419 impl fmt::Display for CommandScore {
420     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
421         write!(f, "{},{}", self.command, self.win_ratio())
422     }
423 }
424
425 #[cfg(not(feature = "energy-cutoff"))]
426 fn sensible_buildings(player: &Player, open_building_spot: bool) -> ArrayVec<[BuildingType; NUMBER_OF_BUILDING_TYPES]> {
427     let mut result = ArrayVec::new();
428     if !open_building_spot {
429         return result;
430     }
431
432     if DEFENCE_PRICE <= player.energy {
433         result.push(BuildingType::Defence);
434     }
435     if MISSILE_PRICE <= player.energy {
436         result.push(BuildingType::Attack);
437     }
438     if ENERGY_PRICE <= player.energy {
439         result.push(BuildingType::Energy);
440     }
441     if TESLA_PRICE <= player.energy && !player.has_max_teslas() {
442         result.push(BuildingType::Tesla);
443     }
444
445     result
446 }
447
448 #[cfg(feature = "energy-cutoff")]
449 fn sensible_buildings(player: &Player, open_building_spot: bool) -> ArrayVec<[BuildingType; NUMBER_OF_BUILDING_TYPES]> {
450     let mut result = ArrayVec::new();
451     if !open_building_spot {
452         return result;
453     }
454
455     let needs_energy = player.energy_generated() <= ENERGY_PRODUCTION_CUTOFF ||
456         player.energy <= ENERGY_STORAGE_CUTOFF;
457
458     if DEFENCE_PRICE <= player.energy {
459         result.push(BuildingType::Defence);
460     }
461     if MISSILE_PRICE <= player.energy {
462         result.push(BuildingType::Attack);
463     }
464     if ENERGY_PRICE <= player.energy && needs_energy {
465         result.push(BuildingType::Energy);
466     }
467     if TESLA_PRICE <= player.energy && !player.has_max_teslas() {
468         result.push(BuildingType::Tesla);
469     }
470     
471     result
472 }
473