Exemplo n.º 1
0
        public static void RegisterClient(int i)
        {
            var client = ApiClient.GetClient <AccountClient>().Result;
            var model  = new RegisterBindingModel
            {
                CallbackUrl     = client.BaseUrl.ToString(),
                Language        = "de",
                Email           = i + "test@localhost",
                UserName        = "******" + i,
                Password        = "******" + i,
                ConfirmPassword = "******" + i
            };

            try
            {
                client.RegisterAsync(model).Wait();
            }
            catch (AggregateException e)
            {
                if (e.InnerExceptions != null && e.InnerExceptions.Count > 0 && e.InnerExceptions[0] is ImperaPlusException)
                {
                    if ((e.InnerExceptions[0] as ImperaPlusException).StatusCode == 400)
                    {
                        // ignore
                    }
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 2
0
        public static async Task <TClientType> GetAuthenticatedClient <TClientType>(string username, string password) where TClientType : ImperaHttpClient
        {
            // Login
            try
            {
                var accountClient = await GetClient <AccountClient>();

                var signinResult = await accountClient.LoginAsync("password", username, password, null, null);

                // Create requested client
                var client = await ApiClient.GetClient <TClientType>();

                client.AuthToken = signinResult.Access_token;
                return(client);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 3
0
        private async Task CreateAndPlayGameToEnd(GameCreationOptions gameCreationOptions)
        {
            var gameHistory = new Dictionary <int, Game>();

            var defaultPlayClient = await ApiClient.GetAuthenticatedClientDefaultUser <PlayClient>();

            var gameClients = new List <Tuple <GameClient, PlayClient, string> >();

            for (int i = 0; i < gameCreationOptions.NumberOfTeams * gameCreationOptions.NumberOfPlayersPerTeam - 1; ++i)
            {
                var gameClient = await ApiClient.GetAuthenticatedClient <GameClient>(i + 1);

                var playClient = await ApiClient.GetAuthenticatedClient <PlayClient>(i + 1);

                gameClients.Add(Tuple.Create(gameClient, playClient, "TestUser" + (i + 1)));
            }

            this.Log("Create game");
            var gameSummary = await this.clientDefault.PostAsync(gameCreationOptions);

            foreach (var gameClient in gameClients)
            {
                this.Log("Find game");
                await this.EnsureGameDoesShowInOpenList(gameClient.Item1, gameSummary.Id);

                this.Log("Join game for player");
                await gameClient.Item1.PostJoinAsync(gameSummary.Id, null);
            }

            this.Log("Make sure game has disappeared from open list");
            await this.EnsureGameDoesNotShowInOpenList(gameClients.First().Item1, gameSummary.Id);

            this.Log("Make sure game is now listed as active");
            IEnumerable <GameSummary> myGames = await clientDefault.GetMyAsync();

            var gameSummary2 = myGames.FirstOrDefault(x => x.Id == gameSummary.Id);

            Assert.IsNotNull(gameSummary2);
            Assert.AreEqual(GameState.Active, gameSummary2.State);
            Assert.IsTrue(gameSummary2.Teams.Any(), "No teams in summary");
            Assert.IsTrue(gameSummary2.Teams.SelectMany(x => x.Players).Any(), "No players in teams");
            Assert.IsNotNull(gameSummary2.CurrentPlayer);

            this.Log("Get game for default player");
            var gameDefault = await this.clientDefault.GetAsync(gameSummary.Id);

            Assert.IsNotNull(gameDefault.Teams);
            Assert.IsTrue(gameDefault.Teams.Any());
            Assert.IsNotNull(gameDefault.Map);
            Assert.AreEqual(PlayState.PlaceUnits, gameDefault.PlayState);

            this.Log("Get map template");
            var mapTemplateClient = await ApiClient.GetClient <MapClient>();

            var mapTemplate = await mapTemplateClient.GetMapTemplateAsync(gameDefault.MapTemplate);

            while (gameDefault.State == GameState.Active)
            {
                bool placeOnlyTurn = false;

                this.Log("Begin of turn");

                var currentPlayerId = gameDefault.CurrentPlayer.Id;
                var currentTeamId   = gameDefault.CurrentPlayer.TeamId;

                this.Log("\tCurrent player:{0} - {1}", currentPlayerId, currentTeamId);

                PlayClient playClient;
                GameClient gameClient;
                var        player = gameClients.FirstOrDefault(x => x.Item3 == gameDefault.CurrentPlayer.Name);
                if (player == null)
                {
                    gameClient = this.clientDefault;
                    playClient = defaultPlayClient;
                }
                else
                {
                    gameClient = player.Item1;
                    playClient = player.Item2;
                }

                var gameState = await gameClient.GetAsync(gameDefault.Id);

                {
                    // Place units
                    this.Log("Placing units - player {0} - {1}", currentPlayerId, gameDefault.UnitsToPlace);
                    var     ownCountries = gameState.Map.Countries.Where(x => x.TeamId == currentTeamId);
                    Country ownCountry;
                    if (ownCountries.Count() == 1)
                    {
                        ownCountry = ownCountries.First();
                    }
                    else
                    {
                        ownCountry = ownCountries.FirstOrDefault(x =>
                                                                 gameDefault.Map.Countries.Any(
                                                                     y => y.TeamId != currentTeamId &&
                                                                     mapTemplate
                                                                     .Connections
                                                                     .Any(c => c.Origin == x.Identifier && c.Destination == y.Identifier)));
                    }

                    if (ownCountry == null)
                    {
                        Assert.Fail("No connected, enemy country found");
                    }

                    var placeOptions = new[] {
                        new PlaceUnitsOptions
                        {
                            CountryIdentifier = ownCountry.Identifier,
                            NumberOfUnits     = gameState.UnitsToPlace
                        }
                    };

                    var placeResponse = await playClient.PostPlaceAsync(gameDefault.Id, placeOptions);

                    this.ApplyMapUpdates(gameState.Map, placeResponse.CountryUpdates);

                    if (placeResponse.State != GameState.Active)
                    {
                        break;
                    }

                    if (placeResponse.CurrentPlayer.Id != currentPlayerId)
                    {
                        this.Log("Place only turn");
                        placeOnlyTurn = true;
                    }
                }

                // Attack
                if (gameState.TurnCounter > 3)
                {
                    bool breakExecution = false;

                    for (int a = 0; a < gameState.Options.AttacksPerTurn; ++a)
                    {
                        var ownCountries = gameState.Map.Countries.Where(x => x.TeamId == currentTeamId);
                        var ownCountry   = ownCountries.FirstOrDefault(x =>
                                                                       x.Units > gameState.Options.MinUnitsPerCountry &&
                                                                       gameState.Map.Countries.Any(y => y.TeamId != currentTeamId &&
                                                                                                   mapTemplate
                                                                                                   .Connections
                                                                                                   .Any(c => c.Origin == x.Identifier && c.Destination == y.Identifier)));
                        if (ownCountry == null)
                        {
                            this.Log("Cannot find own country");

                            // Abort attack
                            break;
                        }

                        // Find enemy country
                        var enemyCountries = gameState.Map.Countries.Where(x => x.TeamId != currentTeamId);
                        var enemyCountry   = enemyCountries.FirstOrDefault(x => mapTemplate
                                                                           .Connections.Any(c =>
                                                                                            c.Origin == ownCountry.Identifier &&
                                                                                            c.Destination == x.Identifier));
                        if (enemyCountry == null)
                        {
                            Assert.Fail("Cannot find enemy country connected to selected own country");
                        }

                        var numberOfUnits = ownCountry.Units - gameState.Options.MinUnitsPerCountry;
                        if (playClient != defaultPlayClient)
                        {
                            numberOfUnits = 1;
                        }

                        var attackOptions = new AttackOptions()
                        {
                            OriginCountryIdentifier      = ownCountry.Identifier,
                            DestinationCountryIdentifier = enemyCountry.Identifier,
                            NumberOfUnits = numberOfUnits
                        };

                        this.Log("Attack from {0} to {1} with {2} units",
                                 attackOptions.OriginCountryIdentifier,
                                 attackOptions.DestinationCountryIdentifier,
                                 attackOptions.NumberOfUnits);

                        var attackResult = await playClient.PostAttackAsync(gameState.Id, attackOptions);

                        if (attackResult.ActionResult == Result.Successful)
                        {
                            this.Log("\tAttack successful, units left {0}", attackResult.CountryUpdates.First(x => x.Identifier == attackOptions.DestinationCountryIdentifier).Units);
                        }
                        else
                        {
                            this.Log("\tAttack failed");
                        }

                        this.ApplyMapUpdates(gameState.Map, attackResult.CountryUpdates);

                        if (attackResult.State != GameState.Active)
                        {
                            breakExecution = true;
                            break;
                        }
                    }

                    if (breakExecution)
                    {
                        break;
                    }
                }

                // Move
                {
                }

                if (!placeOnlyTurn)
                {
                    // Record turn
                    gameHistory.Add(gameState.TurnCounter, await gameClient.GetAsync(gameSummary.Id));

                    // End turn
                    this.Log("End turn");
                    await playClient.PostEndTurnAsync(gameState.Id);
                }

                gameDefault = await this.clientDefault.GetAsync(gameSummary.Id);

                if (gameDefault.State == GameState.Ended)
                {
                    break;
                }

                Assert.IsTrue(
                    gameDefault.CurrentPlayer.Id != currentPlayerId,
                    "Current player did not switch");

                if (gameDefault.TurnCounter > 50)
                {
                    foreach (var p in gameDefault.Teams.SelectMany(x => x.Players))
                    {
                        this.Log("Player {0} has {1} countries",
                                 p.Name,
                                 gameDefault.Map.Countries.Count(x => x.PlayerId == p.Id));
                    }

                    Assert.Inconclusive("Turn counter to high, possibly no end?");
                }
            }

            this.Log("Game ended");

            // Refresh
            gameDefault = await this.clientDefault.GetAsync(gameSummary.Id);

            Assert.IsTrue(
                gameDefault.Teams.SelectMany(x => x.Players)
                .Any(x => x.Outcome == PlayerOutcome.Won &&
                     x.State == PlayerState.InActive),
                "No winner after game has ended");
            Assert.IsTrue(
                gameDefault.Teams.SelectMany(x => x.Players)
                .Any(x => x.Outcome == PlayerOutcome.Defeated &&
                     x.State == PlayerState.InActive),
                "No loser after game has ended");

            // Output debug information
            foreach (var player in gameDefault.Teams.SelectMany(x => x.Players))
            {
                this.Log("Player {0} result {1}", player.Name, player.Outcome);
            }

            this.Log("Verifying history");

            var historyClient = await ApiClient.GetAuthenticatedClientDefaultUser <HistoryClient>();

            foreach (var gameHistoryEntry in gameHistory)
            {
                this.Log("Get history for turn {0}", gameHistoryEntry.Key);

                var historyTurn = await historyClient.GetTurnAsync(gameHistoryEntry.Value.Id, gameHistoryEntry.Value.TurnCounter);

                // Verify players
                foreach (var player in gameHistoryEntry.Value.Teams.SelectMany(x => x.Players))
                {
                    var historyPlayer = historyTurn.Game.Teams.SelectMany(x => x.Players).FirstOrDefault(x => x.Id == player.Id);
                    Assert.IsNotNull(historyPlayer);

                    Assert.AreEqual(player.State, historyPlayer.State);
                    Assert.AreEqual(player.Outcome, historyPlayer.Outcome);
                }

                // Verify map
                foreach (var country in gameHistoryEntry.Value.Map.Countries)
                {
                    var historyCountry = historyTurn.Game.Map.Countries.FirstOrDefault(x => x.Identifier == country.Identifier);
                    Assert.IsNotNull(historyCountry);

                    Assert.AreEqual(country.Units, historyCountry.Units);
                    Assert.AreEqual(country.PlayerId, historyCountry.PlayerId);
                    Assert.AreEqual(country.TeamId, historyCountry.TeamId);
                }
            }
        }