Esempio n. 1
0
        public ActionResults Build(EmptyLand emptyLand, Player player)
        {
            if (emptyLand.OwnerId != player.Id)
            {
                return(ActionResults.Failed("You do not own this building."));
            }

            // Check for materials
            var results = ActionResults.Empty;

            foreach (var buildMaterial in this.BuildMaterials)
            {
                var playerItem = player.Inventory.Items.FirstOrDefault(item => item.ItemType.GetType() == buildMaterial.ItemType.GetType());
                if (playerItem == null || playerItem.Quantity < buildMaterial.Quantity)
                {
                    results.AddResult(ActionResult.Failed($"You need {buildMaterial.Quantity} {buildMaterial.ItemType.Name} to build a farm."));
                }
            }

            if (results.HasResults)
            {
                return(results);
            }

            DomainEvents.Raise(new FarmBuiltEvent(player, this));
            return(ActionResults.Success("You built a farm. Time to start planting."));
        }
Esempio n. 2
0
        public ActionResults Work(Player player)
        {
            if (!player.IsAlive)
            {
                return(ActionResults.Failed("You're dead."));
            }
            if (this.Inventory?.Items?.FirstOrDefault()?.Quantity == 0)
            {
                return(ActionResults.Failed("All the mature trees are gone. Wait for them to grow."));
            }
            if (player.Energy < this.EnergyRequirement)
            {
                return(ActionResults.Failed("You don't have enough energy to work in the forest."));
            }

            var workResults = ActionResults.Success("You gather some wood in the forest.");

            player.ReduceEnergy(this.EnergyRequirement);
            player.EarnMoney(this.Wage);

            player.Inventory.AddItem(1, new BasicBuildingMaterial());
            ReduceTreeCount();

            CheckForInjury(player, workResults);

            DomainEvents.Raise(new PlayerWorkedEvent(player, this));
            DomainEvents.Raise(new ForestWorkedEvent(this));

            return(workResults);
        }
        public IActionResult Post([FromBody] BuildFarmPostModel model)
        {
            var player   = ObjectFactory.Container.GetInstance <GetPlayerService>().GetByUserId(User.Identity.GetId());
            var building = ObjectFactory.Container.GetInstance <GetBuildingService>().GetBuildingByTownIdBuildingId(player.CurrentTown, model.BuildingId);

            var results = ActionResults.Empty;

            if (building is EmptyLand)
            {
                var farm = new Farm(
                    building.Id,
                    building.TownId,
                    building.XCoordinate,
                    building.YCoordinate,
                    player.DisplayName + "'s Farm",
                    ((EmptyLand)building).OwnerId,
                    ((EmptyLand)building).IsForSale,
                    ((EmptyLand)building).Price,
                    ((EmptyLand)building).ModifiedDate,
                    ((EmptyLand)building).CreatedDate);
                results = farm.Build((EmptyLand)building, player);
            }
            else
            {
                results = ActionResults.Failed("You can only build new buildings on empty land.");
            }

            return(Ok(results));
        }
Esempio n. 4
0
        public IActionResult CreateArt(int userId, string artTitle)
        {
            int artId = mainService.CreateArt(userId, artTitle);

            return(ActionResults.Json(new {
                artId = artId
            }));
        }
Esempio n. 5
0
        public IActionResult DisconnectDevice(int userId)
        {
            mainService.DisconnectDevice(userId);

            return(ActionResults.Json(new {
                message = "Device Disconnected."
            }));
        }
Esempio n. 6
0
        public IActionResult SaveSettings([FromBody] SettingsChangedMessage message)
        {
            mainService.PushMessage(message);

            return(ActionResults.Json(new {
                message = "Pushed Message."
            }));
        }
Esempio n. 7
0
        public IActionResult SaveTextMessage([FromBody] SaveTextMessage message)
        {
            mainService.PushMessage(message);

            return(ActionResults.Json(new {
                message = "Pushed Message."
            }));
        }
Esempio n. 8
0
 ///<summary>
 ///<param name="w">卡牌权重</param>
 ///<param name="who">卡牌诉说者ID</param>
 ///<param name="content">卡牌诉说内容</param>
 ///<param name="timeLimited">是否有倒计时</param>
 ///<param name="final">操作后的结果</param>
 ///</summary>
 public Card(int w, int who, string content, bool timeLimited = false, ActionResults final = null)
 {
     weight         = w;
     speakerID      = who;
     speakerContent = content;
     isTimeLimited  = timeLimited;
     results        = final;
 }
Esempio n. 9
0
        public IActionResult PushMessage(int userId, [FromBody] Message message)
        {
            mainService.PushMessage(message);

            return(ActionResults.Json(new {
                message = "Pushed Message."
            }));
        }
Esempio n. 10
0
        public IActionResult ConnectWithoutHololens()
        {
            int userId = mainService.ConnectWithoutHoloLens();

            return(ActionResults.Json(new {
                userId = userId
            }));
        }
Esempio n. 11
0
        public async Task <IActionResult> AddProduct([HttpTrigger(AuthorizationLevel.Function, "post", Route = "products")] HttpRequest request)
        {
            var productModel = await request.DeserializeBody <ProductEditableModel>();

            var newProduct = new Product(productModel.Name, productModel.Price);

            repository.AddProduct(newProduct);

            return(ActionResults.Created($"/api/products/{newProduct.Id}", newProduct));
        }
        public async Task <IActionResult> AddReview([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "reviews/{productId}")] HttpRequest request, string productId)
        {
            var reviewModel = await request.DeserializeBody <ReviewRequestModel>();

            var review = new Review(reviewModel.NumberOfStarts, reviewModel.Description);

            repository.AddProductReview(productId, review);

            return(ActionResults.Created());
        }
Esempio n. 13
0
 public IActionResult GetMessages(int userId)
 {
     if (!mainService.CheckUserExists(userId))
     {
         return(ActionResults.Json(new {
             error = "No such user!"
         }, 400));
     }
     return(ActionResults.Json(new
     {
         messages = JsonConvert.SerializeObject(mainService.GetMessages(userId))
     }));
 }
Esempio n. 14
0
        internal ActionResults ActionFromName(string name)
        {
            var existingAction = (from r in results where r.Name == name select r).FirstOrDefault();

            if (null == existingAction)
            {
                existingAction = new ActionResults {
                    Name = name
                };
                results.Add(existingAction);
            }
            return(existingAction);
        }
Esempio n. 15
0
        public async Task <IActionResult> Create([FromBody] CreateCategoryDto createCategoryDto)
        {
            AuthorizationResult authorizationResult =
                await _authorizationService.AuthorizeAsync(User, PolicyConstants.ManageCategoryRolePolicy);

            if (!authorizationResult.Succeeded)
            {
                return(ActionResults.UnauthorizedResult(User.Identity.IsAuthenticated));
            }

            string categoryId = await _mediator.Send(new CreateCategoryCommand(createCategoryDto));

            return(Created($"{HttpContext.Request.GetDisplayUrl()}/{categoryId}", null));
        }
Esempio n. 16
0
        public async Task <IActionResult> Delete([FromRoute] string categoryId)
        {
            AuthorizationResult authorizationResult =
                await _authorizationService.AuthorizeAsync(User, PolicyConstants.ManageCategoryRolePolicy);

            if (!authorizationResult.Succeeded)
            {
                return(ActionResults.UnauthorizedResult(User.Identity.IsAuthenticated));
            }

            await _mediator.Send(new DeleteCategoryCommand(categoryId));

            return(Ok());
        }
Esempio n. 17
0
        private void CheckForInjury(Player player, ActionResults workResults)
        {
            var injuryRoll = new Random().Next(1, 100);

            // 1% chance of minor injury
            if (injuryRoll <= 1)
            {
                player.ReduceHealth(5);
                workResults.AddResult(ActionResult.Warning("You had a minor injury in the forest."));
            }
            // 95% chance of no injury
            else
            {
            }
        }
        public async Task <IActionResult> AddPromotion([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "promotions")] HttpRequest request)
        {
            var promotionRequest = await request.DeserializeBody <AddPromotionRequestModel>();

            var promotionRequestValidation = promotionRequest.Validate();

            if (promotionRequestValidation.Any())
            {
                return(new BadRequestObjectResult(promotionRequestValidation));
            }

            repository.AddPromotion(new Promotion(promotionRequest));

            return(ActionResults.Created());
        }
Esempio n. 19
0
        public async Task <IActionResult> Delete([FromRoute] string commentId)
        {
            Comment comment = await _mediator.Send(new GetCommentEntityQuery(commentId));

            AuthorizationResult authorizationResult =
                await _authorizationService.AuthorizeAsync(User, comment, PolicyConstants.UpdateCommentRolePolicy);

            if (!authorizationResult.Succeeded)
            {
                return(ActionResults.UnauthorizedResult(User.Identity.IsAuthenticated));
            }

            await _mediator.Send(new DeleteCommentCommand(comment));

            return(Ok());
        }
Esempio n. 20
0
        public async Task <IActionResult> Update([FromRoute] string categoryId,
                                                 [FromBody] UpdateCategoryDto updateCategoryDto)
        {
            AuthorizationResult authorizationResult =
                await _authorizationService.AuthorizeAsync(User, PolicyConstants.ManageCategoryRolePolicy);

            if (!authorizationResult.Succeeded)
            {
                return(ActionResults.UnauthorizedResult(User.Identity.IsAuthenticated));
            }

            return(Ok(new Response <CategoryViewModel>
            {
                Data = await _mediator.Send(new UpdateCategoryCommand(categoryId, updateCategoryDto)),
            }));
        }
Esempio n. 21
0
        public IActionResult ConnectWithHololens(string pin)
        {
            int userId = mainService.ConnectWithHoloLens(pin);

            if (userId != 0)
            {
                return(ActionResults.Json(new {
                    userId = userId
                }, 200));
            }
            else
            {
                return(ActionResults.Json(new {
                    error = "Pin does not match with any device"
                }, 400));
            }
        }
Esempio n. 22
0
        /// <summary>
        /// calculates the reward for an action.
        /// </summary>
        /// <param name="resultedState"></param>
        /// <returns> reward of the action as int</returns>
        private int ActionReward(POGame.POGame resultedState)
        {
            ActionResults results = new ActionResults(this.CurrentPoGame, resultedState);

            if (resultedState.CurrentOpponent.Hero.Health <= 0)
            {
                return(100);                                                                                                                            //make sure to choose the action that actually ends the game :P
            }
            else
            {
                return
                    (results.DamageDealt * Weights[Weight.Damage] +
                     results.MonstersKilled * Weights[Weight.MonstersKilled] +
                     results.HealthDiff * Weights[Weight.HealthDifference] +
                     results.MonstersPlaced * Weights[Weight.MonstersPlaced]);
            }
        }
Esempio n. 23
0
        public async Task <IActionResult> AddModerator([FromRoute] string communityId,
                                                       [FromBody] AddModeratorDto addModeratorDto)
        {
            Community community = await _mediator.Send(new GetCommunityEntityQuery(communityId));

            AuthorizationResult authorizationResult =
                await _authorizationService.AuthorizeAsync(User, community, PolicyConstants.AddModeratorRolePolicy);

            if (!authorizationResult.Succeeded)
            {
                return(ActionResults.UnauthorizedResult(User.Identity.IsAuthenticated));
            }

            await _mediator.Send(new AddModeratorCommand(community, addModeratorDto));

            return(Ok());
        }
Esempio n. 24
0
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            trvSummary.Nodes.Clear();
            CodeBase codeBase = e.Result as CodeBase;

            if (codeBase != null)
            {
                _codeBase = codeBase;
                ShowParseResultsInTree();
            }
            ActionResults actionResults = e.Result as ActionResults;

            if (actionResults != null)
            {
                ShowHitsInTree(actionResults);
            }
            ShowRunnerStatus();
        }
Esempio n. 25
0
        public async Task <IActionResult> Update([FromRoute] string commentId,
                                                 [FromBody] UpdateCommentDto updateCommentDto)
        {
            Comment comment = await _mediator.Send(new GetCommentEntityQuery(commentId));

            AuthorizationResult authorizationResult =
                await _authorizationService.AuthorizeAsync(User, comment, PolicyConstants.UpdateCommentRolePolicy);

            if (!authorizationResult.Succeeded)
            {
                return(ActionResults.UnauthorizedResult(User.Identity.IsAuthenticated));
            }

            return(Ok(new Response <CommentViewModel>
            {
                Data = await _mediator.Send(new UpdateCommentCommand(comment, updateCommentDto)),
            }));
        }
Esempio n. 26
0
 /// <summary>
 /// accept all changes include sub-items
 /// </summary>
 /// <param name="acceptAll"></param>
 public void AcceptChanges(bool acceptAll)
 {
     base.AcceptChanges();
     if (acceptAll)
     {
         // step
         Arguments?.AcceptChanges();
         // executions
         PreActionResults?.Select(x =>
         {
             x.AcceptChanges(acceptAll);
             return(x);
         }).ToList();
         ActionResults?.Select(x =>
         {
             x.AcceptChanges(acceptAll);
             return(x);
         }).ToList();
     }
 }
Esempio n. 27
0
        public ActionResults Purchase(Player purchasingPlayer)
        {
            if (!this.IsForSale)
            {
                return(ActionResults.Failed("This land is not for sale."));
            }
            if (purchasingPlayer.CurrentTown != this.TownId)
            {
                return(ActionResults.Failed("You must be in the same town as the land to purchase it."));
            }
            if (purchasingPlayer.MoneyOnHand < this.Price)
            {
                return(ActionResults.Failed("You do not have enough money to purchase this land."));
            }

            var results = ActionResults.Success($"You've puchased the empty land for ${this.Price}. Time to start building!");

            DomainEvents.Raise <BuildingPurchasedEvent>(new BuildingPurchasedEvent(this, purchasingPlayer));
            return(results);
        }
Esempio n. 28
0
        public ActionResults Work(Player player)
        {
            if (!player.IsAlive)
            {
                return(ActionResults.Failed("You're dead."));
            }
            if (player.Energy < this.EnergyRequirement)
            {
                return(ActionResults.Failed("You don't have enough energy to work in the mines."));
            }

            var workResults = ActionResults.Success($"You earn ${this.Wage} working in the mines.");

            player.ReduceEnergy(this.EnergyRequirement);
            player.EarnMoney(this.Wage);
            player.ReduceHappiness(this.HappinessEffect);

            CheckForInjury(player, workResults);

            DomainEvents.Raise <PlayerWorkedEvent>(new PlayerWorkedEvent(player, this));

            return(workResults);
        }
Esempio n. 29
0
        private void ShowHitsInTree(ActionResults actionResults)
        {
            trvSummary.BeginUpdate();
            try
            {
                string   summaryText = actionResults.Action.Name + ": " + actionResults.Hits.Count + " hit(s)";
                TreeNode summaryNode = new TreeNode(summaryText);
                trvSummary.Nodes.Add(summaryNode);

                List <Hit> sortedHits = SortHits(actionResults.Hits);
                foreach (Hit hit in sortedHits)
                {
                    TreeNode treeNode = CreateNodeForLocation(hit.Location);
                    treeNode.Text = Path.GetFileName(hit.Location.FileName) +
                                    ":" + hit.Location.Offset + ": " + hit.Description;
                    summaryNode.Nodes.Add(treeNode);
                }
                trvSummary.ExpandAll();
            }
            finally
            {
                trvSummary.EndUpdate();
            }
        }
 internal ActionResults ActionFromName(string name)
 {
     var existingAction = (from r in results where r.Name == name select r).FirstOrDefault();
     if (null == existingAction)
     {
         existingAction = new ActionResults { Name = name };
         results.Add(existingAction);
     }
     return existingAction;
 }
Esempio n. 31
0
        private void ShowHitsInTree(ActionResults actionResults)
        {
            trvSummary.BeginUpdate();
            try
            {
                string summaryText = actionResults.Action.Name + ": " + actionResults.Hits.Count + " hit(s)";
                TreeNode summaryNode = new TreeNode(summaryText);
                trvSummary.Nodes.Add(summaryNode);

                List<Hit> sortedHits = SortHits(actionResults.Hits);
                foreach (Hit hit in sortedHits)
                {
                    TreeNode treeNode = CreateNodeForLocation(hit.Location);
                    treeNode.Text = Path.GetFileName(hit.Location.FileName) +
                        ":" + hit.Location.Offset + ": " + hit.Description;
                    summaryNode.Nodes.Add(treeNode);
                }
                trvSummary.ExpandAll();
            }
            finally
            {
                trvSummary.EndUpdate();
            }
        }
Esempio n. 32
0
 public IActionResult GetMediaItems(int userId)
 {
     return(ActionResults.Json(mainService.GetMediaItems(userId, true)));
 }