コード例 #1
0
        public async Task <RecipeResult> GetRecipe(Guid dishGuid)
        {
            RecipeResult result = new RecipeResult();

            try
            {
                GetRecipeResult output = await _eatClient.GetRecipeAsync(dishGuid);

                if (output.ResultCode == -1)
                {
                    throw new Exception();
                }
                result.Recipe             = new Classes.DishRecipe();
                result.Recipe.CookingTime = output.Recipe.CookingTime;
                result.Recipe.Description = output.Recipe.Description;
                result.Recipe.DishGuid    = output.Recipe.DishGuid;
                result.Recipe.PictureUrl  = output.Recipe.PictureUrl;
                result.Recipe.Title       = output.Recipe.Title;
                result.Recipe.Recipe      = output.Recipe.Recipe.Select(r => new Classes.Recipes
                {
                    RecipeGuid = r.RecipeGuid,
                    Order      = r.Order,
                    PictureUrl = r?.PictureUrl,
                    Text       = r?.Text,
                    Title      = r?.Title
                }).OrderBy(r => r.Order).ToList() ?? new List <Classes.Recipes>();
            }
            catch (Exception ex)
            {
                SetException(result, ex);
            }
            return(result);
        }
コード例 #2
0
        public RecipeResult GetResult(string executionId)
        {
            var query =
                from record in _recipeStepResultRecordRepository.Table
                where record.ExecutionId == executionId
                select record;

            var records = query.ToArray();

            if (!records.Any())
            {
                throw new Exception(String.Format("No records were found in the database for recipe execution ID {0}.", executionId));
            }

            var result = new RecipeResult()
            {
                ExecutionId = executionId,
                Steps       =
                    from record in records
                    select new RecipeStepResult {
                    RecipeName   = record.RecipeName,
                    StepName     = record.StepName,
                    IsCompleted  = record.IsCompleted,
                    IsSuccessful = record.IsSuccessful,
                    ErrorMessage = record.ErrorMessage
                }
            };

            return(result);
        }
コード例 #3
0
ファイル: Get.cs プロジェクト: frasermcarthur/RecipeJournal
        public override async Task <ActionResult <RecipeResult> > HandleAsync(int id, CancellationToken cancellationToken = default)
        {
            var result = new RecipeResult
            {
                Title = "Rice Pudding"
            };

            return(await Task.FromResult(Ok(result)));
        }
コード例 #4
0
        public async Task CreateAsync(RecipeResult recipeResult)
        {
            //_session.Save(recipeResult);
            await RecipeSet.AddAsync(new Recipe()
            {
                ExecutionId = recipeResult.ExecutionId, JsonValue = JsonConvert.SerializeObject(recipeResult)
            });

            await SaveChanges();
        }
コード例 #5
0
        public async Task DeleteAsync(RecipeResult recipeResult)
        {
            //_session.Delete(recipeResult);
            var model = await RecipeSet.SingleOrDefaultAsync(c => c.Id == recipeResult.Id);

            if (model != null)
            {
                RecipeSet.Remove(model);
                await SaveChanges();
            }
        }
コード例 #6
0
        public async Task UpdateAsync(RecipeResult recipeResult)
        {
            var model = await RecipeSet.SingleOrDefaultAsync(c => c.ExecutionId == recipeResult.ExecutionId);

            if (model != null)
            {
                //model.ExecutionId = recipeResult.ExecutionId;
                model.JsonValue = JsonConvert.SerializeObject(recipeResult);
                RecipeSet.Update(model);
                await SaveChanges();
            }
        }
コード例 #7
0
        public void DecreaseScore()
        {
            if (Result == RecipeResult.PERFECT)
            {
                Result = RecipeResult.NICE;
            }
            else if (Result == RecipeResult.NICE)
            {
                Result = RecipeResult.BAD;
            }

            CurrentScore -= Malus;
        }
コード例 #8
0
        public async Task <string> ExecuteAsync(string executionId, RecipeDescriptor recipeDescriptor)
        {
            await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.RecipeExecutingAsync(executionId, recipeDescriptor));

            try
            {
                var parsersForFileExtension = _recipeOptions
                                              .RecipeFileExtensions
                                              .Where(rfx => Path.GetExtension(rfx.Key) == Path.GetExtension(recipeDescriptor.RecipeFileInfo.PhysicalPath));

                using (var stream = recipeDescriptor.RecipeFileInfo.CreateReadStream())
                {
                    RecipeResult result = new RecipeResult {
                        ExecutionId = executionId
                    };
                    List <RecipeStepResult> stepResults = new List <RecipeStepResult>();

                    foreach (var parserForFileExtension in parsersForFileExtension)
                    {
                        var recipeParser = _recipeParsers.First(x => x.GetType() == parserForFileExtension.Value);

                        await recipeParser.ProcessRecipeAsync(stream, (recipe, recipeStep) =>
                        {
                            // TODO, create Result prior to run
                            stepResults.Add(new RecipeStepResult
                            {
                                ExecutionId = executionId,
                                RecipeName  = recipeDescriptor.Name,
                                StepId      = recipeStep.Id,
                                StepName    = recipeStep.Name
                            });
                            return(Task.CompletedTask);
                        });
                    }

                    result.Steps = stepResults;
                    await _recipeStore.UpdateAsync(result);
                }

                using (var stream = recipeDescriptor.RecipeFileInfo.CreateReadStream())
                {
                    foreach (var parserForFileExtension in parsersForFileExtension)
                    {
                        var recipeParser = _recipeParsers.First(x => x.GetType() == parserForFileExtension.Value);

                        await recipeParser.ProcessRecipeAsync(stream, async (recipe, recipeStep) =>
                        {
                            var shellContext = _orchardHost.GetOrCreateShellContext(_shellSettings);
                            using (var scope = shellContext.CreateServiceScope())
                            {
                                if (!shellContext.IsActivated)
                                {
                                    var eventBus = scope.ServiceProvider.GetService <IEventBus>();
                                    await eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatingAsync());
                                    await eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatedAsync());

                                    shellContext.IsActivated = true;
                                }

                                var recipeStepExecutor = scope.ServiceProvider.GetRequiredService <IRecipeStepExecutor>();

                                if (_applicationLifetime.ApplicationStopping.IsCancellationRequested)
                                {
                                    throw new OrchardException(T["Recipe cancelled, application is restarting"]);
                                }

                                await recipeStepExecutor.ExecuteAsync(executionId, recipeStep);
                            }

                            // The recipe execution might have invalidated the shell by enabling new features,
                            // so the deferred tasks need to run on an updated shell context if necessary.
                            shellContext = _orchardHost.GetOrCreateShellContext(_shellSettings);
                            using (var scope = shellContext.CreateServiceScope())
                            {
                                var deferredTaskEngine = scope.ServiceProvider.GetService <IDeferredTaskEngine>();

                                // The recipe might have added some deferred tasks to process
                                if (deferredTaskEngine != null && deferredTaskEngine.HasPendingTasks)
                                {
                                    var taskContext = new DeferredTaskContext(scope.ServiceProvider);
                                    await deferredTaskEngine.ExecuteTasksAsync(taskContext);
                                }
                            }
                        });
                    }
                }

                await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.RecipeExecutedAsync(executionId, recipeDescriptor));

                return(executionId);
            }
            catch (Exception)
            {
                await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.ExecutionFailedAsync(executionId, recipeDescriptor));

                throw;
            }
        }
コード例 #9
0
        public static void RegisterRecipes()
        {
            var coppertools = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERTOOLS.Name, 1);
            var clothing    = new InventoryItem(ColonyBuiltIn.ItemTypes.LINEN.Name, 1);

            var copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 5);
            var copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 5);

            var bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 5);
            var bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 5);

            var ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 5);
            var iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONWROUGHT.Name, 5);

            var steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 5);
            var steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 5);

            List <InventoryItem> items;

            foreach (var a in ArmorLookup.Where(a => a.Value is ArmorMetadata metadata))
            {
                items = new List <InventoryItem>();

                // ----------------------------------------
                // Copper
                // ----------------------------------------

                if (a.Value.name.Contains("Copper") && a.Value.Slot == ArmorSlot.Helm)
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 3);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 2);
                    items.AddRange(new[] { copper, copperParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Copper") && a.Value.Slot == ArmorSlot.Chest)
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 5);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 5);
                    items.AddRange(new[] { copper, copperParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Copper") && a.Value.Slot == ArmorSlot.Gloves)
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 2);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 2);
                    items.AddRange(new[] { copper, copperParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Copper") && a.Value.Slot == ArmorSlot.Legs)
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 3);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 3);
                    items.AddRange(new[] { copper, copperParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Copper") && a.Value.Slot == ArmorSlot.Boots)
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 2);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 2);
                    items.AddRange(new[] { copper, copperParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Copper") && a.Value.Slot == ArmorSlot.Shield)
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 2);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 2);
                    items.AddRange(new[] { copper, copperParts, coppertools, clothing });
                }

                // ----------------------------------------
                // Bronze
                // ----------------------------------------

                if (a.Value.name.Contains("Bronze") && a.Value.Slot == ArmorSlot.Helm)
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 3);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 2);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, clothing });
                }

                if (a.Value.name.Contains("Bronze") && a.Value.Slot == ArmorSlot.Chest)
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 5);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 5);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, clothing });
                }

                if (a.Value.name.Contains("Bronze") && a.Value.Slot == ArmorSlot.Gloves)
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 2);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 2);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, clothing });
                }

                if (a.Value.name.Contains("Bronze") && a.Value.Slot == ArmorSlot.Legs)
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 3);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 3);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, clothing });
                }

                if (a.Value.name.Contains("Bronze") && a.Value.Slot == ArmorSlot.Boots)
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 2);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 2);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, clothing });
                }

                if (a.Value.name.Contains("Bronze") && a.Value.Slot == ArmorSlot.Shield)
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 2);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 2);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, clothing });
                }

                // ----------------------------------------
                // Iron
                // ----------------------------------------

                if (a.Value.name.Contains("Iron") && a.Value.Slot == ArmorSlot.Helm)
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 3);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 2);
                    items.AddRange(new[] { iron, ironRivet, coppertools, clothing });
                }

                if (a.Value.name.Contains("Iron") && a.Value.Slot == ArmorSlot.Chest)
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 5);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 5);
                    items.AddRange(new[] { iron, ironRivet, coppertools, clothing });
                }

                if (a.Value.name.Contains("Iron") && a.Value.Slot == ArmorSlot.Gloves)
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 2);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 2);
                    items.AddRange(new[] { iron, ironRivet, coppertools, clothing });
                }

                if (a.Value.name.Contains("Iron") && a.Value.Slot == ArmorSlot.Legs)
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 3);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 3);
                    items.AddRange(new[] { iron, ironRivet, coppertools, clothing });
                }

                if (a.Value.name.Contains("Iron") && a.Value.Slot == ArmorSlot.Boots)
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 2);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 2);
                    items.AddRange(new[] { iron, ironRivet, coppertools, clothing });
                }

                if (a.Value.name.Contains("Iron") && a.Value.Slot == ArmorSlot.Shield)
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 2);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 2);
                    items.AddRange(new[] { iron, ironRivet, coppertools, clothing });
                }

                // ----------------------------------------
                // Steel
                // ----------------------------------------

                if (a.Value.name.Contains("Steel") && a.Value.Slot == ArmorSlot.Helm)
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 3);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 2);
                    items.AddRange(new[] { steel, steelParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Steel") && a.Value.Slot == ArmorSlot.Chest)
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 5);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 5);
                    items.AddRange(new[] { steel, steelParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Steel") && a.Value.Slot == ArmorSlot.Gloves)
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 2);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 2);
                    items.AddRange(new[] { steel, steelParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Steel") && a.Value.Slot == ArmorSlot.Legs)
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 3);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 3);
                    items.AddRange(new[] { steel, steelParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Steel") && a.Value.Slot == ArmorSlot.Boots)
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 2);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 2);
                    items.AddRange(new[] { steel, steelParts, coppertools, clothing });
                }

                if (a.Value.name.Contains("Steel") && a.Value.Slot == ArmorSlot.Shield)
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 2);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 2);
                    items.AddRange(new[] { steel, steelParts, coppertools, clothing });
                }


                var metaData = (ArmorMetadata)a.Value;
                var invItem  = new RecipeResult(metaData.ItemType.ItemIndex);
                var recipe   = new Recipe(metaData.ItemType.name, items, invItem, 5, 0, -100);

                ServerManager.RecipeStorage.AddLimitTypeRecipe(ColonyBuiltIn.NpcTypes.METALSMITHJOB, recipe);
                ServerManager.RecipeStorage.AddScienceRequirement(recipe);
            }
        }
コード例 #10
0
ファイル: RecipeExecutor.cs プロジェクト: bpun/Orchard2
        public async Task <string> ExecuteAsync(string executionId, RecipeDescriptor recipeDescriptor, object environment)
        {
            await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.RecipeExecutingAsync(executionId, recipeDescriptor));

            try
            {
                _environmentMethodProvider = new ParametersMethodProvider(environment);

                var result = new RecipeResult {
                    ExecutionId = executionId
                };

                await _recipeStore.CreateAsync(result);

                using (StreamReader file = File.OpenText(recipeDescriptor.RecipeFileInfo.PhysicalPath))
                {
                    using (var reader = new JsonTextReader(file))
                    {
                        // Go to Steps, then iterate.
                        while (reader.Read())
                        {
                            if (reader.Path == "variables")
                            {
                                reader.Read();

                                var variables = JObject.Load(reader);
                                _variablesMethodProvider = new VariablesMethodProvider(variables);
                            }

                            if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray)
                            {
                                while (reader.Read() && reader.Depth > 1)
                                {
                                    if (reader.Depth == 2)
                                    {
                                        var child = JObject.Load(reader);

                                        var recipeStep = new RecipeExecutionContext
                                        {
                                            Name        = child.Value <string>("name"),
                                            Step        = child,
                                            ExecutionId = executionId,
                                            Environment = environment
                                        };

                                        var stepResult = new RecipeStepResult {
                                            StepName = recipeStep.Name
                                        };
                                        result.Steps.Add(stepResult);
                                        await _recipeStore.UpdateAsync(result);

                                        ExceptionDispatchInfo capturedException = null;
                                        try
                                        {
                                            await ExecuteStepAsync(recipeStep);

                                            stepResult.IsSuccessful = true;
                                        }
                                        catch (Exception e)
                                        {
                                            stepResult.IsSuccessful = false;
                                            stepResult.ErrorMessage = e.ToString();

                                            // Because we can't do some async processing the in catch or finally
                                            // blocks, we store the exception to throw it later.

                                            capturedException = ExceptionDispatchInfo.Capture(e);
                                        }

                                        stepResult.IsCompleted = true;
                                        await _recipeStore.UpdateAsync(result);

                                        if (stepResult.IsSuccessful == false)
                                        {
                                            capturedException.Throw();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.RecipeExecutedAsync(executionId, recipeDescriptor));

                return(executionId);
            }
            catch (Exception)
            {
                await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.ExecutionFailedAsync(executionId, recipeDescriptor));

                throw;
            }
        }
コード例 #11
0
        public async Task <string> ExecuteAsync(string executionId, RecipeDescriptor recipeDescriptor, object environment, CancellationToken cancellationToken)
        {
            await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.RecipeExecutingAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger);

            try
            {
                _environmentMethodProvider   = new ParametersMethodProvider(environment);
                _configurationMethodProvider = new ConfigurationMethodProvider(_shellSettings.ShellConfiguration);

                var result = new RecipeResult {
                    ExecutionId = executionId
                };

                using (var stream = recipeDescriptor.RecipeFileInfo.CreateReadStream())
                {
                    using (var file = new StreamReader(stream))
                    {
                        using (var reader = new JsonTextReader(file))
                        {
                            // Go to Steps, then iterate.
                            while (await reader.ReadAsync())
                            {
                                if (reader.Path == "variables")
                                {
                                    await reader.ReadAsync();

                                    var variables = await JObject.LoadAsync(reader);

                                    _variablesMethodProvider = new VariablesMethodProvider(variables);
                                }

                                if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray)
                                {
                                    while (await reader.ReadAsync() && reader.Depth > 1)
                                    {
                                        if (reader.Depth == 2)
                                        {
                                            var child = await JObject.LoadAsync(reader);

                                            var recipeStep = new RecipeExecutionContext
                                            {
                                                Name             = child.Value <string>("name"),
                                                Step             = child,
                                                ExecutionId      = executionId,
                                                Environment      = environment,
                                                RecipeDescriptor = recipeDescriptor
                                            };

                                            if (cancellationToken.IsCancellationRequested)
                                            {
                                                _logger.LogError("Recipe interrupted by cancellation token.");
                                                return(null);
                                            }

                                            var stepResult = new RecipeStepResult {
                                                StepName = recipeStep.Name
                                            };
                                            result.Steps.Add(stepResult);

                                            ExceptionDispatchInfo capturedException = null;
                                            try
                                            {
                                                await ExecuteStepAsync(recipeStep);

                                                stepResult.IsSuccessful = true;
                                            }
                                            catch (Exception e)
                                            {
                                                stepResult.IsSuccessful = false;
                                                stepResult.ErrorMessage = e.ToString();

                                                // Because we can't do some async processing the in catch or finally
                                                // blocks, we store the exception to throw it later.

                                                capturedException = ExceptionDispatchInfo.Capture(e);
                                            }

                                            stepResult.IsCompleted = true;

                                            if (stepResult.IsSuccessful == false)
                                            {
                                                capturedException.Throw();
                                            }

                                            if (recipeStep.InnerRecipes != null)
                                            {
                                                foreach (var descriptor in recipeStep.InnerRecipes)
                                                {
                                                    var innerExecutionId = Guid.NewGuid().ToString();
                                                    await ExecuteAsync(innerExecutionId, descriptor, environment, cancellationToken);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.RecipeExecutedAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger);

                return(executionId);
            }
            catch (Exception)
            {
                await _recipeEventHandlers.InvokeAsync((handler, executionId, recipeDescriptor) => handler.ExecutionFailedAsync(executionId, recipeDescriptor), executionId, recipeDescriptor, _logger);

                throw;
            }
        }
コード例 #12
0
        public void OnNPCAtJob(BlockJobInstance jobInstance, ref NPCBase.NPCState state)
        {
            MachineJobInstance instance = (MachineJobInstance)jobInstance;

            NPCLookAtJobBlock(jobInstance);
            state.JobIsDone = true;
            if (instance.SelectedRecipe != null)
            {
                if (instance.SelectedRecipeCount > 0 && instance.SelectedRecipe.IsPossible(instance.Owner, state.Inventory))
                {
                    if (PowerManager.Operate(instance.Position))
                    {
                        state.Inventory.Remove(instance.SelectedRecipe.Requirements);
                        craftingResults.Clear();
                        craftingResults.Add(instance.SelectedRecipe.Results);
                        ModLoader.Callbacks.OnNPCCraftedRecipe.Invoke(instance, instance.SelectedRecipe, craftingResults);
                        if (craftingResults.Count > 0)
                        {
                            state.Inventory.Add(craftingResults);
                            RecipeResult toShow = RecipeResult.GetWeightedRandom(craftingResults);
                            if (toShow.Amount > 0)
                            {
                                //Possible way for varied Crafting speeds?
                                //ItemTypes.GetType(toShow.AsItem.Type).CustomDataNode["craftspeed"].GetAs<float>();
                                state.SetIndicator(new IndicatorState(CraftingCooldown, toShow.Type));
                            }
                            else
                            {
                                state.SetCooldown(CraftingCooldown);
                            }
                            if (OnCraftedAudio != null)
                            {
                                AudioManager.SendAudio(instance.Position.Vector, OnCraftedAudio);
                            }
                        }
                        else
                        {
                            state.SetIndicator(new IndicatorState(CraftingCooldown, NPCIndicatorType.None));
                        }
                        if (!instance.IsCrafting)
                        {
                            instance.IsCrafting = true;
                            OnStartCrafting(instance);
                        }
                        state.JobIsDone = false;
                        instance.SelectedRecipeCount--;
                    }
                    else
                    {
                        state.SetIndicator(new IndicatorState(0.3f, ItemTypes.IndexLookup.GetIndex("electricity"), true, false));
                    }
                }
                else
                {
                    instance.SelectedRecipe      = null;
                    instance.SelectedRecipeCount = 0;
                    if (!state.Inventory.IsEmpty)
                    {
                        instance.ShouldTakeItems = true;
                    }
                    state.SetCooldown(0.1);
                    if (instance.IsCrafting)
                    {
                        instance.IsCrafting = false;
                        OnStopCrafting(instance);
                    }
                }
                return;
            }
            if (instance.IsCrafting)
            {
                instance.IsCrafting = false;
                OnStopCrafting(instance);
            }
            Recipes.Recipe.RecipeMatch recipeMatch = Recipes.Recipe.MatchRecipe(GetPossibleRecipes(instance), instance.Owner);
            switch (recipeMatch.MatchType)
            {
            case Recipes.Recipe.RecipeMatchType.FoundMissingRequirements:
            case Recipes.Recipe.RecipeMatchType.AllDone:
            {
                if (!state.Inventory.IsEmpty)
                {
                    instance.ShouldTakeItems = true;
                    state.SetCooldown(0.3);
                    break;
                }
                state.JobIsDone = false;
                float cooldown = Pipliz.Random.NextFloat(8f, 16f);
                if (recipeMatch.MatchType == Recipes.Recipe.RecipeMatchType.AllDone)
                {
                    state.SetIndicator(new IndicatorState(cooldown, BuiltinBlocks.Indices.erroridle));
                }
                else
                {
                    state.SetIndicator(new IndicatorState(cooldown, recipeMatch.FoundRecipe.FindMissingType(instance.Owner.Stockpile), striked: true, green: false));
                }
                break;
            }

            case Recipes.Recipe.RecipeMatchType.FoundCraftable:
                instance.SelectedRecipe  = recipeMatch.FoundRecipe;
                instance.ShouldTakeItems = true;
                state.SetCooldown(0.3);
                break;

            default:
                Assert.IsTrue(condition: false, "Unexpected RecipeMatchType: " + recipeMatch.MatchType);
                break;
            }
        }
コード例 #13
0
        public void PerformGoal(ref NPCBase.NPCState state)
        {
            ThreadManager.AssertIsMainThread();
            state.JobIsDone = true;

            if (!FarmingJob.PositionSub.IsValid)
            {
                state.SetCooldown(8.0, 12.0);
            }
            else
            {
                BlockFarmAreaJobDefinition definition = (BlockFarmAreaJobDefinition)this.Definition;
                Vector3Int vector3Int = FarmingJob.BlockLocation.IsValid ? FarmingJob.BlockLocation : FarmingJob.PositionSub;
                FarmingJob.PositionSub = Vector3Int.invalidPos;
                ItemTypes.ItemType val1;
                if (!World.TryGetTypeAt(vector3Int, out val1))
                {
                    state.SetCooldown(8.0, 12.0);
                }
                else
                {
                    if (val1 == definition.PlacedBlockType)
                    {
                        RecipeMatch = Recipe.MatchRecipe(FarmingJob.Owner.RecipeData.GetAvailableRecipes(definition.NPCTypeString), FarmingJob.Owner, FarmingJob.Owner.RecipeData.GetRecipeGroup(FarmingJob.CraftingGroupID));
                        switch (RecipeMatch.MatchType)
                        {
                        case Recipe.RecipeMatchType.FoundCraftable:
                            Recipe foundRecipe = RecipeMatch.FoundRecipe;
                            if (FarmingJob.NPC.Inventory.TryRemove(foundRecipe.Requirements))
                            {
                                CraftingResults.Clear();

                                for (int index = 0; index < foundRecipe.Results.Count; ++index)
                                {
                                    CraftingResults.Add(foundRecipe.Results[index]);
                                }

                                ModLoader.Callbacks.OnNPCCraftedRecipe.Invoke(Job, foundRecipe, CraftingResults);
                                RecipeResult weightedRandom = RecipeResult.GetWeightedRandom(CraftingResults);
                                float        timeToShow     = definition.Cooldown * Pipliz.Random.NextFloat(0.9f, 1.1f);

                                if (weightedRandom.Amount > 0)
                                {
                                    state.SetIndicator(new IndicatorState(timeToShow, weightedRandom.Type));
                                }
                                else
                                {
                                    state.SetCooldown(timeToShow);
                                }

                                FarmingJob.NPC.Inventory.Add(CraftingResults);
                                ++FarmingJob.GatherCount;

                                if (FarmingJob.GatherCount < definition.MaxGathersPerRun)
                                {
                                    return;
                                }

                                FarmingJob.GatherCount = 0;
                                PutItemsInCrate(ref state);
                                return;
                            }
                            else
                            {
                                PandaJobFactory.SetActiveGoal(Job, new GetItemsFromCrateGoal(Job, FarmingJob.KeyLocation, this, foundRecipe.Requirements, this), ref state);
                                FarmingJob.NPC.Inventory.Add(foundRecipe.Requirements, RecipeMatch.FoundRecipeCount);
                            }
                            state.SetCooldown(0.4, 0.6);
                            return;

                        case Recipe.RecipeMatchType.FoundMissingRequirements:
                        case Recipe.RecipeMatchType.AllDone:
                            if (state.Inventory.IsEmpty)
                            {
                                state.JobIsDone = true;
                                float cooldown = definition.Cooldown;
                                if (RecipeMatch.MatchType == Recipe.RecipeMatchType.AllDone)
                                {
                                    state.SetIndicator(new IndicatorState(cooldown, BuiltinBlocks.Indices.erroridle));
                                }
                                else
                                {
                                    state.SetIndicator(new IndicatorState(cooldown, RecipeMatch.FoundRecipe.FindMissingType(FarmingJob.Owner.Stockpile), true, false));
                                }
                                FarmingJob.Owner.Stats.RecordNPCIdleSeconds(FarmingJob.NPCType, cooldown);
                                return;
                            }
                            PutItemsInCrate(ref state);
                            return;
                        }
                    }
                    if (val1 == BuiltinBlocks.Types.air)
                    {
                        ItemTypes.ItemType val2;
                        if (World.TryGetTypeAt(vector3Int.Add(0, -1, 0), out val2))
                        {
                            if (!definition.PlacedBlockType.RequiresFertileBelow || val2.IsFertile)
                            {
                                if (definition.RequiredBlockItem.Amount != 0 && Job.NPC.Colony.Stockpile.TryRemove(definition.RequiredBlockItem))
                                {
                                    state.SetCooldown(1.5, 2.5);
                                    PandaJobFactory.SetActiveGoal(Job, new GetItemsFromCrateGoal(Job, FarmingJob.KeyLocation, this, new[] { new StoredItem(definition.RequiredBlockItem) }, this), ref state);
                                    Job.NPC.Inventory.Add(definition.RequiredBlockItem);
                                }

                                if (definition.RequiredBlockItem.Amount == 0)
                                {
                                    ServerManager.TryChangeBlock(vector3Int, BuiltinBlocks.Types.air, definition.PlacedBlockType, Job.Owner, ESetBlockFlags.DefaultAudio);
                                    state.SetCooldown(1.5, 2.5);
                                    return;
                                }
                                state.SetIndicator(new IndicatorState(Pipliz.Random.NextFloat(8f, 14f), definition.RequiredBlockItem.Type, true, false));
                                return;
                            }
                        }
                        else
                        {
                            state.SetCooldown(8.0, 12.0);
                            return;
                        }
                    }
                    state.SetCooldown((double)Pipliz.Random.NextFloat(3f, 6f));
                }
            }
        }
コード例 #14
0
            public override void OnNPCAtJob(ref NPCBase.NPCState state)
            {
                OliveFarmerAreaJob def = (OliveFarmerAreaJob)definition;

                ThreadManager.AssertIsMainThread();
                state.JobIsDone = true;
                positionSub     = Vector3Int.invalidPos;
                if (!treeLocation.IsValid)                   // probably idling about
                {
                    state.SetCooldown(Random.NextFloat(8f, 16f));
                    return;
                }

                if (!World.TryGetTypeAt(treeLocation, out ushort type))
                {
                    state.SetCooldown(10.0);
                    return;
                }

                if (type == BuiltinBlocks.Indices.logtemperate)                   // gather olives
                {
                    var recipes = Owner.RecipeData.GetAvailableRecipes(def.NPCTypeString);
                    Recipe.RecipeMatch match = Recipe.MatchRecipe(recipes, Owner);
                    switch (match.MatchType)
                    {
                    case Recipe.RecipeMatchType.AllDone:
                    case Recipe.RecipeMatchType.FoundMissingRequirements:
                        if (state.Inventory.IsEmpty)
                        {
                            state.JobIsDone = true;
                            if (match.MatchType == Recipe.RecipeMatchType.AllDone)
                            {
                                state.SetIndicator(new Shared.IndicatorState(def.Cooldown, BuiltinBlocks.Indices.erroridle));
                            }
                            else
                            {
                                state.SetIndicator(new Shared.IndicatorState(def.Cooldown, match.FoundRecipe.FindMissingType(Owner.Stockpile), true, false));
                            }
                        }
                        else
                        {
                            shouldDumpInventory = true;
                        }
                        return;

                    case Recipe.RecipeMatchType.FoundCraftable:
                        var recipe = match.FoundRecipe;
                        if (Owner.Stockpile.TryRemove(recipe.Requirements))
                        {
                            // should always succeed, as the match above was succesfull
                            GatherResults.Clear();
                            for (int i = 0; i < recipe.Results.Count; i++)
                            {
                                GatherResults.Add(recipe.Results[i]);
                            }

                            ModLoader.Callbacks.OnNPCCraftedRecipe.Invoke(this, recipe, GatherResults);

                            RecipeResult toShow = RecipeResult.GetWeightedRandom(GatherResults);
                            if (toShow.Amount > 0)
                            {
                                state.SetIndicator(new Shared.IndicatorState(def.Cooldown, toShow.Type));
                            }
                            else
                            {
                                state.SetCooldown(def.Cooldown);
                            }

                            NPC.Inventory.Add(GatherResults);

                            GatheredCount++;
                            if (GatheredCount >= def.MaxGathersPerRun)
                            {
                                GatheredCount       = 0;
                                shouldDumpInventory = true;
                            }
                        }
                        return;
                    }
                }
                else if (type == 0)                     // maybe plant sapling?
                {
                    if (World.TryGetTypeAt(treeLocation.Add(0, -1, 0), out ItemTypes.ItemType typeBelow))
                    {
                        if (typeBelow.IsFertile)
                        {
                            ServerManager.TryChangeBlock(treeLocation, BuiltinBlocks.Types.air, BuiltinBlocks.Types.olivesapling, Owner, ESetBlockFlags.DefaultAudio);
                            state.SetCooldown(2.0);
                            return;
                        }
                    }
                    else
                    {
                        state.SetCooldown(10.0);
                        return;
                    }
                }
                else
                {
                    // very likely it's a sapling, so idle about
                }

                // something unexpected or idling
                state.SetCooldown(Random.NextFloat(4f, 8f));
                return;
            }
コード例 #15
0
ファイル: RecipeExecutor.cs プロジェクト: LongBaoLee/Orchard2
        public async Task <string> ExecuteAsync(string executionId, RecipeDescriptor recipeDescriptor)
        {
            await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.RecipeExecutingAsync(executionId, recipeDescriptor));

            try
            {
                RecipeResult result = new RecipeResult {
                    ExecutionId = executionId
                };
                List <RecipeStepResult> stepResults = new List <RecipeStepResult>();

                using (StreamReader file = File.OpenText(recipeDescriptor.RecipeFileInfo.PhysicalPath))
                {
                    using (var reader = new JsonTextReader(file))
                    {
                        VariablesMethodProvider variablesMethodProvider = null;

                        // Go to Steps, then iterate.
                        while (reader.Read())
                        {
                            if (reader.Path == "variables")
                            {
                                reader.Read();

                                var variables = JObject.Load(reader);
                                variablesMethodProvider = new VariablesMethodProvider(variables);
                            }

                            if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray)
                            {
                                int stepId = 0;
                                while (reader.Read() && reader.Depth > 1)
                                {
                                    if (reader.Depth == 2)
                                    {
                                        var child = JToken.Load(reader);

                                        var recipeStep = new RecipeStepDescriptor
                                        {
                                            Id   = (stepId++).ToString(),
                                            Name = child.Value <string>("name"),
                                            Step = child
                                        };

                                        var shellContext = _orchardHost.GetOrCreateShellContext(_shellSettings);
                                        using (var scope = shellContext.CreateServiceScope())
                                        {
                                            if (!shellContext.IsActivated)
                                            {
                                                var eventBus = scope.ServiceProvider.GetService <IEventBus>();
                                                await eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatingAsync());

                                                await eventBus.NotifyAsync <IOrchardShellEvents>(x => x.ActivatedAsync());

                                                shellContext.IsActivated = true;
                                            }

                                            var recipeStepExecutor = scope.ServiceProvider.GetRequiredService <IRecipeStepExecutor>();
                                            var scriptingManager   = scope.ServiceProvider.GetRequiredService <IScriptingManager>();

                                            if (variablesMethodProvider != null)
                                            {
                                                variablesMethodProvider.ScriptingManager = scriptingManager;
                                                scriptingManager.GlobalMethodProviders.Add(variablesMethodProvider);
                                            }

                                            if (_applicationLifetime.ApplicationStopping.IsCancellationRequested)
                                            {
                                                throw new OrchardException(T["Recipe cancelled, application is restarting"]);
                                            }

                                            EvaluateJsonTree(scriptingManager, recipeStep.Step);

                                            await recipeStepExecutor.ExecuteAsync(executionId, recipeStep);
                                        }

                                        // The recipe execution might have invalidated the shell by enabling new features,
                                        // so the deferred tasks need to run on an updated shell context if necessary.
                                        shellContext = _orchardHost.GetOrCreateShellContext(_shellSettings);
                                        using (var scope = shellContext.CreateServiceScope())
                                        {
                                            var recipeStepExecutor = scope.ServiceProvider.GetRequiredService <IRecipeStepExecutor>();

                                            var deferredTaskEngine = scope.ServiceProvider.GetService <IDeferredTaskEngine>();

                                            // The recipe might have added some deferred tasks to process
                                            if (deferredTaskEngine != null && deferredTaskEngine.HasPendingTasks)
                                            {
                                                var taskContext = new DeferredTaskContext(scope.ServiceProvider);
                                                await deferredTaskEngine.ExecuteTasksAsync(taskContext);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.RecipeExecutedAsync(executionId, recipeDescriptor));

                return(executionId);
            }
            catch (Exception)
            {
                await _eventBus.NotifyAsync <IRecipeEventHandler>(x => x.ExecutionFailedAsync(executionId, recipeDescriptor));

                throw;
            }
        }
コード例 #16
0
ファイル: Sword.cs プロジェクト: dgmiller1/Malient-Settlers
        public static void RegisterRecipes()
        {
            var coppertools = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERTOOLS.Name, 1);
            var planks      = new InventoryItem(ColonyBuiltIn.ItemTypes.PLANKS.Name, 1);

            var copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 5);
            var copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 5);

            var bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 5);
            var bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 5);

            var ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 5);
            var iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONWROUGHT.Name, 5);

            var steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 5);
            var steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 5);


            List <InventoryItem> items;

            foreach (var a in WeaponFactory.WeaponLookup.Where(wepKvp => wepKvp.Value is WeaponMetadata weaponMetadata))
            {
                items = new List <InventoryItem>();

                // ----------------------------------------
                // Copper
                // ----------------------------------------

                if (a.Value.name == "Copper Sword")
                {
                    copperParts = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPERPARTS.Name, 3);
                    copper      = new InventoryItem(ColonyBuiltIn.ItemTypes.COPPER.Name, 2);
                    items.AddRange(new[] { copper, copperParts, coppertools, planks });
                }

                // ----------------------------------------
                // Bronze
                // ----------------------------------------

                if (a.Value.name == "Bronze Sword")
                {
                    bronzePlate = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEPLATE.Name, 3);
                    bronze      = new InventoryItem(ColonyBuiltIn.ItemTypes.BRONZEINGOT.Name, 2);
                    items.AddRange(new[] { bronze, bronzePlate, coppertools, planks });
                }

                // ----------------------------------------
                // Iron
                // ----------------------------------------

                if (a.Value.name == "Iron Sword")
                {
                    ironRivet = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONRIVET.Name, 3);
                    iron      = new InventoryItem(ColonyBuiltIn.ItemTypes.IRONINGOT.Name, 2);
                    items.AddRange(new[] { iron, ironRivet, coppertools, planks });
                }

                // ----------------------------------------
                // Steel
                // ----------------------------------------

                if (a.Value.name == "Steel Sword")
                {
                    steelParts = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELPARTS.Name, 3);
                    steel      = new InventoryItem(ColonyBuiltIn.ItemTypes.STEELINGOT.Name, 2);
                    items.AddRange(new[] { steel, steelParts, coppertools, planks });
                }

                var metadata = a.Value as WeaponMetadata;
                var invItem  = new RecipeResult(metadata.ItemType.ItemIndex);
                var recipe   = new Recipe(metadata.ItemType.name, items, invItem, 5);

                ServerManager.RecipeStorage.AddLimitTypeRecipe(ColonyBuiltIn.NpcTypes.METALSMITHJOB, recipe);
                ServerManager.RecipeStorage.AddScienceRequirement(recipe);
            }
        }
コード例 #17
0
        private void AddRecipeResultAgents( TreeNode parent, RecipeResult recipeResult )
        {
            IEnumerable<AgentSlotInfo> infos = Db.GetAgentSlotInfosForRecipeResult( recipeResult );
             foreach ( AgentSlotInfo info in infos )
             {
            TreeNode child = parent.Nodes.Add( @"a. " + info.DisplayName );
            child.Tag = info;

            if ( info.IsSpecific )
            {
               AddRecipes( child, info.Items.First().Id, EntityTypes.Item );
            }
            else
            {
               string toolTipText = "Select individual agent:\n\n";
               ContextMenu menu = new ContextMenu();
               int index = 1;
               foreach ( Item item in info.Items )
               {
                  menu.MenuItems.Add( item.Name, ( sender, args ) =>
                     {
                        info.SpecificItem = item;
                        child.Text = @"a. " + item.Name;
                        child.Nodes.Clear();
                        AddRecipes( child, item.Id, EntityTypes.Item );
                        //child.ExpandAll();
                        BuildManifest();
                        ManifestTreeNodeThemes.Apply( child );
                     } );
                  toolTipText += string.Format( "{0} - {1}\n", index++, item.Name );
               }

               child.ContextMenu = menu;
               child.ToolTipText = toolTipText;
            }

            ManifestTreeNodeThemes.Apply( child );
             }

             ManifestTreeNodeThemes.Apply( parent );
        }
コード例 #18
0
        public virtual void PerformGoal(ref NPCBase.NPCState state)
        {
            CraftingJobInstance.NPC.LookAt(CraftingJobInstance.Position.Vector);
            RecipeSettingsGroup = Job.Owner.RecipeData.GetRecipeGroup(CraftingJobInstance.CraftingGroupID);
            state.JobIsDone     = true;
            state.SetCooldown(0.05, 0.15);

            if (CraftingJobInstance.SelectedRecipe != null)
            {
                if (CraftingJobInstance.SelectedRecipeCount > 0 && CraftingJobInstance.SelectedRecipe.IsPossible(Job.Owner, state.Inventory, RecipeSettingsGroup))
                {
                    if (!state.Inventory.TryRemove(CraftingJobInstance.SelectedRecipe.Requirements))
                    {
                        GetItemsFromCrate(ref state);
                    }
                    else
                    {
                        CraftingResults.Clear();
                        CraftingResults.Add(CraftingJobInstance.SelectedRecipe.Results);
                        ModLoader.Callbacks.OnNPCCraftedRecipe.Invoke(Job, CraftingJobInstance.SelectedRecipe, CraftingResults);
                        float cd = CraftingJobSettings.CraftingCooldown * Pipliz.Random.NextFloat(0.9f, 1.1f);

                        if (CraftingResults.Count > 0)
                        {
                            state.Inventory.Add(CraftingResults);
                            RecipeResult toShow = RecipeResult.GetWeightedRandom(CraftingResults);

                            if (toShow.Amount > 0)
                            {
                                state.SetIndicator(new IndicatorState(cd, toShow.Type));
                            }
                            else
                            {
                                state.SetCooldown(cd);
                            }

                            if (CraftingJobSettings.OnCraftedAudio != null)
                            {
                                AudioManager.SendAudio(GetPosition().Vector, CraftingJobSettings.OnCraftedAudio);
                            }
                        }
                        else
                        {
                            state.SetIndicator(new IndicatorState(cd, NPCIndicatorType.None));
                        }

                        if (!CraftingJobInstance.IsCrafting)
                        {
                            CraftingJobInstance.IsCrafting = true;
                            OnStartCrafting();
                        }

                        state.JobIsDone = false;
                        CraftingJobInstance.SelectedRecipeCount--;
                    }
                }
                else
                {
                    CraftingJobInstance.SelectedRecipe      = null;
                    CraftingJobInstance.SelectedRecipeCount = 0;

                    state.SetCooldown(0.05, 0.15);
                    StopCrafting();
                }

                return;
            }

            StopCrafting();

            if (!state.Inventory.IsEmpty)
            {
                PutItemsInCrate(ref state);
                return;
            }

            GetNextRecipe(ref state);
        }
コード例 #19
0
        public static string GetName(this RecipeResult prop)
        {
            var description = EnumHelper.GetAttributeOfType <DisplayAttribute>(prop);

            return(description?.Name ?? prop.ToString() ?? "");
        }
コード例 #20
0
        public void PerformGoal(ref NPCBase.NPCState state)
        {
            CraftingJobWaterInstance instance = JobInstance;
            Colony owner = instance.Owner;

            state.JobIsDone = true;
            if (!this.CheckWater(instance))
            {
                state.SetCooldown(0.3, 0.5);
            }
            else
            {
                int index1;
                if (WaterSettings.BlockTypes.ContainsByReference <ItemTypes.ItemType>(instance.BlockType, out index1))
                {
                    UnityEngine.Vector3 vector = instance.NPC.Position.Vector;
                    switch (index1)
                    {
                    case 1:
                        ++vector.x;
                        break;

                    case 2:
                        --vector.x;
                        break;

                    case 3:
                        ++vector.z;
                        break;

                    case 4:
                        --vector.z;
                        break;
                    }
                    instance.NPC.LookAt(vector);
                }

                recipeMatch = Recipe.MatchRecipe <AvailableRecipesEnumerator>(owner.RecipeData.GetAvailableRecipes(WaterSettings.NPCTypeString), owner);
                switch (recipeMatch.MatchType)
                {
                case Recipe.RecipeMatchType.FoundCraftable:
                    Recipe foundRecipe = recipeMatch.FoundRecipe;
                    if (state.Inventory.TryRemove(foundRecipe.Requirements))
                    {
                        CraftingResults.Clear();
                        for (int index2 = 0; index2 < foundRecipe.Results.Count; ++index2)
                        {
                            CraftingResults.Add(foundRecipe.Results[index2]);
                        }
                        if (WaterSettings.OnCraftedAudio != null)
                        {
                            AudioManager.SendAudio(instance.Position.Vector, WaterSettings.OnCraftedAudio);
                        }
                        ModLoader.Callbacks.OnNPCCraftedRecipe.Invoke(Job, foundRecipe, CraftingResults);
                        RecipeResult weightedRandom = RecipeResult.GetWeightedRandom(CraftingResults);
                        float        timeToShow     = WaterSettings.Cooldown * Pipliz.Random.NextFloat(0.9f, 1.1f);
                        if (weightedRandom.Amount > 0)
                        {
                            state.SetIndicator(new IndicatorState(timeToShow, weightedRandom.Type));
                        }
                        else
                        {
                            state.SetCooldown((double)timeToShow);
                        }
                        state.Inventory.Add(CraftingResults);
                        ++instance.GatheredCount;
                        if (instance.GatheredCount < WaterSettings.MaxGatheredBeforeCrate)
                        {
                            break;
                        }
                        instance.GatheredCount = 0;
                        PutItemsInCrate(ref state);
                        break;
                    }
                    else
                    {
                        GetItemsFromCrate(ref state);
                    }
                    break;

                case Recipe.RecipeMatchType.FoundMissingRequirements:
                case Recipe.RecipeMatchType.AllDone:
                    if (state.Inventory.IsEmpty)
                    {
                        state.JobIsDone = true;
                        if (recipeMatch.MatchType == Recipe.RecipeMatchType.AllDone)
                        {
                            state.SetIndicator(new IndicatorState(WaterSettings.Cooldown, BuiltinBlocks.Indices.erroridle));
                        }
                        else
                        {
                            state.SetIndicator(new IndicatorState(WaterSettings.Cooldown, recipeMatch.FoundRecipe.FindMissingType(owner.Stockpile), true, false));
                        }
                        Job.Owner.Stats.RecordNPCIdleSeconds(WaterSettings.NPCType, WaterSettings.Cooldown);
                        GetItemsFromCrate(ref state);
                        break;
                    }
                    GetItemsFromCrate(ref state);
                    break;
                }
            }
        }
コード例 #21
0
 public Task UpdateAsync(RecipeResult recipeResult)
 {
     _session.Save(recipeResult);
     return(Task.CompletedTask);
 }
コード例 #22
0
 public Task DeleteAsync(RecipeResult recipeResult)
 {
     _session.Delete(recipeResult);
     return(Task.CompletedTask);
 }
コード例 #23
0
 public RecipeResultTag(RecipeResult reciperes)
 {
     Internal = reciperes;
 }
コード例 #24
0
 public void Fail()
 {
     Result = RecipeResult.BAD;
 }
コード例 #25
0
        private void AddRecipeResultsToNode( TreeNode parentNode, IEnumerable<RecipeResult> recipeResults, RecipeResult recipeResult )
        {
            if ( recipeResults.Count() > 1 )
             {
            parentNode.Text += @" - " + Db.GetIngredientSlotsInfoForRecipeResult( recipeResult ).GetSpecificItemNames();

            string toolTipText = "Potential Result Combos:\n\n";
            ContextMenu menu = new ContextMenu();
            int index = 1;
            foreach ( RecipeResult rec in recipeResults )
            {
               IEnumerable<IngredientSlotInfo> infos = Db.GetIngredientSlotsInfoForRecipeResult( rec );
               menu.MenuItems.Add( new MenuItem( infos.GetSpecificItemNames(), ( sender, args ) =>
               {
                  parentNode.Nodes.Clear();
                  AddRecipeResultsToNode( parentNode, recipeResults, rec );
                  //parentNode.ExpandAll();
               } ) );
               toolTipText += string.Format( "{0} - {1}\n", index++, infos.GetSpecificItemNames() );
            }

            parentNode.ContextMenu = menu;
            parentNode.ToolTipText = toolTipText;
             }

             AddRecipeResultIngredients( parentNode, recipeResult );
             AddRecipeResultAgents( parentNode, recipeResult );
             ManifestTreeNodeThemes.Apply( parentNode );
             BuildManifest();
        }