summaryrefslogtreecommitdiff
path: root/src/game.rs
blob: a08fff28f5063000db9d01811ec77d97f3b66205 (plain)
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
use crate::geometry::*;
use crate::command::{Command, Action};
use crate::json;

mod player;
use player::*;

mod powerup;
use powerup::*;

mod map;
use map::*;

use arrayvec::ArrayVec;
use fnv::FnvHashSet;

// TODO: How much sense does it actually make to split the worms between the players?
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct GameBoard {
    pub round: u16,
    pub max_rounds: u16,
    pub players: [Player; 2],
    pub powerups: ArrayVec<[Powerup; 2]>,
    pub map: Map,
    pub occupied_cells: FnvHashSet<Point2d<i8>>,
    pub outcome: SimulationOutcome
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SimulationOutcome {
    PlayerWon(usize),
    Draw,
    Continue,
}

impl GameBoard {
    pub fn new(json: json::State) -> GameBoard {
        let commando_damage = json.my_player.worms[0].weapon.damage;
        let commando_range = json.my_player.worms[0].weapon.range;

        let player = Player {
            active_worm: json.active_worm_index().unwrap(),
            moves_score: json.my_player.score - json.my_player.health_score(),
            select_moves: json.my_player.remaining_worm_selections,
            worms: json.my_player.worms.iter().map(|w| Worm {
                id: w.id,
                health: w.health,
                position: Point2d::new(w.position.x, w.position.y),
                weapon_damage: commando_damage,
                weapon_range: commando_range,
                bombs: w.banana_bombs.as_ref().map(|b| b.count).unwrap_or(0)
            }).collect(),
        };

        let opponent = Player {
            active_worm: 0,
            moves_score: json.opponents[0].score - json.opponents[0].health_score(),
            select_moves: json.opponents[0].remaining_worm_selections,
            worms: json.opponents.iter().flat_map(|o| &o.worms).map(|w| Worm {
                id: w.id,
                health: w.health,
                position: Point2d::new(w.position.x, w.position.y),
                weapon_damage: commando_damage,
                weapon_range: commando_range,
                bombs: if w.health == 100 { 3 } else { 0 } // TODO: parse and check worm type rather, move these out to constants
            }).collect()
        };

        let mut map = Map::default();
        for cell in json.map.iter().flatten() {
            if cell.cell_type == json::CellType::Dirt {
                map.set(Point2d::new(cell.x, cell.y))
            }
        }

        let players = [player, opponent];
        let occupied_cells = players.iter()
                .flat_map(|p| p.worms.iter())
                .map(|w| w.position)
                .collect();
            
        GameBoard {
            round: json.current_round,
            max_rounds: json.max_rounds,
            players,
            powerups: json.map.iter().flatten().filter_map(|c| {
                c.powerup.as_ref().map(|p| Powerup {
                    position: Point2d::new(c.x, c.y),
                    value: p.value
                })
            }).collect(),
            map,
            occupied_cells,
            outcome: SimulationOutcome::Continue
        }
    }

    pub fn update(&mut self, json: json::State) {
        for w in &json.my_player.worms {
            if let Some(worm) = self.players[0].find_worm_mut(w.id) {
                worm.health = w.health;
                worm.position = Point2d::new(w.position.x, w.position.y);
            }
        }
        for w in json.opponents.iter().flat_map(|o| &o.worms) {
            if let Some(worm) = self.players[1].find_worm_mut(w.id) {
                worm.health = w.health;
                worm.position = Point2d::new(w.position.x, w.position.y);
            }
        }

        self.players[0].moves_score = json.my_player.score - json.my_player.health_score();
        self.players[1].moves_score = json.opponents[0].score - json.opponents[0].health_score();

        self.powerups = json.map.iter().flatten().filter_map(|c| {
            c.powerup.as_ref().map(|p| Powerup {
                position: Point2d::new(c.x, c.y),
                value: p.value
            })
        }).collect();

        for cell in json.map.iter().flatten() {
            if cell.cell_type == json::CellType::Air {
                self.map.clear(Point2d::new(cell.x, cell.y))
            }
        }

        for player in &mut self.players {
            player.clear_dead_worms();
            player.next_active_worm();
        }
        debug_assert_eq!(json.active_worm_index().unwrap(), self.players[0].active_worm);

        self.round += 1;
        debug_assert_eq!(json.current_round, self.round);

        self.occupied_cells = self.players.iter()
            .flat_map(|p| p.worms.iter())
            .map(|w| w.position)
            .collect();
    }

    pub fn simulate(&mut self, moves: [Command; 2]) {
        let actions = [moves[0].action, moves[1].action];

        self.simulate_select(moves);
        self.simulate_moves(actions);
        self.simulate_digs(actions);
        self.simulate_bombs(actions);
        self.simulate_shoots(actions);

        for player in &mut self.players {
            player.clear_dead_worms();
            player.next_active_worm();
        }

        self.round += 1;

        self.outcome = match (self.players[0].worms.len(), self.players[1].worms.len(), self.round > self.max_rounds) {
            (0, 0, _) => SimulationOutcome::Draw,
            (_, 0, _) => SimulationOutcome::PlayerWon(0),
            (0, _, _) => SimulationOutcome::PlayerWon(1),
            (_, _, true) => SimulationOutcome::Draw,
            _ => SimulationOutcome::Continue
        };
    }

    fn simulate_select(&mut self, moves: [Command; 2]) {
        moves.iter().zip(self.players.iter_mut())
            .for_each(|(m, player)| {
                if let Some(worm) = m.worm {
                    debug_assert!(player.select_moves > 0, "Could not make select move, out of select tokens");
                    player.select_moves = player.select_moves.saturating_sub(1);
                    player.active_worm = player.find_worm_position(worm).unwrap_or(0);
                }
            });
    }

    fn simulate_moves(&mut self, actions: [Action; 2]) {
        match actions {
            [Action::Move(p1), Action::Move(p2)] if p1.x == p2.x && p1.y == p2.y => {
                // TODO: Get this from some sort of config rather
                let damage = 20;

                debug_assert_eq!(Some(false), self.map.at(Point2d::new(p1.x, p1.y)), "Movement target wasn't empty, ({}, {})", p1.x, p1.y);
                // Worms have a 50% chance of swapping places
                // here. I'm treating that as an edge case that I
                // don't need to handle for now.
                for player in &mut self.players {
                    if let Some(worm) = player.active_worm_mut() {
                        worm.health = worm.health.saturating_sub(damage);
                    }
                    player.moves_score += 5;
                }
            },
            _ => {
                for player_index in 0..actions.len() {
                    if let Action::Move(p) = actions[player_index] {
                        debug_assert_eq!(Some(false), self.map.at(p), "Movement target wasn't empty, ({}, {})", p.x, p.y);

                        self.players[player_index].moves_score += 5;

                        if let Some(worm) = self.players[player_index].active_worm_mut() {
                            debug_assert!(
                                (worm.position.x - p.x).abs() <= 1 &&
                                    (worm.position.y - p.y).abs() <= 1,
                                "Tried to move too far away, ({}, {})", p.x, p.y
                            );

                            self.occupied_cells.remove(&worm.position);
                            self.occupied_cells.insert(p);

                            worm.position = p;
                            
                            self.powerups.retain(|power| {
                                if power.position == worm.position {
                                    worm.health += power.value;
                                    false
                                } else {
                                    true
                                }
                            });
                        }
                    }
                }
            }
        }
    }
    
    fn simulate_digs(&mut self, actions: [Action; 2]) {
        for player_index in 0..actions.len() {
            if let Action::Dig(p) = actions[player_index] {
                debug_assert!(
                    Some(true) == self.map.at(p) ||
                        (player_index == 1 && actions[0] == Action::Dig(p)),
                    "Tried to dig through air, ({}, {})", p.x, p.y
                );
                debug_assert!{
                    (self.players[player_index].active_worm().unwrap().position.x - p.x).abs() <= 1 &&
                        (self.players[player_index].active_worm().unwrap().position.y - p.y).abs() <= 1,
                    "Tried to dig too far away, ({}, {})", p.x, p.y
                };

                self.players[player_index].moves_score += 7;

                self.map.clear(p);
            }
        }
    }

    fn simulate_bombs(&mut self, actions: [Action; 2]) {
        // NB: Damage radius has the cell distance rounded UP, throwing range has the cell distance rounded DOWN
        
        for player_index in 0..actions.len() {
            if let Action::Bomb(p) = actions[player_index] {
                if let Some(worm) = self.players[player_index].active_worm_mut() {
                    debug_assert!(worm.bombs > 0, "Worm is throwing a bomb it doesn't have");
                    debug_assert!((worm.position - p).magnitude_squared() < 6*6); // max range is 5, but it's 5 after rounding down
                    
                    worm.bombs = worm.bombs.saturating_sub(1);

                    let damage_radius = 2;
                    // damage as per https://forum.entelect.co.za/uploads/default/original/2X/8/89e6e6cf35791a0448b5a6bbeb63c558ce41804a.jpeg

                    // TODO: Clear up dirt and give points
                    // TODO: Hurt all worm and give / remove points
                }
            }
        }
        
    }
    
    fn simulate_shoots(&mut self, actions: [Action; 2]) {
        'players_loop: for player_index in 0..actions.len() {
            if let Action::Shoot(dir) = actions[player_index] {
                if let Some(worm) = self.players[player_index].active_worm() { 
                    let (center, weapon_range, weapon_damage) = {
                        (worm.position, worm.weapon_range, worm.weapon_damage)
                    };
                    let diff = dir.as_vec();

                    let range = if dir.is_diagonal() {
                        ((f32::from(weapon_range) + 1.) / 2f32.sqrt()).floor() as i8
                    } else {
                        weapon_range as i8
                    };

                    for distance in 1..=range {
                        let target = center + diff * distance;
                        match self.map.at(target) {
                            Some(false) => {
                                let target_own_worm: Option<&mut Worm> = self.players[player_index]
                                    .worms.iter_mut()
                                    .find(|w| w.position == target);
                                
                                if let Some(target_worm) = target_own_worm {
                                    target_worm.health -= weapon_damage;
                                    if target_worm.health <= 0 {
                                        self.players[player_index].moves_score -= 40;
                                        self.occupied_cells.remove(&target_worm.position);
                                    } else {
                                        // TODO: Review these points
                                        self.players[player_index].moves_score -= 20;
                                    }
                                    continue 'players_loop;
                                }

                                let target_opponent_worm: Option<&mut Worm> = self.players[GameBoard::opponent(player_index)]
                                    .worms.iter_mut()
                                    .find(|w| w.position == target);
                                if let Some(target_worm) = target_opponent_worm {
                                    target_worm.health -= weapon_damage;
                                    if target_worm.health <= 0 {
                                        self.players[player_index].moves_score += 40;
                                        self.occupied_cells.remove(&target_worm.position);
                                    } else {
                                        self.players[player_index].moves_score += 20;
                                    }
                                    
                                    continue 'players_loop;
                                }
                            },
                            _ => break
                        }
                    }

                    // You get here if the shot missed. Hits are an early return.
                    self.players[player_index].moves_score += 2;
                }
            }
        }
    }

    pub fn opponent(player_index: usize) -> usize {
        (player_index + 1)%2
    }

    pub fn valid_move_commands(&self, player_index: usize) -> ArrayVec<[Command;8]> {
        // TODO: This might also involve selects
        if let Some(worm) = self.players[player_index].active_worm() {
            Direction::all()
                .iter()
                .map(Direction::as_vec)
                .map(|d| worm.position + d)
                .filter(|p| !self.occupied_cells.contains(p))
                .filter_map(|p| match self.map.at(p) {
                    Some(false) => Some(Command::new(Action::Move(p))),
                    Some(true) => Some(Command::new(Action::Dig(p))),
                    _ => None,
                })
                .collect()
        } else {
            ArrayVec::new()
        }
    }
    
    pub fn valid_shoot_commands(&self, player_index: usize, center: Point2d<i8>, weapon_range: u8) -> ArrayVec<[Command;8]> {
        // TODO: We might also throw bombs
        let range = weapon_range as i8;
        let dir_range = ((weapon_range as f32 + 1.) / 2f32.sqrt()).floor() as i8;

        self.players[GameBoard::opponent(player_index)].worms
            .iter()
            .filter_map(|w| {
                let diff = w.position - center;
                if diff.x == 0 && diff.y.abs() <= range {
                    if diff.y > 0 {
                        Some((Direction::South, diff.y))
                    } else {
                        Some((Direction::North, -diff.y))
                    }
                } else if diff.y == 0 && diff.x.abs() <= range {
                    if diff.x > 0 {
                        Some((Direction::East, diff.x))
                    } else {
                        Some((Direction::West, -diff.x))
                    }
                } else if diff.x.abs() == diff.y.abs() && diff.x.abs() <= dir_range {
                    match (diff.x > 0, diff.y > 0) {
                        (true, true) => Some((Direction::SouthEast, diff.x)),
                        (false, true) => Some((Direction::SouthWest, -diff.x)),
                        (true, false) => Some((Direction::NorthEast, diff.x)),
                        (false, false) => Some((Direction::NorthWest, -diff.x)),
                    }
                } else {
                    None
                }
            })
            .filter(|(dir, range)| {
                // TODO if this filtered all players, I don't  need to dedup
                let diff = dir.as_vec();
                !(1..*range).any(|distance|
                                 self.map.at(center + diff * distance) != Some(false) &&
                                 !self.players[player_index].worms.iter().any(|w| w.position == center + diff * distance))
            })
            .map(|(dir, _range)| Command::new(Action::Shoot(dir)))
            .collect()
    }
}

#[cfg(test)]
mod test {
    
}