Inheritance: ItemBase
        public void Add_Food_Items()
        {
            //Arrange
            var chips = new FoodItem { FoodItemId = 1, Title = "Chips" };
            var candy = new FoodItem { FoodItemId = 2, Title = "Candy" };
            var pizza = new FoodItem { FoodItemId = 3, Title = "Pizza" };
            var milk = new FoodItem { FoodItemId = 4, Title = "Milk" };

            var model = new EventBaseViewModel
            {
                AllEventFoodItems = new List<FoodItemViewModel>
                    {
                        new FoodItemViewModel(chips),
                        new FoodItemViewModel(candy)
                    },
                WillBringTheseFoodItems = new List<FoodItemViewModel>(new[] { new FoodItemViewModel(pizza), new FoodItemViewModel(milk),  }), // this is what the user is bringing
            };

            //These are in the database
            var dataModel = new Event
            {
                Coordinator = new Person { MyFoodItems = new List<FoodItem> { pizza, milk } },
                FoodItems = new List<FoodItem> { chips, candy } // Pizza and milk will be added
            };

            A.CallTo(() => FoodRepo.GetAll()).Returns(new List<FoodItem>{ chips, candy, pizza, milk }.AsQueryable());

            //Act
            EventService.AppendNewFoodItems(dataModel, model);

            //Assert
            Assert.AreEqual(dataModel.FoodItems.Count, 4); //only the candy is removed.
        }
Exemplo n.º 2
0
 public Food(FoodType type, FoodItem item, int n)
 {
     Id = Guid.NewGuid();
     Type = type;
     Item = item;
     N = n;
 }
Exemplo n.º 3
0
        public static FoodItem ToDataModel(this C.FoodItem domain)
        {
            var model = new FoodItem { };

            domain.Map(model);

            return model;
        }
        /// <summary>
        /// Get a data model for this food item.
        /// </summary>
        /// <returns></returns>
        public FoodItem GetDataModel()
        {
            var dataModel = new FoodItem();
            dataModel.FoodItemId = FoodItemId;
            dataModel.Title = Title;
            dataModel.Description = Description;

            return dataModel;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Implements value types equality using structures
        /// </summary>
        /// <remarks>
        /// Own equality implementation for value type should be made in order to: 
        /// 1. Use == operator
        /// 2. Performance - avoid boxing and unboxing and also using reflection
        /// 3. Change meaning of Equals(), e.g. not all fields may be checked
        /// 
        /// Steps required to implement equality (best practice is to implement all 3): 
        /// 1. Override object.Equals() -> avoid reflection
        /// 2. Implement IEquatable<FoodItem> -> avoid boxing, give type safety
        /// 3. Allow using == operator 
        /// 4. Implement != operator
        /// 5. Implement object.GetHashCode() - required by Equals()
        /// </remarks>
        internal static void ValueTypesEquality()
        {
            FoodItem banana = new FoodItem("banana", FoodGroup.Fruits);
            FoodItem banana2 = new FoodItem("banana", FoodGroup.Fruits);
            FoodItem chocolate = new FoodItem("chocolate", FoodGroup.Sweets);

            Console.WriteLine("bananas: " + (banana == banana2));
            Console.WriteLine("banana and chocolate: "+ (banana == chocolate));
        }
Exemplo n.º 6
0
        static void Map(this C.FoodItem foodItem, FoodItem existing)
        {
            existing.Name = foodItem.Name;

            existing.Description = foodItem.Description;

            existing.VendorFoodCategoryID = foodItem.FoodCategoryId;

            existing.IsActive = foodItem.IsActive;

            existing.Cost = foodItem.Cost;

            existing.Price = foodItem.Price;
        }
Exemplo n.º 7
0
        public ActionResult AddEntry(string date,string title,float calories)
        {
            FlabberUser user = FlabberContext.CurrentUser;
            if (user == null)
                return RedirectToAction("Index", "Home");

            // Get the date. Force to UTC.
            DateTime userDate = DateTime.Parse(date);
            userDate = DateTime.SpecifyKind(userDate, DateTimeKind.Local);

            // Add the entry
            FoodEntry entry = new FoodEntry();
            entry.Calories = calories;
            entry.Title = title;
            entry.Date = userDate;
            entry.User = user;
            entry.Id = Guid.NewGuid();
            FoodEntry.Repository.SaveOrUpdate(entry);

            // Add to the autocomplete list
            title = title.Trim();
            FoodItem item = FoodItem.Repository.First("@Title", title);
            if (item == null)
            {
                item = new FoodItem();
                item.Title = title;
                item.User = user;
                item.Brand = "Notset";
                item.Calories = calories;
                item.Id = Guid.NewGuid();
                FoodItem.Repository.SaveOrUpdate(item);

                // Update the cache if it exists
                string cacheKey = string.Format("FoodItems{0}", user.Id);
                if (HttpContext.Cache[cacheKey] != null)
                {
                    List<FoodItem> list = (List<FoodItem>)HttpContext.Cache[cacheKey];
                    list.Add(item);

                    HttpContext.Cache[cacheKey] = list;
                }
            }

            return RedirectToAction("Index", "Food");
        }
        public async Task UpdateAsync(FoodItem foodItem)
        {
            if (foodItem == null)
            {
                throw new ArgumentNullException(nameof(foodItem));
            }

            try
            {
                var filter = Builders <FoodItem> .Filter.Eq(item => item.Id, foodItem.Id);

                // Note: Upsert will create a new item if it cant find an item to update.
                await _collection.ReplaceOneAsync(filter, foodItem, new ReplaceOptions { IsUpsert = true });
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Exception has been thrown when calling UpdateAsync: {exception.Message}");
            }
        }
    public static FoodItem CreateFromCommaString(string commaSeparatedValues)
    {
        var foodItem = new FoodItem();

        if (string.IsNullOrWhiteSpace(commaSeparatedValues))
        {
            return(foodItem);
        }
        var values = commaSeparatedValues.Split(',')
                     .Select(value => value.Trim()).ToList();
        double price;

        foodItem.FoodCategory = values[0];
        if (values.Count > 1)
        {
            foodItem.FoodType = values[1];
        }
        if (values.Count > 2)
        {
            foodItem.Size = values[2];
        }
        if (values.Count > 3 && double.TryParse(values[3], out price))
        {
            foodItem.Price = price;
        }

        if (values.Count > 4)
        {
            for (int i = 4; i < values.Count; i += 2)
            {
                var ingredient = new Ingredient {
                    Name = values[i]
                };
                double qty;
                if (values.Count > i + 1 && double.TryParse(values[i + 1], out qty))
                {
                    ingredient.Quantity = qty;
                }
                foodItem.Ingredients.Add(ingredient);
            }
        }
        return(foodItem);
    }
        public IActionResult Single(int id)
        {
            try
            {
                FoodItem foodItem = _foodRepository.GetSingle(id);

                if (foodItem == null)
                {
                    return(NotFound());
                }

                return(Ok(Mapper.Map <FoodItemViewModel>(foodItem)));
            }
            catch (Exception exception)
            {
                _logger.LogCritical("Error", exception);
                return(new StatusCodeResult(500));
            }
        }
Exemplo n.º 11
0
    public FoodItem RemoveSceneFood(int index)
    {
        if (index == -1)
        {
            index = currentScene.ID;
        }

        if (scenes[index].currentObject == null)
        {
            return(null);
        }

        FoodItem temp = scenes[index].currentObject.GetFoodItem();

        scenes[index].currentObject.DestroySelf();
        scenes[index].currentObject = null;

        return(temp);
    }
Exemplo n.º 12
0
        // GET: FoodItems/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            FoodItem foodItem = db.FoodItems.Find(id);

            if (foodItem == null)
            {
                return(HttpNotFound());
            }
            ViewBag.CourseID              = new SelectList(db.Courses, "CourseID", "CourseType", foodItem.CourseID);
            ViewBag.DietaryRestrictionID  = new SelectList(db.DietaryRestrictions, "DietaryRestrictionID", "DietType", foodItem.DietaryRestrictionID);
            ViewBag.DietaryRestrictionID2 = new SelectList(db.DietaryRestrictions, "DietaryRestrictionID", "DietType", foodItem.DietaryRestrictionID2);
            ViewBag.DietaryRestrictionID3 = new SelectList(db.DietaryRestrictions, "DietaryRestrictionID", "DietType", foodItem.DietaryRestrictionID3);
            ViewBag.ReviewID              = new SelectList(db.Reviews, "ReviewID", "UserID", foodItem.ReviewID);
            return(View(foodItem));
        }
Exemplo n.º 13
0
        public ActionResult Buy(string id, string returnUrl)
        {
            // TODO Add FoodItem to ApplicationUser's Shopping Cart Entity in the DB, if it doesn't exist? create a new one

            FoodItem foodItem = db.FoodItems.Find(id);

            if (foodItem == null)
            {
                return(HttpNotFound());
            }
            if (returnUrl != null)
            {
                ViewBag.ReturnUrl = returnUrl;
            }



            return(View(foodItem));
        }
        public IActionResult Remove(int id)
        {
            try
            {
                FoodItem foodItem = _foodRepository.GetSingle(id);

                if (foodItem == null)
                {
                    return(NotFound());
                }

                _foodRepository.Delete(id);
                return(NoContent());
            }
            catch (Exception exception)
            {
                return(new StatusCodeResult(500));
            }
        }
Exemplo n.º 15
0
        public IHttpActionResult Remove(int id)
        {
            try
            {
                FoodItem foodItem = _foodRepository.GetSingle(id);

                if (foodItem == null)
                {
                    return(NotFound());
                }

                _foodRepository.Delete(id);
                return(StatusCode(HttpStatusCode.NoContent));
            }
            catch (Exception exception)
            {
                return(InternalServerError(exception));
            }
        }
Exemplo n.º 16
0
        public IActionResult Post([FromBody] FoodItem value)
        {
            _log4net.Info(" Http POST Request");

            /* _context.FoodItems.Add(value);
             * _context.SaveChanges();
             * return "Success";
             */
            string s = "Success";

            if (_context.Post(value) == s)
            {
                return(Ok());
            }
            else
            {
                return(BadRequest());
            }
        }
        public void TestAddStateInvalid()
        {
            var accessor   = TestLibrary.TestLibrary.SetUpHttpContextAccessor();
            var unitOfWork = TestLibrary.TestLibrary.SetUpIUnitOfWork();
            var tempData   = new TempDataDictionary(accessor.Object.HttpContext, Mock.Of <ITempDataProvider>());

            var controller = new AdminController(unitOfWork.Object, accessor.Object);

            controller.TempData = tempData;
            var foodItem = new FoodItem {
                Id = 1
            };

            controller.ModelState.AddModelError("test", "test");

            var result = controller.AddEditFood(foodItem) as ViewResult;

            Assert.IsType <ViewResult>(result);
        }
Exemplo n.º 18
0
        public IHttpActionResult FindFoodItem(int id)
        {
            FoodItem FoodItemInfo = db.FoodItems.Find(id);

            if (FoodItemInfo == null)
            {
                return(NotFound());
            }
            FoodItemDto SelectedFoodItem = new FoodItemDto
            {
                Restaurant    = FoodItemInfo.Restaurant,
                FoodItemID    = FoodItemInfo.FoodItemID,
                FoodItemName  = FoodItemInfo.FoodItemName,
                FoodItemDesc  = FoodItemInfo.FoodItemDesc,
                FoodItemPrice = FoodItemInfo.FoodItemPrice
            };

            return(Ok(SelectedFoodItem));
        }
Exemplo n.º 19
0
    IEnumerator BakeFood()
    {
        SetActiveFoodSlots(false);

        while (items.Count(c => c.cooked) < 2 && !woodsSlot.IsEmpty())
        {
            foreach (Slot slot in slots)
            {
                if (slot.IsEmpty())
                {
                    break;
                }

                if (slot.GetItem().type == Item.Type.FOOD)
                {
                    FoodItem foodItem = (FoodItem)slot.GetItem();

                    if (foodItem.cooked)
                    {
                        continue;
                    }

                    foodItem.bakingAmount += bakingSpeed * Time.deltaTime;

                    bakeBar.fillAmount = foodItem.bakingAmount / foodItem.bakingDuration;

                    if (foodItem.bakingAmount >= foodItem.bakingDuration)
                    {
                        foodItem.cooked = true;
                        slot.SetItem(null);
                    }
                }
            }

            yield return(null);
        }

        ClearFoodSlots();
        mealSlot.SetItem(resultItem, 1);
        bakeBar.fillAmount = 0f;
        SetActiveFoodSlots(true);
        mealSlot.Add();
    }
 public static FoodItem GetFoodItem(int id, bool includeDeleted = false)
 {
     var connection = DatabaseHandler.GetLocalDbConnection();
     var command = new SqlCommand();
     if (includeDeleted)
         command.CommandText = $"SELECT * FROM [dbo].[Items] WHERE [Id] = {id}";
     else
         command.CommandText = $"SELECT * FROM [dbo].[Items] WHERE [Id] = {id} AND [Deleted] = 0";
     command.Connection = connection;
     var reader = command.ExecuteReader();
     var foodItem = new FoodItem();
     if (reader.Read())
         foodItem = new FoodItem(reader.GetInt32(0), reader.GetString(1), Convert.ToDouble(reader[2]),
             reader.GetInt32(3), Convert.ToDouble(reader[4]) * StaticAccessor.Discounts[3],
             Convert.ToDouble(reader[4]) * StaticAccessor.Discounts[2],
             Convert.ToDouble(reader[4]) * StaticAccessor.Discounts[3], reader.GetBoolean(5));
     connection.Close();
     return foodItem;
 }
Exemplo n.º 21
0
    protected override void OnAwake()
    {
        btnReturn        = transform.Find("Top/Btn_Return").gameObject;
        btnUpgrade       = transform.Find("Bottom/Btn_Upgrade").gameObject;
        btnBattle        = transform.Find("Bottom/Btn_Battle").gameObject;
        btnUnload        = transform.Find("Bottom/Btn_Unload").gameObject;
        btnAutoToAddFood = transform.Find("Bottom/Btn_AutoToAddFood").gameObject;
        title            = transform.Find("Top/Title").GetComponent <UILabel>();

        Transform foodTrans = transform.Find("Bottom/Foods");

        for (int i = 1; i <= 6; i++)
        {
            FoodItem  tab   = new FoodItem();
            Transform trans = foodTrans.Find(i.ToString());
            tab.itemBtn     = trans.gameObject;
            tab.itemTexture = trans.Find("Texture").GetComponent <UITexture>();
            tab.itemQuality = trans.Find("Quality").GetComponent <UISprite>();
            mFoods.Add(tab);
        }

        expSlider = transform.Find("Bottom/Progress").GetComponent <UISlider>();
        expNum    = transform.Find("Bottom/Progress/Num").GetComponent <UILabel>();

        leftView                  = transform.Find("Left/View").GetComponent <UIScrollView>();
        leftGrid                  = transform.Find("Left/View/Grid").GetComponent <UIGrid>();
        leftCenterOnChild         = transform.Find("Left/View/Grid").GetComponent <UICenterOnChild>();
        leftCenterOnChild.enabled = false;
        leftTemp                  = transform.Find("Left/View/Temp").gameObject;
        leftTemp.SetActive(false);

        Transform right = transform.Find("Right/Background");

        currPropertyText1 = right.Find("1/Text1").GetComponent <UILabel>();
        currPropertyText2 = right.Find("1/Text2").GetComponent <UILabel>();
        mainPropertyText1 = right.Find("2/Text1").GetComponent <UILabel>();
        mainPropertyText2 = right.Find("2/Text2").GetComponent <UILabel>();
        desc = right.Find("3/Desc").GetComponent <UILabel>();

        mModelTexture = transform.Find("ModelTexture").GetComponent <UITexture>();
        InitItems();
        ShowRender();
    }
Exemplo n.º 22
0
        public void AddItem(FoodItem foodItem, int quantity)
        {
            foreach (CartItem cartItem in CartItems)
            {
                if (cartItem.FoodItem == foodItem)
                {
                    cartItem.Quantity += quantity;
                    UpdateSession();
                    return;
                }
            }

            CartItem item = new CartItem {
                FoodItem = foodItem, Quantity = quantity
            };

            CartItems.Add(item);
            UpdateSession();
        }
Exemplo n.º 23
0
    /// <summary>
    /// Returns a dictionary of stats info on the incoming item.  May return null.
    /// </summary>
    /// <returns>The stats dict.</returns>
    private Dictionary <StatType, int> GetStatsDict(string itemID)
    {
        Item item = DataLoaderItems.GetItem(itemID);
        Dictionary <StatType, int> dictStats = null;

        switch (item.Type)
        {
        case ItemType.Foods:
            FoodItem foodItem = (FoodItem)item;
            dictStats = foodItem.Stats;
            break;

        case ItemType.Usables:
            UsableItem usableItem = (UsableItem)item;
            dictStats = usableItem.Stats;
            break;
        }
        return(dictStats);
    }
Exemplo n.º 24
0
        public void SpreadFood(int foodCount, Coord topLeft, Coord bottomRight)
        {
            topLeft     = Navigator.EnsureBounds(topLeft);
            bottomRight = Navigator.EnsureBounds(bottomRight);
            const int tryCount = 100;

            for (int i = 0; i < foodCount; i++)
            {
                var newFoodItem = new FoodItem(GenerateId())
                {
                    Energy = Random.Next(1, MaxEnergyPerFoodItem + 1),
                };
                for (int j = 0; j < tryCount; j++)
                {
                    newFoodItem.Point = new Coord(topLeft.X + Random.Next(bottomRight.X - topLeft.X), topLeft.Y + Random.Next(bottomRight.Y - topLeft.Y));

                    if (Navigator.IsWall(newFoodItem.Point))
                    {
                        continue;
                    }

                    var unitInPoint = Navigator.FindUnit(newFoodItem.Point);
                    if (unitInPoint == null)
                    {
                        AddFood(newFoodItem);
                        break;
                    }

                    var individual = unitInPoint as Individual;
                    if (individual != null)
                    {
                        continue;
                    }

                    var food = unitInPoint as FoodItem;
                    if (food != null)
                    {
                        food.Energy += newFoodItem.Energy;
                        break;
                    }
                }
            }
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Create([Bind("FoodItemID,FoodItemName,FoodDescription,Cost,FoodGroupID")] FoodItem foodItem)
        {
            if (ModelState.IsValid)
            {
                await repository.Add(foodItem);

                await repository.AddFoodForUser(CurrentUser.User, foodItem);

                return(RedirectToAction(nameof(Index)));
            }

            var viewModel = new FoodItemCreateViewModel()
            {
                FoodGroups = ctx.FoodGroups.AsEnumerable(),
                FoodItem   = new FoodItem()
            };

            return(View(viewModel));
        }
Exemplo n.º 26
0
 public ActionResult AddFoodItems(Additem f)
 {
     try
     {
         FoodItem f1 = new FoodItem();
         f1.FoodId   = f.FoodId;
         f1.Category = f.Category;
         f1.Name     = f.Name;
         f1.Price    = f.Price;
         CanteenAutomationSystemDbEntities1 cas = new CanteenAutomationSystemDbEntities1();
         cas.FoodItems.Add(f1);
         cas.SaveChanges();
         return(RedirectToAction("ManageFoodItems"));
     }
     catch (Exception e)
     {
         return(View());
     }
 }
Exemplo n.º 27
0
    async void GetFoodDateFromFile()
    {
        TextAsset content = await Addressables.LoadAssetAsync <TextAsset>("").Task;

        JSONObject js = JSONObject.Create(content.text);

        //下面开始赋值
        for (int i = 0; i < js.Count; i++)
        {
            JSONObject _nowItem = js[i];
            FoodItem   foodItem = new FoodItem(_nowItem.GetField("picPath").str, _nowItem.GetField("audio_question").str, _nowItem.GetField("audioPath_2").str,
                                               _nowItem.GetField("audioPath_3").str, _nowItem.GetField("audioPath_4").str, _nowItem.GetField("audioPath_5").str);
            string _name = _nowItem.GetField("name").str;
            foodNames.Add(_name);
            foodData.Add(_name, foodItem);
            colorFoodList[_nowItem.GetField("color").str].Add(_name);
            typeFoodList[_nowItem.GetField("type").str].Add(_name);
        }
    }
Exemplo n.º 28
0
    public override void PlaceObject(GameObject obj)
    {
        //To do add utensil stuff
        base.PlaceObject(obj);

        //temporary function until counters/player/endgoal is added

        //if obj is empty

        //add obj

        //else


        if (obj.GetComponent <FoodItem>())
        {
            FoodItem obj_item = obj.GetComponent <FoodItem>();
            if (prepared && obj_item.prepared)
            {
                //if the placement already has a prepared item, combine to make a product
                //then delete the two items after product has been made
                GameObject product_obj = Instantiate(Resources.Load("Product Prefab"), obj.transform.position, obj.transform.rotation) as GameObject;

                Product product = product_obj.GetComponent <Product>();
                product.AddItem(obj_item.type);
                product.AddItem(type);

                Destroy(obj_item.gameObject);
                Destroy(gameObject);
            }
        }
        else if (obj.GetComponent <Product>() && prepared)
        {
            //if placement has a product, add item to it
            obj.GetComponent <Product>().AddItem(type);
            Destroy(gameObject);
        }
        else
        {
            //add food to counter
            transform.position = obj.transform.position;
        }
    }
Exemplo n.º 29
0
        async void InsertNewEntry()
        {
            FoodItem item = new FoodItem();

            item.ID         = 0;
            item.DATE       = mDateTime;
            item.NAME       = mFoodName;
            item.PATH       = mFileName;
            item.HOTEFFECT  = true;
            item.COOLEFFECT = false;
            item.IMGWIDTH   = mWidth;
            item.IMGHEIGHT  = mHeight;
            item.IMGBYTES   = GlobalVariables.SerializeByteArrayToString(mImageBytes);
            Dictionary <int, int> answers = new Dictionary <int, int>();

            foreach (var questions in GlobalVariables.Questions)
            {
                answers.Add(questions.Key, -1);
            }
            item.ANSWERS = GlobalVariables.SerializeDictionary(answers);
            if (GlobalVariables.foodItemsDatabase != null)
            {
                int i = await GlobalVariables.foodItemsDatabase.SaveItemAsync(item);

                if (i == 1)
                {
                    List <FoodItem> food = await GlobalVariables.foodItemsDatabase.QueryIdByDate(mDateTime);

                    int id = food.First().ID;
                    await Navigation.PushAsync(new EditDetailsPage(id, GlobalVariables.EntryType.NEW_ENTRY));

                    if (Settings.StageSettings == GlobalVariables.STAGE_1)
                    {
                        CheckForStage2();
                    }
                }
            }
            else
            {
                Console.WriteLine("Unable to store data, no cm found");
            }
        }
Exemplo n.º 30
0
        public static int Update(FoodItem foodItem, bool rollback = false)
        {
            //Update Row
            try
            {
                int results;
                using (AmbrosiaEntities dc = new AmbrosiaEntities())
                {
                    DbContextTransaction transaction = null;
                    if (rollback)
                    {
                        transaction = dc.Database.BeginTransaction();
                    }

                    //New Table Object for row
                    tblFoodItem row = dc.tblFoodItems.FirstOrDefault(g => g.Id == foodItem.Id);

                    if (row != null)
                    {
                        //Set properties
                        row.FDCId    = foodItem.FDCId;
                        row.MealId   = foodItem.MealId;
                        row.Quantity = foodItem.Quantity;

                        results = dc.SaveChanges();
                        if (rollback)
                        {
                            transaction.Rollback();
                        }
                    }
                    else
                    {
                        throw new Exception("Row was not found!!");
                    }
                    return(results);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 31
0
    protected override void OnAwake()
    {
        Transform pivot = transform.Find("Pivot");

        btnClose         = pivot.Find("BtnClose").gameObject;
        btnUpgrade       = pivot.Find("Bottom/BtnUpgrade").gameObject;
        btnBattle        = pivot.Find("Bottom/BtnBattle").gameObject;
        btnUnload        = pivot.Find("Bottom/BtnUnload").gameObject;
        btnAutoToAddFood = pivot.Find("Bottom/BtnAutoToAddFood").gameObject;

        Transform foodTrans = pivot.Find("Bottom/Foods");

        for (int i = 1; i <= 6; i++)
        {
            FoodItem  tab   = new FoodItem();
            Transform trans = foodTrans.Find(i.ToString());
            tab.itemBtn     = trans.gameObject;
            tab.itemTexture = trans.Find("Texture").GetComponent <UITexture>();
            tab.itemQuality = trans.Find("Quality").GetComponent <UISprite>();
            mFoods.Add(tab);
        }

        expSlider = pivot.Find("Bottom/Progress").GetComponent <UISlider>();
        expNum    = pivot.Find("Bottom/Progress/Num").GetComponent <UILabel>();

        petView                  = pivot.Find("View").GetComponent <UIScrollView>();
        petGrid                  = pivot.Find("View/Grid").GetComponent <UIGrid>();
        petCenterOnChild         = pivot.Find("View/Grid").GetComponent <UICenterOnChild>();
        petCenterOnChild.enabled = false;
        petTemp                  = pivot.Find("View/Temp").gameObject;
        petTemp.SetActive(false);

        petCurrPropertyText1 = pivot.Find("1/Text1").GetComponent <UILabel>();
        petCurrPropertyText2 = pivot.Find("1/Text2").GetComponent <UILabel>();
        petMainPropertyText1 = pivot.Find("2/Text1").GetComponent <UILabel>();
        petMainPropertyText2 = pivot.Find("2/Text2").GetComponent <UILabel>();
        petDesc = pivot.Find("3/Desc").GetComponent <UILabel>();

        petTexture = pivot.Find("ModelTexture").GetComponent <UITexture>();
        InitItems();
        ShowRender();
    }
Exemplo n.º 32
0
    public void AdjustScore(FoodItem food, bool addToScore)
    {
        int   scoreValue = 1;
        float totalCategoryMultiplierBonuses = 0;

        // Checking here because the food scriptable objects have not been set up yet
        if (food.foodScriptableObject != null)
        {
            scoreValue = food.foodScriptableObject.pointValue;

            foreach (sFood.FoodCategory category in food.foodScriptableObject.foodCategories)
            {
                totalCategoryMultiplierBonuses += _foodCategoryMultiplierBonus[category];
            }
        }
        else
        {
            Debug.Log("ScoreSystem::AdjustScore - Food Object does not have food scriptable object set: " + food.gameObject.name);
        }

        if (!addToScore)
        {
            scoreValue *= -1;
        }

        scoreValue += (int)(scoreValue * Math.Max(totalCategoryMultiplierBonuses - 1, 0));
        scoreValue += (int)(scoreValue * Math.Max(_globalScoreMultiplierBonus - 1, 0));

        _currentScore += scoreValue;

        // Debugging purposes. Remove when UI is added.
        Debug.Log("ScoreSystem::AdjustScore - Player Score is now: " + _currentScore);
        UpdateTotalScoreDisplay();

        if (_gameStateController != null)
        {
            if (_gameStateController.GetScoreToWin() <= _currentScore)
            {
                _gameStateController.EndGame();
            }
        }
    }
Exemplo n.º 33
0
        public async Task <IActionResult> Create([Bind("Id,Name,Description,Image,CategoryId,SubCategoryId,Price")] FoodItem foodItem)
        {
            if (!ModelState.IsValid)
            {
                return(View(foodItem));
            }
            _context.Add(foodItem);
            await _context.SaveChangesAsync();

            var webRootPath  = _webHostEnvironment.WebRootPath;
            var files        = HttpContext.Request.Form.Files;
            var thisFoodItem = await _context.FoodItem.FindAsync(foodItem.Id);

            // var imageSaveDateTime = DateTime.Now.ToString();


            if (files.Count > 0)
            {
                var upload    = Path.Combine(webRootPath, "images");
                var extention = Path.GetExtension(files[0].FileName);
                using (var filestream = new FileStream(Path.Combine(upload, thisFoodItem.Id + extention), FileMode.Create))
                {
                    await files[0].CopyToAsync(filestream);
                }

                thisFoodItem.Image = @"\images\" + thisFoodItem.Id + extention;
            }
            else
            {
                var sourceImage = Path.Combine(webRootPath, "images", StaticItems.defaultImage);
                var destination = Path.Combine(webRootPath, "images", thisFoodItem.Id + ".png");
                System.IO.File.Copy(sourceImage, destination);
                thisFoodItem.Image = @"\images\" + thisFoodItem.Id + ".png";
            }
            await _context.SaveChangesAsync();



            // ViewData["CategoryId"] = new SelectList(_context.Category, "Id", "Name", foodItem.CategoryId);
            //ViewData["SubCategoryId"] = new SelectList(_context.SubCategory, "Id", "Name", foodItem.SubCategoryId);
            return(RedirectToAction(nameof(Index)));
        }
Exemplo n.º 34
0
        public static int Insert(FoodItem foodItem, bool rollback = false)
        {
            try
            {
                int results;

                using (AmbrosiaEntities dc = new AmbrosiaEntities())
                {
                    DbContextTransaction transaction = null;
                    if (rollback)
                    {
                        transaction = dc.Database.BeginTransaction();
                    }
                    // Make a new row
                    tblFoodItem row = new tblFoodItem();

                    // Set the properties
                    row.Id       = Guid.NewGuid();
                    row.FDCId    = foodItem.FDCId;
                    row.Quantity = foodItem.Quantity;
                    row.MealId   = foodItem.MealId;


                    // Back fill the Id on the  object (parameter)
                    foodItem.Id = row.Id;

                    // Insert the row
                    dc.tblFoodItems.Add(row);

                    results = dc.SaveChanges();
                    if (rollback)
                    {
                        transaction.Rollback();
                    }
                }
                return(results);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 35
0
        public void formatItems(string[] items, List <FoodItem> foodList)
        {
            for (int i = 0; i < items.Length; i++)
            {
                //Quality control
                var foodItem = new FoodItem();

                string       temp    = items[i];
                const string pattern = @"\s*(?<foodName>([^\d+]+))\s*(?<isNegative>([^\w]))\s*(?<SellinValue>\d+)\s(?<Quality>\d+)";
                Regex        r       = new Regex(pattern, RegexOptions.Compiled);

                Match m = r.Match(temp);

                try {
                    string foodName    = m.Groups["foodName"].Value;
                    int    quality     = int.Parse(m.Groups["Quality"].Value);
                    int    sellinValue = int.Parse(m.Groups["SellinValue"].Value);
                    string isNegative  = m.Groups["isNegative"].Value;

                    if (isNegative == "-")
                    {
                        sellinValue = sellinValue * -1;
                    }

                    foodItem.Name        = foodName.TrimEnd();
                    foodItem.SellinValue = sellinValue;
                    foodItem.Quality     = quality;
                }
                catch
                {
                    string foodName    = "Invalid";
                    int?   quality     = null;
                    int?   sellinValue = null;
                    string isNegative  = null;
                }

                foodList.Add(foodItem);
            }


            return;
        }
Exemplo n.º 36
0
    void OnTriggerEnter(Collider c)
    {
        if ( c.GetComponent<FoodItem>() ) {
            FoodItem item = c.GetComponent<FoodItem>();

            // register feedback
            audio.Play();
            textScanner.text = item.ToScanString(true);
            scannerMesh.material.color = new Color( 1f, 0.25f, 0f, 1f );

            // add to cart, update cart
            cart.Add( item );
            // UpdateCart();

            // move item along
            if ( item == currentHeld )
                currentHeld = null;
            item.rigidbody.velocity = transform.forward * 15f - transform.up * 3f;
        }
    }
Exemplo n.º 37
0
    private void CreateFoodItem(string title, int stackSize, int id, int foodPower, int waterPower)// id 2000-2999
    {
        FoodItem item = new FoodItem {
            Title = title, StackSize = stackSize, Id = id, FoodPower = foodPower, WaterPower = waterPower
        };

        item.Icon = "ItemSprite/" + id;
        if (item.Icon == null)
        {
            item.Icon = "ItemSprite/Unknown";
        }

        item.WorldObj = "ItemObj/" + id;
        if (item.WorldObj == null)
        {
            item.WorldObj = "ItemObj/Unknown";
        }

        IDB.Add(item);
    }
Exemplo n.º 38
0
 //used to avoid reinserting the last element in the database when the user refreshes the page
 public FoodItem findLatestFood()
 {
     using (var _dcm = new DatabaseConnectionManager())
     {
         int count = _dcm.FoodItems.Count();
         if (count != 0)
         {
             long     maxId      = _dcm.FoodItems.Max(x => x.Id);
             FoodItem query_food = _dcm.FoodItems.Where(x => x.Id == maxId).FirstOrDefault();
             return(query_food);
         }
         else
         {
             FoodItem query_food = new FoodItem();
             query_food.Name         = "Initial food";
             query_food.PurchaseDate = new DateTime(2020 - 01 - 01);
             return(query_food);
         }
     }
 }
        public ActionResult AddFoodItem(EventBaseViewModel model)
        {
            var response = new Response { Error = false };

            try
            {
                //Add to the food items table if it doesn't exist
                var newFoodItem = new FoodItem { Title = model.AddFoodItem.Title, Description = model.AddFoodItem.Description };
                _foodRepository.Insert(newFoodItem);
                _foodRepository.SubmitChanges();

                //Add to the user's personal list of food items
                var thePerson = _personRepository.GetAll().FirstOrDefault(x => x.PersonId == model.PersonId);
                thePerson.MyFoodItems.Add(newFoodItem);

                //Add the person's pending food item to session
                SessionUtility.Events.AddFoodItem(newFoodItem.FoodItemId, model.EventId);
                SessionUtility.Person.AddFoodItem(newFoodItem.FoodItemId, model.PersonId);

                //Get list of all pending food ids for this event from session
                var pendingEventFoodItemIds = SessionUtility.Events.GetPendingFoodItems(model.EventId);
                var pendingPersonFoodItemIds = SessionUtility.Person.GetPendingFoodItems(model.PersonId);

                //Populate the food items already being brought
                var foodList = GetSelectedFoodItems(pendingEventFoodItemIds, pendingPersonFoodItemIds, model.EventId);
                response.Data = RenderRazorViewToString("_FoodItemListTemplate", foodList);

                //Save to the database if no errors have occurred
                _personRepository.SubmitChanges();
            }
            catch (Exception)
            {
                //TODO: log error to database
                response.Error = true;
                response.Message = Constants.SERVICE_ADD_FOOD_ITEM_FAIL;
            }

            return Json(response);
        }
Exemplo n.º 40
0
 public Food(FoodType type, FoodItem item, int n)
 {
     Type = type;
     Item = item;
     N = n;
 }
Exemplo n.º 41
0
 public GetFoodItemByIdResponse()
 {
     FoodItem = new FoodItem();
 }
 public FoodItemViewModel(FoodItem model)
 {
     FoodItemId = model.FoodItemId;
     Title = model.Title;
     Description = model.Description;
 }
Exemplo n.º 43
0
 public void AddFood(FoodItem food)
 {
     OrderedFood.Add(food);
 }