sc2 0.2.0

organelle networks for StarCraft II Client API
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524

#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate serde_derive;

extern crate organelle;
extern crate docopt;
extern crate glob;
extern crate rand;
extern crate serde;

extern crate sc2;

use std::path::PathBuf;
use std::rc::Rc;

use organelle::{ Organelle, Soma, Impulse, ResultExt, Dendrite };
use docopt::Docopt;
use rand::random;
use sc2::{
    Result,
    Signal,
    Synapse,
    Axon,
    FrameData,
    PlayerSetup,
    Race,
    GameSettings,
    LauncherSettings,
    Map,
    Command,
    Ability,
    UnitType,
    Point2,
    Tag,
    ActionTarget,
    Alliance,
    Vector2,
};

const VERSION: &'static str = env!("CARGO_PKG_VERSION");

pub const USAGE: &'static str = "
StarCraft II Rust API Example.

Usage:
  example (-h | --help)
  example [options]
  example --version

Options:
  -h --help                         Show this screen.
  --version                         Show version.
  --wine                            Use Wine to run StarCraft II (for Linux).
  -d <path> --dir=<path>            Path to the StarCraft II installation.
  -p <port> --port=<port>           Port to make StarCraft II listen on.
  -m <name> --map=<name>            Path to the StarCraft II map.
  -r --realtime                     Run StarCraft II in real time
  -s <count> --step-size=<count>    How many steps to take per call.
  --replay-dir=<path>               Path to a replay pack
";

#[derive(Debug, Deserialize)]
pub struct Args {
    pub flag_dir:                   Option<PathBuf>,
    pub flag_port:                  Option<u16>,
    pub flag_map:                   Option<PathBuf>,
    pub flag_replay_dir:            Option<PathBuf>,
    pub flag_wine:                  bool,
    pub flag_version:               bool,
    pub flag_realtime:              bool,
    pub flag_step_size:             Option<u32>,
}

pub fn get_launcher_settings(args: &Args) -> Result<LauncherSettings> {
    let default_settings = LauncherSettings::default();

    Ok(
        LauncherSettings {
            use_wine: args.flag_wine,
            dir: args.flag_dir.clone(),
            base_port: {
                if let Some(port) = args.flag_port {
                    port
                }
                else {
                    default_settings.base_port
                }
            }
        }
    )
}

pub fn get_game_settings(args: &Args) -> Result<GameSettings> {
    let map = match args.flag_map {
        Some(ref map) => Map::LocalMap(map.clone()),
        None => bail!("no map specified")
    };

    Ok(GameSettings { map: map })
}

const TARGET_SCV_COUNT: usize = 15;

pub enum TerranSoma {
    Init(Init),
    Setup(Setup),

    InGame(InGame),
}

impl TerranSoma {
    pub fn organelle(interval: u32) -> Result<Self> {
        Ok(
            TerranSoma::Init(
                Init {
                    axon: Axon::new(
                        vec![
                            Dendrite::RequireOne(Synapse::Agent),
                        ],
                        vec![ ],
                    )?,
                    interval: interval,
                }
            )
        )
    }
}

impl Soma for TerranSoma {
    type Signal = Signal;
    type Synapse = Synapse;

    fn update(self, msg: Impulse<Signal, Synapse>)
        -> organelle::Result<TerranSoma>
    {
        match self {
            TerranSoma::Init(state) => state.update(msg),
            TerranSoma::Setup(state) => state.update(msg),

            TerranSoma::InGame(state) => state.update(msg),
        }.chain_err(
            || organelle::ErrorKind::SomaError
        )
    }
}

pub struct Init {
    axon:           Axon,
    interval:       u32,
}

impl Init {
    fn update(mut self, msg: Impulse<Signal, Synapse>) -> Result<TerranSoma> {
        if let Some(msg) = self.axon.update(msg)? {
            match msg {
                Impulse::Start => Setup::setup(self.axon, self.interval),

                Impulse::Signal(_, msg) => {
                    bail!("unexpected message {:#?}", msg)
                },
                _ => bail!("unexpected protocol message"),
            }
        }
        else {
            Ok(TerranSoma::Init(self))
        }
    }
}

pub struct Setup {
    axon:           Axon,
    interval:       u32,
}

impl Setup {
    fn setup(axon: Axon, interval: u32) -> Result<TerranSoma> {
        Ok(TerranSoma::Setup(Setup { axon: axon, interval: interval }))
    }

    fn update(mut self, msg: Impulse<Signal, Synapse>)-> Result<TerranSoma> {
        if let Some(msg) = self.axon.update(msg)? {
            match msg {
                Impulse::Signal(_, Signal::RequestPlayerSetup(_)) => {
                    self.axon.send_req_input(
                        Synapse::Agent,
                        Signal::PlayerSetup(
                            PlayerSetup::Player {
                                race: Race::Terran
                            }
                        )
                    )?;

                    Ok(TerranSoma::Setup(self))
                },
                Impulse::Signal(_, Signal::RequestUpdateInterval) => {
                    self.axon.send_req_input(
                        Synapse::Agent, Signal::UpdateInterval(self.interval)
                    )?;

                    Ok(TerranSoma::Setup(self))
                },
                Impulse::Signal(_, Signal::GameStarted) => {
                    InGame::start(self.axon, self.interval)
                },

                Impulse::Signal(_, msg) => {
                    bail!("unexpected message {:#?}", msg)
                },
                _ => bail!("unexpected protocol message"),
            }
        }
        else {
            Ok(TerranSoma::Setup(self))
        }
    }
}

pub struct InGame {
    axon:           Axon,
    interval:       u32,
}

impl InGame {
    fn start(axon: Axon, interval: u32) -> Result<TerranSoma> {
        Ok(TerranSoma::InGame(InGame { axon: axon, interval: interval }))
    }

    fn update(mut self, msg: Impulse<Signal, Synapse>) -> Result<TerranSoma> {
        if let Some(msg) = self.axon.update(msg)? {
            match msg {
                Impulse::Signal(_, Signal::Observation(frame)) => {
                    self.on_frame(frame)
                },

                Impulse::Signal(_, Signal::GameEnded) => {
                    Setup::setup(self.axon, self.interval)
                },

                Impulse::Signal(_, msg) => {
                    bail!("unexpected message {:#?}", msg)
                },
                _ => bail!("unexpected protocol message")
            }
        }
        else {
            Ok(TerranSoma::InGame(self))
        }
    }

    fn on_frame(self, frame: Rc<FrameData>) -> Result<TerranSoma> {
        let commands = self.create_commands(&*frame)?;

        let agent = self.axon.req_input(Synapse::Agent)?;

        let mut messages: Vec<Signal> = commands.into_iter()
            .map(|cmd| Signal::Command(cmd))
            .collect()
        ;

        messages.push(Signal::UpdateComplete);

        self.axon.effector()?.send_in_order(agent, messages);

        Ok(TerranSoma::InGame(self))
    }

    fn create_commands(&self, frame: &FrameData) -> Result<Vec<Command>> {
        let mut commands = vec![ ];
        // if there are marines and the command center is not found, send them
        // scouting.
        if let Some(cmd) = self.scout_with_marines(&frame) {
            commands.push(cmd);
        }

        // build supply depots if they are needed
        if let Some(cmd) = self.try_build_supply_depot(&frame) {
            commands.push(cmd);
            return Ok(commands)
        }

        // build terran SCV's if they are needed
        if let Some(cmd) = self.try_build_scv(&frame) {
            commands.push(cmd);
            return Ok(commands)
        }

        // build barracks if they are ready to be built
        if let Some(cmd) = self.try_build_barracks(&frame) {
            commands.push(cmd);
            return Ok(commands)
        }

        // just keep building marines if possible
        if let Some(cmd) = self.try_build_marine(&frame) {
            commands.push(cmd);
            return Ok(commands)
        }

        Ok(commands)
    }

    fn find_enemy_structure(&self, frame: &FrameData) -> Option<Tag> {
        let units = frame.state.filter_units(
            |u| u.alliance == Alliance::Enemy && (
                u.unit_type == UnitType::TerranCommandCenter ||
                u.unit_type == UnitType::TerranSupplyDepot ||
                u.unit_type == UnitType::TerranBarracks
            )
        );

        if !units.is_empty() {
            Some(units[0].tag)
        }
        else {
            None
        }
    }

    fn find_enemy_pos(&self, frame: &FrameData) -> Option<Point2> {
        if frame.data.terrain_info.enemy_start_locations.is_empty() {
            None
        }
        else {
            //TODO: should be random I think
            Some(frame.data.terrain_info.enemy_start_locations[0])
        }
    }

    fn scout_with_marines(&self, frame: &FrameData) -> Option<Command> {
        let units = frame.state.filter_units(
            |u| u.alliance == Alliance::Domestic &&
                u.unit_type == UnitType::TerranMarine &&
                u.orders.is_empty()
        );

        for ref u in units {
            match self.find_enemy_structure(frame) {
                Some(enemy_tag) => {
                    return Some(
                        Command::Action {
                            units: vec![ Rc::clone(u) ],
                            ability: Ability::Attack,
                            target: Some(ActionTarget::UnitTag(enemy_tag))
                        }
                    )
                },
                None => ()
            }

            match self.find_enemy_pos(frame) {
                Some(target_pos) => {
                    return Some(
                        Command::Action {
                            units: vec![ Rc::clone(u) ],
                            ability: Ability::Smart,
                            target: Some(ActionTarget::Location(target_pos))
                        }
                    )
                },
                None => ()
            }
        }

        None
    }

    fn try_build_supply_depot(&self, frame: &FrameData) -> Option<Command> {
        // if we are not supply capped, don't build a supply depot
        if frame.state.food_used + 2 <= frame.state.food_cap {
            return None
        }

        // find a random SVC to build a depot
        self.try_build_structure(frame, Ability::BuildSupplyDepot)
    }

    fn try_build_scv(&self, frame: &FrameData) -> Option<Command> {
        let scv_count = frame.state.filter_units(
            |u| u.unit_type == UnitType::TerranScv
        ).len();

        if scv_count < TARGET_SCV_COUNT {
            self.try_build_unit(
                frame, Ability::TrainScv, UnitType::TerranCommandCenter
            )
        }
        else {
            None
        }
    }

    fn try_build_barracks(&self, frame: &FrameData) -> Option<Command> {
        let scv_count = frame.state.filter_units(
            |u| u.unit_type == UnitType::TerranScv
        ).len();
        // wait until we have our quota of SCVs
        if scv_count < TARGET_SCV_COUNT {
            return None
        }

        let barracks_count = frame.state.filter_units(
            |u| u.unit_type == UnitType::TerranBarracks
        ).len();

        if barracks_count > 0 {
            return None
        }

        self.try_build_structure(frame, Ability::BuildBarracks)
    }

    fn try_build_marine(&self, frame: &FrameData) -> Option<Command> {
        self.try_build_unit(
            frame, Ability::TrainMarine, UnitType::TerranBarracks
        )
    }

    fn try_build_unit(
        &self, frame: &FrameData, ability: Ability, unit_type: UnitType
    )
        -> Option<Command>
    {
        let units = frame.state.filter_units(
            |u| u.unit_type == unit_type && u.orders.is_empty()
        );

        if units.is_empty() {
            None
        }
        else {
            Some(
                Command::Action {
                    units: vec![ Rc::clone(&units[0]) ],
                    ability: ability,
                    target: None
                }
            )
        }
    }

    fn try_build_structure(&self, frame: &FrameData, ability: Ability)
        -> Option<Command>
    {
        let units = frame.state.filter_units(
            |u| u.alliance == Alliance::Domestic
        );

        // if a unit is already building this structure, do nothing
        for u in &units {
            for o in &u.orders {
                if o.ability == ability {
                    return None
                }
            }
        }

        if !units.is_empty() {
            let r = Vector2::new(random(), random());

            let u = random::<usize>() % units.len();

            Some(
                Command::Action {
                    units: vec![ Rc::clone(&units[u]) ],
                    ability: ability,
                    target: Some(
                        ActionTarget::Location(
                            Point2::new(units[u].pos.x, units[u].pos.y)
                            + r * 5.0
                        )
                    )
                }
            )
        }
        else {
            None
        }
    }
}

quick_main!(
    || -> sc2::Result<()> {
        let args: Args = Docopt::new(USAGE)
            .and_then(|d| d.deserialize())
            .unwrap_or_else(|e| e.exit())
        ;

        if args.flag_version {
            println!("bot-mp version {}", VERSION);
            return Ok(())
        }

        let mut organelle = Organelle::new(
            sc2::MeleeSoma::organelle(
                sc2::MeleeSettings {
                    launcher: get_launcher_settings(&args)?,
                    players: (
                        sc2::AgentSoma::organelle(
                            TerranSoma::organelle(
                                args.flag_step_size.unwrap_or(1)
                            )?
                        )?,
                        sc2::AgentSoma::organelle(
                            TerranSoma::organelle(
                                args.flag_step_size.unwrap_or(1)
                            )?
                        )?,
                    ),
                    suite: sc2::MeleeSuite::EndlessRepeat(
                        get_game_settings(&args)?
                    )
                }
            )?
        );

        organelle.add_soma(sc2::CtrlcBreakerSoma::sheath()?);

        organelle.run()?;

        Ok(())
    }
);