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
use crate::{
    analyzer::{player::Player, Analyzer},
    geom::*,
    models::{GameCommand, PLAYER_MAX_SPEED, PLAYER_MIN_SPEED},
};
use rand::{thread_rng, Rng};
use std::{collections::VecDeque, fmt::Debug, time::Duration};

/// `Behavior` trait abstracts an action or a series of actions that a `Player`
/// can take. It may be useful if you want to model a complex behavior, that
/// spans multiple ticks, or whose interpretation changes dynamically. You can
/// use `Sequence::with_slice()` to combine multiple behaviors.
///
/// Some `Behavior`s take `Target` as an argument to dynamically specify which
/// player to act against. See its documentation for details (later in this
/// file).
///
/// # Examples
///
/// A stateful usage of `Behavior`.
///
/// ```
/// impl Handlar for Player {
///     fn tick(...) {
///         self.analyzer.push_state(state, Instant::now());
///
///         if let Some(next_command) = self.current_behavior.next_command(&self.analyzer) {
///             return Some(next_command);
///         }
///
///         // Creates a Behavior and stores it in the Player struct, as we need to
///         // persist the state across ticks and keep track of the number of times it
///         // fired.
///         self.current_behavior = Self::next_behavior();
///
///         self.current_behavior.next_command(&analyzer)
///     }
///
///     fn next_behavior() -> Sequence {
///         // Behavior to keep chasing the target (in this case, the player with
///         // the highest score.) It yields to the next behavior when the distance
///         // to the player is less than 200.0.
///         let chase = Chase { target: Target::HighestScore, distance: 200.0 };
///
///         // Behavior to fire at the target player twice.
///         let fire = FireAt::with_times(Target::HighestScore, 2);
///
///         // A sequence of behaviors: chase and then fire twice.
///         Sequence::with_slice(&[&chase, &fire])
///     }
/// }
/// ```
///
/// A stateless usage of `Behavior`.
///
/// ```
/// impl Handlar for Player {
///     fn tick(...) {
///         self.analyzer.push_state(state, Instant::now());
///
///         // Find one of the bullets that are colliding within a second.
///         if let Some(bullet) = self.analyzer.bullets_colliding(Duration::from_secs(1)).next() {
///             let angle = bullet.velocity.tangent();
///
///             // Try to dodge from the bullet by moving to a direction roughly
///             // perpendicular to the bullet velocity.
///             let dodge = Sequence::with_slice(&[
///                 &Rotate::with_margin_degrees(angle, 30.0),
///                 &Forward::with_steps(1),
///             ]);
///
///             // This Behavior works without persisting it somewhere for the next tick() as
///             // in the previous example. At the next tick(), Rotate behavior will most likely
///             // return None, proceeding immediately to the Forward behavior. If the situation
///             // changes e.g. the bullet hit someone else, or there are other bullets
///             // colliding, then it may take the Rotate behavior again, but it's likely an
///             // optimal adjustment (assuming your logic of selecting a bullet to dodge is
///             // stable.)
///             return dodge.next_command(&self.analyzer);
///         }
///         None
///     }
/// }
/// ```
pub trait Behavior: Send + Debug {
    // Returns the next `GameCommand` to achieve this `Behavior`. None if there
    // is nothing more to do.
    fn next_command(&mut self, _: &Analyzer) -> Option<GameCommand>;

    // `Clone` does not work nicely with `Box` yet, so you'll need to implement
    // this method manually for each struct.
    fn box_clone(&self) -> Box<Behavior>;
}

impl Clone for Box<Behavior> {
    fn clone(&self) -> Self {
        self.box_clone()
    }
}

impl Default for Box<Behavior> {
    fn default() -> Self {
        Box::new(Noop {})
    }
}

/// `Sequence` represents a series of `Behavior`s. The first
/// `Behavior::next_command()` is repeatedly called until it yields `None`, and
/// then it moves to the second `Behavior`, and so forth.
#[derive(Clone, Debug)]
pub struct Sequence {
    inner: VecDeque<Box<Behavior>>,
}

impl Behavior for Sequence {
    fn next_command(&mut self, analyzer: &Analyzer) -> Option<GameCommand> {
        while let Some(next) = self.inner.front_mut() {
            if let Some(command) = next.next_command(analyzer) {
                return Some(command);
            }
            self.inner.pop_front();
        }
        None
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

impl Sequence {
    pub fn new() -> Self {
        Sequence::with_slice(&[])
    }

    pub fn with_slice(behaviors: &[&Behavior]) -> Self {
        Self { inner: behaviors.into_iter().map(|b| b.box_clone()).collect::<VecDeque<_>>() }
    }
}

/// A `Behavior` to do nothing.
#[derive(Clone, Debug)]
pub struct Noop;

impl Behavior for Noop {
    fn next_command(&mut self, _: &Analyzer) -> Option<GameCommand> {
        None
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

/// A `Behavior` to keep yielding `GameCommand::Throttle` commands until it
/// travels the `distance`.
#[derive(Clone, Debug)]
pub struct Forward {
    pub distance: f32,
}

impl Behavior for Forward {
    fn next_command(&mut self, _: &Analyzer) -> Option<GameCommand> {
        if self.distance > 0.0 {
            let next_move = PLAYER_MAX_SPEED.max(self.distance);
            self.distance -= next_move;
            Some(GameCommand::Throttle(next_move))
        } else {
            None
        }
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

impl Forward {
    /// Creates a new `Forward` to move `steps`. Each step is the maximum
    /// distance one can travel by a tick.
    pub fn with_steps(steps: u32) -> Self {
        Self { distance: PLAYER_MAX_SPEED * steps as f32 }
    }
}

/// A `Behavior` to rotate to the specified `angle`. It yield `None` if the
/// current angle is within the error `margin`.
#[derive(Clone, Debug)]
pub struct Rotate {
    angle: Radian,
    margin: Radian,
}

impl Behavior for Rotate {
    fn next_command(&mut self, analyzer: &Analyzer) -> Option<GameCommand> {
        if (analyzer.own_player().angle.positive() - self.angle.positive()).abs() > self.margin {
            Some(GameCommand::Rotate(self.angle.positive().get()))
        } else {
            None
        }
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

impl Rotate {
    pub fn new(angle: Radian) -> Self {
        Self::with_margin_degrees(angle, 0.1)
    }

    pub fn with_margin_degrees(angle: Radian, margin_degrees: f32) -> Self {
        Self { angle, margin: Radian::degrees(margin_degrees) }
    }
}

/// A `Behavior` to fire the specified number of `times`.j
#[derive(Clone, Debug)]
pub struct Fire {
    times: u32,
}

impl Behavior for Fire {
    fn next_command(&mut self, _: &Analyzer) -> Option<GameCommand> {
        if self.times > 0 {
            self.times -= 1;
            Some(GameCommand::Fire)
        } else {
            None
        }
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

impl Fire {
    pub fn new() -> Self {
        Self::with_times(1)
    }

    pub fn with_times(times: u32) -> Self {
        Self { times }
    }
}

/// A `Behavior` to rotate to the `target` and fire the specified number of
/// `times`.
#[derive(Clone, Debug)]
pub struct FireAt {
    target: Target,
    times: u32,
    next: Sequence,
}

impl Behavior for FireAt {
    fn next_command(&mut self, analyzer: &Analyzer) -> Option<GameCommand> {
        if let Some(next_command) = self.next.next_command(analyzer) {
            return Some(next_command);
        }

        if self.times > 0 {
            if let Some(target) = self.target.get(analyzer) {
                self.times -= 1;
                let angle = analyzer.own_player().angle_to(target);
                self.next =
                    Sequence::with_slice(&[&Rotate::with_margin_degrees(angle, 5.0), &Fire::new()]);
                return self.next.next_command(analyzer);
            }
        }
        None
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

impl FireAt {
    pub fn new(target: Target) -> Self {
        Self::with_times(target, 1)
    }

    pub fn with_times(target: Target, times: u32) -> Self {
        Self { target, times, next: Sequence::new() }
    }
}

/// A `Behavior` to send a random command.
#[derive(Clone, Debug)]
struct Random;

impl Behavior for Random {
    fn next_command(&mut self, _: &Analyzer) -> Option<GameCommand> {
        let mut rng = thread_rng();
        match rng.gen_range(0, 4) {
            0 => None,
            1 => Some(GameCommand::Rotate(rng.gen_range(0.0, 2.0 * std::f32::consts::PI))),
            2 => Some(GameCommand::Throttle(rng.gen_range(PLAYER_MIN_SPEED, PLAYER_MAX_SPEED))),
            3 => Some(GameCommand::Fire),
            _ => unreachable!(),
        }
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

/// A `Behavior` to keep moving towards the specified `target` until it reaches
/// within the `distance`.
#[derive(Clone, Debug)]
pub struct Chase {
    pub target: Target,
    pub distance: f32,
}

impl Behavior for Chase {
    fn next_command(&mut self, analyzer: &Analyzer) -> Option<GameCommand> {
        if let Some(target) = self.target.get(analyzer) {
            let distance_to_target = analyzer.own_player().distance(target);
            if distance_to_target > self.distance {
                let angle = analyzer.own_player().angle_to(target);
                return Sequence::with_slice(&[
                    &Rotate::with_margin_degrees(angle, 10.0),
                    &Forward::with_steps(1),
                ])
                .next_command(analyzer);
            }
        }
        None
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

/// A `Behavior` to keep dodging nearby bullets as much as possible. Note that
/// the current implementation has a lot of room for improvements.
#[derive(Clone, Debug)]
pub struct Dodge;

impl Behavior for Dodge {
    fn next_command(&mut self, analyzer: &Analyzer) -> Option<GameCommand> {
        if let Some(bullet) = analyzer.bullets_colliding(Duration::from_secs(3)).next() {
            let angle = bullet.velocity.tangent();
            Sequence::with_slice(&[
                &Rotate::with_margin_degrees(angle, 30.0),
                &Forward::with_steps(1),
            ])
            .next_command(analyzer)
        } else {
            None
        }
    }

    fn box_clone(&self) -> Box<Behavior> {
        Box::new(self.clone())
    }
}

/// `Target enum` is used to specify a `Player` based on some predefined
/// conditions. Some `Behavior`s like `FireAt` works with `Target` to dynamically
/// compute the target `Player`.
#[derive(Clone, Debug)]
pub enum Target {
    /// Player specified by an ID.
    Id(u32),

    /// Player currently closest to you.
    Closest,

    /// Player that is least moving in the past.b
    LeastMoving,

    /// Player with the highest score so far.
    HighestScore,

    /// Player with the highest predicted score at a certain time in the future.
    HighestScoreAfter(Duration),
}

impl Target {
    /// Returns a reference to a `Player` based on the condition. `None` if no
    /// players match the condition.
    pub fn get<'a>(&self, analyzer: &'a Analyzer) -> Option<&'a Player> {
        match self {
            Target::Id(id) => analyzer.player(*id),
            Target::Closest => analyzer.player_closest(),
            Target::LeastMoving => analyzer.player_least_moving(),
            Target::HighestScore => analyzer.player_highest_score(),
            Target::HighestScoreAfter(after) => analyzer.player_highest_score_after(*after),
        }
    }
}