public void CreateGameWithBotShouldSucceed()
        {
            // Arrange
            var mapTemplate         = this.TestData.CreateAndSaveMapTemplate();
            var gameCreationOptions = new GameCreationOptions
            {
                Name                   = "TestGame",
                MapTemplate            = mapTemplate.Name,
                NumberOfPlayersPerTeam = 1,
                NumberOfTeams          = 2,
                VictoryConditions      = new[] { VictoryConditionType.Survival },
                VisibilityModifier     = new[] { VisibilityModifierType.None },
                TimeoutInSeconds       = 600,
                AddBot                 = true
            };

            this.UnitOfWork.Commit();

            // Act
            var game = this.gameService.Create(gameCreationOptions);

            // Assert
            Assert.IsNotNull(game);
            Assert.AreEqual(GameState.Active, game.State);
            Assert.IsTrue(game.Teams.SelectMany(x => x.Players).Any(x => x.Name == Constants.BotName));
        }
        public void CreateGameShouldSucceed()
        {
            // Arrange
            var mapTemplate         = this.TestData.CreateAndSaveMapTemplate();
            var gameCreationOptions = new GameCreationOptions
            {
                Name                   = "TestGame",
                MapTemplate            = mapTemplate.Name,
                NumberOfPlayersPerTeam = 1,
                NumberOfTeams          = 2,
                VictoryConditions      = new[] { VictoryConditionType.Survival },
                VisibilityModifier     = new[] { VisibilityModifierType.None },
                TimeoutInSeconds       = 600
            };

            this.UnitOfWork.Commit();

            // Act
            var game      = this.gameService.Create(gameCreationOptions);
            var openGames = this.gameService.GetOpen();

            // Assert
            Assert.IsNotNull(game);
            Assert.IsNotNull(openGames);
            var dbGame = this.UnitOfWork.Games.Find(game.Id);

            Assert.IsNotNull(dbGame);
            Assert.AreEqual(dbGame.Id, game.Id);
            Assert.IsTrue(dbGame.Teams.SelectMany(x => x.Players).Any(x => x.UserId == this.TestUser.Id));
        }
Ejemplo n.º 3
0
        public IActionResult Post([FromBody] GameCreationOptions creationOptions)
        {
            Require.NotNull(creationOptions, nameof(creationOptions));

            var game = this.gameService.Create(creationOptions);

            return(this.Ok(game));
        }
        public void PlaceUnitsSucceeds()
        {
            // Arrange
            var mapTemplate         = this.TestData.CreateAndSaveMapTemplate();
            var gameCreationOptions = new GameCreationOptions
            {
                Name                   = "TestGame",
                MapTemplate            = mapTemplate.Name,
                NumberOfPlayersPerTeam = 1,
                NumberOfTeams          = 2,
                VictoryConditions      = new[] { VictoryConditionType.Survival },
                VisibilityModifier     = new[] { VisibilityModifierType.None },
                TimeoutInSeconds       = 5 * 60,
                AddBot                 = true
            };

            this.UnitOfWork.Commit();

            var game = this.gameService.Create(gameCreationOptions);

            this.UnitOfWork.Commit();

            var fullGame = this.gameService.Get(game.Id);

            if (fullGame.CurrentPlayer.Name == "Bot")
            {
                Assert.Inconclusive();
                return;
            }

            TestUserProvider.User = this.UnitOfWork.Users.FindById(fullGame.CurrentPlayer.UserId);

            // Act
            var actionResult = this.playService.Place(game.Id, new[]
            {
                new PlaceUnitsOptions
                {
                    CountryIdentifier = fullGame.Map.Countries.First(x => x.PlayerId == fullGame.CurrentPlayer.Id).Identifier,
                    NumberOfUnits     = fullGame.UnitsToPlace
                }
            });

            // Assert
            Assert.IsNotNull(actionResult);
            Assert.IsNotNull(actionResult.CountryUpdates);
            Assert.AreEqual(1, actionResult.CountryUpdates.Count());
        }
        private GameSummary CreateGame(string suffix = null)
        {
            var mapTemplate = this.TestData.CreateAndSaveMapTemplate();

            this.UnitOfWork.Commit();

            var gameCreationOptions = new GameCreationOptions
            {
                Name                   = "TestGame" + (suffix ?? string.Empty),
                MapTemplate            = mapTemplate.Name,
                NumberOfPlayersPerTeam = 1,
                NumberOfTeams          = 2,
                VictoryConditions      = new[] { VictoryConditionType.Survival },
                VisibilityModifier     = new[] { VisibilityModifierType.None },
                TimeoutInSeconds       = 5 * 60,
                AddBot                 = true
            };

            var game = this.gameService.Create(gameCreationOptions);

            return(game);
        }
Ejemplo n.º 6
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);
                }
            }
        }
Ejemplo n.º 7
0
        public GameSummary Create(GameCreationOptions creationOptions)
        {
            var user = this.CurrentUser;

            var mapTemplate = this.mapTemplateProvider.GetTemplate(creationOptions.MapTemplate);

            if (mapTemplate == null)
            {
                throw new Exceptions.ApplicationException("Cannot find map template", ErrorCode.CannotFindMapTemplate);
            }

            if (creationOptions.VictoryConditions == null || !creationOptions.VictoryConditions.Any())
            {
                throw new Exceptions.ApplicationException("VictoryConditions are required", ErrorCode.GenericApplicationError);
            }

            if (creationOptions.VisibilityModifier == null || !creationOptions.VisibilityModifier.Any())
            {
                throw new Exceptions.ApplicationException("VisibilityModifier are required", ErrorCode.GenericApplicationError);
            }

            if (creationOptions.TimeoutInSeconds < 5 * 60)
            {
                throw new Exceptions.ApplicationException("Timouts has to be at least 300 seconds", ErrorCode.GenericApplicationError);
            }

            var password = creationOptions.Password;

            if (password != null)
            {
                // Trim any whitespace off the password and optionall convert to null, disabling it
                password = password.Trim();
                if (string.IsNullOrWhiteSpace(password))
                {
                    password = null;
                }
            }

            var game = this.gameService.Create(
                Domain.Enums.GameType.Fun,
                user,
                creationOptions.Name,
                password,
                creationOptions.TimeoutInSeconds,
                mapTemplate.Name,
                creationOptions.NumberOfPlayersPerTeam,
                creationOptions.NumberOfTeams,
                Mapper.Map <IEnumerable <Domain.Enums.VictoryConditionType> >(creationOptions.VictoryConditions),
                Mapper.Map <IEnumerable <Domain.Enums.VisibilityModifierType> >(creationOptions.VisibilityModifier));

            game.Options.MapDistribution = Mapper.Map <Domain.Enums.MapDistribution>(creationOptions.MapDistribution);

            game.Options.AttacksPerTurn      = creationOptions.AttacksPerTurn;
            game.Options.MovesPerTurn        = creationOptions.MovesPerTurn;
            game.Options.InitialCountryUnits = creationOptions.InitialCountryUnits;
            game.Options.MinUnitsPerCountry  = creationOptions.MinUnitsPerCountry;
            game.Options.NewUnitsPerTurn     = creationOptions.NewUnitsPerTurn;

            game.Options.MaximumNumberOfCards = creationOptions.MaximumNumberOfCards;

            // Add player, use the given password
            game.AddPlayer(user, password);

            if (creationOptions.AddBot)
            {
                using (TraceContext.Trace("Add Bot"))
                {
                    var botUser = this.UnitOfWork.Users.Query().First(x => x.UserName == Constants.BotName);
                    game.AddPlayer(botUser, password);
                }
            }

            this.UnitOfWork.Games.Add(game);

            if (game.CanStart)
            {
                using (TraceContext.Trace("Start Game"))
                {
                    game.Start(mapTemplate, this.randomGenProvider.GetRandomGen());
                }
            }

            using (TraceContext.Trace("Save Game"))
            {
                this.UnitOfWork.Commit();
            }

            return(Mapper.Map <GameSummary>(game));
        }