コード例 #1
0
ファイル: GridMarket.cs プロジェクト: vash1127/QuantumHangar
        public void PurchaseGrid(GridsForSale grid)
        {
            //Need to check hangar of the person who bought the grid

            if (!Config.GridMarketEnabled)
            {
                return;
            }
            //Get Item from market list for price
            MarketList Item = null;

            List <MarketList> Allitems = new List <MarketList>();

            //Incluse all offers!
            Allitems.AddRange(GridList);
            Allitems.AddRange(PublicOfferseGridList);


            try
            {
                Item = Allitems.First(x => x.Name == grid.name);
            }
            catch
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Grid has been removed from market!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }


            MyPlayer.PlayerId BuyPlayer = new MyPlayer.PlayerId(grid.BuyerSteamid);
            MySession.Static.Players.TryGetPlayerById(BuyPlayer, out MyPlayer Buyer);

            GridMethods BuyerMethods = new GridMethods(grid.BuyerSteamid, Config.FolderDirectory);

            //string BuyerPath = GridMethods.CreatePathForPlayer(Config.FolderDirectory, grid.BuyerSteamid);

            if (Buyer == null)
            {
                Hangar.Debug("Unable to get steamID. Glitched player?");
                return;
                //Some kind of error message directed to player.
            }

            //Debug("Seller SteamID: " + Item.Steamid);
            MyCharacter Player = Buyer.Character;

            Hangar.Debug("Player Buying grid: " + Player.DisplayName + " [" + grid.BuyerSteamid + "]");

            //Start transfer of grids!
            int MaxStorage = Config.NormalHangarAmount;

            if (Player.PromoteLevel >= MyPromoteLevel.Scripter)
            {
                MaxStorage = Config.ScripterHangarAmount;
            }

            PlayerInfo BuyerData = new PlayerInfo();

            //Get PlayerInfo from file
            try
            {
                BuyerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json")));
                if (BuyerData.Grids.Count >= MaxStorage)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! No room in hangar!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }
            }
            catch
            {
                Hangar.Debug("Buyer doesnt have anything stored in their hangar! THIS IS NOT AN ERROR!");
                //ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", MyFontEnum.Red, grid.BuyerSteamid);
                //Debug("Deserialization error! Make sure files exist! \n" + e);
                //New player. Go ahead and create new. Should not have a timer.
            }



            //Adjust player prices (We need to check if buyer has enough moneyies hehe)
            bool RetrieveSuccessful = Utils.TryGetPlayerBalance(grid.BuyerSteamid, out long BuyerBallance);

            if (!RetrieveSuccessful || BuyerBallance < Item.Price)
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! Not enough credits!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }



            string NewGridName    = Item.Name;
            bool   FileStilExists = true;
            int    i = 0;

            if (File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc")))
            {
                while (FileStilExists)
                {
                    i++;
                    if (!File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + "[" + i + "].sbc")))
                    {
                        FileStilExists = false;
                    }
                    //Turns out there is already a ship with that name in this players hangar!
                    if (i > 50)
                    {
                        _ChatManager.SendMessageAsOther("GridMarket", "Dude what the actual f**k do you need 50 of these for?", VRageMath.Color.Yellow, grid.BuyerSteamid);
                        Hangar.Debug("Dude what the actual f**k do you need 50 of these for? Will not continue due to... security reasons. @" + NewGridName);
                        return;
                    }
                }

                NewGridName = NewGridName + "[" + i + "]";
            }



            if (Item.Steamid == 0)
            {
                //Check to see if the item existis in the dir
                string PublicOfferPath = ServerOffersDir;
                string GridPath        = Path.Combine(PublicOfferPath, Item.Name + ".sbc");

                //Add counter just in case some idiot


                string BuyerGridPath = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                if (!File.Exists(GridPath))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Server Offer got manually deleted from folder! Blame admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Someone tried to buy a ship that doesnt exist! Did you delete it?? @" + GridPath);
                }

                //Need to check if player can buy
                PublicOffers Offer;
                int          Index;
                try
                {
                    Offer = Config.PublicOffers.First(x => x.Name == Item.Name);
                    Index = Config.PublicOffers.IndexOf(Offer);
                }
                catch (Exception e)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Unknown error! @" + GridPath, e, ErrorType.Fatal);
                    return;
                    //Something went wrong
                }



                if (Offer.TotalPerPlayer != 0 && !WithinPlayerLimits(Item.PlayerPurchases, grid.BuyerSteamid, Offer.TotalPerPlayer))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Youve reached your buy limit on this grid!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                //File check complete!
                Hangar.Debug("Old Buyers Balance: " + BuyerBallance);

                //Create PlayerAccount
                PlayerAccount BuyerAccount = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);


                //Need to figure out HOW to get the data in here
                GridStamp stamp = new GridStamp();
                stamp.GridForSale = false;
                stamp.GridName    = NewGridName;


                //Add it to buyers info
                File.Copy(GridPath, BuyerGridPath);
                BuyerData.Grids.Add(stamp);


                //Update ALL blocks
                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);


                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);

                MarketServers.Update(SendAccountUpdate);

                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);

                //Write all files!
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));

                Offer.NumberOfBuys++;

                if (Offer.TotalPerPlayer != 0)
                {
                    AddPlayerPurchase(PublicOfferseGridList, Item, grid.BuyerSteamid);
                }

                //Check Total Limit
                if (Offer.NumberOfBuys >= Offer.TotalAmount)
                {
                    Config.PublicOffers[Index].Forsale = false;
                    //Update offers and refresh
                    UpdatePublicOffers();
                }
            }
            else
            {
                //This is a player offer

                GridMethods SellerMethods = new GridMethods(Item.Steamid, Dir);
                //string SellerPath = GridMethods.CreatePathForPlayer(Dir, Item.Steamid);
                Debug("Seller SteamID: " + Item.Steamid);


                PlayerInfo SellerData = new PlayerInfo();


                try
                {
                    SellerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json")));
                }
                catch (Exception e)
                {
                    Hangar.Debug("Seller Hangar Playerinfo is missing! Did they get deleted by admin?", e, ErrorType.Warn);
                    _ChatManager.SendMessageAsOther("GridMarket", "Seller hangar info is missing! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RemoveItem;
                SendMessage.List.Add(Item);
                MarketServers.Update(SendMessage);


                PlayerAccount BuyerAccount  = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);
                PlayerAccount SellerAccount = new PlayerAccount(Item.Seller, Item.Steamid, Item.Price, true);



                //Get grids
                GridStamp gridsold = SellerData.Grids.FirstOrDefault(x => x.GridName == grid.name);
                //Reset grid for sale and remove it from the sellers hangarplayerinfo
                gridsold.GridForSale          = false;
                gridsold.ForceSpawnNearPlayer = true;
                SellerData.Grids.Remove(gridsold);
                gridsold.GridName = NewGridName;

                //Add it to buyers info
                BuyerData.Grids.Add(gridsold);

                //Move grid in folders!
                string SellerGridPath = Path.Combine(SellerMethods.FolderPath, grid.name + ".sbc");
                string BuyerGridPath  = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                File.Move(SellerGridPath, BuyerGridPath);

                //After move we need to update all block owners and authors! this meanings opening up the grid and deserializing it to iterate the grid! (we dont want the seller to still be the author)

                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);

                //byte[] Definition = MyAPIGateway.Utilities.SerializeToBinary(grid);

                //Get grid definition of removed grid. (May not even need to get this lol)
                //GridsForSale RemovedGrid = Main.GridDefinition.FirstOrDefault(x => x.name == Item.Name);


                //We need to send to all to remove the item from the list

                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);
                SendAccountUpdate.BalanceUpdate.Add(SellerAccount);

                MarketServers.Update(SendAccountUpdate);
                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);



                //Write all files!
                FileSaver.Save(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json"), SellerData);
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(SellerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(SellerData));
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));
            }
            //Transfer Grid and transfer Author/owner!
        }
コード例 #2
0
        private bool SellOnMarket(string IDPath, GridStamp Grid, PlayerInfo Data, MyIdentity Player, long NumPrice, string Description)
        {
            string path = Path.Combine(IDPath, Grid.GridName + ".sbc");

            if (!File.Exists(path))
            {
                //Context.Respond("Grid doesnt exist! Contact an admin!");
                return(false);
            }



            Parallel.Invoke(() =>
            {
                MyObjectBuilderSerializer.DeserializeXML(path, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                var shipBlueprint             = myObjectBuilder_Definitions.ShipBlueprints;
                MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];



                byte[] Definition       = MyAPIGateway.Utilities.SerializeToBinary(grid);
                GridsForSale GridSell   = new GridsForSale();
                GridSell.name           = Grid.GridName;
                GridSell.GridDefinition = Definition;


                //Seller faction
                var fc = MyAPIGateway.Session.Factions.GetObjectBuilder();

                MyObjectBuilder_Faction factionBuilder;
                try
                {
                    factionBuilder = fc.Factions.First(f => f.Members.Any(m => m.PlayerId == Player.IdentityId));
                    if (factionBuilder != null || factionBuilder.Tag != "")
                    {
                        Grid.SellerFaction = factionBuilder.Tag;
                    }
                }
                catch
                {
                    try
                    {
                        Hangar.Debug("Player " + Player.DisplayName + " has a bugged faction model! Attempting to fix!");
                        factionBuilder = fc.Factions.First(f => f.Members.Any(m => m.PlayerId == Player.IdentityId));
                        MyObjectBuilder_FactionMember member = factionBuilder.Members.First(x => x.PlayerId == Player.IdentityId);

                        bool IsFounder;
                        bool IsLeader;

                        IsFounder = member.IsFounder;
                        IsLeader  = member.IsLeader;

                        factionBuilder.Members.Remove(member);
                        factionBuilder.Members.Add(member);
                    }
                    catch (Exception a)
                    {
                        Hangar.Debug("Welp tbh fix failed! Please why no fix. :(", a, Hangar.ErrorType.Trace);
                    }

                    //Bugged player!
                }



                MarketList List       = new MarketList();
                List.Name             = Grid.GridName;
                List.Description      = Description;
                List.Seller           = "Auction House";
                List.Price            = NumPrice;
                List.Steamid          = Convert.ToUInt64(IDPath);
                List.MarketValue      = Grid.MarketValue;
                List.SellerFaction    = Grid.SellerFaction;
                List.GridMass         = Grid.GridMass;
                List.SmallGrids       = Grid.SmallGrids;
                List.LargeGrids       = Grid.LargeGrids;
                List.NumberofBlocks   = Grid.NumberofBlocks;
                List.MaxPowerOutput   = Grid.MaxPowerOutput;
                List.GridBuiltPercent = Grid.GridBuiltPercent;
                List.JumpDistance     = Grid.JumpDistance;
                List.NumberOfGrids    = Grid.NumberOfGrids;
                List.BlockTypeCount   = Grid.BlockTypeCount;
                List.PCU = Grid.GridPCU;


                //List item as server offer
                List.ServerOffer = true;



                //We need to send to all to add one item to the list!
                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.AddItem;
                SendMessage.GridDefinition.Add(GridSell);
                SendMessage.List.Add(List);


                Servers.Update(SendMessage);
            });

            return(true);
        }