public void CanAssignNewTaskTest()
        {
            var newTask = new Task { Name = "New task" };
            newTask.Tips.Add(new Tip { Name = "Tip 0", SuspendTime = 0 });
            newTask.Tips.Add(new Tip { Name = "Tip 1", SuspendTime = 30 });
            newTask.Tips.Add(new Tip { Name = "Tip 2", SuspendTime = 60 });

            Expect.Call(dispatcherFactory.CrearteDispatcher(game)).Return(taskDispatcher);
            Expect.Call(taskDispatcher.GetNextTaskForTeam(null, null, null)).Return(newTask).IgnoreArguments();
            Expect.Call(teamTaskStateRepository.SaveOrUpdate(null)).IgnoreArguments();
            Expect.Call(acceptedTipRepository.SaveOrUpdate(null)).IgnoreArguments();

            mocks.ReplayAll();

            var service = new TaskService(taskRepository, teamTaskStateRepository, acceptedCodeRepository,
                                          acceptedBadCodeRepository, acceptedTipRepository, dispatcherFactory);

            var teamGameState = new TeamGameState{ Game = game, Team = team };
            var oldTask = new Task { Name = "Old task" };

            var recalcDateTime = new DateTime(2011, 1, 1, 21, 0, 0);
            service.AssignNewTask(teamGameState, oldTask, recalcDateTime);

            mocks.VerifyAll();

            Assert.AreEqual(newTask, teamGameState.ActiveTaskState.Task);
            Assert.AreEqual(recalcDateTime, teamGameState.ActiveTaskState.TaskStartTime);
            Assert.AreEqual(1, teamGameState.ActiveTaskState.AcceptedTips.Count());
            Assert.AreEqual(0, teamGameState.AcceptedTasks.Count());
        }
Example #2
0
        public AjaxStoreResult GetTask(int gameId, int taskId)
        {
            Task task = taskRepository.Get(taskId);

            return(new AjaxStoreResult(new List <Task> {
                task
            }, 1));
        }
Example #3
0
        public void CanCompareTasks() {
            Task instance = new Task();
			instance.Name = "New task";

            Task instanceToCompareTo = new Task();
			instanceToCompareTo.Name = "New task";

			instance.ShouldEqual(instanceToCompareTo);
        }
        /// <summary>
        /// Creates a valid, transient Task; typical of something retrieved back from a form submission
        /// </summary>
        public static Task CreateTransientTask()
        {
            Task task = new Task() {
                Name = "New task",
                Game = new Game() { Name = "New game" }
            };

            EntityIdSetter.SetIdOf<int>(task.Game, 1);
            return task;
        }
 public static Team AssignTask(this Team team, Task task, DateTime taskStartTime)
 {
     var tts = new TeamTaskState
     {
         Task = task,
         TaskStartTime = taskStartTime,
         TeamGameState = team.TeamGameState
     };
     team.TeamGameState.ActiveTaskState = tts;
     return team;
 }
Example #6
0
        public AjaxStoreResult CreateTask()
        {
            Task task = new Task();
            Tip  tip  = new Tip {
                Name = "Здесь должен быть текст задания...", SuspendTime = 0, Task = task
            };

            task.Tips.Add(tip);
            return(new AjaxStoreResult(new List <Task> {
                task
            }, 1));
        }
Example #7
0
        public AjaxStoreResult CreateTip(int taskId)
        {
            Tip tip = new Tip()
            {
                Name = "Новая подсказка"
            };
            Task task = taskRepository.Get(taskId);

            tip.SuspendTime = task.Tips.Count * task.Game.TimePerTip;
            return(new AjaxStoreResult(new List <Tip> {
                tip
            }, 1));
        }
Example #8
0
        public AjaxResult DeleteTask(int id)
        {
            var response = new AjaxResult();

            try
            {
                Task task = taskRepository.Get(id);
                response.ExtraParamsResponse.Add(new Parameter("id", task.Id.ToString()));
                taskRepository.Delete(task);
            }
            catch (Exception e)
            {
                response.ErrorMessage = e.Message;
            }
            return(response);
        }
Example #9
0
        public ActionResult SaveCode(int taskId)
        {
            AjaxStoreResult ajaxStoreResult = new AjaxStoreResult(StoreResponseFormat.Save);

            try
            {
                StoreDataHandler     dataHandler = new StoreDataHandler(HttpContext.Request["data"]);
                ChangeRecords <Code> obj         = dataHandler.ObjectData <Code>();

                Task task = taskRepository.Get(taskId);
                foreach (Code code in obj.Updated)
                {
                    code.Task = task;
                    if (code.IsValid())
                    {
                        codeRepository.SaveOrUpdate(code);
                    }
                }

                foreach (Code code in obj.Created)
                {
                    code.Task = task;
                    if (code.IsValid())
                    {
                        codeRepository.SaveOrUpdate(code);
                    }
                }

                foreach (Code code in obj.Deleted)
                {
                    code.Task = task;
                    if (code.IsValid())
                    {
                        codeRepository.Delete(code);
                    }
                }
                codeRepository.DbContext.CommitChanges();
                ajaxStoreResult.SaveResponse.Success = true;
            }
            catch (Exception e)
            {
                ajaxStoreResult.SaveResponse.Success      = false;
                ajaxStoreResult.SaveResponse.ErrorMessage = e.Message;
                codeRepository.DbContext.RollbackTransaction();
            }
            return(ajaxStoreResult);
        }
Example #10
0
        public AjaxFormResult SaveTask([TaskBinder(Fetch = true)] Task task)
        {
            var response = new AjaxFormResult();

            try
            {
                if (ViewData.ModelState.IsValid && task.IsValid())
                {
                    if (task.Id == 0)
                    {
                        task.Game = User.Game;
                        Tip tip = new Tip {
                            Name = "Здесь должен быть текст задания...", SuspendTime = 0, Task = task
                        };
                        task.Tips.Add(tip);
                        tipRepository.SaveOrUpdate(tip);

                        response.ExtraParams["newID"] = task.Id.ToString();
                        response.ExtraParams["name"]  = task.Name;
                    }
                    response.Success = true;
                }
                else
                {
                    response.Success = false;
                    response.Errors.Add(new FieldError("Task_ID", "The CustomerID field is required"));

                    taskRepository.DbContext.RollbackTransaction();
                }
            }
            catch (Exception e)
            {
                response.Success            = false;
                response.ExtraParams["msg"] = e.ToString();
            }
            return(response);
        }
Example #11
0
 /// <summary>
 /// Назначение нового задания команде.
 /// </summary>
 public void AssignNewTask(TeamGameState teamGameState, Task oldTask, DateTime dateTimeNow)
 {
     taskService.AssignNewTask(teamGameState, oldTask, dateTimeNow);
 }
        public void ShouldNotOvertime4NeedForSpeedTaskTest()
        {
            var needForSpeedTask = new Task { TaskType = TaskTypes.NeedForSpeed };
            needForSpeedTask.Tips.Add(new Tip { SuspendTime = 60 + 10, Task = needForSpeedTask });
            needForSpeedTask.Codes.Add(new Code { Name = "1", Task = needForSpeedTask });

            var team = new Team()
                .CreateTeamGameState(game)
                .AssignTask(needForSpeedTask, new DateTime(2010, 1, 1, 21, 0, 0));
            team.TeamGameState.ActiveTaskState.AccelerationTaskStartTime = new DateTime(2010, 1, 1, 22, 00, 0);

            Expect.Call(repository.Get(1)).Return(game);
            DoNotExpect.Call(() => gameService.CloseTaskForTeam(
                team.TeamGameState.ActiveTaskState,
                TeamTaskStateFlag.Overtime));
            DoNotExpect.Call(() => gameService.AssignNewTask(team.TeamGameState, task1));

            mocks.ReplayAll();

            service.RecalcGameState(new DateTime(2010, 1, 1, 22, 15, 0));

            mocks.VerifyAll();
        }
        public void SouldNotAssignTip4RussianRouletteTaskTest()
        {
            var russianRouletteTask = new Task { TaskType = TaskTypes.RussianRoulette };
            russianRouletteTask.Tips.Add(new Tip { SuspendTime = 0, Task = russianRouletteTask });
            russianRouletteTask.Tips.Add(new Tip { SuspendTime = 30, Task = russianRouletteTask });
            russianRouletteTask.Tips.Add(new Tip { SuspendTime = 60, Task = russianRouletteTask });

            var team = new Team()
                .CreateTeamGameState(game)
                .AssignTask(russianRouletteTask, new DateTime(2010, 1, 1, 21, 0, 0));

            Expect.Call(repository.Get(1))
                .Return(game);

            DoNotExpect.Call(() => gameService.AssignNewTaskTip(null, null));

            mocks.ReplayAll();

            service.RecalcGameState(new DateTime(2010, 1, 1, 21, 0, 0));

            mocks.VerifyAll();

            Assert.AreEqual(0, team.TeamGameState.ActiveTaskState.AcceptedTips.Count());
        }
 public EncounterViewData WithTask(Task task)
 {
     Task = task;
     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 CanEnsureTaskCreationIsValid()
        {
            Task taskFromForm = new Task();
            ViewResult result = controller.Create(taskFromForm).AssertViewRendered();

            result.ViewData.Model.ShouldNotBeNull();
            result.ViewData.Model.ShouldBeOfType(typeof(TasksController.TaskFormViewModel));
        }
        /// <summary>
        /// Вычисление приоритета для задания.
        /// </summary>
        /// <param name="task">Задание для которого нужно вычислить приоритет.</param>
        /// <param name="oldTask">Предыдущее задание выполненное командой.</param>
        /// <param name="executingTasks">Задания выполняемые в данных момент другими командами.</param>
        /// <param name="excludeExecutedTasks">Задания выполненные командами, которые помечены опцией "Анти-слив".</param>
        /// <returns>Приоритет задания.</returns>
        private static int GetTaskPoints(Task task, Task oldTask, Dictionary<Task, int> executingTasks, List<Task> excludeExecutedTasks, TeamGameState teamGameState)
        {
            int taskPoints = 1000;

            //--------------------------------------------------------------------
            // Если задание связано с предыдущим выданным, то +MaxPoints )))
            if (task.AfterTask != null)
            {
                if (oldTask == null)
                    return MinPoints; // Не выдавать

                if (task.AfterTask == oldTask)
                {
                    var oldTeamTaskState = teamGameState.AcceptedTasks.First(x => x.Task == oldTask);
                    if (task.GiveTaskAfter == GiveTaskAfter.Strictly)
                    {
                        if (oldTeamTaskState.State == (int)TeamTaskStateFlag.Success)
                        {
                            return MaxPoints; // Выдать незамедлительно
                        }
                        return MinPoints; // Не выдавать
                    }
                    if (task.GiveTaskAfter == GiveTaskAfter.StrictlyOrFinaly)
                    {
                        if (oldTeamTaskState.State == (int)TeamTaskStateFlag.Success)
                        {
                            return MaxPoints; // Выдать незамедлительно
                        }
                        return -1000; // Выдать с наименьшим приоритетом

                    }
                    if (task.GiveTaskAfter == GiveTaskAfter.InAnyCase)
                    {
                        return MaxPoints; // Выдать незамедлительно
                    }
                }
                return MinPoints;
            }

            //--------------------------------------------------------------------
            // Если задание типа Челлендж, то +500
            if (task.StreetChallendge)
            {
                taskPoints += 500;
                return taskPoints;
            }

            //--------------------------------------------------------------------
            // Если задание c агентами выполняется другой командой, то -500
            // Задание с агентами одновременно может выполняться только одной командой
            if (task.Agents && executingTasks.ContainsKey(task))
                taskPoints -= 500;

            //--------------------------------------------------------------------
            // Если задание выполнено командами, которые помечены опцией "Анти-слив", то -700
            if (excludeExecutedTasks.Contains(task))
                taskPoints -= 700;

            //--------------------------------------------------------------------
            // Если задание выполняет другая команда, то -50
            if (executingTasks.ContainsKey(task))
                taskPoints -= 50 * executingTasks[task];

            //--------------------------------------------------------------------
            // Если предыдущее задание команды входит в список блокировки по предшествованию, то -400
            if (task.NotAfterTasks.Contains(oldTask))
                taskPoints -= 400;

            //--------------------------------------------------------------------
            // Если хотя бы одно задание из списка блокировки по одновременности выполняется, то -200
            if (task.NotOneTimeTasks.Intersect(executingTasks.Keys).Count() > 0)
                taskPoints -= 200;

            //--------------------------------------------------------------------
            // Если задание содержит коды со сложностью "+500", то +30
            foreach (Code code in task.Codes)
            {
                if (code.Danger == "+500")
                {
                    taskPoints += 30;
                    break;
                }
            }

            //--------------------------------------------------------------------
            // Повышаем приоритет для заданий с бонусами
            // П = П + 10 * (число бонусных кодов в задании)
            int bonusCodes = 0;
            foreach (Code code in task.Codes)
            {
                bonusCodes += code.IsBonus ? 1 : 0;
            }
            taskPoints += bonusCodes * 10;

            //--------------------------------------------------------------------
            // Применяем собственный приоритет задачи
            taskPoints += task.Priority;

            return taskPoints;
        }
        public void CanFinishTeamGameTest()
        {
            Expect.Call(dispatcherFactory.CrearteDispatcher(game)).Return(taskDispatcher);
            Expect.Call(taskDispatcher.GetNextTaskForTeam(null, null, null)).Return(null).IgnoreArguments();

            mocks.ReplayAll();

            var service = new TaskService(taskRepository, teamTaskStateRepository, acceptedCodeRepository,
                                          acceptedBadCodeRepository, acceptedTipRepository, dispatcherFactory);

            var teamGameState = new TeamGameState { Game = game, Team = team };
            var oldTask = new Task { Name = "Old task" };

            var recalcDateTime = new DateTime(2011, 1, 1, 21, 0, 0);
            service.AssignNewTask(teamGameState, oldTask, recalcDateTime);

            mocks.VerifyAll();

            Assert.IsNull(teamGameState.ActiveTaskState);
            Assert.AreEqual(recalcDateTime, teamGameState.GameDoneTime);
            Assert.AreEqual(0, teamGameState.AcceptedTasks.Count());
        }
        public Task GetNextTaskForTeam(IRepository<Task> taskRepository, TeamGameState teamGameState, Task oldTask)
        {
            // Получаем все незаблокированные задания для текущей игры
            var gameTasks = taskRepository.GetAll()
                .Where(t => t.Game == teamGameState.Game && !t.Locked);

            // Формируем список номеров групп заданий, с которыми команда уже познакомилась
            List<int> executedGroupTags = new List<int>();
            foreach (TeamTaskState acceptedTask in teamGameState.AcceptedTasks.Where(x => x.Task.GroupTag != 0))
            {
                if (!executedGroupTags.Contains(acceptedTask.Task.GroupTag))
                    executedGroupTags.Add(acceptedTask.Task.GroupTag);
            }

            // Получаем доступные (невыполненные) для команды задания
            List<Task> accessibleTasks = new List<Task>();
            foreach (Task task in gameTasks)
            {
                // Если задание не получено
                // и задание не входит ни в одну "засвеченную" группу,
                // и не запрещена выдача задания текущей команде,
                // то добавляем задание в список
                if (!teamGameState.AcceptedTasks.Any(x => x.Task == task) &&
                    !executedGroupTags.Contains(task.GroupTag) &&
                    !task.NotForTeams.Contains(teamGameState.Team))
                    accessibleTasks.Add(task);
            }

            // Формируем список выполняемых заданий другими командами
            Dictionary<Task, int> executingTasks = new Dictionary<Task, int>();
            foreach (Team team in teamGameState.Game.Teams)
            {
                if (team.TeamGameState != null && team.TeamGameState.ActiveTaskState != null)
                {
                    Task task = team.TeamGameState.ActiveTaskState.Task;
                    if (executingTasks.ContainsKey(task))
                    {
                        executingTasks[task] = executingTasks[task] + 1;
                    }
                    else
                    {
                        executingTasks.Add(task, 1);
                    }
                }
            }

            // Получаем задания выполненные командами, которые помечены опцией "Анти-слив"
            var excludeExecutedTasks = new List<Task>();
            foreach (Team team in teamGameState.Team.PreventTasksAfterTeams)
            {
                if (team.TeamGameState != null)
                {
                    foreach (var task in team.TeamGameState.AcceptedTasks)
                    {
                        if (!excludeExecutedTasks.Contains(task.Task))
                            excludeExecutedTasks.Add(task.Task);
                    }
                }
            }

            List<Task> tasksWithMaxPoints = new List<Task>();
            int maxPoints = 0;

            // Рассчитываем приоритет для каждого задания
            // и отбираем задания с максимальным приоритетом
            foreach (Task task in accessibleTasks)
            {
                int taskPoints = GetTaskPoints(task, oldTask, executingTasks, excludeExecutedTasks, teamGameState);

                // Не выдавать задание вообще
                if (taskPoints == MinPoints)
                    continue;

                if (taskPoints > maxPoints)
                {
                    maxPoints = taskPoints;
                    tasksWithMaxPoints.Clear();
                    tasksWithMaxPoints.Add(task);
                }
                else if (taskPoints == maxPoints)
                {
                    tasksWithMaxPoints.Add(task);
                }
            }

            // Если заданий с одинаковым приоритетом несколько,
            // то берем произвольное
            if (tasksWithMaxPoints.Count > 1)
            {
                // Выбираем новое задание из доступных с максимальным приоритетом
                Task newTask = null;
                Random rnd = new Random();
                int indx = rnd.Next(tasksWithMaxPoints.Count);
                int i = 0;
                foreach (Task task in tasksWithMaxPoints)
                {
                    if (i == indx)
                        newTask = task;
                    i++;
                }

                return newTask;
            }
            return tasksWithMaxPoints.Count == 0 ? null : tasksWithMaxPoints.First();
        }
        public void CanNotAssignNewTaskTest()
        {
            var service = new TaskService(taskRepository, teamTaskStateRepository, acceptedCodeRepository,
                                          acceptedBadCodeRepository, acceptedTipRepository, dispatcherFactory);

            var oldTask = new Task { Name = "Old task" };
            var teamGameState = new TeamGameState { Game = game, Team = team, ActiveTaskState = new TeamTaskState { Task = oldTask } };

            service.AssignNewTask(teamGameState, oldTask, new DateTime(2011, 1, 1, 21, 0, 0));
        }
Example #21
0
        public void AssignNewTask(TeamGameState teamGameState, Task oldTask, DateTime recalcTime)
        {
            Check.Require(teamGameState.ActiveTaskState == null, "Невозможно назначить команде новую задачу, т.к. коменде уже назначена задача.");

            // Пытаемся получить следующее задание для команды
            Task newTask = dispatcherFactory.CrearteDispatcher(teamGameState.Game)
                .GetNextTaskForTeam(taskRepository, teamGameState, oldTask);

            // Если нет нового задания, то команда завершила игру
            if (newTask == null)
            {
                TeamFinishGame(teamGameState, recalcTime);
                return;
            }

            TeamTaskState teamTaskState = new TeamTaskState {
                    TaskStartTime = recalcTime,
                    TaskFinishTime = null,
                    State = (int) TeamTaskStateFlag.Execute,
                    TeamGameState = teamGameState,
                    Task = newTask,
                    NextTask = null
                };

            teamGameState.ActiveTaskState = teamTaskState;

            teamTaskStateRepository.SaveOrUpdate(teamTaskState);
            //Сразу же отправляем команде первую подсказку (т.е. текст задания)
            AssignNewTaskTip(teamTaskState, teamTaskState.Task.Tips.First(), recalcTime);
        }
 private void TransferFormValuesTo(Task taskToUpdate, Task taskFromForm)
 {
     taskToUpdate.Name = taskFromForm.Name;
     taskToUpdate.StreetChallendge = taskFromForm.StreetChallendge;
     taskToUpdate.Agents = taskFromForm.Agents;
     taskToUpdate.Locked = taskFromForm.Locked;
     taskToUpdate.TaskType = taskFromForm.TaskType;
     taskToUpdate.Priority = taskFromForm.Priority;
     taskToUpdate.GroupTag = taskFromForm.GroupTag;
     taskToUpdate.AfterTask = taskFromForm.AfterTask;
     taskToUpdate.GiveTaskAfter = taskFromForm.GiveTaskAfter;
 }
Example #23
0
 /// <summary>
 /// Назначение нового задания команде.
 /// </summary>
 public void AssignNewTask(TeamGameState teamGameState, Task oldTask)
 {
     taskService.AssignNewTask(teamGameState, oldTask);
 }
 public AjaxStoreResult CreateTask()
 {
     Task task = new Task();
     Tip tip = new Tip { Name = "Здесь должен быть текст задания...", SuspendTime = 0, Task = task };
     task.Tips.Add(tip);
     return new AjaxStoreResult(new List<Task> { task }, 1);
 }
        public void SetUp()
        {
            mocks = new MockRepository();
            taskService = mocks.DynamicMock<ITaskService>();
            gameRepository = mocks.DynamicMock<IRepository<Game>>();
            teamRepository = mocks.DynamicMock<IRepository<Team>>();
            teamGameStateRepository = mocks.DynamicMock<IRepository<TeamGameState>>();
            dbContext = mocks.DynamicMock<IDbContext>();

            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 });

            service = new GameService(gameRepository, teamRepository, teamGameStateRepository, taskService);
        }
        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();
        }