Exemple #1
0
    public void MySave()
    {
        Inv.SaveInv(Inv.items);
        filds = new List <SaveField>();
        foreach (Transform child in GameObject.Find("Field").transform)
        {
            filds.Add(child.GetComponent <fild>().Save());
        }
        if (!Directory.Exists(Application.dataPath + "/Saves"))
        {
            Directory.CreateDirectory(Application.dataPath + "/Saves");
        }
        FileStream      fs1       = new FileStream(Application.dataPath + "/Saves/fild.sv", FileMode.Create);
        BinaryFormatter formater1 = new BinaryFormatter();

        formater1.Serialize(fs1, filds);
        fs1.Close();

        events = ListFildEvent.list;
        foreach (fildEvents ev in events)
        {
            ev.TimeLeft = new DateTime(ev.TimeEvent.Subtract(DateTime.Now).Ticks);
        }
        FileStream      fs2       = new FileStream(Application.dataPath + "/Saves/ev.sv", FileMode.Create);
        BinaryFormatter formater2 = new BinaryFormatter();

        formater2.Serialize(fs2, events);
        fs2.Close();
    }
Exemple #2
0
        public override void OpenShop(string shop)
        {
            base.OpenShop(shop);

            if (shop == "Potions")
            {
                AddItem(ItemID.TrapsightPotion, Utils.UniversalPotionCost);
                AddItem(ItemID.HunterPotion, Utils.UniversalPotionCost);
                AddItem(ItemID.InfernoPotion, Utils.UniversalPotionCost);
                return;
            }

            if (shop == "Arrr")
            {
                AddItem(ItemID.Sail);
                AddItem(ItemID.ParrotCracker);
                AddItem(ItemID.BunnyCannon);

                AddItem(ItemID.RangerEmblem, Utils.Coins(0, 0, 0, 1));
                AddItem(ItemID.SorcererEmblem, Utils.Coins(0, 0, 0, 1));
                AddItem(ItemID.SummonerEmblem, Utils.Coins(0, 0, 0, 1));
                AddItem(ItemID.WarriorEmblem, Utils.Coins(0, 0, 0, 1));
                return;
            }

            // Default Shop
            Inv.SetupShop(17);
        }
Exemple #3
0
 public void OnPointerClick(PointerEventData eventData)
 {
     if (this.name == "inventory")
     {
         ToolsClick.currentTool = "arrow";
         Cursor.SetCursor(Resources.Load <Texture2D>("Sprite/InstrumentsPanel/arrow2"), Vector2.zero, CursorMode.Auto);
         if (Inv.inventoryPanel.activeSelf == false)
         {
             Inv.lockPanelInv.SetActive(true);
             Inv.inventoryPanel.SetActive(true);
             Inv.filterPanel.SetActive(true);
             Shop.shopPanel.SetActive(false);
             Inv.buyFildPanel.SetActive(false);
             Inv.FillInventory("first");
         }
         else
         {
             Inv.lockPanelInv.SetActive(false);
             Inv.actionPanel.SetActive(false);
             Inv.filterPanel.SetActive(false);
             Inv.inventoryPanel.SetActive(false);
         }
     }
     else
     {
         Cursor.SetCursor(Resources.Load <Texture2D>("Sprite/InstrumentsPanel/" + this.name + "2"), Vector2.zero, CursorMode.Auto);
         ToolsClick.currentTool = this.name;
     }
 }
        protected void Edit_Screen()
        {
            ComLibrary com = new ComLibrary();
            Message    msg = new Message(g_user_id, g_lang);
            Inv        inv = new Inv(g_user_id, g_lang);
            DataSet    ds  = new DataSet();

            gdvDetail.DataSource = null;
            gdvDetail.DataBind();
            ViewState["gdvDetail"] = null;

            inv.sch_id = ddlTYPE.SelectedValue;

            //ds = inv.GetRecvDisbList2();
            //if (ds == null)
            //{
            //    lblMsg.Text = inv.strErr;
            //    lblMsg.ForeColor = Color.Red;
            //    return;
            //}
            //if (ds.Tables[0].Rows.Count == 0)
            //{
            //    lblMsg.Text = msg.GetMessage("DATA_NOT_EXIST_ERR");
            //    lblMsg.ForeColor = Color.Red;
            //    return;
            //}
            //else
            //{
            //    DataTable dt = ds.Tables[0];
            //    ViewState["gdvDetail"] = dt;
            //    Edit_Grid();
            //}
        }
Exemple #5
0
        private void RefreshBTN_Click(object sender, EventArgs e)
        {
            Inv    inv   = InvBLL.Buscar(1);
            double Total = inv.Total;

            TotalInvWrite.Text = Total.ToString();
        }
Exemple #6
0
        public override void OpenShop(string shop)
        {
            base.OpenShop(shop);

            if (shop == "Guns")
            {
                ShopBulletMain();
                ShopBulletOther();
                ShopPistol();
                ShopRifle();
                ShopShotgun();

                // Msc
                if (NPC.downedPlantBoss)
                {
                    AddItem(ItemID.SniperRifle);
                    AddItem(ItemID.RifleScope);
                }
                if (!Main.dayTime)
                {
                    AddItem(ItemID.IllegalGunParts);
                }
                if (Main.hardMode)
                {
                    AddItem(ItemID.EmptyBullet);
                }
                AddItem(ItemID.AmmoBox);
                AddItem(ItemID.AmmoReservationPotion, Utils.UniversalPotionCost);
                return;
            }

            // Default Shop
            Inv.SetupShop(2);
        }
        public static bool Guardar(Producto producto)
        {
            bool     paso = false;
            Contexto db   = new Contexto();

            try
            {
                if (db.producto.Add(producto) != null)
                {
                    paso = db.SaveChanges() > 0;
                }
                Inv inv = InvBLL.Buscar(1);
                inv.Total += producto.ValorInv;
                InvBLL.Modificar(inv);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                db.Dispose();
            }
            return(paso);
        }
        public static bool Modificar(Producto producto)
        {
            bool     paso      = false;
            Producto productos = ProductosBLL.Buscar(producto.IdProducto);
            Contexto db        = new Contexto();

            try
            {
                float resultado = producto.ValorInv - productos.ValorInv;

                Inv inve = InvBLL.Buscar(1);
                inve.Total += resultado;
                InvBLL.Modificar(inve);

                db.Entry(producto).State = EntityState.Modified;
                paso = (db.SaveChanges() > 0);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                db.Dispose();
            }
            return(paso);
        }
Exemple #9
0
        public Game(string Username)
        {
            InitializeComponent();
            health.Maximum     = 100;
            health.Value       = 100;
            maxHealth.Text     = health.Maximum.ToString();
            currentHealth.Text = health.Value.ToString();
            alive = true;
            String User = Username;

            userName.Text = User;
            //newEnemies.Add( new Enemy(this, 500, 300));
            for (int i = 0; i < 10; i++)
            {
                myInv [i] = new Inv(this, 965 - (38 * i), 12, i);
            }


            testEnemies.Add(new Enemy(this, 300, 100));

            testFood.Add(new Apples(this, 400, 300));


            testFood.Add(new Banana(this, 400, 200));
            Test();


            System.IO.Stream song   = Properties.Resource.Upbeat_Happy_Orchestral_2_by_Gavin_Luke____Epic_Classical_Music_;
            SoundPlayer      player = new SoundPlayer(song);

            //player.Open(new WaveReader(song));
            player.Play();
        }
Exemple #10
0
        public JObject Diff()
        {
            this.Url.ToString();
            string sPath  = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).Path;
            string sQuery = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).QueryString.ToString();

            if (sPath != "/favicon.ico")
            {
                var    query = QueryHelpers.ParseQuery(sQuery);
                string sKey  = query.FirstOrDefault(t => t.Key.ToLower() == "id").Value;

                if (string.IsNullOrEmpty(sKey))
                {
                    sKey = Inv.LookupID(query.First().Key, query.First().Value);
                }

                if (!int.TryParse(query.FirstOrDefault(t => t.Key.ToLower() == "index").Value, out int index))
                {
                    index = 1;
                }

                if (!int.TryParse(query.FirstOrDefault(t => t.Key.ToLower() == "mode").Value, out int mode))
                {
                    mode = 0;
                }

                return(Inv.GetDiff(sKey, index, mode));
            }
            return(null);
        }
        private void HandleInv(CommandMessage rxMsg)
        {
            var inventory = new Inv().DeSerialize(rxMsg.Data);


            logger.Debug("Inventory recieved: " + inventory.Kind);
            if (inventory.Kind == "block")
            {
                if (blocksInTransit.Count == 0)
                {
                    blocksInTransit = ReduceBlocksInTransit(inventory.Items); //reduce blocksInTransit, don't wanna download whole chain again
                                                                              //blocksInTransit = (inventory.Items); //dont reduce blocksInTransit - download whole chain
                    logger.Debug("Reduced blocks, to download : " + blocksInTransit.Count);
                }
                if (blocksInTransit.Count == 0)
                {
                    return;                             //this means, blockInTransit was reduced totaly and nothing is needed
                }
                var latestHashToTake = blocksInTransit[0];
                SendGetData(rxMsg.Client.ToString(), "block", latestHashToTake);
                blocksInTransit.RemoveAt(0);
            }
            else if (inventory.Kind == "tx")
            {
                var txId = inventory.Items[0];
                //request it only if I dont have it yet
                if (!TransactionPool.ContainsKey(HexadecimalEncoding.ToHexString(txId)))
                {
                    SendGetData(rxMsg.Client.ToString(), "tx", txId);
                }
            }
        }
Exemple #12
0
 public void DropFruit()
 {
     if (stage == "stage5")
     {
         int countEv = UnityEngine.Random.Range(mincountFruit, maxcountFruit);
         Inv.GetHarvestToInventory(countEv, fruitId, "harvest");
         ExpBar.AddExp(countExpiriens);
         if (iterationFruit >= 1)
         {
             iterationFruit--;
             stage = "stage3";
             shangeSprite("stage3");
             stageThree = buffStageThree;
             stageFour  = buffStageFour;
             growing    = true;
         }
         else
         {
             if (stage != "stage6")
             {
                 stage = "stage6";
                 shangeSprite("stage6");
             }
         }
     }
 }
Exemple #13
0
        public override void OpenShop(string shop)
        {
            base.OpenShop(shop);

            if (shop == "Potions")
            {
                AddItem(ItemID.CalmingPotion, Utils.UniversalPotionCost);
                AddItem(ItemID.FeatherfallPotion, Utils.UniversalPotionCost);
                return;
            }

            if (shop == "Seeds")
            {
                AddItem(ItemID.GrassSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.CorruptSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.HallowedSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.MushroomGrassSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.CrimsonSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.BlinkrootSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.DaybloomSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.DeathweedSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.FireblossomSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.MoonglowSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.WaterleafSeeds, Utils.UniversalSeedCost);
                AddItem(ItemID.ShiverthornSeeds, Utils.UniversalSeedCost);
                return;
            }

            // Default Shop
            Inv.SetupShop(3);
        }
Exemple #14
0
    // Initialize a link between the player and inventory
    internal void SetInventory(Inv inventory)
    {
        this.inventory = inventory;

        // Handle inventory updates and force refresh when needed
        inventory.OnItemChange += inventory_OnitemChange;
        Refresh();
    }
    /// <summary>
    /// Wystrzeliwuje Ray z kamery gracza i wypisuje wszystkie napotkane obiekty
    /// </summary>
    void Strzal()
    {
        Ray promien = new Ray(Camera.main.transform.position, Camera.main.transform.forward);

        RaycastHit[] trafienia = Physics.RaycastAll(promien, 2f);

        foreach (RaycastHit hit in trafienia)
        {
            //Używanie przedmiotów
            if (hit.transform.root != transform)
            {
                if (hit.transform.root.tag == "Dziura" && rodzajPrzedmiotu == PrzedmiotEnum.spawarka)
                {
                    hit.transform.GetComponent <Dziura>().hp -= 10;
                }
                if (hit.transform.root.tag == "szafka" && rodzajPrzedmiotu == PrzedmiotEnum.wkrentarka)
                {
                    if (hit.transform.GetComponent <Wkrenty>())
                    {
                        hit.transform.GetComponent <Wkrenty>().progress += 10f;
                    }
                    if (hit.transform.GetComponent <WkrentyPod>())
                    {
                        hit.transform.GetComponent <WkrentyPod>().progress += 10f;
                    }
                }
                if (hit.transform.root.tag == "ogien" && rodzajPrzedmiotu == PrzedmiotEnum.gasnica)
                {
                    //hit.transform.GetComponent<Ogien>().hp -= 50;
                }
                if (hit.transform.root.tag == "zaslepka" && rodzajPrzedmiotu == PrzedmiotEnum.plaski)
                {
                    //hit.transform.GetComponent<null>().hp -= 50;
                }
                if (hit.transform.root.tag == "mSzyba" && rodzajPrzedmiotu == PrzedmiotEnum.szyba)
                {
                    Statek statek = FindObjectOfType <Statek>();
                    statek.szyba = 1;
                    Inv inwentory = FindObjectOfType <Inv>();
                    inwentory.obiektWRence = 0;
                }
                if (hit.transform.root.tag == "mZbiornik" && rodzajPrzedmiotu == PrzedmiotEnum.zbiornik)
                {
                    hit.transform.GetComponent <Mzbiornik>().Zbiornik();
                    Statek statek = FindObjectOfType <Statek>();
                    statek.zbiornik = 1;
                    Inv inwentory = FindObjectOfType <Inv>();
                    inwentory.obiektWRence = 0;
                }
                if (hit.transform.root.tag == "rSzyba" && rodzajPrzedmiotu == PrzedmiotEnum.grinder)
                {
                    hit.transform.GetComponent <rGlass>().hp -= 10;
                    grinderPartic.active = true;
                }
            }
        }
    }
        private void newuser_MouseDown(object sender, MouseButtonEventArgs e)
        {

            string time = DateTime.Now.ToString("HH:mm");
            Inv U = new Inv();
            SucFul S = new SucFul();
            ErrorPage E = new ErrorPage();


        }
 public void Load()
 {
     if (File.Exists(string.Concat(Application.persistentDataPath, savePath)))
     {
         IFormatter formatter = new BinaryFormatter();
         Stream     stream    = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Open, FileAccess.Read);
         Container = (Inv)formatter.Deserialize(stream);
         stream.Close();
     }
 }
Exemple #18
0
        public static List <B2b> GetB2BGst1Save(DataTable dtInvoice, DataTable dtInvoiceItemRate)
        {
            #region B2B Section
            List <B2b> _resB2BList = new List <B2b>();

            List <Inv> _resB2BInv = new List <Inv>();
            List <Itm> _resB2BItm = new List <Itm>();
            #endregion

            List <B2b> _b2bList     = new List <B2b>();
            var        distinctctin = (from DataRow dRow in dtInvoice.Rows
                                       select new { col1 = dRow["ctin"] }).Distinct().ToList();

            for (int k = 0; k < distinctctin.Count(); k++)
            {
                B2b _b2b = new B2b();
                _b2b.ctin = distinctctin[k].ToString().Replace("col1 =", "").Replace("{", "").Replace("}", "");
                string _selectParam    = "ctin =" + "'" + _b2b.ctin.TrimStart().TrimEnd() + "'";
                var    currInvoiceLoop = dtInvoice.Select(_selectParam).CopyToDataTable();

                List <ItmDet> _itmdetList = new List <ItmDet>();
                string        JSONString  = string.Empty;
                JSONString = JsonConvert.SerializeObject(currInvoiceLoop);
                _resB2BInv = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Inv> >(JSONString);

                string JSONStringItem = string.Empty;
                JSONStringItem = JsonConvert.SerializeObject(dtInvoiceItemRate);
                _itmdetList    = Newtonsoft.Json.JsonConvert.DeserializeObject <List <ItmDet> >(JSONStringItem);
                _b2b.inv       = _resB2BInv;
                List <Inv> _invList = new List <Inv>();
                for (int i = 0; i < currInvoiceLoop.Rows.Count; i++)
                {
                    Inv           _inv       = new Inv();
                    List <ItmDet> itmdetList = new List <ItmDet>();
                    List <Itm>    _itmList   = new List <Itm>();
                    string        invoiceId  = _b2b.inv[i].InvoiceId;
                    var           _curritm   = (List <ItmDet>)_itmdetList.Where(x => x.InvoiceId == invoiceId).Select(x => x).ToList();
                    _inv = _resB2BInv[i];

                    for (int j = 0; j < _curritm.Count(); j++)
                    {
                        Itm    _itm    = new Itm();
                        ItmDet _itmdet = new ItmDet();
                        _itmdet      = (_curritm[j]);
                        _itm.num     = i + 1;
                        _itm.itm_det = _itmdet;
                        _itmList.Add(_itm);
                        _inv.itms   = _itmList;
                        _b2b.inv[i] = _inv;
                    }
                }
                _b2bList.Add(_b2b);
            }
            return(_b2bList);
        }
Exemple #19
0
 public string InventoryToString(Detail detail = Detail.none)
 {
     if (Inv.Count == 0)
     {
         return("empty");
     }
     return(detail switch
     {
         (Detail.Names) => string.Join(", ", Inv.Select(i => $"{i.IconDisplay} {i.Name}{(i.IsBroken ? " (Broken)" : "")}").ToArray()),
         (Detail.NameAndPrice) => string.Join("\n", Inv.Select(i => $"{i.IconDisplay} {i.Name} - {(Count <= 60 ? "<:coin:569836987767324672>" : "")}{i.Price}").ToArray()),
         _ => string.Join("", Inv.Select(i => i.IconDisplay).ToArray()),
     });
Exemple #20
0
    public void OnPointerClick(PointerEventData eventData)
    {
        switch (this.name)
        {
        case "Sell":
            int itemId = 0;
            if (Inv.currentType == "harvest")
            {
                itemId = Inv.currentHarv.ItemId;
            }
            else if (Inv.currentType == "sead")
            {
                itemId = Inv.currentSead.ItemId;
            }
            else if (Inv.currentType == "fertilizer")
            {
                itemId = Inv.currentFert.ItemId;
            }
            Money.money += Inv.items[itemId].ItemPrice;
            Inv.items[itemId].ItemCount -= 1;
            if (Inv.items[itemId].ItemCount <= 0)
            {
                Inv.DropItem(itemId);
                Inv.actionPanel.SetActive(false);
                Inv.FillInventory("current");
            }
            else
            {
                int id = Inv.currSelect;
                Inv.FillInventory("current");
                Inv.Select(id);
            }
            GameObject.Find("Sounds").GetComponent <Sounds>().PlayBuy();
            break;

        case "Plant":
            Inv.actionPanel.SetActive(false);
            Inv.inventoryPanel.SetActive(false);
            Inv.filterPanel.SetActive(false);
            if (Inv.currentType == "fertilizer")
            {
                ToolsClick.currentTool = "fertilizer";
            }
            else
            {
                ToolsClick.currentTool = "planted";
            }
            Cursor.SetCursor(Resources.Load <Texture2D>("Sprite/InstrumentsPanel/cartoon-seeds2"), Vector2.zero, CursorMode.Auto);
            Inv.lockPanelInv.SetActive(false);
            break;
        }
    }
        public override void OpenShop(string shop)
        {
            base.OpenShop(shop);

            if (shop == "Buffs")
            {
                AddItem(ItemID.GravitationPotion, Utils.UniversalPotionCost);
                AddItem(ItemID.SwiftnessPotion, Utils.UniversalPotionCost);

                AddItem(ItemID.ThornsPotion, Utils.UniversalPotionCost);

                AddItem(ItemID.TitanPotion, Utils.UniversalPotionCost);

                AddItem(ItemID.WarmthPotion, Utils.UniversalPotionCost);

                AddItem(ItemID.WrathPotion, Utils.UniversalPotionCost);

                return;
            }

            if (shop == "Robotics")
            {
                AddItem(ItemID.ProximityMineLauncher);
                AddItem(ItemID.Nanites);
                AddItem(ItemID.PortalGun);
                AddItem(ItemID.PortalGunStation);

                if (NPC.downedGolemBoss)
                {
                    AddItem(ItemID.ElectrosphereLauncher);
                }

                if (NPC.downedFishron)
                {
                    AddItem(ItemID.RocketLauncher);
                }

                if (NPC.downedAncientCultist)
                {
                    AddItem(ItemID.SnowmanCannon);
                }

                if (NPC.downedTowerVortex)
                {
                    AddItem(ItemID.NailGun);
                }
                return;
            }

            // Default Shop
            Inv.SetupShop(14);
        }
Exemple #22
0
        public JsonResult Search()
        {
            this.Url.ToString();
            string sPath  = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).Path;
            string sQuery = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).QueryString.ToString();

            if (sPath != "/favicon.ico")
            {
                var query = QueryHelpers.ParseQuery(sQuery);
                return(Json(Inv.search(query.FirstOrDefault(t => string.IsNullOrEmpty(t.Value)).Key, query.FirstOrDefault(t => t.Key.ToLower() == "$select").Value)));
            }
            return(null);
        }
 void Clos()
 {
     if (Active == true)
     {
         Inv.SetActive(false);
         FireplacePart.SetActive(false);
         InfoPart.SetActive(true);
         CtrlPart.SetActive(true);
         RightFinger.SetActive(true);
         InventoryScript.InvOpn = false;
         Hit.collider.gameObject.GetComponent <FirePlaceScript>().Active = false;
     }
 }
Exemple #24
0
 public void OnPointerClick(PointerEventData eventData)
 {
     if (Money.money >= this.price && ExpBar.currentCountlvl >= this.level)
     {
         Money.money -= this.price;
         Inv.GetHarvestToInventory(1, this.id, "sead");
         GameObject.Find("Sounds").GetComponent <Sounds>().PlayBuy();
     }
     else
     {
         GameObject.Find("Sounds").GetComponent <Sounds>().PlayFail();
     }
 }
Exemple #25
0
 public void OnPointerClick(PointerEventData eventData)
 {
     if (Money.money >= this.itemPrice)
     {
         Money.money -= this.itemPrice;
         Inv.GetHarvestToInventory(1, this.id, "fertilizer");
         GameObject.Find("Sounds").GetComponent <Sounds>().PlayBuy();
     }
     else
     {
         GameObject.Find("Sounds").GetComponent <Sounds>().PlayFail();
     }
 }
Exemple #26
0
        public override void OpenShop(string shop)
        {
            base.OpenShop(shop);

            if (shop == "Logic")
            {
                AddItem(ItemID.LogicGateLamp_Faulty);
                AddItem(ItemID.LogicGateLamp_Off);
                AddItem(ItemID.LogicGate_AND);
                AddItem(ItemID.LogicGate_NAND);
                AddItem(ItemID.LogicGate_NOR);
                AddItem(ItemID.LogicGate_NXOR);
                AddItem(ItemID.LogicGate_OR);
                AddItem(ItemID.LogicGate_XOR);
                AddItem(ItemID.LogicSensor_Above, Utils.Coins(0, 0, 1));
                AddItem(ItemID.LogicSensor_Honey, Utils.Coins(0, 0, 1));
                AddItem(ItemID.LogicSensor_Lava, Utils.Coins(0, 0, 1));
                AddItem(ItemID.LogicSensor_Liquid, Utils.Coins(0, 0, 1));
                AddItem(ItemID.LogicSensor_Moon, Utils.Coins(0, 0, 1));
                AddItem(ItemID.LogicSensor_Sun, Utils.Coins(0, 0, 1));
                AddItem(ItemID.LogicSensor_Water, Utils.Coins(0, 0, 1));
                return;
            }

            if (shop == "Solutions")
            {
                AddItem(ItemID.PurpleSolution);
                AddItem(ItemID.RedSolution);
                AddItem(ItemID.GreenSolution);
                AddItem(ItemID.DarkBlueSolution);
                AddItem(ItemID.BlueSolution);
                return;
            }

            if (shop == "Gear")
            {
                AddItem(ItemID.Teleporter);
                AddItem(ItemID.Jetpack);
                AddItem(ItemID.Solidifier);
                AddItem(ItemID.BlendOMatic);
                AddItem(ItemID.FleshCloningVaat);
                AddItem(ItemID.SteampunkBoiler);
                AddItem(ItemID.Cog);
                AddItem(ItemID.StaticHook);
                AddItem(ItemID.ConveyorBeltRight);
                return;
            }

            // Default Shop
            Inv.SetupShop(11);
        }
        private void LoadInventory()
        {
            // Decided to switch to just using JSON to store the inventory
            try
            {
                using (Stream stream = File.OpenRead(DBLoc))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Inventory));
                    Inv = (Inventory)serializer.ReadObject(stream);
                    Inv.CorrectItemErrors();                     // No idea why I need this
                }
            }
            catch
            {
                // using statements automatically close IDisposible objects
                using (StreamReader sr = new StreamReader(DBLoc))
                {
                    string head = sr.ReadLine();

                    string headId = head.Split(',')[0];
                    headId = headId.Remove(0, 2);
                    int itemcount = int.Parse(headId);
                    Inv = new Inventory();

                    for (int i = 0; i < itemcount; i++)
                    {
                        string currentitem = sr.ReadLine();

                        // Created this CSVHelper in case some idiot decides to put a
                        // comma in a name or something and corrupt the inventory file.
                        Item item = CSVHelper.DeserializeItem(currentitem);
                        Inv.Items.Add(item.Id, item);
                    }
                }
                int    j        = 0;
                string filename = Path.Combine(Path.GetDirectoryName(DBLoc), Path.GetFileNameWithoutExtension(DBLoc)
                                               + ".old" + Path.GetExtension(DBLoc));

                while (File.Exists(filename))
                {
                    filename = Path.Combine(Path.GetDirectoryName(DBLoc), Path.GetFileNameWithoutExtension(DBLoc)
                                            + ".old" + j++.ToString() + Path.GetExtension(DBLoc));
                }

                File.Move(DBLoc, filename);
                DBLoc = Path.Combine(Path.GetDirectoryName(DBLoc), Path.GetFileNameWithoutExtension(DBLoc) + ".json");
                SaveInventory();
            }
        }
        public void SendInv(string address, string kind, List <byte[]> items)
        {
            var message = new CommandMessage();

            message.Command = CommandType.Inv;
            message.Client  = _blockchainPeer.ClientDetails();
            var inv = new Inv()
            {
                Items = items,
                Kind  = kind
            };

            message.Data = inv.Serialize();
            _blockchainPeer.SendMessageToAddressAsync(message, address);
        }
Exemple #29
0
        public JArray QueryAll()
        {
            this.Url.ToString();
            string sPath  = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).Path;
            string sQuery = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest) this.Request).QueryString.ToString();

            if (sPath != "/favicon.ico")
            {
                //string sUri = Microsoft.AspNetCore.Http.Extensions.UriHelper.GetDisplayUrl(Request);
                var query = QueryHelpers.ParseQuery(sQuery);

                return(Inv.queryAll(string.Join(",", query.Where(t => string.IsNullOrEmpty(t.Value)).Select(t => t.Key).ToList()), query.FirstOrDefault(t => t.Key.ToLower() == "$select").Value));
            }
            return(null);
        }
        public override void OpenShop(string shop)
        {
            base.OpenShop(shop);

            if (shop == "Gear")
            {
                AddItem(ItemID.StrangeGlowingMushroom);
                AddItem(ItemID.MushroomSpear);
                AddItem(ItemID.Hammush);
                AddItem(ItemID.Autohammer);
                return;
            }

            // Default Shop
            Inv.SetupShop(10);
        }
        private void ListenerLoop()
        {
            try
            {
                NetworkStream ns = _tcpClient.GetStream();

                while (ns.CanRead)
                {
                    #region Read header and payload from network

                    Header header;
                    Payload payload;
                    try
                    {
                        header = new Header(BinaryReader);
                        payload =
                            (header.Length == 0)
                            ? new Payload(header.Command, null)
                            : new Payload(header.Command, BinaryReader.ReadBytes(header.Length));
                    }
                    catch (Exception e)
                    {
                        string excptionStr = e.ToString();
                        if ((e is IOException) || (e is SocketException))
                            excptionStr = "";
                        Debug.WriteLine("соединение " + NetworkAddress + " потерено " + excptionStr);
                        Bitmessage.NodeIsDisconnected.Set();
                        break;
                    }

                    #endregion Read header and payload from network

                    bool checksum = header.Checksum.SequenceEqual(payload.Checksum());

                    if (checksum && payload.IsValid)
                    {
                        debug("Command=" + header.Command);

                        #region Save payload to Inventory

                        if ((header.Command == "msg") || (header.Command == "pubkey") || (header.Command == "broadcast") || (header.Command == "getpubkey"))
                        {
                            _nodeConnectionInventory.Insert(payload.InventoryVector);
                            payload.SaveAsync(Bitmessage);
                        }

                        #endregion Save to Inventory

                        #region VERSION

                        if (header.Command == "version")
                        {
                            var v = new Version(payload);
                            debug("Подключились с " + v.UserAgent);
                            if ((v.Value != 1) && (v.Value != 2))
                                Stop("Version = " + v.Value);
                            else if (v.Nonce == Version.EightBytesOfRandomDataUsedToDetectConnectionsToSelf)
                            {
                                Bitmessage.DeleteNode(NetworkAddress);
                                Stop("DetectConnectionsToSelf");
                            }
                            else
                                Send(new Verack());
                        }

                        #endregion VERSION

                        #region INV

                        else if (header.Command == "inv")
                        {
                            var inputInventory = new Inv(payload.SentData);
                            var buff4GetData = new MemoryInventory(inputInventory.Count);

                            debug("прислали inv. Inventory.Count=" + inputInventory.Count);

                            //lock (Bitmessage.MemoryInventory)
                            //{
                                foreach (byte[] inventoryVector in inputInventory)
                                {
                                    _nodeConnectionInventory.Insert(inventoryVector);
                                    if (!Bitmessage.MemoryInventory.Exists(inventoryVector))
                                    {
                                        Bitmessage.MemoryInventory.AddWait(inventoryVector);
                                        buff4GetData.Insert(inventoryVector);
                                    }
                                }
                            //}

                            if (buff4GetData.Count > 0)
                            {
                                debug("SendGetdata count=" + buff4GetData.Count);
                                Send(new GetData(buff4GetData));
                            }
                            else
                                debug("All know, don't send GetData");
                        }

                        #endregion

                        #region verack

                        else if (header.Command == "verack")
                        {
                            Send(new Inv(Bitmessage.MemoryInventory));

                            NetworkAddress.TimeLastSeen = DateTime.UtcNow;
                            NetworkAddress.SaveAsync(Bitmessage.DB);

                        }

                        #endregion

                        #region getpubkey

                        else if (header.Command == "getpubkey")
                        {
                            var getpubkey = new GetPubkey(payload);

                            PrivateKey pk = Bitmessage.FindPrivateKey(getpubkey);
                            if ((pk != null) &&
                                (pk.LastPubkeySendTime.ToUnix() <
                                 (DateTime.UtcNow.ToUnix() - Payload.LengthOfTimeToHoldOnToAllPubkeys)))
                            {
                                pk.SendAsync(Bitmessage);
                            }
                        }

                            #endregion getpubkey

                            #region pubkey

                        else if (header.Command == "pubkey")
                        {
                            int pos = payload.FirstByteAfterTime;
                            var pubkey = new Pubkey(payload.SentData, ref pos, true);

                            if (pubkey.Status == Status.Valid)
                            {
                                pubkey.SaveAsync(Bitmessage.DB);
                                Bitmessage.OnReceivePubkey(pubkey);
                            }
                            else
                                Bitmessage.OnReceiveInvalidPubkey(pubkey);
                        }

                            #endregion PUBKEY

                            #region msg

                        else if (header.Command == "msg")
                        {
                            var msg = new Msg(Bitmessage, payload);
                            msg.SaveAsync(Bitmessage.DB);

                            if (msg.Status == Status.Valid)
                                Bitmessage.OnReceiveMsg(msg);
                            else
                                Bitmessage.OnReceiveInvalidMsg(msg);
                        }

                            #endregion MSG

                            #region broadcast

                        else if (header.Command == "broadcast")
                        {
                            var broadcast = new Broadcast(Bitmessage, payload);
                            broadcast.SaveAsync(Bitmessage.DB);

                            if (broadcast.Status == Status.Valid)
                                Bitmessage.OnReceiveBroadcast(broadcast);
                            else
                                Bitmessage.OnReceiveInvalidBroadcast(broadcast);
                        }

                            #endregion BROADCAST

                            #region addr

                        else if (header.Command == "addr")
                        {
                            int pos = 0;
                            UInt64 numberOfAddressesIncluded = payload.SentData.ReadVarInt(ref pos);
                            if ((numberOfAddressesIncluded > 0) && (numberOfAddressesIncluded < 1001))
                            {
                                if (payload.Length != (pos + (38*(int) numberOfAddressesIncluded)))
                                    throw new Exception(
                                        "addr message does not contain the correct amount of data. Ignoring.");

                                while (pos < payload.Length)
                                {
                                    NetworkAddress networkAddress = NetworkAddress.GetFromAddrList(payload.SentData,
                                                                                                   ref pos);
                                    Bitmessage.AddNode(networkAddress);
                                }
                            }
                        }

                            #endregion addr

                            #region getdata

                        else if (header.Command == "getdata")
                        {
                            debug("Load getdata");
                            var getData = new GetData(payload.SentData);

                            foreach (byte[] hash in getData.Inventory)
                                Payload.SendAsync(this, hash.ToHex(false));
                        }

                            #endregion getdata

                            #region ping

                        else if (header.Command == "ping")
                        {
                            Send(new Pong());
                        }

                            #endregion ping

                            #region pong

                        else if (header.Command == "pong")
                        {

                        }

                            #endregion pong

                        else debug("unknown command");
                    }
                    else
                        debug("checksum error");
                }
                _tcpClient.Close();
            }
            // ReSharper disable EmptyGeneralCatchClause
            catch(Exception e)
            {
                debug("Закрываю соединение " + e);
            } // ReSharper restore EmptyGeneralCatchClause

            Bitmessage.NodeIsDisconnected.Set();
        }