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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
use std::{self, mem};

use futures::prelude::*;
use futures::unsync::{mpsc, oneshot};
use organelle;
use organelle::{Axon, Constraint, Impulse, Organelle, Soma};
use tokio_core::reactor;
use url::Url;

use super::{Error, Result};
use ctrlc_breaker::CtrlcBreakerSoma;
use data::{GameSetup, PlayerSetup};
use launcher::{GamePorts, Launcher, LauncherSoma, LauncherTerminal};
use synapses::{Dendrite, Synapse, Terminal};

/// update scheme for the agents to use
#[derive(Debug, Copy, Clone)]
pub enum UpdateScheme {
    /// update as fast as possible
    Realtime,
    /// step the game with a fixed interval
    Interval(u32),
}

/// empty trait to prevent users from passing their own somas to MeleeBuilder
pub trait MeleeCompetitor {
    type Soma: Soma + 'static;

    fn into_soma(self) -> Self::Soma;
}

/// build a Melee coordinator
pub struct MeleeBuilder<
    P1: MeleeCompetitor + 'static,
    P2: MeleeCompetitor + 'static,
> {
    players: (P1, P2),
    launcher: Option<Launcher>,
    suite: Option<MeleeSuite>,
    update_scheme: UpdateScheme,
    break_on_ctrlc: bool,
    handle: Option<reactor::Handle>,
}

impl<P1, P2> MeleeBuilder<P1, P2>
where
    P1: MeleeCompetitor + 'static,
    P2: MeleeCompetitor + 'static,
{
    /// start building a melee soma with the given agent or computer somas
    pub fn new(player1: P1, player2: P2) -> Self {
        Self {
            players: (player1, player2),

            launcher: None,
            suite: None,
            update_scheme: UpdateScheme::Realtime,
            break_on_ctrlc: false,
            handle: None,
        }
    }

    /// the settings for the launcher soma
    pub fn launcher_settings(self, settings: Launcher) -> Self {
        Self {
            launcher: Some(settings),
            ..self
        }
    }

    /// play one game with the given settings
    pub fn one_and_done(self, game: GameSetup) -> Self {
        Self {
            suite: Some(MeleeSuite::OneAndDone(game)),
            ..self
        }
    }

    /// keep restarting game with the given settings
    pub fn repeat_forever(self, game: GameSetup) -> Self {
        Self {
            suite: Some(MeleeSuite::EndlessRepeat(game)),
            ..self
        }
    }

    /// the method of updating the game instance
    pub fn update_scheme(self, scheme: UpdateScheme) -> Self {
        Self {
            update_scheme: scheme,
            ..self
        }
    }

    /// stop running upon CTRL-C
    ///
    /// this is only necessary with Wine. CTRL-C doesn't seem to kill it for
    /// some reason by default.
    pub fn break_on_ctrlc(self, flag: bool) -> Self {
        Self {
            break_on_ctrlc: flag,
            ..self
        }
    }

    /// the tokio core handle to use
    pub fn handle(self, handle: reactor::Handle) -> Self {
        Self {
            handle: Some(handle),
            ..self
        }
    }

    /// build the melee coordinator
    pub fn create(self) -> Result<Melee>
    where
        P1::Soma: Soma,
        P2::Soma: Soma,

        <P1::Soma as Soma>::Synapse: organelle::Synapse,
        <P2::Soma as Soma>::Synapse: organelle::Synapse,

        <P1::Soma as Soma>::Synapse: From<Synapse> + Into<Synapse>,
        <P2::Soma as Soma>::Synapse: From<Synapse> + Into<Synapse>,

        <<P1::Soma as Soma>::Synapse as organelle::Synapse>::Terminal: From<Terminal>
            + Into<Terminal>,
        <<P2::Soma as Soma>::Synapse as organelle::Synapse>::Terminal: From<Terminal>
            + Into<Terminal>,
        <<P1::Soma as Soma>::Synapse as organelle::Synapse>::Dendrite: From<Dendrite>
            + Into<Dendrite>,
        <<P2::Soma as Soma>::Synapse as organelle::Synapse>::Dendrite: From<Dendrite>
            + Into<Dendrite>,
    {
        if self.launcher.is_none() {
            bail!("missing launcher settings")
        } else if self.suite.is_none() {
            bail!("missing melee suite")
        } else if self.handle.is_none() {
            bail!("missing reactor handle")
        }

        let handle = self.handle.unwrap();

        let mut organelle = Organelle::new(
            MeleeSoma::axon(self.suite.unwrap(), self.update_scheme)?,
            handle.clone(),
        );

        let launcher =
            organelle.add_soma(LauncherSoma::axon(self.launcher.unwrap())?);

        let melee = organelle.nucleus();

        let player1 = organelle.add_soma(self.players.0.into_soma());
        let player2 = organelle.add_soma(self.players.1.into_soma());

        if self.break_on_ctrlc {
            organelle.add_soma(CtrlcBreakerSoma::axon());
        }

        organelle.connect(melee, launcher, Synapse::Launcher)?;

        organelle.connect(melee, player1, Synapse::Melee)?;
        organelle.connect(melee, player2, Synapse::Melee)?;

        Ok(Melee {
            handle: handle,
            organelle: organelle,
        })
    }
}

/// coordinates matches between the given players
pub struct Melee {
    handle: reactor::Handle,
    organelle: Organelle<Axon<MeleeSoma>>,
}

impl IntoFuture for Melee {
    type Item = ();
    type Error = Error;
    type Future = Box<Future<Item = Self::Item, Error = Self::Error>>;

    #[async(boxed)]
    fn into_future(self) -> Result<()> {
        await!(self.organelle.run(self.handle))?;
        Ok(())
    }
}

/// suite of games to choose from when pitting bots against each other
enum MeleeSuite {
    OneAndDone(GameSetup),
    /// repeat this game indefinitely
    EndlessRepeat(GameSetup),
}

/// create a melee synapse
pub fn synapse() -> (MeleeTerminal, MeleeDendrite) {
    let (tx, rx) = mpsc::channel(1);

    (MeleeTerminal::new(tx), MeleeDendrite::new(rx))
}

/// controller that pits agents against each other
pub struct MeleeSoma {
    suite: Option<MeleeSuite>,
    launcher: Option<LauncherTerminal>,
    agents: Vec<Option<MeleeTerminal>>,
    update_scheme: UpdateScheme,
}

impl MeleeSoma {
    /// melee soma only works as a controller in a melee organelle
    fn axon(
        suite: MeleeSuite,
        update_scheme: UpdateScheme,
    ) -> Result<Axon<Self>> {
        Ok(Axon::new(
            Self {
                suite: Some(suite),
                launcher: None,
                agents: vec![],
                update_scheme: update_scheme,
            },
            vec![],
            vec![
                Constraint::One(Synapse::Launcher),
                Constraint::Variadic(Synapse::Melee),
            ],
        ))
    }
}

impl Soma for MeleeSoma {
    type Synapse = Synapse;
    type Error = Error;

    #[async(boxed)]
    fn update(mut self, msg: Impulse<Self::Synapse>) -> Result<Self> {
        match msg {
            Impulse::AddTerminal(
                _,
                Synapse::Launcher,
                Terminal::Launcher(tx),
            ) => {
                self.launcher = Some(tx);
                Ok(self)
            },
            Impulse::AddTerminal(_, Synapse::Melee, Terminal::Melee(tx)) => {
                self.agents.push(Some(tx));
                Ok(self)
            },
            Impulse::Start(_, main_tx, handle) => {
                assert!(self.launcher.is_some());
                assert!(self.suite.is_some());

                if self.agents.len() != 2 {
                    bail!("expected 2 agents, got {}", self.agents.len())
                }

                assert!(self.agents[0].is_some() && self.agents[1].is_some());

                let main_tx2 = main_tx.clone();

                handle.spawn(
                    run_melee(
                        mem::replace(&mut self.suite, None).unwrap(),
                        self.update_scheme,
                        mem::replace(&mut self.launcher, None).unwrap(),
                        (
                            mem::replace(&mut self.agents[0], None).unwrap(),
                            mem::replace(&mut self.agents[1], None).unwrap(),
                        ),
                        main_tx2,
                    ).or_else(move |e| {
                        main_tx
                            .send(Impulse::Error(e.into()))
                            .map(|_| ())
                            .map_err(|_| ())
                    }),
                );

                Ok(self)
            },

            _ => bail!("unexpected impulse"),
        }
    }
}

#[async]
fn run_melee(
    suite: MeleeSuite,
    update_scheme: UpdateScheme,
    launcher: LauncherTerminal,
    agents: (MeleeTerminal, MeleeTerminal),
    main_tx: mpsc::Sender<Impulse<Synapse>>,
) -> Result<()> {
    let (game, _suite) = match suite {
        MeleeSuite::OneAndDone(game) => (game, None),
        MeleeSuite::EndlessRepeat(game) => {
            let suite = Some(MeleeSuite::EndlessRepeat(game.clone()));

            (game, suite)
        },
    };

    let player1 = await!(agents.0.clone().get_player_setup(game.clone()))?;
    let player2 = await!(agents.1.clone().get_player_setup(game.clone()))?;

    let is_pvp = {
        if player1.is_player() && player2.is_computer() {
            false
        } else if player1.is_computer() && player2.is_player() {
            false
        } else if player1.is_player() && player2.is_player() {
            true
        } else {
            bail!("invalid player setups")
        }
    };

    if is_pvp {
        // launch both at the same time
        let instances = {
            let launch1 = launcher.clone().launch();
            let launch2 = launcher.clone().launch();

            await!(launch1.join(launch2))?
        };

        // connect to both at the same time
        {
            let connect1 = agents.0.clone().connect(instances.0.get_url()?);
            let connect2 = agents.1.clone().connect(instances.1.get_url()?);

            await!(connect1.join(connect2))?;
        }

        await!(
            agents
                .0
                .clone()
                .create_game(game.clone(), vec![player1, player2])
        )?;

        let mut ports = await!(launcher.clone().get_game_ports())?;

        ports.client_ports.push(instances.0.ports);
        ports.client_ports.push(instances.1.ports);

        {
            let join1 =
                agents.0.clone().join_game(player1, Some(ports.clone()));
            let join2 = agents.1.clone().join_game(player2, Some(ports));

            await!(join1.join(join2))?;
        }

        {
            let run1 = agents.0.clone().run_game(update_scheme);
            let run2 = agents.1.clone().run_game(update_scheme);

            await!(run1.join(run2))?;
        }

        // just quit for now
        await!(
            main_tx
                .send(Impulse::Stop)
                .map(|_| ())
                .map_err(|_| Error::from("unable to stop"))
        )?;
    } else {
        let (player, computer) = if player1.is_computer() {
            ((agents.1, player2), (agents.0, player1))
        } else if player2.is_computer() {
            ((agents.0, player1), (agents.1, player2))
        } else {
            unreachable!()
        };

        assert!(player.1.is_player() && computer.1.is_computer());

        let instance = await!(launcher.clone().launch())?;

        await!(player.0.clone().connect(instance.get_url()?))?;
        await!(
            player
                .0
                .clone()
                .create_game(game.clone(), vec![player.1, computer.1])
        )?;
        await!(player.0.clone().join_game(player.1, None))?;

        await!(player.0.clone().run_game(update_scheme))?;

        // just quit for now
        await!(
            main_tx
                .send(Impulse::Stop)
                .map(|_| ())
                .map_err(|_| Error::from("unable to stop"))
        )?;
    }

    Ok(())
}

#[derive(Debug)]
enum MeleeRequest {
    PlayerSetup(GameSetup, oneshot::Sender<PlayerSetup>),
    Connect(Url, oneshot::Sender<()>),

    CreateGame(GameSetup, Vec<PlayerSetup>, oneshot::Sender<()>),
    JoinGame(PlayerSetup, Option<GamePorts>, oneshot::Sender<()>),
    RunGame(UpdateScheme, oneshot::Sender<()>),
}

/// wrapper around a sender to provide a melee interface
#[derive(Debug, Clone)]
pub struct MeleeTerminal {
    tx: mpsc::Sender<MeleeRequest>,
}

/// interface to be enforced by melee dendrites
pub trait MeleeContract: Sized {
    /// errors from the dendrite
    type Error: std::error::Error + Send + Into<Error>;

    /// fetch the player setup from the agent
    fn get_player_setup(
        self,
        game: GameSetup,
    ) -> Box<Future<Item = (Self, PlayerSetup), Error = Self::Error>>;

    /// connect to an instance
    fn connect(self, url: Url)
        -> Box<Future<Item = Self, Error = Self::Error>>;

    /// create a game
    fn create_game(
        self,
        game: GameSetup,
        players: Vec<PlayerSetup>,
    ) -> Box<Future<Item = Self, Error = Self::Error>>;

    /// join a game
    fn join_game(
        self,
        setup: PlayerSetup,
        ports: Option<GamePorts>,
    ) -> Box<Future<Item = Self, Error = Self::Error>>;

    /// run the game
    fn run_game(
        self,
        update_scheme: UpdateScheme,
    ) -> Box<Future<Item = Self, Error = Self::Error>>;
}

/// wrapper around a receiver to provide a controlled interface
#[derive(Debug)]
pub struct MeleeDendrite {
    rx: mpsc::Receiver<MeleeRequest>,
}

impl MeleeDendrite {
    fn new(rx: mpsc::Receiver<MeleeRequest>) -> Self {
        Self { rx: rx }
    }

    /// wrap a dendrite and use the contract to respond to any requests
    #[async]
    pub fn wrap<T>(self, mut dendrite: T) -> Result<()>
    where
        T: MeleeContract + 'static,
    {
        #[async]
        for req in self.rx.map_err(|_| -> Error { unreachable!() }) {
            match req {
                MeleeRequest::PlayerSetup(game, tx) => {
                    let result = await!(dendrite.get_player_setup(game))
                        .map_err(|e| e.into())?;

                    tx.send(result.1).unwrap();

                    dendrite = result.0;
                },
                MeleeRequest::Connect(url, tx) => {
                    dendrite =
                        await!(dendrite.connect(url)).map_err(|e| e.into())?;

                    tx.send(()).unwrap();
                },
                MeleeRequest::CreateGame(game, players, tx) => {
                    dendrite = await!(
                        dendrite
                            .create_game(game, players)
                            .map_err(|e| e.into())
                    )?;

                    tx.send(()).unwrap();
                },
                MeleeRequest::JoinGame(setup, ports, tx) => {
                    dendrite = await!(
                        dendrite.join_game(setup, ports).map_err(|e| e.into())
                    )?;

                    tx.send(()).unwrap();
                },
                MeleeRequest::RunGame(update_scheme, tx) => {
                    dendrite = await!(
                        dendrite.run_game(update_scheme).map_err(|e| e.into())
                    )?;

                    tx.send(()).unwrap();
                },
            }
        }

        Ok(())
    }
}

impl MeleeTerminal {
    fn new(tx: mpsc::Sender<MeleeRequest>) -> Self {
        Self { tx: tx }
    }

    /// get a player setup from the agent
    #[async]
    pub fn get_player_setup(self, game: GameSetup) -> Result<PlayerSetup> {
        let (tx, rx) = oneshot::channel();

        await!(
            self.tx
                .send(MeleeRequest::PlayerSetup(game, tx))
                .map_err(|_| Error::from("unable to request player setup"))
        )?;

        await!(rx.map_err(|_| Error::from("unable to receive player setup")))
    }

    /// tell agent to connect to instance
    #[async]
    pub fn connect(self, url: Url) -> Result<()> {
        let (tx, rx) = oneshot::channel();

        await!(
            self.tx
                .send(MeleeRequest::Connect(url, tx))
                .map_err(|_| Error::from("unable to request player setup"))
        )?;

        await!(rx.map_err(|_| Error::from("unable to receive player setup")))
    }

    /// tell agent to create a game
    #[async]
    pub fn create_game(
        self,
        game: GameSetup,
        players: Vec<PlayerSetup>,
    ) -> Result<()> {
        let (tx, rx) = oneshot::channel();

        await!(
            self.tx
                .send(MeleeRequest::CreateGame(game, players, tx))
                .map_err(|_| Error::from("unable to create game"))
        )?;

        await!(rx.map_err(|_| Error::from("unable to create game")))
    }

    /// tell agent to join a game
    #[async]
    pub fn join_game(
        self,
        setup: PlayerSetup,
        ports: Option<GamePorts>,
    ) -> Result<()> {
        let (tx, rx) = oneshot::channel();

        await!(
            self.tx
                .send(MeleeRequest::JoinGame(setup, ports, tx))
                .map_err(|_| Error::from("unable to join game"))
        )?;

        await!(rx.map_err(|_| Error::from("unable to join game")))
    }

    /// run the game to completion
    #[async]
    pub fn run_game(self, update_scheme: UpdateScheme) -> Result<()> {
        let (tx, rx) = oneshot::channel();

        await!(
            self.tx
                .send(MeleeRequest::RunGame(update_scheme, tx))
                .map_err(|_| Error::from("unable to run game"))
        )?;

        await!(rx.map_err(|_| Error::from("unable to run game")))
    }
}

// /// MeleeSoma state that pits players against the built-in AI
// pub struct PlayerVsComputer {
//     suite: Option<MeleeSuite>,

//     game: GameSettings,
//     player_setup: PlayerSetup,
//     computer_setup: PlayerSetup,

//     player: Handle,
// }

// impl PlayerVsComputer {
//     fn start(
//         suite: Option<MeleeSuite>,
//         player: (Handle, PlayerSetup),
//         computer: (Handle, PlayerSetup),
//         game: GameSettings,
//     ) -> Result<MeleeSoma> {
//         Ok(MeleeSoma::PlayerVsComputer(PlayerVsComputer {
//             suite: suite,

//             game: game,
//             player_setup: player.1,
//             computer_setup: computer.1,

//             player: player.0,
//         }))
//     }
//     fn update(
//         self,
//         axon: &Axon,
//         msg: Impulse<Signal, Synapse>,
//     ) -> Result<MeleeSoma> {
//         match msg {
//             Impulse::Signal(src, Signal::Ready) => {
//                 self.on_agent_ready(axon, src)
//             },
//             Impulse::Signal(src, Signal::GameCreated) => {
//                 self.on_game_created(axon, src)
//             },
//             Impulse::Signal(src, Signal::GameEnded) => {
//                 self.on_game_ended(axon, src)
//             },

// Impulse::Signal(_, msg) => bail!("unexpected message {:#?}",
// msg),             _ => bail!("unexpected protocol message"),
//         }
//     }

//     fn on_agent_ready(self, axon: &Axon, src: Handle) -> Result<MeleeSoma> {
//         if src != self.player {
//             bail!("expected source of Ready to be the agent")
//         }

//         axon.effector()?.send(
//             self.player,
//             Signal::CreateGame(
//                 self.game.clone(),
//                 vec![self.player_setup, self.computer_setup],
//             ),
//         );

//         Ok(MeleeSoma::PlayerVsComputer(self))
//     }

//     fn on_game_created(self, axon: &Axon, src: Handle) -> Result<MeleeSoma> {
//         if src != self.player {
//             bail!("expected source of GameCreated to be the agent")
//         }

//         axon.effector()?
//             .send(self.player, Signal::GameReady(self.player_setup, None));

//         Ok(MeleeSoma::PlayerVsComputer(self))
//     }

//     fn on_game_ended(self, axon: &Axon, src: Handle) -> Result<MeleeSoma> {
//         if src != self.player {
//             bail!("expected source of GameEnded to be an agent")
//         }

//         if self.suite.is_none() {
//             Completed::complete(axon)
//         } else {
//             Setup::setup(axon, self.suite.unwrap())
//         }
//     }
// }

// pub struct Completed;

// impl Completed {
//     fn complete(axon: &Axon) -> Result<MeleeSoma> {
//         axon.effector()?.stop();

//         Ok(MeleeSoma::Completed(Completed {}))
//     }

//     fn update(
//         self,
//         _axon: &Axon,
//         msg: Impulse<Signal, Synapse>,
//     ) -> Result<MeleeSoma> {
//         match msg {
// Impulse::Signal(_, msg) => bail!("unexpected message {:#?}",
// msg),             _ => bail!("unexpected protocol message"),
//         }
//     }
// }