private void CheckForGameFinish(Game game, DateTime recalcDateTime)
 {
     if ((recalcDateTime - game.GameDate).TotalMinutes >= game.TotalTime && game.GameState == GameStates.Started)
     {
         gameService.StopGame(game);
     }
 }
        public void CanEnsureGameCreationIsValid()
        {
            Game gameFromForm = new Game();
            ViewResult result = controller.Create(gameFromForm).AssertViewRendered();

            result.ViewData.Model.ShouldNotBeNull();
            result.ViewData.Model.ShouldBeOfType(typeof(GamesController.GameFormViewModel));
        }
        public void CanCompareGames() {
            Game instance = new Game();
			instance.Name = "New gme";

            Game instanceToCompareTo = new Game();
			instanceToCompareTo.Name = "New gme";

			instance.ShouldEqual(instanceToCompareTo);
        }
 public static Team CreateTeamGameState(this Team team, Game game)
 {
     var tgs = new TeamGameState
     {
         Game = game,
         Team = team
     };
     team.TeamGameState = tgs;
     team.Game = game;
     game.Teams.Add(team);
     return team;
 }
        public ActionResult Create(Game game)
        {
            if (ViewData.ModelState.IsValid && game.IsValid())
            {
                gameRepository.SaveOrUpdate(game);

                Message = "Игра успешно создана.";
                return this.RedirectToAction(c => c.Index());
            }

            return View(game);
        }
        public void CanCloseGameTest()
        {
            Game game = new Game { GameState = GameStates.Finished };
            var team = new Team()
                .CreateTeamGameState(game);

            mocks.ReplayAll();

            service.CloseGame(game);

            mocks.VerifyAll();

            Assert.AreEqual(GameStates.Cloused, game.GameState);
            Assert.IsNull(team.TeamGameState);
            Assert.IsNull(team.Game);
        }
        public void CloseGame(Game game)
        {
            Check.Require(game.GameState == GameStates.Finished,
                String.Format(
                    "Невозможно закрыть игру, когда она находится в режиме {0}.",
                    Enum.GetName(typeof(GameStates), game.GameState))
                );

            game.GameState = GameStates.Cloused;

            // Для каждой команды сбрасываем игровое состояние
            foreach (Team team in game.Teams)
            {
                team.TeamGameState = null;
                team.Game = null;
            }
        }
        public void CanCloseGameTest()
        {
            Expect.Call(teamGameStateRepository.DbContext).Return(dbContext);

            Game game = new Game { GameState = GameStates.Finished };
            var team = new Team()
                .CreateTeamGameState(game);

            mocks.ReplayAll();

            service.CloseGame(game);

            mocks.VerifyAll();

            Assert.AreEqual(GameStates.Cloused, game.GameState);
            Assert.IsNull(team.TeamGameState);
            Assert.IsNull(team.Game);
        }
        public void StopGame(Game game, DateTime recalcTime)
        {
            Check.Require(game.GameState == GameStates.Started, String.Format(
                    "Невозможно остановить игру, когда она находится в режиме {0}.",
                    Enum.GetName(typeof(GameStates), game.GameState))
                );

            // Останавливаем демона
            if (gameDemon != null)
            {
                gameDemon.Stop();
                gameDemon = null;
            }

            // Останавливаем игру
            game.GameState = GameStates.Finished;

            // Для каждой команды устанавливаем время окончания игры
            foreach (Team team in game.Teams)
            {
                if (team.TeamGameState != null && team.TeamGameState.GameDoneTime == null)
                {
                    if (team.TeamGameState.ActiveTaskState != null)
                    {
                        taskService.CloseTaskForTeam(team.TeamGameState.ActiveTaskState, TeamTaskStateFlag.Overtime, recalcTime);
                    }

                    team.TeamGameState.GameDoneTime = recalcTime;
                }
            }
        }
 public ITaskDispatcher CrearteDispatcher(Game game)
 {
     // В зависимости от типа игры нужно создать конкретный диспетчер задач.
     return new RuleTaskDispatcher();
 }
        public void StartGame(Game game)
        {
            Check.Require(game.GameState == GameStates.Startup, String.Format(
                    "Невозможно перевести игру в рабочий режим, когда она находится в режиме {0}.",
                    Enum.GetName(typeof(GameStates), game.GameState))
                );

            // Переводим игру в рабочий режим
            game.GameState = GameStates.Started;

            // Запускаем демона
            GetGameDemon(game.Id).Start();
        }
        public void StartupGame(Game game)
        {
            Check.Require(game.GameState == GameStates.Planned, String.Format(
                    "Невозможно перевести игру в предстартовый режим, когда она находится в режиме {0}.",
                    Enum.GetName(typeof(GameStates), game.GameState))
                );

            Check.Require(!gameRepository.GetAll().Any(
                g =>
                g.GameState == GameStates.Startup || g.GameState == GameStates.Started ||
                g.GameState == GameStates.Finished),
                "Невозможно запустить игру, т.к. уже существует запущенная игра."
                );

            // Для каждой команды, имеющей игроков, создаем игровое состояние
            foreach (Team team in game.Teams.Where(t => t.Users.Count > 0))
            {
                team.TeamGameState = new TeamGameState { Team = team, Game = game };
                teamGameStateRepository.SaveOrUpdate(team.TeamGameState);
                team.TeamGameStates.Add(team.TeamGameState);
            }

            // Переводим игру в предстартовый режим
            game.GameState = GameStates.Startup;
        }
        public void Setup()
        {
            mocks = new MockRepository();

            taskRepository = mocks.DynamicMock<IRepository<Task>>();
            teamTaskStateRepository = mocks.DynamicMock<IRepository<TeamTaskState>>();
            acceptedCodeRepository = mocks.DynamicMock<IRepository<AcceptedCode>>();
            acceptedBadCodeRepository = mocks.DynamicMock<IRepository<AcceptedBadCode>>();
            acceptedTipRepository = mocks.DynamicMock<IRepository<AcceptedTip>>();
            dispatcherFactory = mocks.DynamicMock<ITaskDispatcherFactory>();
            taskDispatcher = mocks.DynamicMock<ITaskDispatcher>();

            game = new Game { Name = "Game" };
            team = new Team { Name = "Team" };
        }
        /// <summary>
        /// Сброс состояния игры.
        /// Переводит игру в начальное состояние, 
        /// удаляет состояния команд.
        /// </summary>
        /// <param name="game"></param>
        public void ResetGame(Game game)
        {
            Check.Require(
                game.GameState == GameStates.Startup ||
                game.GameState == GameStates.Finished ||
                game.GameState == GameStates.Cloused ||
                game.GameState == GameStates.Planned,
                String.Format(
                    "Невозможно сбросить состояние игры, когда она находится в режиме {0}.",
                    Enum.GetName(typeof(GameStates), game.GameState))
                );

            game.GameState = GameStates.Planned;

            // Для каждой команды сбрасываем игровое состояние
            foreach (Team team in game.Teams)
            {
                team.TeamGameState = null;
            }
        }
        public ActionResult Edit(Game game)
        {
            Game gameToUpdate = gameRepository.Get(game.Id);
            TransferFormValuesTo(gameToUpdate, game);

            if (ViewData.ModelState.IsValid && game.IsValid())
            {
                Message = "Игра успешно изменена.";
                return this.RedirectToAction(c => c.Index());
            }

            gameRepository.DbContext.RollbackTransaction();
            return View(game);
        }
 private void TransferFormValuesTo(Game gameToUpdate, Game gameFromForm)
 {
     gameToUpdate.Name = gameFromForm.Name;
     gameToUpdate.GameDate = gameFromForm.GameDate;
     gameToUpdate.Description = gameFromForm.Description;
     gameToUpdate.TotalTime = gameFromForm.TotalTime;
 }
        public void CloseGame(Game game)
        {
            Check.Require(game.GameState == GameStates.Finished,
                String.Format(
                    "Невозможно закрыть игру, когда она находится в режиме {0}.",
                    Enum.GetName(typeof(GameStates), game.GameState))
                );

            game.GameState = GameStates.Cloused;
            gameRepository.SaveOrUpdate(game);

            // Для каждой команды сбрасываем игровое состояние
            foreach (Team team in game.Teams)
            {
                team.TeamGameState = null;
                team.Game = null;
                teamRepository.SaveOrUpdate(team);
            }

            teamGameStateRepository.DbContext.CommitChanges();
        }
        /// <summary>
        /// Creates a valid, transient Game; typical of something retrieved back from a form submission
        /// </summary>
        private static Game CreateTransientGame()
        {
            Game game = new Game() {
                Name = "New gme",
                GameDate = DateTime.Parse("01.01.1975 0:00:00"),
                Description = "Game Description",
                TotalTime = 9*60,
                TimePerTask = 90,
                TimePerTip = 30
            };

            return game;
        }
        public void CanStopGameTest()
        {
            IGameDemon gameDemon = mocks.DynamicMock<IGameDemon>();
            GameService gameService = new GameService(gameRepository,
                teamRepository, teamGameStateRepository, taskService, gameDemon);

            Game game = new Game { GameState = GameStates.Started };
            Team team = new Team()
                .CreateTeamGameState(game)
                .AssignTask(task1, new DateTime(2010, 1, 1, 21, 0, 0));

            Expect.Call(gameDemon.Stop);
            Expect.Call(gameRepository.SaveOrUpdate(game));
            Expect.Call(
                () => taskService.CloseTaskForTeam(
                    team.TeamGameState.ActiveTaskState,
                    TeamTaskStateFlag.Overtime));
            Expect.Call(teamRepository.SaveOrUpdate(team));
            Expect.Call(teamGameStateRepository.SaveOrUpdate(team.TeamGameState));
            Expect.Call(teamGameStateRepository.DbContext).Return(dbContext);

            mocks.ReplayAll();

            gameService.StopGame(game);

            mocks.VerifyAll();

            Assert.AreEqual(GameStates.Finished, game.GameState);
        }
        public void CanStartGameTest()
        {
            IGameDemon gameDemon = mocks.DynamicMock<IGameDemon>();
            GameService gameService = new GameService(gameRepository,
                teamRepository, teamGameStateRepository, taskService, gameDemon);

            Game game = new Game { GameState = GameStates.Startup };

            Expect.Call(gameRepository.SaveOrUpdate(game));
            Expect.Call(gameDemon.Start);

            mocks.ReplayAll();

            gameService.StartGame(game);

            mocks.VerifyAll();

            Assert.AreEqual(GameStates.Started, game.GameState);
        }
 private void TransferFormValuesTo(Game gameToUpdate, Game gameFromForm)
 {
     gameToUpdate.Name = gameFromForm.Name;
     gameToUpdate.GameDate = gameFromForm.GameDate;
     gameToUpdate.Description = gameFromForm.Description;
     gameToUpdate.TotalTime = gameFromForm.TotalTime;
     gameToUpdate.TimePerTask = gameFromForm.TimePerTask;
     gameToUpdate.TimePerTip = gameFromForm.TimePerTip;
     gameToUpdate.PrefixMainCode = gameFromForm.PrefixMainCode;
     gameToUpdate.PrefixBonusCode = gameFromForm.PrefixBonusCode;
 }
        /// <summary>
        /// Создает новый класс Game, взамен созданного прокси класса hnibernat-ом.
        /// Пока по невыясненным причинам Newtonsoft.Json отказывается сериализовать 
        /// прокси класс созданный hnibernatе. Причем клас Task сериализуется без проблем.
        /// </summary>
        private Game FixGameNHProxyForJson(Game game)
        {
            Game bagGame = new Game
            {
               Name = game.Name,
               Description = game.Description,
               GameDate = game.GameDate,
               TotalTime = game.TotalTime,
               TimePerTask = game.TimePerTask,
               TimePerTip = game.TimePerTip,
               PrefixMainCode = game.PrefixMainCode,
               PrefixBonusCode = game.PrefixBonusCode,
               GameState = game.GameState

            };

            bagGame.SetIdTo(game.Id);
            return bagGame;
        }
        public AjaxFormResult SaveGame(Game game)
        {
            var response = new AjaxFormResult();
            try
            {
                Game gameToUpdate = gameRepository.Get(game.Id);
                TransferGameFormValuesTo(gameToUpdate, game);

                if (ViewData.ModelState.IsValid && game.IsValid())
                {
                    response.Success = true;
                }
                else
                {
                    response.Success = false;
                    response.Errors.Add(new FieldError("Game_ID", "The ID field is required"));
                }
            }
            catch (Exception e)
            {
                response.Success = false;
                response.ExtraParams["msg"] = e.ToString();
            }
            return response;
        }
        public void CanStartupTest()
        {
            Expect.Call(gameRepository.GetAll()).Return(new List<Game> { new Game() });
            Expect.Call(teamGameStateRepository.DbContext).Return(dbContext);

            mocks.ReplayAll();

            Game game = new Game();
            var team = new Team { Game = game };
            team.Users.Add(new User { Team = team });
            game.Teams.Add(team);
            service.StartupGame(game);

            mocks.VerifyAll();

            Assert.AreEqual(GameStates.Startup, game.GameState);
            Assert.IsNotNull(team.TeamGameState);
            Assert.AreEqual(1, team.TeamGameStates.Count);
        }
 public EncounterViewData WithGame(Game game)
 {
     Game = game;
     return this;
 }
        public void SetUp()
        {
            mocks = new MockRepository();
            gameService = mocks.DynamicMock<IGameService>();
            repository = mocks.DynamicMock<IRepository<Game>>();
            service = new RecalcGameStateService(1, repository, gameService);

            game = new Game
            {
                GameState = GameStates.Started,
                GameDate = new DateTime(2010, 1, 1, 21, 0, 0),
                TotalTime = 540,
                TimePerTask = 90,
                TimePerTip = 30
            };

            task1 = new Task();
            task1Tip0 = new Tip { SuspendTime = 0, Task = task1 };
            task1Tip1 = new Tip { SuspendTime = 30, Task = task1 };
            task1Tip2 = new Tip { SuspendTime = 60, Task = task1 };
            task1.Tips.Add(task1Tip0);
            task1.Tips.Add(task1Tip1);
            task1.Tips.Add(task1Tip2);
            task1.Codes.Add(new Code { Name = "1", Task = task1 });

            game.Tasks.Add(task1);
        }
        public void SetUp()
        {
            mocks = new MockRepository();
            gameService = mocks.DynamicMock<IGameService>();
            repository = mocks.DynamicMock<IRepository<Game>>();
            dbContext = mocks.DynamicMock<IDbContext>();
            service = new RecalcGameStateService(1, repository, gameService);

            game = new Game
            {
                GameState = GameStates.Started,
                GameDate = new DateTime(2010, 1, 1, 21, 0, 0),
                TotalTime = 540,
                TimePerTask = 90,
                TimePerTip = 30
            };

            task1 = new Task();
            task1Tip0 = new Tip { SuspendTime = 0, Task = task1 };
            task1Tip1 = new Tip { SuspendTime = 30, Task = task1 };
            task1Tip2 = new Tip { SuspendTime = 60, Task = task1 };
            task1.Tips.Add(task1Tip0);
            task1.Tips.Add(task1Tip1);
            task1.Tips.Add(task1Tip2);
            task1.Codes.Add(new Code { Name = "1", Task = task1 });

            game.Tasks.Add(task1);

            Expect.Call(repository.DbContext).Return(dbContext).Repeat.Any();
            Expect.Call(dbContext.BeginTransaction()).Repeat.Any();
            Expect.Call(() => dbContext.CommitTransaction()).Repeat.Any();
        }