/// <summary> /// Returns a string of nutrient content information for display purposes /// </summary> /// <remarks> /// Simliar to <see cref="GetNutrientValue(string, string)"/>, but instead of returning a double this method returns a string for display in nutrition labels /// </remarks> /// <param name="nutrientId">The string identifier of the target <see cref="Nutrient"/> record</param> /// <param name="type">A string representation of the detail expected in <see cref="Nutrient"/> record</param> /// <returns>A string representinng specified nutrition content</returns> public string GetNutrientDisplayValue(string nutrientId, string type) { if (Nutrients == null || Nutrients.Count == 0) { return(""); } else { Nutrient nutrient = Nutrients.Where(x => x.NId == nutrientId).FirstOrDefault(); if (nutrient == null) { return(""); } else { if (type == "regular") { return($"{String.Format("{0:0.##}", (nutrient.Measures.Where(x => (x.Label == SelectedPortionLabel) && (x.Qty == SelectedPortionQty)).FirstOrDefault().Value * NumberOfServings))} {nutrient.Unit}"); } else if (type == "explore") { return($"{String.Format("{0:0.##}", nutrient.Value)} {nutrient.Unit}"); } else { return(""); } } } }
public async Task <Nutrients> GetNutritionsInformationAsync(int productID) { string url = "https://api.nal.usda.gov/ndb/V2/"; //https://fdc.nal.usda.gov/ using (var client = new HttpClient()) { client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(@"application/json")); HttpResponseMessage response = await client.GetAsync(string.Format("reports?ndbno={0}&type=f&format=json&api_key={1}", productID, API_KEY)); HttpContent content = response.Content; string result = await content.ReadAsStringAsync(); JObject jobject = JObject.Parse(result); var NutritionsList = jobject["foods"][0]["food"]["nutrients"]. Where(n => nutrientIds.Contains((string)n["nutrient_id"])).ToList(); var Nutritions = new Nutrients() { Energy = (float)NutritionsList.First(n => (int)n["nutrient_id"] == 208)["value"], Fats = (float)NutritionsList.First(n => (int)n["nutrient_id"] == 204)["value"], Protein = (float)NutritionsList.First(n => (int)n["nutrient_id"] == 203)["value"] }; return(Nutritions); } }
/// <summary> /// Used to determine the variable measure label of a selected food and create a meaningful object as a result /// </summary> /// <returns>A <see cref="Measure"/> object</returns> public Measure SelectedMeasure() { if ((Nutrients != null && Nutrients.Count > 0) && PortionIndex != 0) { int measureIndex = PortionIndex - 1; Measure whatever; if (SelectedPortionLabel == "100 g") { whatever = null; } else { whatever = Nutrients.SelectMany(s => s.Measures) .Where(f => (f.Label == SelectedPortionLabel) && (f.Qty == SelectedPortionQty)).First(); } return(whatever); } else { return(null); } }
public static void LoadScene(int _sceneId) { Application.LoadLevel(2); // Call All Reset Statics PlayerChildFSM.ResetStatics(); PlayerMain.ResetStatics(); player_control.ResetStatics(); GameManager.ResetStatics(); EndGamePanel.ResetStatics(); PlayerSquadFSM.ResetStatics(); SquadChildFSM.ResetStatics(); Wall.ResetStatics(); WallRenderer.ResetStatics(); Nutrients.ResetStatics(); ECPoolManager.ResetStatics(); ECIdleState.ResetStatics(); DirectionDatabase.ResetStatics(); FormationDatabase.ResetStatics(); PathQuery.ResetStatics(); PointDatabase.ResetStatics(); PositionQuery.ResetStatics(); ECTracker.ResetStatics(); EnemyMainFSM.ResetStatics(); Application.LoadLevel(_sceneId); }
public void SetMaxAndCurrent(Nutrients nutrient, int max) { MediaNutrient mediaNutrient = GetNutrient(nutrient, true); mediaNutrient.SetMax(max); mediaNutrient.Saturate(); }
// Public Fuunctions // AddSquadChildCount(): This function is called when a squad child "collides" with a nutrient public bool AddSquadChildCount() { nCurrentSquadChildCount++; transform.localScale += Vector3.one * fSizeExpandPerSpawn; if (transform.localScale.x > fMaximumSizeIncrease) { transform.localScale = Vector3.one * fMaximumSizeIncrease; } // if: The current number of squad child cells is the required spawn amount if (nCurrentSquadChildCount >= nSquadChildToSpawn) { nCurrentSquadChildCount = 0; Nutrients spawnNutrient = Spawn(transform.position); // if: There is not spawnable if (spawnNutrient == null) { return(false); } spawnNutrient.endPosition = new Vector2( -endPosition.x, transform.position.y + Random.Range(-5f, 5f) * fMaximumOffset); transform.localScale = Vector3.one; mAnimate.ExpandContract(0.5f, 1, 1.5f); } return(true); }
void Awake() { Singleton = this; TypeToDiffuse[typeof(Height)] = new Height(GetPositions(WaterSources).ToList(), GetPositions(MountainSources).ToList()); DebugDiffuseAble.Add(TypeToDiffuse[typeof(Height)]); InitializeMap(TypeToDiffuse[typeof(Height)]); TypeToDiffuse[typeof(SaltLevels)] = new SaltLevels(NoSaltSources, SaltSources); DebugDiffuseAble.Add(TypeToDiffuse[typeof(SaltLevels)]); InitializeMap(TypeToDiffuse[typeof(SaltLevels)], 5); TypeToDiffuse[typeof(Temperature)] = new Temperature(HotSources, ColdSources); DebugDiffuseAble.Add(TypeToDiffuse[typeof(Temperature)]); InitializeMap(TypeToDiffuse[typeof(Temperature)]); TypeToDiffuse[typeof(Hydration)] = new Hydration(HydrationSources, DrySource); DebugDiffuseAble.Add(TypeToDiffuse[typeof(Hydration)]); InitializeMap(TypeToDiffuse[typeof(Hydration)]); TypeToDiffuse[typeof(Nutrients)] = new Nutrients(NutrientsSources, NoNutrientsSource); DebugDiffuseAble.Add(TypeToDiffuse[typeof(Nutrients)]); InitializeMap(TypeToDiffuse[typeof(Nutrients)]); TypeToDiffuse[typeof(Tree)] = new Tree(TreeSources, CitySources); DebugDiffuseAble.Add(TypeToDiffuse[typeof(Tree)]); }
public int PlanImport(Nutrients nutrient, int requested, ClampMode mode) { int allowed; MetabolismOptions meOp; if (nutrient == Nutrients.AA) { allowed = Budget(ref importAA, requested, mode == ClampMode.Self); meOp = MetabolismOptions.ImportAA; } else if (nutrient == Nutrients.C) { allowed = Budget(ref importC, requested, mode == ClampMode.Self); meOp = MetabolismOptions.ImportC; } else { allowed = Budget(ref importN, requested, mode == ClampMode.Self); meOp = MetabolismOptions.ImportN; } if (mode == ClampMode.Others) { ClampOthers(meOp); } return(allowed); }
// Just Derive? public IEnumerator <KeyValuePair <Nutrient, NutrientAmount> > GetEnumerator() { List <string> NutrientRainbowOrder = new List <string>() { "Calcium", "Potassium", "Vitamin D", "Folic Acid", "Vitamin B12", "Vitamin A", "Iron", "Protein", "Carbohydrates", "Fat", "Fiber" }; foreach (string s in NutrientRainbowOrder) { if (Nutrients.ContainsKey(s)) { yield return(new KeyValuePair <Nutrient, NutrientAmount>(_LastNutrients[s], Nutrients[s])); } } }
private static float getSkill(List <FoodItem> foodList) { Nutrients nutrientAvg = default(Nutrients); float totalCal = 0; foreach (var food in foodList) { if (food.Calories > 0) { totalCal += food.Calories; nutrientAvg += food.Nutrition * food.Calories; } } if (totalCal > 0) { nutrientAvg *= 1.0f / totalCal; } float BalanceBonus = nutrientAvg.Values().Max() > 0 ? (nutrientAvg.Values().Sum() / (nutrientAvg.Values().Max() * 4)) * 2 : 0; float NutrientSkillRate = ((nutrientAvg.NutrientTotal() * BalanceBonus) + EcoSim.Obj.EcoDef.BaseSkillGainRate) * DifficultySettings.Obj.Config.DifficultyModifiers.SkillGainMultiplier; return(NutrientSkillRate); }
public Nutrients GetNearestResource() { Nutrients[] nutrientsPool = Nutrients.playerNutrientPool; Nutrients nearestNutrient = null; for (int i = 0; i < nutrientsPool.Length; i++) { // if: The current nutrients is NOT in the pool and NOT being collected by player if (!nutrientsPool[i].IsInPool && nutrientsPool[i].IsCollectable) { // if: This function only returns nutrients that is below the EnemyMain if (nutrientsPool[i].transform.position.y < EnemyMainFSM.Instance().transform.position.y - EnemyMainFSM.Instance().transform.lossyScale.y) { // if: Target only nutrients that are middle of the playing field if (Mathf.Abs(nutrientsPool[i].transform.position.x) < 4f) { // if: There is no nearest nutrients yet if (nearestNutrient == null) { nearestNutrient = nutrientsPool[i]; } // else if: The checking nutrient is nearer than the curent nearest nutrient else if (Vector3.Distance(nearestNutrient.transform.position, PlayerSquadFSM.Instance.transform.position) > Vector3.Distance(nutrientsPool[i].transform.position, PlayerSquadFSM.Instance.transform.position)) { nearestNutrient = nutrientsPool[i]; } } } } } return(nearestNutrient); }
/// <summary> /// Used to determine and retrieve the specified nutrient content in a food based on target nutrient, portion type, and quantity /// </summary> /// <remarks> /// Unlike <see cref="GetNutrientDisplayValue(string, string)"/>, this method is used during the meal logging process /// </remarks> /// <param name="nutrientId">The string identifier of the target <see cref="Nutrient"/> record</param> /// <param name="type">A string representation of the detail expected in <see cref="Nutrient"/> record</param> /// <returns>A double value representing total content of specified nutrient</returns> public double GetNutrientValue(string nutrientId, string type) { if (Nutrients == null || Nutrients.Count == 0) { return(0); } else { Nutrient nutrient = Nutrients.Where(x => x.NId == nutrientId).FirstOrDefault(); if (nutrient == null) { return(0); } else { if (type == "regular") { return(Convert.ToDouble(nutrient.Measures.Where(x => (x.Label == SelectedPortionLabel) && (x.Qty == SelectedPortionQty)).FirstOrDefault().Value *NumberOfServings)); } else if (type == "explore" || type == "noMeasure") { return(Convert.ToDouble(nutrient.Value)); } else { return(0); } } } }
public Item(String name, int id, Calories cals, Nutrients nut) { this.name = name; this.itemID = id; this.calories = cals; this.nutrients = nut; }
private Item CreateItemFromInfo(String[] info) { Calories cals = new Calories(Convert.ToDouble(info[2]), Calories.GetUnitsFromString(info[3])); Nutrients nuts = new Nutrients(Convert.ToDouble(info[4]), Convert.ToDouble(info[5]), Convert.ToDouble(info[6]), Convert.ToDouble(info[7])); Item item = new Item(info[1], idGen.GetNewID(), cals, nuts); return(item); }
void SetMediaComposition(Nutrients nutrient) { currentMedia.SetMaxAndCurrent(nutrient, Random.Range( minMedia.GetMax(nutrient), maxMedia.GetMax(nutrient) )); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Id != null) { hashCode = hashCode * 59 + Id.GetHashCode(); } if (Title != null) { hashCode = hashCode * 59 + Title.GetHashCode(); } if (Meta != null) { hashCode = hashCode * 59 + Meta.GetHashCode(); } if (Categories != null) { hashCode = hashCode * 59 + Categories.GetHashCode(); } if (Author != null) { hashCode = hashCode * 59 + Author.GetHashCode(); } if (Keywords != null) { hashCode = hashCode * 59 + Keywords.GetHashCode(); } if (Topics != null) { hashCode = hashCode * 59 + Topics.GetHashCode(); } if (Attributes != null) { hashCode = hashCode * 59 + Attributes.GetHashCode(); } if (Ingredients != null) { hashCode = hashCode * 59 + Ingredients.GetHashCode(); } if (BaseIngredients != null) { hashCode = hashCode * 59 + BaseIngredients.GetHashCode(); } if (Nutrients != null) { hashCode = hashCode * 59 + Nutrients.GetHashCode(); } if (DiabeticExchanges != null) { hashCode = hashCode * 59 + DiabeticExchanges.GetHashCode(); } return(hashCode); } }
public Nutrient Lookup(string key) { if (!Nutrients.ContainsKey(key)) { return(Nutrient.Null); } return(Nutrients[key]); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Name != null) { hashCode = hashCode * 59 + Name.GetHashCode(); } if (Categories != null) { hashCode = hashCode * 59 + Categories.GetHashCode(); } if (Nutrients != null) { hashCode = hashCode * 59 + Nutrients.GetHashCode(); } if (CalorieConversionFactor != null) { hashCode = hashCode * 59 + CalorieConversionFactor.GetHashCode(); } if (ProteinConversionFactor != null) { hashCode = hashCode * 59 + ProteinConversionFactor.GetHashCode(); } if (Components != null) { hashCode = hashCode * 59 + Components.GetHashCode(); } if (Portions != null) { hashCode = hashCode * 59 + Portions.GetHashCode(); } if (CommonName != null) { hashCode = hashCode * 59 + CommonName.GetHashCode(); } if (Footnote != null) { hashCode = hashCode * 59 + Footnote.GetHashCode(); } if (SearchTerm != null) { hashCode = hashCode * 59 + SearchTerm.GetHashCode(); } if (Score != null) { hashCode = hashCode * 59 + Score.GetHashCode(); } return(hashCode); } }
public int Extract(Nutrients nutrient, int energy) { MediaNutrient mediaNutrient = GetNutrient(nutrient); if (mediaNutrient == null) { Debug.LogError(nutrient + " does not exist"); return(0); } int extraction = GetExtractionVolume(mediaNutrient, energy); Debug.Log("Extractin " + extraction); return(mediaNutrient.Extract(extraction)); }
public static string NutrientToName(Nutrients nutrient) { switch (nutrient) { case Nutrients.AA: return("Amino Acids"); case Nutrients.C: return("Carbon"); case Nutrients.N: return("Nitrogen"); } return(""); }
public Nutrients makeNutrientsRequest() { var jNutrients = JsonConvert.DeserializeObject <dynamic>(getResponse(this.endPoint)); Dictionary <String, String> dict = new Dictionary <String, String>(); dict.Add("calories", (String)jNutrients.nutrition.calories); dict.Add("fat", (String)jNutrients.nutrition.fat); dict.Add("protein", (String)jNutrients.nutrition.protein); dict.Add("carbs", (String)jNutrients.nutrition.carbs); Nutrients foodNutrient = new Nutrients((int)jNutrients.id, dict); return(foodNutrient); }
public NutrientAmount this[string n] { get { if (Nutrients.ContainsKey(n)) { return(Nutrients[n]); } return(0.0); } set { if (Nutrients.ContainsKey(n)) { Nutrients[n] = value; } } }
private void TranslateNutrients(ObservableCollection <NutrientViewModel> nutrients) { if (nutrients != null) { var nutrientTranslator = new NutrientLanguageNames(_repo); foreach (var nutrient in nutrients) { var name = nutrient.Name.Replace("_100g", ""); TranslateNutrient(nutrientTranslator, name, name, nutrient); } var sortedNutrients = nutrients.OrderBy(o => o.Order).ToList(); Nutrients.Clear(); foreach (var nutrient in sortedNutrients) { Nutrients.Add(nutrient); } } }
public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = 17; hash = hash * 23 + Code.GetHashCode(); if (Name != null) { hash = hash * 23 + Name.GetHashCode(); } if (Nutrients != null) { hash = hash * 23 + Nutrients.GetHashCode(); } return(hash); } }
protected MediaNutrient GetNutrient(Nutrients nutrient, bool addIfMissing = false) { for (int i = 0, l = nutrients.Count; i < l; i++) { if (nutrients[i].nutrient == nutrient) { return(nutrients[i]); } } if (addIfMissing) { MediaNutrient mediaNutrient = new MediaNutrient(); mediaNutrient.nutrient = nutrient; mediaNutrient.name = NutrientToName(nutrient); nutrients.Add(mediaNutrient); return(mediaNutrient); } return(null); }
}//end method /// <summary> /// Sets the progress bar value to max when the progress bar overflows. Otherwise /// the progress bar would show 0. /// </summary> /// <param name="nutrient"></param> private void SetNutrientProgressBarToMaxOnOverflow(Nutrients nutrient) { if (nutrient == Nutrients.CALORIES) { caloriesProgressBar.Value = caloriesProgressBar.Maximum; } if (nutrient == Nutrients.CARBS) { carbsProgressBar.Value = carbsProgressBar.Maximum; } if (nutrient == Nutrients.FAT) { fatProgressBar.Value = fatProgressBar.Maximum; } if (nutrient == Nutrients.PROTEIN) { proteinProgressBar.Value = proteinProgressBar.Maximum; } }//end method
// SpawnNutrients(): Handles the spawning of nutrients IEnumerator SpawnNutrients() { while (true) { yield return(new WaitForSeconds(fNutrientsDelay)); if (UnityEngine.Random.value <= fNutrientsChance) { float xPos = 0; if (Random.Range(0, 2) == 1) { xPos = 6.5f; } else { xPos = -6.5f; } Vector3 spawnPos = new Vector3(xPos, Random.Range(fLowerLimit, fUpperLimit), 0); Nutrients.Spawn(spawnPos); } } }
private void dataGridViewFood_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { Console.WriteLine("Method call"); RESTClient rClient = new RESTClient(); int rowindex = dataGridViewFood.CurrentCell.RowIndex; int columnindex = dataGridViewFood.CurrentCell.ColumnIndex; try { rClient.endPoint = "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/food/products/" + dataGridViewFood.Rows[rowindex].Cells[columnindex].Value.ToString(); Nutrients nutrient = rClient.makeNutrientsRequest(); NutritionInfo ni = new NutritionInfo(); ni.setCalories(nutrient.getfoodNutrients()["calories"]); ni.setFat(nutrient.getfoodNutrients()["fat"]); ni.setProtein(nutrient.getfoodNutrients()["protein"]); ni.setCarbs(nutrient.getfoodNutrients()["carbs"]); ni.ShowDialog(); } catch { } }
public void Deposit(Nutrients nutrient, int volume) { GetNutrient(nutrient, true).Deposit(volume); }
public int GetMax(Nutrients nutrient) { return(GetNutrient(nutrient).MaxValue); }
public override void Execute() { targetNutrients = m_scFSM.GetNearestResource(); // if: The target nutrient is too close to the wall, disable the target if (targetNutrients != null) if (Mathf.Abs(targetNutrients.transform.position.x) >= 4f) targetNutrients = null; // Seperation Factor // vSeperationVector: The final vector used to space away from all the other nearby cells Vector3 vSeperationVector = Vector3.zero; Collider2D[] array_nearbyCollider = Physics2D.OverlapCircleAll(m_scFSM.transform.position, 0.5f, Constants.s_onlySquadChildLayer); if (array_nearbyCollider.Length > 0) { for (int i = 0; i < array_nearbyCollider.Length; i++) { // if: The current gameObject is itself if (array_nearbyCollider[i] == m_scFSM.gameObject) continue; // vDirectionVector: The vector that the current squad child should be travelling in to space away from the current neighbour Vector3 vDirectionVector = (m_scFSM.transform.position - array_nearbyCollider[i].transform.position); // if: Somehow this is triggered, which is very often... if (vDirectionVector.magnitude > 0) vSeperationVector += vDirectionVector.normalized / vDirectionVector.sqrMagnitude; } // Average the the final vector to use for spacing away vSeperationVector = vSeperationVector / array_nearbyCollider.Length; vSeperationVector = Vector3.ClampMagnitude(vSeperationVector, 7f); } // Attraction Factor ExecuteMethod.OnceInUpdate("SC_FindResourceState.RecalculateCenter", null, null); Vector3 vAttractionVector = vCenterPosition - m_scFSM.transform.position; vAttractionVector *= 10f; // Final Velocity Vector // toTargetVector: The vector between the target nutrients and the current squad child cells Vector3 toTargetVector; // if: There is no target nutrient, the find nutrients group will idle infront of squad group if (targetNutrients == null) toTargetVector = PlayerSquadFSM.Instance.transform.position + new Vector3(0f, 2f, 0f) - m_scFSM.transform.position; else toTargetVector = targetNutrients.transform.position - m_scFSM.transform.position; toTargetVector *= 10f; if (targetNutrients != null) SquadChildFSM.Circle(targetNutrients.transform.position); //Debug.Log("toTargetVector: " + toTargetVector.magnitude + ", vSeperationVector: " + vSeperationVector.magnitude + ", vAttractionVector: " + vAttractionVector.magnitude); // Apply vector to velocity /* Quick Vector Summary: * toTargetVector -> The vector between the nutrients and the 'FindResource' group * vSeperationVector -> The personal space vector * vAttractionVector -> The 'stay as a group' vector */ m_scFSM.RigidBody.AddForce(toTargetVector + vSeperationVector + vAttractionVector * Time.deltaTime * 100f, ForceMode2D.Force); m_scFSM.RigidBody.velocity = Vector3.ClampMagnitude(m_scFSM.RigidBody.velocity, 3f); // if: The distance between the two bodies is less than a certain distance if (targetNutrients != null) { if (Vector3.Distance(targetNutrients.transform.position, m_scFSM.transform.position) < 0.5f) { // if: The current squad child is added to the nutrients if (targetNutrients.AddSquadChildCount()) { m_scFSM.Advance(SCState.Dead); targetNutrients = null; } } } }