public void ShowHideTrade(bool makingOffer = true, TradeOffer offer = null) { tradeThisDiscription.renderer.enabled = !tradeThisDiscription.renderer.enabled; forThisDiscription.renderer.enabled = !forThisDiscription.renderer.enabled; offerTradeButton.renderer.enabled = !offerTradeButton.renderer.enabled; offerTradeButton.collider.enabled = !offerTradeButton.collider.enabled; offerTradeButtonText.renderer.enabled = !offerTradeButtonText.renderer.enabled; endTradeButtonText.renderer.enabled = !endTradeButtonText.renderer.enabled; endTradeButton.renderer.enabled = !endTradeButton.renderer.enabled; endTradeButton.collider.enabled = !endTradeButton.collider.enabled; int[] getArray = {}; int[] giveArray = {}; if(!makingOffer){ PlayerHand get = offer.convertGetResourcesToPlayerHand(); getArray = get.ToArray (); PlayerHand give = offer.convertGiveResourcesToPlayerHand(); giveArray = give.ToArray (); } GameObject[][] tradingObjects = {tradeThisText, forThisText, tradeThis, forThis}; int counter = 0; int objCounter = 0; foreach (GameObject[] arr in tradingObjects) { counter = 0; foreach (GameObject obj in arr){ obj.renderer.enabled = !obj.renderer.enabled; if (obj.collider != null) obj.collider.enabled = !obj.collider.enabled; if (obj.collider == null && makingOffer){ obj.GetComponent<TextMesh>().text = "0"; } else if (obj.collider == null){ if(objCounter == 2) obj.GetComponent<TextMesh>().text = ""+giveArray[counter]; else obj.GetComponent<TextMesh>().text = ""+getArray[counter]; counter++; } } objCounter++; } //TODO make gui for trading offer if (makingOffer) { offerTradeButtonText.GetComponent<TextMesh> ().text = "Offer Trade!"; endTradeButtonText.GetComponent<TextMesh> ().text = "End Trading"; } else { offerTradeButtonText.GetComponent<TextMesh> ().text = "Accept Offer"; endTradeButtonText.GetComponent<TextMesh> ().text = "Decline Offer"; } }
public override void OnTradeOfferRecieved(TradeOffer offer){ Debug.Log (playerName + ": Resolving Trade offer"); if(hasSet == false){ ResolveTradeOffer(true); } else{ ResolveTradeOffer(false); } }
public override void OnNewTradeOffer(TradeOffer offer) { //receiving a trade offer if (IsAdmin) { //parse inventories of bot and other partner //either with webapi or generic inventory //Bot.GetInventory(); //Bot.GetOtherInventory(OtherSID); var myItems = offer.Items.GetMyItems(); var theirItems = offer.Items.GetTheirItems(); Log.Info("They want " + myItems.Count + " of my items."); Log.Info("And I will get " + theirItems.Count + " of their items."); //do validation logic etc if (DummyValidation(myItems, theirItems)) { TradeOfferAcceptResponse acceptResp = offer.Accept(); if (acceptResp.Accepted) { Bot.AcceptAllMobileTradeConfirmations(); Log.Success("Accepted trade offer successfully : Trade ID: " + acceptResp.TradeId); } } else { // maybe we want different items or something //offer.Items.AddMyItem(0, 0, 0); //offer.Items.RemoveTheirItem(0, 0, 0); if (offer.Items.NewVersion) { string newOfferId; if (offer.CounterOffer(out newOfferId)) { Bot.AcceptAllMobileTradeConfirmations(); Log.Success("Counter offered successfully : New Offer ID: " + newOfferId); } } } } else { //we don't know this user so we can decline if (offer.Decline()) { Log.Info("Declined trade offer : " + offer.TradeOfferId + " from untrusted user " + OtherSID.ConvertToUInt64()); } } }
public PrintTradeOffer(TradeOffer offer, OutputStream outputStream) { Offer = offer; OutputStream = outputStream; }
public bool processTradeRequest(GameState gamestate, TradeOffer trade, GameEngine gameengine) { if(debugMessages) { GameEngine.print ("PLAYER " + trade.tradeHost.id + " ATTEMPTING TO BROKER TRADE WITH PLAYER " + this.id); } bool doesAcceptTrade = false; if(isAI) { // Verify that trade is permissible based on player hand if(hand.IsViableTradeRequest(trade)) { // if player trade evaluation returns true, accept trade request doesAcceptTrade = evaluateTradeRequest(gamestate, trade); } } else { if (Input.GetMouseButtonDown (0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if(hit.transform == gameengine.acceptTradeButton){ return true; } if(hit.transform == gameengine.declineTradeButton){ return false; } } } } return doesAcceptTrade; }
public IEnumerator ProcessTradeOffer (TradeOffer offer) { // wait for 2 frames, incase this was a counter offer yield return new WaitForEndOfFrame(); yield return new WaitForEndOfFrame(); Debug.Log (playerName+": Trade Offer Recieved"); // process trade offer isProcessingTradeOffer = true; Debug.Log (playerName+": Processing Trade Offer..."); OnTradeOfferRecieved(offer); while(isProcessingTradeOffer == true){ yield return new WaitForEndOfFrame(); } Debug.Log (playerName+": Done processing trade offer..."); // did we accept? if(didAcceptTrade == true){ // make the swap Debug.Log ("YAY TRADE ACCEPTED"); // get all the data from the trade GamePlayer senderPlayer = offer.GetSender(); GamePlayer recieverPlayer = offer.GetReciever(); BoardTile senderProperty = offer.GetSenderProperty(); BoardTile recieverProperty = offer.GetRecieverProperty(); // swap the funds senderPlayer.money += offer.recieverFunds; senderPlayer.money -= offer.senderFunds; recieverPlayer.money += offer.senderFunds; recieverPlayer.money -= offer.recieverFunds; // swap the properties senderPlayer.RemoveProperty(senderProperty); recieverPlayer.RemoveProperty(recieverProperty); senderPlayer.AddProperty(recieverProperty); recieverPlayer.AddProperty(senderProperty); // notify the sender that the trade was accepted senderPlayer.TradeOfferAccepted(); UpdateOwnedProperties(); Debug.Log ("Trade Complete!"); } else{ // nothing happens, trade failed offer.GetSender().TradeOfferDeclined(); Debug.Log ("TRADE REJECTED"); } }
public void TradeOfferRouter(TradeOffer offer) { GetUserHandler(offer.PartnerSteamId).OnTradeOfferUpdated(offer); }
public override void OnNewTradeOffer(TradeOffer offer) { if (offer.OfferState != TradeOfferState.TradeOfferStateActive) { return; } Log.Debug("Trade offer from user {0}.", OtherSID.ToString()); if (IsAdmin) { offer.Accept(); Log.Success("Accepted trade offer from admin '{0}'.", Bot.SteamFriends.GetFriendPersonaName(OtherSID)); SendChatMessage("Trade offer complete."); Console.Beep(); } else { bool? hasMatchingOrder = Bot.Orders.HasMatchingOrder(this, offer); Order ord = Bot.Orders.GetMatchingOrder(this, offer); bool isFullStock = IsFullStock(ord); if (hasMatchingOrder == true && !isFullStock) { offer.Accept(); Log.Success("Accepted valid trade offer from user {0}.", OtherSID.ToString()); SendChatMessage("I have accepted your trade offer."); SendChatToAdmins("Accepted trade offer from user {0}: {1}", OtherSID.ToString(), ord.ToString(Trade.CurrentSchema, true)); Console.Beep(); } else if (isFullStock) { offer.Decline(); Log.Warn("Declined trade offer from user {0}, as stock was full."); SendChatMessage("Unfortunately I seem to have full stock of that item. Your offer has been declined."); } else if (hasMatchingOrder != null) { offer.Decline(); Log.Warn("Declined invalid trade offer from user {0}.", OtherSID.ToString()); SendChatMessage("There seems to be a problem with your trade offer. It has been declined."); } else { SendChatMessage("Unable to retrieve your inventory, and thus am unable to respond to your offer."); //SendChatToAdmins("There was an error retrieving the inventory of {0}.", OtherSID.ToString()); } //offer.Decline(); //Log.Warn("Declined trade offer from user {0}.", OtherSID.ToString()); //SendChatMessage("I don't know you. I cannot accept your trade offer."); } }
public override void OnTradeOfferUpdated(TradeOffer offer) { }
public TradeRequest(int player1, int player2) { TradeOffer1 = new TradeOffer(player1); TradeOffer2 = new TradeOffer(player2); }
private void SendOfferToHandler(Offer offer) { var tradeOffer = new TradeOffer(session, offer); tradeOfferHistory.Add(offer.TradeOfferId); OnNewTradeOffer(tradeOffer); }
public void TradeOfferSold(TradeOffer tradeOffer) { AddMoney(tradeOffer.totalValue); }
/// <summary> /// Checks active trade list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MQueueWorker_DoWork(object sender, DoWorkEventArgs e) { while (!mQueueWorker.CancellationPending) { /*If we should pause our actions*/ while (mSessionState == SessionState.Locked) { mQueueSleeping = true; Thread.Sleep(500); } mQueueSleeping = false; /*Add all trades from queue list to main list*/ if (mActiveTradesListQueue.Count > 0) { mActiveTradesList.AddRange(mActiveTradesListQueue); mActiveTradesListQueue.Clear(); } /*List of items that will be deleted from main list when this function has run*/ var deleteList = new List <Config.TradeObject>(); /*Go through the active trades list*/ foreach (var trade in mActiveTradesList) { /*Try to get the trade offer state*/ mLog.Write(Log.LogLevel.Info, $"Checking active {trade.tradeType} trade offer to user {trade.SteamId}"); /*Get updated trade offer from api*/ TradeOffer offer = mBotHost.GetTradeOffer(trade.tradeStatus.Tradelink); if (offer == null) { mLog.Write(Log.LogLevel.Warn, $"Trade offer returned null"); trade.errorCount++; continue; } /*Get the state of the offer*/ mLog.Write(Log.LogLevel.Info, $"Trade offer status: {offer.OfferState}"); if (offer.OfferState == TradeOfferState.TradeOfferStateAccepted) { deleteList.Add(trade); if (trade.tradeType == Config.TradeType.Deposit) { /*The trade was a deposit, so we'll enter the items to the database*/ mDatabase.InsertItems(trade.Items); mLog.Write(Log.LogLevel.Info, $"Items added to database"); trade.tradeStatus.Status = Config.TradeStatusType.DepositAccepted; } else if (trade.tradeType == Config.TradeType.Withdraw) { /*Set state to accepted which is final stage*/ /*These items will be moved to back-up database*/ var idList = trade.Items.Select(o => o.ID).ToList(); mDatabase.UpdateItemStates(idList, Database.ItemState.Accepted); mLog.Write(Log.LogLevel.Info, $"{idList.Count} items updated in the database"); trade.tradeStatus.Status = Config.TradeStatusType.WithdrawAccepted; } } else if (offer.OfferState == TradeOfferState.TradeOfferStateActive) { /*Check if the age of the offer is older than what we allow*/ /*If it's too old we want to remove it, but only if it's a deposit trade*/ if ((Functions.GetUnixTimestamp() - offer.TimeCreated) > mSettings.tradeOfferExpireTimeSeconds && trade.tradeType == Config.TradeType.Deposit) { deleteList.Add(trade); mLog.Write(Log.LogLevel.Info, $"Trade offer is too old"); trade.tradeStatus.Status = Config.TradeStatusType.DepositDeclined; bool cancelResult = mBotHost.CancelTradeOffer(trade.tradeStatus.Tradelink); mLog.Write(Log.LogLevel.Info, $"Q: Were we able to cancel the offer? A: {cancelResult}"); } } else if (offer.OfferState != TradeOfferState.TradeOfferStateNeedsConfirmation) { /*This offer has a a state that we don't want to deal with, so we'll remove it*/ deleteList.Add(trade); trade.tradeStatus.Status = (trade.tradeType == Config.TradeType.Deposit) ? Config.TradeStatusType.DepositDeclined : Config.TradeStatusType.WithdrawDeclined; if (trade.tradeType == Config.TradeType.Withdraw) { /*If the withdraw got declined or failed, then we'll remove the used items*/ mDatabase.RemoveUsedItems(trade.Items.Select(o => o.AssetId).ToList()); } /*If the offer has been countered then we'll decline it, else just leave it*/ if (offer.OfferState == TradeOfferState.TradeOfferStateCountered) { bool cancelResult = mBotHost.DeclineTradeOffer(trade.tradeStatus.Tradelink); mLog.Write(Log.LogLevel.Info, $"Q: Were we able to decline the offer? A: {cancelResult}"); } } } /*Go through all storage offers*/ foreach (var trade in mActiveStorageTradesList) { /*Try to get the trade offer state*/ mLog.Write(Log.LogLevel.Info, $"Checking active storage trade offer"); /*Get updated trade offer from api*/ TradeOffer offer = mBotHost.GetTradeOffer(trade.tradeStatus.Tradelink); if (offer == null) { mLog.Write(Log.LogLevel.Warn, $"Trade offer returned null"); trade.errorCount++; continue; } /*Get offers for the bot that has the offer pending and accept them*/ var bot = mBotList.FirstOrDefault(o => o.GetBotSteamId64() == trade.SteamId); bot?.GetOffers(); /*We only care if it's active*/ if (offer.OfferState == TradeOfferState.TradeOfferStateAccepted) { mLog.Write(Log.LogLevel.Info, $"Storage trade offer accepted. Updating items."); /*Offer was accepted, so we'll first update the owners and then set the itemstate back to active (0)*/ mDatabase.UpdateItemOwners(trade); /*Update the itemstate to be active again*/ mDatabase.UpdateItemStates(trade.Items.Select(o => o.ID).ToList(), Database.ItemState.Active); deleteList.Add(trade); } else if (offer.OfferState != TradeOfferState.TradeOfferStateNeedsConfirmation && offer.OfferState != TradeOfferState.TradeOfferStateActive) { /*For some reason the storage offer failed so we'll delete it and reset the items*/ mDatabase.RemoveUsedItems(trade.Items.Select(o => o.AssetId).ToList()); mDatabase.UpdateItemStates(trade.Items.Select(o => o.ID).ToList(), Database.ItemState.Active); deleteList.Add(trade); } } /*Remove all changed offers from the active trade list*/ if (deleteList.Count > 0) { mActiveTradesList = mActiveTradesList.Except(deleteList).ToList(); mActiveStorageTradesList = mActiveStorageTradesList.Except(deleteList).ToList(); } Website.UpdateTrade(deleteList); Thread.Sleep(7000); } }
public void TradeOfferBought(TradeOffer tradeOffer) { RemoveMoney(tradeOffer.totalValue); AddResource(tradeOffer.productId, tradeOffer.amount); }
public void OpenBuyScreen(TradeOfferWidget widget, TradeOffer offer) { buyWidget.gameObject.SetActive(true); buyWidget.Init(this, offer); selectedWidget = widget; }
public async Task InitializeData() { _dbContext.Database.EnsureDeleted(); if (_dbContext.Database.EnsureCreated()) { await InitializeUsers(); /* * var konventen = new List<Konvent> * { * new Konvent("Home Konvent"), * new Konvent("Faculteiten Konvent"), * new Konvent("Senioren Konvent") * }; * _dbContext.Konventen.AddRange(konventen); * _dbContext.SaveChanges(); */ //Konventen en verenigingen Konvent k1 = new Konvent("Konvent 1", new List <Kleur>() { new Kleur("Bruin", "#6E2C00"), new Kleur("Zwart", "#000000") }); Konvent k2 = new Konvent("Konvent 2"); var verenigingen = new List <Vereniging> { new Vereniging("*****@*****.**", "Vereniging 1", "*****@*****.**", "BE32123456789002", new List <Kleur>() { new Kleur("Blauw", "#3498DB"), new Kleur("Wit", "#FFFFFF") }, k2), new Vereniging("*****@*****.**", "Vereniging 2", "*****@*****.**", "BE32123456789002", new List <Kleur>() { new Kleur("Geel", "#F4D03F"), new Kleur("Zwart", "#000000"), new Kleur("Paars", "#6a0dad") }, k1), new Vereniging("*****@*****.**", "Vereniging 3", "*****@*****.**", "BE32123456789002", new List <Kleur>() { new Kleur("Blauw", "#3498DB"), new Kleur("Paars", "#A569BD"), new Kleur("Groen", "#52BE80") }, k2, true), new Vereniging("*****@*****.**", "Vereniging 4", "*****@*****.**", "BE32123456789002"), new Vereniging("*****@*****.**", "Vereniging 5", "*****@*****.**", "BE32123456789002", new List <Kleur>() { new Kleur("Zwart", "#000000"), new Kleur("Wit", "#FFFFFF") }, k1), new Vereniging("*****@*****.**", "Vereniging 6", "*****@*****.**", "BE32123456789002", new List <Kleur>() { new Kleur("Groen", "#52BE80"), new Kleur("Oranje", "#F5B041"), new Kleur("Wit", "#FFFFFF") }, k2) }; _dbContext.Verenigingen.AddRange(verenigingen); Konvent k3 = new Konvent("Konvent 3"); _dbContext.Konventen.Add(k3); //Editie binnen 20dagen en 30 dagen voor opvulling McEditie editie20 = new McEditie("Editie XXX", DateTime.Now.AddDays(20), DateTime.Now.AddDays(20).AddHours(5), "Expo Hallen", 20, 25, 100); Verkoopmoment vm1 = new Verkoopmoment(editie20, DateTime.Now.AddDays(14), DateTime.Now.AddDays(15), 25, 45); Verkoopmoment vm2 = new Verkoopmoment(editie20, DateTime.Now.AddDays(16), DateTime.Now.AddDays(17), 25, 45); _dbContext.McEdities.Add(editie20); McEditie editie30 = new McEditie("Editie XXXI", DateTime.Now.AddDays(30), DateTime.Now.AddDays(30).AddHours(5), "Expo Hallen", 20, 25, 100); Verkoopmoment vm3 = new Verkoopmoment(editie30, DateTime.Now.AddDays(24), DateTime.Now.AddDays(25), 25, 45); Verkoopmoment vm4 = new Verkoopmoment(editie30, DateTime.Now.AddDays(26), DateTime.Now.AddDays(27), 25, 45); _dbContext.McEdities.Add(editie30); //TEST EDITIE - parameters aanpassen, tijd uitgedrukt in MINUTEN const int aantalVM = 2; const int lengteVM = 2; const int tijdTussenVM = 0; //0 voor geen pauze tussen const int tijdTussenVMenEditie = 180; const int tijdTotEersteVM = -15; const int lengteEditie = 120; const int maxTickets = 2000; const int kostPerMedewerker = 25; const int ticketPrijs = 20; //hier niet meer aankomen const int tijdTotMC = tijdTotEersteVM + (aantalVM * lengteVM) + ((aantalVM - 1) * tijdTussenVM) + tijdTussenVMenEditie; McEditie testEditie = new McEditie("Testeditie", DateTime.Now.AddMinutes(tijdTotMC), DateTime.Now.AddMinutes(tijdTotMC + lengteEditie), "Expo Hallen", ticketPrijs, kostPerMedewerker, maxTickets, false); var vms = new List <Verkoopmoment>(); for (int i = 0; i < aantalVM; i++) { int startVM = tijdTotEersteVM + (i * (lengteVM + tijdTussenVM)); Verkoopmoment vm = new Verkoopmoment(testEditie, DateTime.Now.AddMinutes(startVM), DateTime.Now.AddMinutes(startVM + lengteVM), 25, 45); vms.Add(vm); } _dbContext.McEdities.Add(testEditie); _dbContext.SaveChanges(); foreach (Vereniging v in verenigingen) { await CreateUser(v.Email, v.Email, "P@ssword1", "vereniging"); } _dbContext.SaveChanges(); Vereniging v2 = _dbContext.Verenigingen.Where(v => v.GroepNaam == "Vereniging 2").SingleOrDefault(); Vereniging v3 = _dbContext.Verenigingen.Where(v => v.GroepNaam == "Vereniging 3").SingleOrDefault(); Vereniging v4 = _dbContext.Verenigingen.Where(v => v.GroepNaam == "Vereniging 4").SingleOrDefault(); v2.IsGroot = true; var b1 = new Bestelling(vms[0], v2, 45); vms[0].Bestellingen.Add(b1); b1.IsBetaald = true; var b2 = new Bestelling(vms[0], v3, 10); vms[0].Bestellingen.Add(b2); b2.IsBetaald = true; vms[1].Bestellingen.Add(new Bestelling(vms[1], v2, 45)); vms[1].Bestellingen.Add(new Bestelling(vms[1], v4, 5)); var b3 = new Bestelling(vms[1], v3, 10); vms[1].Bestellingen.Add(b3); b3.IsBetaald = true; TradeOffer offer1 = testEditie.PlaceTradeOffer(v2, 4); TradeOffer offer2 = testEditie.PlaceTradeOffer(v4, 3); offer1.AddResponse(v3, 3); offer1.AddResponse(v4, 4); offer2.AddResponse(v2, 2); testEditie.StartDoorverkoop(); testEditie.StartDownload(); _dbContext.SaveChanges(); } }
private bool evaluateTradeRequest(GameState gamestate, TradeOffer trade) { bool acceptTradeRequest = false; if(!isAI) { // Allow player to accept / reject / modify trade } else { List<AIEngine.Objective> objectives = AIEngine.GetObjectives(this, gamestate.getGamestateBoard(), gamestate); foreach(AIEngine.Objective objective in objectives) { PlayerHand thisPlayerNeedResources = objective.GetCardDifferential(); PlayerHand thisPlayerGiveResources = trade.convertGetResourcesToPlayerHand(); // tradeHost gets the resources that this Player gives PlayerHand thisPlayerGetResources = trade.convertGiveResourcesToPlayerHand(); // tradeHost gives the resources that this Player gets if(debugMessages) { GameEngine.print (objective.GetObjectiveScore() + ": OBJECTIVE SCORE"); GameEngine.print ("PLAYER " + this.id + " GIVES TO TRADEHOST:" + "GIVE " + trade.getBrick + " BRICK, " + "GIVE " + trade.getOre + " ORE, " + "GIVE " + trade.getWood + " WOOD, " + "GIVE " + trade.getGrain + " GRAIN, " + "GIVE " + trade.getSheep + " SHEEP"); GameEngine.print ("FOR " + trade.giveBrick + " BRICK, " + "FOR " + trade.giveOre + " ORE, " + "FOR " + trade.giveWood + " WOOD, " + "FOR " + trade.giveGrain + " GRAIN, " + "FOR " + trade.giveSheep + " SHEEP"); int[] x = thisPlayerNeedResources.ToArray(); GameEngine.print ("PLAYER " + this.id + " (SELLER) NEEDS:" + x[0] + " BRICK, " + x[1] + " ORE, " + x[2] + " WOOD, " + x[3] + " GRAIN, " + x[4] + " SHEEP"); } bool resourcesNeededOverlapsWithResourcesReceived = false; // Compare Cards Received with Cards Needed for(int i = 0; i < 5; i++) { if(thisPlayerNeedResources.GetResourceQuantity(i) < 0 && thisPlayerGetResources.GetResourceQuantity(i) > 0) { resourcesNeededOverlapsWithResourcesReceived = true; } } bool resourcesNeededOverlapsWithResourcesGiven = false; for(int i = 0; i < 5; i++) { if(thisPlayerNeedResources.GetResourceQuantity(i) >= 0 && thisPlayerNeedResources.GetResourceQuantity(i) - thisPlayerGiveResources.GetResourceQuantity(i) < 0) { resourcesNeededOverlapsWithResourcesGiven = true; } } if(debugMessages) { // If any resources needed and received overlap && any resources needed and given do not overlap GameEngine.print ("NEEDS OVERLAPS WITH GET?: " + resourcesNeededOverlapsWithResourcesReceived + "(-true-), " + "NEEDS OVERLAPS WITH GIVE?: " + resourcesNeededOverlapsWithResourcesGiven + " (-false-)"); } if(resourcesNeededOverlapsWithResourcesReceived && !resourcesNeededOverlapsWithResourcesGiven) { if(debugMessages) { GameEngine.print ("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GET NEEDED RESOURCES & ONLY TRADE SURPLUS RESOURCES @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); } if(trade.IsFairTrade() || trade.isGoodTradeForSeller()) { acceptTradeRequest = true; } else { System.Random rand = new System.Random(); if(rand.Next (100) < 25) // 25% Chance to accept an unfair trade (technically could be better for them, but sometimes worse for them) { acceptTradeRequest = true; } } } if(acceptTradeRequest) { if(debugMessages) { GameEngine.print ("# # # # # # # # # # # # # # # # # # # # # # # # # # # ACCEPT TRADE # # # # # # # # # # # # # # # # # # # # # # # # # # #"); } break; } } } return acceptTradeRequest; }
/// <summary> /// Put a trade offer on to the market /// </summary> /// <param name="offer"></param> public static int PutTradeOffer(TradeOffer offer) { try { string query = "INSERT INTO TradeOffers (SellerName, ReceiverName, " + "WoodSender, ClaySender, WoolSender, StoneSender, IronSender, StrawSender, FoodSender, GoldSender, " + "WoodReceiver, ClayReceiver, WoolReceiver, StoneReceiver, IronReceiver, StrawReceiver, FoodReceiver, GoldReceiver) " + "OUTPUT INSERTED.Id " + "VALUES (@Seller, @Receiver, " + "@WoodS, @ClayS, @WoolS, @StoneS, @IronS, @StrawS, @FoodS, @GoldS, " + "@WoodR, @ClayR, @WoolR, @StoneR, @IronR, @StrawR, @FoodR, @GoldR);"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(query, connection)) { command.Parameters.AddWithValue("@Seller", offer.SellerName); command.Parameters.AddWithValue("@Receiver", offer.ReceiverName); int value = 0; offer.SellerResources.TryGetValue(ResourceType.Wood, out value); command.Parameters.AddWithValue("@WoodS", value); offer.SellerResources.TryGetValue(ResourceType.Clay, out value); command.Parameters.AddWithValue("@ClayS", value); offer.SellerResources.TryGetValue(ResourceType.Wool, out value); command.Parameters.AddWithValue("@WoolS", value); offer.SellerResources.TryGetValue(ResourceType.Stone, out value); command.Parameters.AddWithValue("@StoneS", value); offer.SellerResources.TryGetValue(ResourceType.Iron, out value); command.Parameters.AddWithValue("@IronS", value); offer.SellerResources.TryGetValue(ResourceType.Straw, out value); command.Parameters.AddWithValue("@StrawS", value); offer.SellerResources.TryGetValue(ResourceType.Food, out value); command.Parameters.AddWithValue("@FoodS", value); offer.SellerResources.TryGetValue(ResourceType.Gold, out value); command.Parameters.AddWithValue("@GoldS", value); offer.ReceiverResources.TryGetValue(ResourceType.Wood, out value); command.Parameters.AddWithValue("@WoodR", value); offer.ReceiverResources.TryGetValue(ResourceType.Clay, out value); command.Parameters.AddWithValue("@ClayR", value); offer.ReceiverResources.TryGetValue(ResourceType.Wool, out value); command.Parameters.AddWithValue("@WoolR", value); offer.ReceiverResources.TryGetValue(ResourceType.Stone, out value); command.Parameters.AddWithValue("@StoneR", value); offer.ReceiverResources.TryGetValue(ResourceType.Iron, out value); command.Parameters.AddWithValue("@IronR", value); offer.ReceiverResources.TryGetValue(ResourceType.Straw, out value); command.Parameters.AddWithValue("@StrawR", value); offer.ReceiverResources.TryGetValue(ResourceType.Food, out value); command.Parameters.AddWithValue("@FoodR", value); offer.ReceiverResources.TryGetValue(ResourceType.Gold, out value); command.Parameters.AddWithValue("@GoldR", value); return((int)command.ExecuteScalar()); } } } catch (SqlException ex) { SqlExceptionHandling(ex); } return(0); }
/// <summary> /// Called when a trade offer is updated, including the first time it is seen. /// When the bot is restarted, this might get called again for trade offers it's been previously called on. Thus, you can't rely on /// this method being called only once after an offer is accepted! If you need to rely on that functionality (say for giving users non-Steam currency), /// you need to keep track of which trades have been paid out yourself /// </summary> public abstract void OnTradeOfferUpdated(TradeOffer offer);
public bool CandelOffer(Offer offer) { TradeOffer tradeOffer = new TradeOffer(session, offer); return(tradeOffer.Cancel()); }
public void ShowHideTrade(bool makingOffer = true, TradeOffer offer = null) { tradeThisDiscription.renderer.enabled = !tradeThisDiscription.renderer.enabled; forThisDiscription.renderer.enabled = !forThisDiscription.renderer.enabled; offerTradeButton.renderer.enabled = !offerTradeButton.renderer.enabled; offerTradeButton.collider.enabled = !offerTradeButton.collider.enabled; offerTradeButtonText.renderer.enabled = !offerTradeButtonText.renderer.enabled; endTradeButtonText.renderer.enabled = !endTradeButtonText.renderer.enabled; endTradeButton.renderer.enabled = !endTradeButton.renderer.enabled; endTradeButton.collider.enabled = !endTradeButton.collider.enabled; int[] getArray = {}; int[] giveArray = {}; if (!makingOffer) { PlayerHand get = offer.convertGetResourcesToPlayerHand(); getArray = get.ToArray(); PlayerHand give = offer.convertGiveResourcesToPlayerHand(); giveArray = give.ToArray(); } GameObject[][] tradingObjects = { tradeThisText, forThisText, tradeThis, forThis }; int counter = 0; int objCounter = 0; foreach (GameObject[] arr in tradingObjects) { counter = 0; foreach (GameObject obj in arr) { obj.renderer.enabled = !obj.renderer.enabled; if (obj.collider != null) { obj.collider.enabled = !obj.collider.enabled; } if (obj.collider == null && makingOffer) { obj.GetComponent <TextMesh>().text = "0"; } else if (obj.collider == null) { if (objCounter == 2) { obj.GetComponent <TextMesh>().text = "" + giveArray[counter]; } else { obj.GetComponent <TextMesh>().text = "" + getArray[counter]; } counter++; } } objCounter++; } //TODO make gui for trading offer if (makingOffer) { offerTradeButtonText.GetComponent <TextMesh> ().text = "Offer Trade!"; endTradeButtonText.GetComponent <TextMesh> ().text = "End Trading"; } else { offerTradeButtonText.GetComponent <TextMesh> ().text = "Accept Offer"; endTradeButtonText.GetComponent <TextMesh> ().text = "Decline Offer"; } }
public bool DeclineOffer(Offer offer) { var tradeOffer = new TradeOffer(session, offer); return(tradeOffer.Decline()); }
public bool TryGetOffer(string offerId, out TradeOffer tradeOffer) { tradeOffer = null; var resp = webApi.GetTradeOffer(offerId); if (resp != null) { if (IsOfferValid(resp.Offer)) { tradeOffer = new TradeOffer(session, resp.Offer); return true; } else { Debug.WriteLine("Offer returned from steam api is not valid : " + resp.Offer.TradeOfferId); } } return false; }
/// <summary> /// Called when a new trade offer is received /// </summary> /// <param name="offer"></param> public virtual void OnNewTradeOffer(TradeOffer offer) { }
public virtual void OnTradeOfferRecieved (TradeOffer offer) { ResolveTradeOffer(true); }
bool ProposedTrade(Player player, AiInfo aiInfo) { var setsMissingAProperty = _context.SetsMissingProperties(player); if (setsMissingAProperty.Count == 0) { return(false); } var possibleTraders = _context.GetAllPlayers() .Where(p => p.Id != player.Id) .Where(p => !aiInfo.TradeCooldowns.ContainsKey(p.Id)); foreach (var trader in possibleTraders) { var interestingTradables = _context.TradableProperties(trader.Id) .Where(propId => setsMissingAProperty.Contains(_context.GetTileComponent <Property>(propId).SetId)) .ToList(); if (interestingTradables.Count == 0) { continue; } var receiverAssetsSum = interestingTradables.Sum(x => _context.GetTileComponent <Property>(x).BasePrice); if (0.75f * receiverAssetsSum > player.Cash) { continue; } var receiverAssets = new PlayerAssets(trader.Id, interestingTradables, 0, 0); var weights = new List <(int, int)>(8); weights.Add((-1, 70)); for (float coeff = 0.75f; coeff < 1.1f; coeff += 0.05f) { var moneyGiven = receiverAssetsSum * coeff; if (moneyGiven > player.Cash) { break; } var weight = (int)((coeff - 1) * 120); weight += (int)(player.Cash / moneyGiven * 25); weights.Add(((int)(moneyGiven), weight)); } var choice = weights.ChaosChoice(aiInfo.ChaosFactor); if (choice == -1) { continue; } var initiatorAssets = new PlayerAssets(player.Id, null, choice, 0); var offer = new TradeOffer(initiatorAssets, receiverAssets); _context.Add(offer); aiInfo.TradeCooldowns.Add(trader.Id, 4); return(true); } return(false); }
public TradeDownForm(DraftModel draftModel, DraftForm draftForm, TradeOffer to) { activeTeam = to.LowerTeam; HumanTeam = to.HigherTeam; dm = draftModel; df = draftForm; dm.tradeDownForm = this; InitializeComponent(); for (int i = 0; i < 32; i++) { nextpicks[i] = dm.GetNextPick(i, df.CurrentPick) + 1; teamnames[i] = dm.model.TeamModel.GetTeamNameFromTeamId(i); cons[i] = dm.model.TeamModel.GetTeamRecord(i).CON; conversations[i] = new List <string>(); } for (int i = 0; i < 32; i++) { if (i == HumanTeam) { continue; } int lowestPick = 300; int nextTeam = -1; foreach (KeyValuePair <int, int> pick in nextpicks) { if (pick.Value < lowestPick && !teamsByNextPick.Contains(pick.Key)) { lowestPick = pick.Value; nextTeam = pick.Key; } } teamsByNextPick.Add(nextTeam); } myLabel.Text = teamnames[HumanTeam] + "' Picks"; CPUlabel.Text = teamnames[activeTeam] + "' Picks"; picksList[to.HigherTeam] = new List <int>(); picksList[to.HigherTeam].Add(to.pickNumber); foreach (int pick in to.higherAvailable) { picksList[to.HigherTeam].Add(pick); } for (int i = 1; i <= 7; i++) { if (!dm.futureTradedPicks[to.HigherTeam].ContainsKey(i)) { picksList[to.HigherTeam].Add(1000 + i); } } FillTeamBoxes(); FillPickLists(activeTeam); RefreshPickBoxes(); selectPrevious(); }
public void Add(TradeOffer tradeOffer) { Contract.Requires(() => tradeOffer != null, $"{nameof(tradeOffer)} may not be null"); tradeOffers.Add(tradeOffer); }
/// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.GetOffer(offerId, out tradeOffer); }
public TradeUpForm(DraftModel draftModel, DraftForm draftForm, TradeOffer tradeOffer) { dm = draftModel; df = draftForm; dm.tradeUpForm = this; HigherCON = dm.model.TeamModel.GetTeamRecord(df.CurrentSelectingId).CON; LowerCON = dm.model.TeamModel.GetTeamRecord(dm.HumanTeamId).CON; InitializeComponent(); ourteam = dm.model.TeamModel.GetTeamNameFromTeamId(dm.HumanTeamId); theirteam = dm.model.TeamModel.GetTeamNameFromTeamId(df.CurrentSelectingId); myLabel.Text = ourteam + "' Picks"; CPUlabel.Text = theirteam + "' Picks"; to = tradeOffer; foreach (int pick in to.lowerAvailable) { myPicksList.Add(pick); } theirPicksList.Add(to.pickNumber); foreach (int pick in to.higherAvailable) { theirPicksList.Add(pick); } for (int i = 1; i <= 7; i++) { if (!dm.futureTradedPicks[to.LowerTeam].ContainsKey(i)) { myPicksList.Add(1000 + i); } } if (to.allowFuturePicksFromHigher) { // This was preventing all future draft picks from being eligible to be traded // changed to 1 instead of startRound //int startRound = to.pickNumber / 32 + 3; for (int i = 1; i <= 7; i++) { if (!dm.futureTradedPicks[to.HigherTeam].ContainsKey(i)) { theirPicksList.Add(1000 + i); } } } refreshPickLists(); offerButton.Enabled = false; resetButton.Enabled = false; refreshTotals(); }
private void acceptTrade(TradeOffer offer) { string pass = Bot.BotDBPassword; List <TradeAsset> theirItems = offer.Items.GetTheirItems(); SteamID userID = offer.PartnerSteamId; string postData = "password="******"&owner=" + userID; string theirItemsJSON = JsonConvert.SerializeObject(theirItems); postData += "&items=" + theirItemsJSON; string url = Bot.BotWebsiteURL + "/php/check-items.php"; var request = (HttpWebRequest)WebRequest.Create(url); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //Uncomment this line to view the response from check-items.php Log.Success("Response received from check-items.php: \n" + responseString); JSONClass responseJsonObj = JsonConvert.DeserializeObject <JSONClass>(responseString); if (responseJsonObj.success == 1) { //Get data array from json var jsonData = responseJsonObj.data; if (jsonData.minDeposit == 1) { doWebWithCatch(10, () => { if (offer.Accept()) { Log.Success("Offer accepted from " + userID); //Put items into the pot string urlPutItemsIn = Bot.BotWebsiteURL + "/php/deposit.php"; var requestUrlPutItemsIn = (HttpWebRequest)WebRequest.Create(urlPutItemsIn); string postDataPutItemsIn = "password="******"&owner=" + userID; postDataPutItemsIn += "&items=" + jsonData.allItems; //Log.Success (jsonData.allItems); var dataPutItemsIn = Encoding.ASCII.GetBytes(postDataPutItemsIn); requestUrlPutItemsIn.Method = "POST"; requestUrlPutItemsIn.ContentType = "application/x-www-form-urlencoded"; requestUrlPutItemsIn.ContentLength = dataPutItemsIn.Length; using (var stream = requestUrlPutItemsIn.GetRequestStream()) { stream.Write(dataPutItemsIn, 0, dataPutItemsIn.Length); } var responsePutItemsIn = (HttpWebResponse)requestUrlPutItemsIn.GetResponse(); string responsePutItemsInString = new StreamReader(responsePutItemsIn.GetResponseStream()).ReadToEnd(); //Uncomment this line to view the response from deposit.php //Log.Success ("Response received from deposit.php: " + responsePutItemsInString); JSONClass responseJsonObjPutItemsIn = JsonConvert.DeserializeObject <JSONClass> (responsePutItemsInString); jsonData = responseJsonObjPutItemsIn.data; } }); //Check if it should start the timer if (jsonData.startTimer == 1) { //Check if the timer is already running. if (!timerRunning) { timer = new System.Timers.Timer(); timer.Elapsed += new ElapsedEventHandler(timerEvent); timer.Interval = 1000; timer.Start(); timerRunning = true; } } //Check if the pot is over if (jsonData.potOver == 1) { //End the timer timerTime = 0; timer.Stop(); sendWinnings(responseJsonObj); } else { //Only try this one time, because even if it gives an error, it still gets declined. doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("Server deposit request failed, declining trade. Error message:\n" + responseJsonObj.errMsg); } }); } } else { //Only try this one time, because even if it gives an error, it still gets declined. doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("Minimum deposit not reached, offer declined."); } }); } } else { doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("The depositor's inventory could not be accessed."); } }); } }
public void AddNewTradeOffer(TradeOffer tradeOffer) => repository.Add(tradeOffer);
// Returns a fair trade proposal private TradeOffer BuildFairTrade(int currentTurn, PlayerHand cardDifferential) { int[] resourceRequest = new int[5]; int[] resourceSurplus = new int[5]; for(int i = 0; i < 5; i++) { int cards = cardDifferential.GetResourceQuantity(i); if(cards < 0) { resourceRequest[i] = - cards; } else { resourceSurplus[i] = cards; } } TradeOffer trade = new TradeOffer (this, currentTurn, resourceSurplus, resourceRequest); trade.EqualizeTrade (); return trade; }
/// <summary> /// Manually validate if a trade offer went through by checking /inventoryhistory/ /// </summary> /// <param name="tradeOffer">A 'TradeStatus' object</param> /// <returns>True if the trade offer was successfully accepted, false if otherwise</returns> public bool ValidateTradeAccept(TradeOffer tradeOffer) { var history = GetTradeHistory(1); foreach (var completedTrade in history) { var givenItems = new List<Trade.TradeAsset>(); foreach (var myItem in tradeOffer.ItemsToGive) { var genericItem = new Trade.TradeAsset(myItem.AppId, myItem.ContextId, myItem.AssetId, myItem.Amount); givenItems.Add(genericItem); } var receivedItems = new List<Trade.TradeAsset>(); foreach (var otherItem in tradeOffer.ItemsToReceive) { var genericItem = new Trade.TradeAsset(otherItem.AppId, otherItem.ContextId, otherItem.AssetId, otherItem.Amount); receivedItems.Add(genericItem); } if (givenItems.Count == completedTrade.GivenItems.Count && receivedItems.Count == completedTrade.ReceivedItems.Count) { foreach (var item in completedTrade.GivenItems) { var genericItem = new Trade.TradeAsset(item.appid, item.contextid, item.assetid, item.amount); if (!givenItems.Contains(genericItem)) return false; } foreach (var item in completedTrade.ReceivedItems) { var genericItem = new Trade.TradeAsset(item.appid, item.contextid, item.assetid, item.amount); if (!receivedItems.Contains(genericItem)) return false; } return true; } } return false; }
private bool GetPermissionToRetryTradeRequest(int currentTurn, TradeOffer trade) { bool permission = false; String key = trade.GenerateTradeKey (); int lastRequestTurn = 0; recentTradeRequests.TryGetValue (key, out lastRequestTurn); // replaces lastRequestTurn w/ value found in dictionary, untouched if key not found if(debugMessages) { GameEngine.print ("REQUEST KEY: " + key + "$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$_$"); GameEngine.print ("TURN LAST REQUESTED: " + lastRequestTurn); } if(lastRequestTurn < currentTurn) // request not yet made this turn { if(debugMessages) { GameEngine.print("OVERWRITE KEY; FORMERLY " + lastRequestTurn + ", NOW: " + currentTurn); } if(lastRequestTurn != 0) { recentTradeRequests.Remove(key); } recentTradeRequests.Add(key, currentTurn); permission = true; } else { if(trade.TotalGetResources() > 1) { trade.dropGetCard(); trade.EqualizeTrade(); if(debugMessages) { GameEngine.print ("{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{-- REATTEMPT WITH FEWER CARDS REQUESTED --}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"); } permission = GetPermissionToRetryTradeRequest(currentTurn, trade); } } return permission; }
private bool AcceptTrade(TradeOffer tradeOffer) { var tradeOfferId = tradeOffer.Id; var url = "https://steamcommunity.com/tradeoffer/" + tradeOfferId + "/accept"; var referer = "http://steamcommunity.com/tradeoffer/" + tradeOfferId + "/"; var data = new NameValueCollection(); data.Add("sessionid", SteamWeb.SessionId); data.Add("serverid", "1"); data.Add("tradeofferid", tradeOfferId.ToString()); data.Add("partner", tradeOffer.OtherSteamId.ToString()); string response = RetryWebRequest(SteamWeb, url, "POST", data, true, referer); if (string.IsNullOrEmpty(response)) { return false;// ValidateTradeAccept(tradeOffer); } else { try { dynamic json = JsonConvert.DeserializeObject(response); var id = json.tradeid; return true; } catch { return false;// ValidateTradeAccept(tradeOffer); } } }
public override void OnTradeOfferUpdated(TradeOffer offer) { if(offer.OfferState == TradeOfferState.TradeOfferStateAccepted) { Log.Success("Trade Complete."); } }
public override void OnNewTradeOffer(TradeOffer offer) { var escrow = Bot.GetEscrowDuration(offer.TradeOfferId); if (escrow.DaysMyEscrow != 0 || escrow.DaysTheirEscrow != 0) { doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("User has not been using the Mobile Authenticator for 7 days or has turned off trade confirmations, offer declined."); } }); } else { //Get password from file on desktop string pass = Bot.BotDBPassword; //Get items in the trade, and ID of user sending trade var theirItems = offer.Items.GetTheirItems(); var myItems = offer.Items.GetMyItems(); var userID = offer.PartnerSteamId; bool shouldDecline = false; //Check if they are trying to get items from the bot if (myItems.Count > 0 || theirItems.Count == 0) { //shouldDecline = true; Log.Error("Offer declined because the offer wasn't a gift; the user wanted items instead of giving."); } //Check to make sure all items are for CS: GO. foreach (TradeAsset item in theirItems) { if (item.AppId != 730) { shouldDecline = true; Log.Error("Offer declined because one or more items was not for CS: GO."); } } //Check if there are more than 10 items in the trade if (theirItems.Count > 5) { shouldDecline = true; Log.Error("Offer declined because there were more than 5 items in the deposit."); } if (shouldDecline) { doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("Offer declined."); } }); return; } Log.Success("Offer approved, accepting."); //Send items to server and check if all items add up to more than $1. //If they do, accept the trade. If they don't, decline the trade. string postData = "password="******"&owner=" + userID; string theirItemsJSON = JsonConvert.SerializeObject(theirItems); postData += "&items=" + theirItemsJSON; string url = Bot.BotWebsiteURL + "/php/check-items.php"; var request = (HttpWebRequest)WebRequest.Create(url); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //Uncomment this line to view the response from check-items.php //Log.Success ("Response received from check-items.php: \n" + responseString); JSONClass responseJsonObj = JsonConvert.DeserializeObject<JSONClass>(responseString); if (responseJsonObj.success == 1) { //Get data array from json var jsonData = responseJsonObj.data; if (jsonData.minDeposit == 1) { doWebWithCatch(10, () => { if (offer.Accept()) { Log.Success("Offer accepted from " + userID); //Put items into the pot string urlPutItemsIn = Bot.BotWebsiteURL + "/php/deposit.php"; var requestUrlPutItemsIn = (HttpWebRequest)WebRequest.Create(urlPutItemsIn); string postDataPutItemsIn = "password="******"&owner=" + userID; postDataPutItemsIn += "&items=" + jsonData.allItems; //Log.Success (jsonData.allItems); var dataPutItemsIn = Encoding.ASCII.GetBytes(postDataPutItemsIn); requestUrlPutItemsIn.Method = "POST"; requestUrlPutItemsIn.ContentType = "application/x-www-form-urlencoded"; requestUrlPutItemsIn.ContentLength = dataPutItemsIn.Length; using (var stream = requestUrlPutItemsIn.GetRequestStream()) { stream.Write(dataPutItemsIn, 0, dataPutItemsIn.Length); } var responsePutItemsIn = (HttpWebResponse)requestUrlPutItemsIn.GetResponse(); string responsePutItemsInString = new StreamReader(responsePutItemsIn.GetResponseStream()).ReadToEnd(); //Uncomment this line to view the response from deposit.php //Log.Success ("Response received from deposit.php: " + responsePutItemsInString); JSONClass responseJsonObjPutItemsIn = JsonConvert.DeserializeObject<JSONClass>(responsePutItemsInString); jsonData = responseJsonObjPutItemsIn.data; } }); //Check if it should start the timer if (jsonData.startTimer == 1) { //Check if the timer is already running. if (!timerRunning) { timer = new System.Timers.Timer(); timer.Elapsed += new ElapsedEventHandler(timerEvent); timer.Interval = 1000; timer.Start(); timerRunning = true; } } //Check if the pot is over if (jsonData.potOver == 1) { //End the timer timerTime = 0; timer.Stop(); //Get items to give and keep, and the winner and their trade token var itemsToGive = jsonData.tradeItems; var itemsToKeep = jsonData.profitItems; string winnerSteamIDString = jsonData.winnerSteamId; SteamID winnerSteamID = new SteamID(winnerSteamIDString); string winnerTradeToken = jsonData.winnerTradeToken; Log.Success("Winner steam id: " + winnerSteamIDString + ", token: " + winnerTradeToken); //Get bot's inventory json string botInvUrl = "http://steamcommunity.com/profiles/" + Bot.SteamUser.SteamID.ConvertToUInt64() + "/inventory/json/730/2"; var botInvRequest = (HttpWebRequest)WebRequest.Create(botInvUrl); var botInvResponse = (HttpWebResponse)botInvRequest.GetResponse(); string botInvString = new StreamReader(botInvResponse.GetResponseStream()).ReadToEnd(); BotInventory botInventory = JsonConvert.DeserializeObject<BotInventory>(botInvString); if (botInventory.success != true) { Log.Error("An error occured while fetching the bot's inventory."); return; } var rgInventory = botInventory.rgInventory; //Create trade offer for the winner var winnerTradeOffer = Bot.NewTradeOffer(winnerSteamID); //Loop through all winner's items and add them to trade List<long> alreadyAddedToWinnerTrade = new List<long>(); foreach (CSGOItemFromWeb item in itemsToGive) { long classId = item.classId, instanceId = item.instanceId; //Loop through all inventory items and find the asset id for the item long assetId = 0; foreach (var inventoryItem in rgInventory) { var value = inventoryItem.Value; long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid; if (tClassId == classId && tInstanceId == instanceId) { //Check if this assetId has already been added to the trade if (alreadyAddedToWinnerTrade.Contains(tAssetId)) { continue; //This is for when there are 2 of the same weapon, but they have different assetIds } assetId = tAssetId; break; } } //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId); winnerTradeOffer.Items.AddMyItem(730, 2, assetId, 1); alreadyAddedToWinnerTrade.Add(assetId); } //Send trade offer to winner if (itemsToGive.Count > 0) { string winnerTradeOfferId, winnerMessage = "Congratulations, you have won on " + Bot.BotWebsiteName + "! Here are your items."; doWebWithCatch(-1, () => { if (winnerTradeOffer.SendWithToken(out winnerTradeOfferId, winnerTradeToken, winnerMessage)) { Bot.AcceptAllMobileTradeConfirmations(); Log.Success("Offer sent to winner."); } }); } else { Log.Info("No items to give... strange"); } //Now, send all of the profit items to my own account //Put your own Steam ID here var profitTradeOffer = Bot.NewTradeOffer(new SteamID(Bot.ProfitAdmin)); //Loop through all profit items and add them to trade List<long> alreadyAddedToProfitTrade = new List<long>(); foreach (CSGOItemFromWeb item in itemsToKeep) { long classId = item.classId, instanceId = item.instanceId; //Loop through all inventory items and find the asset id for the item long assetId = 0; foreach (var inventoryItem in rgInventory) { var value = inventoryItem.Value; long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid; if (tClassId == classId && tInstanceId == instanceId) { //Check if this assetId has already been added to the trade if (alreadyAddedToProfitTrade.Contains(tAssetId)) { continue; //This is for when there are 2 of the same weapon, but they have different assetIds } assetId = tAssetId; break; } } //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId); profitTradeOffer.Items.AddMyItem(730, 2, assetId, 1); alreadyAddedToProfitTrade.Add(assetId); } //Send trade offer to myself with profit items Log.Success(itemsToKeep.Count + ""); if (itemsToKeep.Count > 0) { string profitTradeOfferId, profitMessage = "Here are the profit items from the round."; doWebWithCatch(10, () => { if (profitTradeOffer.Send(out profitTradeOfferId, profitMessage)) { //Don't need the token because I am friends with the bot. Bot.AcceptAllMobileTradeConfirmations(); Log.Success("Profit trade offer sent."); } }); } } else { //Only try this one time, because even if it gives an error, it still gets declined. doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("Server deposit request failed, declining trade. Error message:\n" + responseJsonObj.errMsg); } }); } } else { //Only try this one time, because even if it gives an error, it still gets declined. doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("Minimum deposit not reached, offer declined."); } }); } } } }
public TradeOffer NewOffer(SteamID other) { var offer = new TradeOffer(session, other); return offer; }
/// <summary> /// Called when a trade offer is updated, including the first time it is seen. /// When the bot is restarted, this might get called again for trade offers it's been previously called on. Thus, you can't rely on /// this method being called only once after an offer is accepted! If you need to rely on that functionality (say for giving users non-Steam currency), /// you need to keep track of which trades have been paid out yourself /// </summary> public abstract void OnTradeOfferUpdated(TradeOffer offer);
/* * Handles interactions with game FSM and player input. */ void Update() { Player currentTurnPlayer = gamestate.GetCurrentTurnPlayer(); UpdateHumanCardCounts(); long elapsedTicksSinceLastAIAction = DateTime.Now.Ticks - lastAIActionTime.Ticks; double secondsSinceLastAIAction = new TimeSpan(elapsedTicksSinceLastAIAction).TotalSeconds; //AI Interaction if (currentTurnPlayer.isAI) { if (secondsSinceLastAIAction >= FORCED_TIME_BETWEEN_AI_ACTIONS) { System.Random rand = new System.Random(); //Initial settlement placement if (curState == GameState.State.placeSettlement) { List <Node> locationOptions = AIEngine.GetFavorableStartingLocations(board); //Attempt to place elements in decreasing score order for (int i = 0; i < locationOptions.Count; i++) { if (board.CanBuildSettlementHere(locationOptions[i].visual.transform, currentTurnPlayer, true)) { lastStructurePlaced = board.PlaceSettlement(locationOptions[i].visual.transform, currentTurnPlayer, false); break; } } IncrementState(); UpdateTurnInfo("Placing Initial Road", currentTurnPlayer.id); } //Initial road placement else if (curState == GameState.State.placeRoad) { List <Edge> favorableRoads = AIEngine.GetFavorableRoadExpansions(currentTurnPlayer, board, lastStructurePlaced); foreach (Edge road in favorableRoads) { if (board.CanBuildRoadHere(road.visual.transform, currentTurnPlayer)) { lastRoadPlaced = board.PlaceRoad(road.visual.transform, currentTurnPlayer, false); break; } } IncrementState(); } //Roll dice else if (curState == GameState.State.roll) { if (rollForAI) { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (interactDebug) { print("mouse press"); } if (Physics.Raycast(ray, out hit)) { if (hit.transform == dice.transform) { IncrementState(); updateDice(); } } } } else { IncrementState(); updateDice(); } } //Trade with players else if (curState == GameState.State.trade) { proposedObjective = null; if (debugMessages) { print("~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~"); } //TODO List <AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate); // Trade With Other Players int tradeOffersThisTurn = 0; bool hasAnyOfferBeenAccepted = false; foreach (AIEngine.Objective objective in objectives) { if (objective.Score() > 0 && objective.TotalCardsNeeded() > 0 && tradeOffersThisTurn < 3 && !hasAnyOfferBeenAccepted) { TradeOffer offer = currentTurnPlayer.generateAITradeRequest(gamestate.getTurnCounter(), objective); if (null != offer) { if (debugMessages) { print("TRADENUM: " + tradeOffersThisTurn + " | " + gamestate.GetCurrentTurnPlayer() + "\nATTEMPTING TO TRADE WITH OTHER PLAYERS TO ACHIEVE OBJECT: " + objective.GetObjectiveScore()); } tradeOffersThisTurn++; hasAnyOfferBeenAccepted = tradeManager.ExecuteTradeOfferNotification(offer); proposedObjective = objective; } } } // Trade With Bank foreach (AIEngine.Objective objective in objectives) { if (objective.Score() > 0 && objective.TotalCardsNeeded() > 0 && !hasAnyOfferBeenAccepted) { if (debugMessages) { print(gamestate.GetCurrentTurnPlayer() + " ATTEMPTING TO TRADE WITH BANK"); } TradeOffer offer = currentTurnPlayer.generateAITradeWithBank(objective); if (null != offer) { tradeManager.ExecuteTradeWithBank(offer, gamestate.GetCurrentTurnPlayer()); hasAnyOfferBeenAccepted = true; } } } if (!hasAnyOfferBeenAccepted && debugMessages) { print(gamestate.GetCurrentTurnPlayer() + " MADE NO TRADES THIS TURN"); } IncrementState(); FORCED_TIME_BETWEEN_AI_ACTIONS = 0f; //TODO Remove } //Building phase else if (curState == GameState.State.place) { FORCED_TIME_BETWEEN_AI_ACTIONS = 0f; //TODO Remove //TODO List <AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate); foreach (AIEngine.Objective objective in objectives) { print(objective); } foreach (AIEngine.Objective objective in objectives) { if (objective.TotalCardsNeeded() == 0) { AIEngine.PerformObjective(objective, board); break; } } /*//Attempt main objective that we traded for * if (proposedObjective != null) { * AIEngine.PerformObjective(proposedObjective, board); * } * //Attempt to get -any- objective to work * else { * List<AIEngine.Objective> objectives = AIEngine.GetObjectives(currentTurnPlayer, board, gamestate); * foreach (AIEngine.Objective objective in objectives) { * if (AIEngine.PerformObjective(objective, board)) { * break; * } * } * }*/ IncrementState(); } //Place robber else if (curState == GameState.State.robber) { Player competitorPlayer = gamestate.BiggestCompetitorToPlayer(currentTurnPlayer); List <Tile> possiblePlacements = AIEngine.GetListOfRobberPlacements(currentTurnPlayer, competitorPlayer, board); bool robberPlaced = false; //Attempt to place robber on recommended tiles foreach (Tile tile in possiblePlacements) { int index = board.tiles.IndexOf(tile); if (board.PlaceRobber(board.tileHitboxes[index].transform)) { robberPlaced = true; break; } } //If for some reason we're out of recommendations... while (!robberPlaced) { print("ERROR: ATTEMPTING TO RANDOMLY PLACE ROBBER!"); int tileIndex = rand.Next(board.tiles.Count); robberPlaced = board.PlaceRobber(board.tileHitboxes[tileIndex].transform); } IncrementState(); } lastAIActionTime = DateTime.Now; //Prevent AI from acting too quickly } } //Human Interaction else { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (interactDebug) { print("mouse press"); } if (Physics.Raycast(ray, out hit)) { //Need to place something if (curState == GameState.State.placeSettlement || curState == GameState.State.placeRoad || curState == GameState.State.place) { bool isSetup = (curState == GameState.State.placeSettlement || curState == GameState.State.placeRoad); //Choose what to build or use preselected if (curState == GameState.State.place) { if (hit.transform == roadSelector.transform && currentTurnPlayer.CanBuildRoad()) { objectToBuild = hit.transform; if (interactDebug) { print("on a building"); } } else if (hit.transform == citySelector.transform && currentTurnPlayer.CanBuildCity()) { objectToBuild = hit.transform; if (interactDebug) { print("on a building"); } } else if (hit.transform == settlementSelector.transform && currentTurnPlayer.CanBuildSettlement()) { objectToBuild = hit.transform; if (interactDebug) { print("on a building"); } } else if (hit.transform == endTurnButton.transform) { IncrementState(); } } else if (curState == GameState.State.placeSettlement) { objectToBuild = settlementSelector.transform; } else if (curState == GameState.State.placeRoad) { objectToBuild = roadSelector.transform; } if (objectToBuild != null) { if (objectToBuild == roadSelector.transform && board.roadHitboxes.ContainsKey(hit.transform)) { Node structureToBuildNear = (curState == GameState.State.placeRoad) ? lastStructurePlaced : null; if (board.CanBuildRoadHere(hit.transform, currentTurnPlayer, structureToBuildNear, true)) { lastRoadPlaced = board.PlaceRoad(hit.transform, currentTurnPlayer, !isSetup); objectToBuild = null; if (interactDebug) { print("road built!"); } if (curState == GameState.State.placeRoad) { IncrementState(); } } } else if (objectToBuild == settlementSelector.transform && board.settlementHitboxes.ContainsKey(hit.transform)) { if (board.CanBuildSettlementHere(hit.transform, currentTurnPlayer, isSetup, true)) { lastStructurePlaced = board.PlaceSettlement(hit.transform, currentTurnPlayer, !isSetup); objectToBuild = null; if (interactDebug) { print("settlement built!"); } if (curState == GameState.State.placeSettlement) { IncrementState(); } } } else if (objectToBuild == citySelector.transform && board.settlements.ContainsKey(hit.transform)) { if (board.CanBuildCityHere(hit.transform, currentTurnPlayer, true)) { lastStructurePlaced = board.PlaceCity(hit.transform, currentTurnPlayer); objectToBuild = null; if (interactDebug) { print("city built!"); } } } } } //Place robber on a chit else if (curState == GameState.State.robber) { if (board.PlaceRobber(hit.transform)) { IncrementState(); //increment if successfully placed } } //Request trades with other players or bank else if (curState == GameState.State.trade) { UpdateTradePanel(hit.transform); if (hit.transform == endTradeButton.transform) { IncrementState(); } else if (hit.transform == offerTradeButton.transform) { OfferTrade(); } else if (hit.transform == endTurnButton.transform) { IncrementState(); IncrementState(); } //tradeManager.ExecuteTradeWithBank(offer, gamestate.GetCurrentTurnPlayer()); } //listen for click on dice else if (curState == GameState.State.roll) { if (interactDebug) { print(hit.transform == dice.transform); } if (hit.transform == dice.transform) { IncrementState(); updateDice(); } } else { if (interactDebug) { print("should not be here"); } } } } } }
/// <summary> /// Check if the tradeoffer is sent from an admin, if so, accept it and throw a marked message, else move on /// </summary> /// <param name="_steamFriendsHelper"></param> /// <param name="_tradeOffer"></param> /// <param name="_tradePartnerID"></param> /// <returns></returns> private async Task <bool> AdminTradeOffer(SteamFriendsHelper _steamFriendsHelper, TradeOffer _tradeOffer, SteamID _tradePartnerID) { if (_steamFriendsHelper.IsBotAdmin(_tradePartnerID, m_botInfo.Admins)) { if (await m_tradeOfferWebAPI.AcceptTradeOffer(_tradeOffer.TradeOfferID).ConfigureAwait(false)) { m_logger.Warning($"Tradeoffer {_tradeOffer.TradeOfferID} was sent by admin {_tradePartnerID.ConvertToUInt64()}"); } return(true); } return(false); }
public static void AddNewTradeOfferSoldLog(TradeOffer trade) { AddEventLogs(new EventLogTradeDealSold(trade)); }
private void CreateTradeOffer(Bot bot, GameServerRequest gsr) { float tradeValue = -1; string message = gsr.Arguments; string[] assetIDs = null; string[] myAssetIDs = null; string[] steamIDitems = message.Split('/'); SteamID steamid = GetSteamIDFromString(steamIDitems[0]); if (!steamid.IsValid) { return; } TradeOffer to = bot.TradeOfferManager.NewOffer(steamid); GameServer gameServer = bot.Manager.GetServerByID(gsr.ServerID); if (steamIDitems[1].Length > 1 && steamIDitems[1] != "NULL") { assetIDs = steamIDitems[1].Split(','); List <long> contextId = new List <long>(); contextId.Add(2); bot.OtherGenericInventory.load((int)Games.CSGO, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(assetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = (ItemDescription)bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.OtherGenericInventory.load((int)Games.TF2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(assetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = (ItemDescription)bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.OtherGenericInventory.load((int)Games.Dota2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(assetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = (ItemDescription)bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } } if (steamIDitems[2].Length > 1 && steamIDitems[2] != "NULL") { myAssetIDs = steamIDitems[2].Split(','); List <long> contextId = new List <long>(); contextId.Add(2); bot.MyGenericInventory.load((int)Games.CSGO, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(myAssetIDs, item.assetid.ToString()) > -1) { ItemDescription description = (ItemDescription)bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.MyGenericInventory.load((int)Games.TF2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(myAssetIDs, item.assetid.ToString()) > -1) { ItemDescription description = (ItemDescription)bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.MyGenericInventory.load((int)Games.Dota2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(myAssetIDs, item.assetid.ToString()) > -1) { ItemDescription description = (ItemDescription)bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } } if (steamIDitems[3] != "NULL") { tradeValue = float.Parse(steamIDitems[3], CultureInfo.InvariantCulture); } string offerId = ""; string token = bot.GetToken(steamid); if (bot.Friends.Contains(steamid.ConvertToUInt64())) { to.Send(out offerId, String.Format("\"{0}\" the {1}@{2}", gameServer.Name, DateTime.Now.ToString("dd/MM/yyyy"), DateTime.Now.ToString("HH:mm"))); } else if (token != null) { to.SendWithToken(out offerId, token, String.Format("\"{0}\" the {1}@{2}", gameServer.Name, DateTime.Now.ToString("dd/MM/yyyy"), DateTime.Now.ToString("HH:mm"))); } else { bot.Manager.Send(gsr.ServerID, gsr.ModuleID, NetworkCode.ASteambotCode.TradeToken, steamid.ConvertToUInt64().ToString() + "/" + "trade_token_not_found"); } if (offerId != "") { bot.Manager.Send(gsr.ServerID, gsr.ModuleID, NetworkCode.ASteambotCode.CreateTradeOffer, steamid.ConvertToUInt64() + "/" + offerId); bot.TradeoffersGS.Add(offerId, gsr.ServerID + "|" + gsr.ModuleID + "|" + tradeValue); bot.TradeOfferValue.Add(offerId, tradeValue); bot.AcceptMobileTradeConfirmation(offerId); bot.UpdateTradeOfferInDatabase(to, -1); } else { if (token != null) { bot.Manager.Send(gsr.ServerID, gsr.ModuleID, NetworkCode.ASteambotCode.TradeToken, steamid.ConvertToUInt64().ToString() + "/" + "trade_token_invalid"); } bot.Manager.Send(gsr.ServerID, gsr.ModuleID, NetworkCode.ASteambotCode.CreateTradeOffer, steamid.ConvertToUInt64() + "/" + "-1"); } }
public bool? TradeOfferMatches(UserHandler handler, TradeOffer offer) { handler.GetOtherInventory(); handler.Bot.GetInventory(); if (handler.OtherInventory == null) { handler.Log.Error("Inventory retrieval failed. Ignoring trade."); return null; } if (IsBuyOrder) { TF2Value paying = TF2Value.Zero; foreach (var asset in offer.Items.GetMyItems()) { Inventory.Item item = handler.Bot.MyInventory.GetItem((ulong)asset.AssetId); if (item == null) { //handler.Log.Error("No item matching asset ID " + asset.AssetId.ToString()); continue; } if (item.Defindex == TF2Value.SCRAP_DEFINDEX) paying += TF2Value.Scrap; else if (item.Defindex == TF2Value.RECLAIMED_DEFINDEX) paying += TF2Value.Reclaimed; else if (item.Defindex == TF2Value.REFINED_DEFINDEX) paying += TF2Value.Refined; else if (item.Defindex == TF2Value.KEY_DEFINDEX) paying += TF2Value.Key; else return false; // I only pay in pure if it's a buy order. } foreach (var asset in offer.Items.GetTheirItems()) { Inventory.Item item = handler.Trade.OtherInventory.GetItem((ulong)asset.AssetId); if (item == null) { //handler.Log.Error("No item matching asset ID " + asset.AssetId.ToString()); continue; } if (item.Defindex == TF2Value.SCRAP_DEFINDEX) paying -= TF2Value.Scrap; else if (item.Defindex == TF2Value.RECLAIMED_DEFINDEX) paying -= TF2Value.Reclaimed; else if (item.Defindex == TF2Value.REFINED_DEFINDEX) paying -= TF2Value.Refined; else if (item.Defindex == TF2Value.KEY_DEFINDEX) paying -= TF2Value.Key; } if (paying > Price) { return false; } bool hasWantedStuff = false; foreach (var asset in offer.Items.GetTheirItems()) { Inventory.Item item = handler.OtherInventory.GetItem((ulong)asset.AssetId); if (!MatchesItem(item)) { continue; } hasWantedStuff = true; break; } return hasWantedStuff; } else { TF2Value paid = TF2Value.Zero; foreach (var asset in offer.Items.GetTheirItems()) { Inventory.Item item = handler.OtherInventory.GetItem((ulong)asset.AssetId); if (item == null) { //handler.Log.Error("No item matching asset ID " + asset.AssetId.ToString()); continue; } if (item.Defindex == TF2Value.SCRAP_DEFINDEX) paid += TF2Value.Scrap; else if (item.Defindex == TF2Value.RECLAIMED_DEFINDEX) paid += TF2Value.Reclaimed; else if (item.Defindex == TF2Value.REFINED_DEFINDEX) paid += TF2Value.Refined; else if (item.Defindex == TF2Value.KEY_DEFINDEX) paid += TF2Value.Key; } foreach (var asset in offer.Items.GetMyItems()) { Inventory.Item item = handler.OtherInventory.GetItem((ulong)asset.AssetId); if (item == null) { //handler.Log.Error("No item matching asset ID " + asset.AssetId.ToString()); continue; } if (item.Defindex == TF2Value.SCRAP_DEFINDEX) paid -= TF2Value.Scrap; else if (item.Defindex == TF2Value.RECLAIMED_DEFINDEX) paid -= TF2Value.Reclaimed; else if (item.Defindex == TF2Value.REFINED_DEFINDEX) paid -= TF2Value.Refined; else if (item.Defindex == TF2Value.KEY_DEFINDEX) paid -= TF2Value.Key; } if (paid < Price) { return false; } var myAssets = offer.Items.GetMyItems(); if (myAssets.Count == 1) { var asset = myAssets.First(); Inventory.Item item = handler.Bot.MyInventory.GetItem((ulong)asset.AssetId); return MatchesItem(item); } return false; } }
/// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return(tradeOfferManager.GetOffer(offerId, out tradeOffer)); }
public override void OnTradeOfferUpdated(TradeOffer offer) { if(offer.OfferState == TradeOfferState.TradeOfferStateActive && !offer.IsOurOffer) { OnNewTradeOffer(offer); } }
IEnumerator m_EndOfTurn () { // trading? // check for a set hasSet = false; // iterate over the group of properties for(int i=0;i<numberOfPropertiesInGroup.Length;i++){ if(numberOfPropertiesInGroup[i] == GameController.singleton.numberOfEachPropertyGroup[i]){ hasSet = true; } } // only if no properties left if(hasSet == false){ // find the property group with the largest amount in it int largestPropertyGroupNum = -1; int largestGroupIndex = -1; for(int i=0;i<numberOfPropertiesInGroup.Length;i++){ if(numberOfPropertiesInGroup[i] > largestPropertyGroupNum){ largestPropertyGroupNum = numberOfPropertiesInGroup[i]; largestGroupIndex = i; } } // calculate our desired property group TileGroup desiredGroup = (TileGroup)largestGroupIndex; Debug.Log ("Desired Group is: "+desiredGroup); // get all the properties in the game BoardTile[] propertyList = GameController.GetAllProperties(); BoardTile desiredProperty = null; // find a property from another player in our desired group for(int i=0;i<propertyList.Length;i++){ // find the property we want in our group if(propertyList[i].tileGroup == desiredGroup && propertyList[i].owner != playerIndex){ // this is the property we want desiredProperty = propertyList[i]; // stop the loop i = propertyList.Length; } } Debug.Log ("Desired Property is: "+desiredProperty); // check if the property is owned, because theres no point trying to trade if it isnt if(desiredProperty.owner != -1){ Debug.Log ("Desired Property owner is: "+desiredProperty.owningPlayer.playerName); // find a property we want to trade BoardTile sendingProperty = null; // iterate over all the properties we own for(int i=0;i<ownedProperties.Count;i++){ // check for a property not part of our desired group if(ownedProperties[i].tileGroup != desiredGroup){ // we have found a property to send sendingProperty = ownedProperties[i]; // stop the loop i = ownedProperties.Count; } } Debug.Log ("Sending Property is: "+sendingProperty); if(desiredProperty != null && sendingProperty != null){ // make a trade for the desired property TradeOffer tradeOffer = new TradeOffer(this,desiredProperty.owningPlayer,sendingProperty,desiredProperty,0,0); // propose the offer ProposeNewTradeOffer(tradeOffer); // wait for a response Debug.Log (playerName+": WaitingForTradeResponse"); while(pendingTradeOffer == true){ Debug.Log (playerName+ ": pending trade offer? = "+pendingTradeOffer); yield return new WaitForEndOfFrame(); } } } else{ Debug.Log ("Desired Property isnt owned :("); } } // variable to hold the full property group TileGroup fullPropertyGroup = TileGroup.other; // check for a set to upgrade for(int i=0;i<ownedProperties.Count;i++){ if(ownedProperties[i].improvement != HouseImprovement.Hotel && ownedProperties[i].fullSet == true && ownedProperties[i].canBuildHouses == true){ // set our desired set to upgrade fullPropertyGroup = ownedProperties[i].tileGroup; // stop the loop i=ownedProperties.Count; } } // Get the properties in our group BoardTile[] groupProperties = GetPropertiesInGroup(fullPropertyGroup); // buy houses on them. for(int i=0;i<groupProperties.Length;i++){ BuyHouse(groupProperties[i]); } Debug.Log("Ending Turn Now..."); DoneTurnEnd(); }
public void ProposeNewTradeOffer(TradeOffer offer){ pendingTradeOffer = true; if(isProcessingTradeOffer == true){ Debug.Log (playerName+": Already proposing a trade offer, aborting current trade..."); // decline this offer ResolveTradeOffer(false); } // check if the offer has a recipient if(offer.recieverPlayerId == -1){ // we don't have a trade offer any more pendingTradeOffer = false; // end the function return; } GamePlayer target = offer.GetReciever(); // check for a valid offer. otherwise, we just can't make this trade // do both players have the required funds if(offer.recieverFunds > target.money || offer.senderFunds > money){ if(offer.senderFunds < 0 || offer.recieverFunds < 0){ // no more trade offer Debug.Log (playerName+": Cannot Propose trade offer as the required funds cannot be transferred"); pendingTradeOffer = false; } } else{ Debug.Log (playerName+": New Trade Offer Proposed to "+target.playerName); target.StartCoroutine(target.ProcessTradeOffer(offer)); } }
public TradeValidationRequest(TradeOffer tradeOffer) { TradeOffer = tradeOffer; }
public bool IsViableTradeRequest(TradeOffer trade) { if(debugMessages) { GameEngine.print (brick + " -> " + trade.getBrick + " BRICK\n" + ore + " -> " + trade.getOre + " ORE\n" + wood + " -> " + trade.getWood + " WOOD\n" + grain + " -> " + trade.getGrain + " GRAIN\n" + sheep + " -> " + trade.getSheep + " SHEEP"); } bool isViableTrade = brick >= trade.getBrick && ore >= trade.getOre && wood >= trade.getWood && grain >= trade.getGrain && sheep >= trade.getSheep; if(debugMessages) { if (!isViableTrade) { GameEngine.print ("IS VIABLE TRADE: " + isViableTrade); } else { GameEngine.print ("= = = = = = = IS VIABLE TRADE: " + isViableTrade + " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); GameEngine.print ("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); } } return isViableTrade; }
public void Run(HSInputState state) { var player = _context.GetPlayer(state.PlayerId.Value); var commandChoice = _context.GetComponent <HSCommandChoice>(); if (commandChoice == null) { if (!_context.ContainsComponent <HSCommandChoiceRequest>()) { var commands = GetAvailableCommands(player); _context.Add(new PrintCommands(commands)); _context.Add(new HSCommandChoiceRequest(commands, player.Id)); } return; } _context.Add(new ClearOutput()); switch (commandChoice.Command) { case MonopolyCommand.ManageProperty: state.Set(HSState.PropManageChooseProperty, player.Id); break; case MonopolyCommand.CreateTradeOffer: var offer = new TradeOffer(); offer.InitiatorAssets.PlayerId = player.Id; _context.Add(offer); state.Set(HSState.TradeChoosePlayer, player.Id); break; case MonopolyCommand.MakeMove: _context.Add(new ThrowDice()); _context.Add(new MoveDice(player.Id)); state.Nullify(); break; case MonopolyCommand.EndTurn: _context.Add(new EndTurn()); state.Nullify(); break; case MonopolyCommand.PrintPlayerStatus: _context.Add(new PrintPlayerStatus(commandChoice.PlayerId)); break; case MonopolyCommand.PrintGameStatus: _context.Add(new PrintGameStatus()); break; case MonopolyCommand.PrintMap: _context.Add(new PrintMap()); break; case MonopolyCommand.PayJailFine: _context.Add(new JailPayFine(player.Id)); break; case MonopolyCommand.JailRollDice: _context.Add(new ThrowDice()); _context.Add(new JailDiceRoll(player.Id)); break; case MonopolyCommand.UseJailCard: _context.Add(new JailUseCard(player.Id)); break; } _context.Remove <HSCommandChoice>(c => c.Command == commandChoice.Command); }
public override void OnNewTradeOffer(TradeOffer offer) { string tradeid; if (IsAdmin && offer.Accept(out tradeid)) { Log.Success("Accepted Admin trade offer successfully : Trade ID: " + tradeid); } }
public TradeOfferStateChangedEventArgs(TradeOffer tradeOffer) { TradeOffer = tradeOffer; }
public override void OnNewTradeOffer(TradeOffer offer) { //Get password from file on desktop string pass = System.IO.File.ReadAllText(@"C:\Users\Jordan Turley\Desktop\password.txt"); //Get items in the trade, and ID of user sending trade var theirItems = offer.Items.GetTheirItems (); var myItems = offer.Items.GetMyItems (); var userID = offer.PartnerSteamId; bool shouldDecline = false; //Check if they are trying to get items from the bot if (myItems.Count > 0 || theirItems.Count == 0) { shouldDecline = true; Log.Error ("Offer declined because the offer wasn't a gift; the user wanted items instead of giving."); } //Check to make sure all items are for CS: GO. foreach (TradeAsset item in theirItems) { if (item.AppId != 730) { shouldDecline = true; Log.Error ("Offer declined because one or more items was not for CS: GO."); } } //Check if there are more than 10 items in the trade if (theirItems.Count > 10) { shouldDecline = true; Log.Error ("Offer declined because there were more than 10 items in the deposit."); } if (shouldDecline) { if (offer.Decline ()) { Log.Error ("Offer declined."); } return; } Log.Success ("Offer approved, accepting."); //Send items to server and check if all items add up to more than $1. //If they do, accept the trade. If they don't, decline the trade. string postData = "password="******"&owner=" + userID; string theirItemsJSON = JsonConvert.SerializeObject (theirItems); postData += "&items=" + theirItemsJSON; string url = "http://csgowinbig.com/php/check-items.php"; var request = (HttpWebRequest)WebRequest.Create (url); var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //Log.Success ("Response received from server: \n" + responseString); JSONClass responseJsonObj = JsonConvert.DeserializeObject<JSONClass> (responseString); if (responseJsonObj.success == 1) { //Get data array from json var jsonData = responseJsonObj.data; if (jsonData.minDeposit == 1) { if (offer.Accept ()) { Log.Success ("Offer accepted from " + userID); //Put items into the pot string urlPutItemsIn = "http://csgowinbig.com/php/deposit.php"; var requestUrlPutItemsIn = (HttpWebRequest)WebRequest.Create (urlPutItemsIn); string postDataPutItemsIn = "password="******"&owner=" + userID; postDataPutItemsIn += "&items=" + jsonData.allItems; //Log.Success (jsonData.allItems); var dataPutItemsIn = Encoding.ASCII.GetBytes (postDataPutItemsIn); requestUrlPutItemsIn.Method = "POST"; requestUrlPutItemsIn.ContentType = "application/x-www-form-urlencoded"; requestUrlPutItemsIn.ContentLength = dataPutItemsIn.Length; using (var stream = requestUrlPutItemsIn.GetRequestStream ()) { stream.Write (dataPutItemsIn, 0, dataPutItemsIn.Length); } var responsePutItemsIn = (HttpWebResponse)requestUrlPutItemsIn.GetResponse (); string responsePutItemsInString = new StreamReader (responsePutItemsIn.GetResponseStream ()).ReadToEnd (); JSONClass responseJsonObjPutItemsIn = JsonConvert.DeserializeObject<JSONClass> (responsePutItemsInString); jsonData = responseJsonObjPutItemsIn.data; } //Check if the pot is over if (jsonData.potOver == 1) { //Get items to give and keep, and the winner and their trade token var itemsToGive = jsonData.tradeItems; var itemsToKeep = jsonData.profitItems; string winnerSteamIDString = jsonData.winnerSteamID; SteamID winnerSteamID = new SteamID (winnerSteamIDString); string winnerTradeToken = jsonData.winnerTradeToken; Log.Success ("Winner steam id: " + winnerSteamIDString + ", token: " + winnerTradeToken); //Get bot's inventory json string botInvUrl = "http://steamcommunity.com/profiles/76561198238743988/inventory/json/730/2"; var botInvRequest = (HttpWebRequest)WebRequest.Create (botInvUrl); var botInvResponse = (HttpWebResponse)botInvRequest.GetResponse (); string botInvString = new StreamReader (botInvResponse.GetResponseStream()).ReadToEnd(); BotInventory botInventory = JsonConvert.DeserializeObject<BotInventory> (botInvString); if (botInventory.success != true) { Log.Error ("An error occured while fetching the bot's inventory."); return; } var rgInventory = botInventory.rgInventory; //Create trade offer for the winner var winnerTradeOffer = Bot.NewTradeOffer (winnerSteamID); //Loop through all winner's items and add them to trade List<long> alreadyAddedToWinnerTrade = new List<long> (); foreach (CSGOItemFromWeb item in itemsToGive) { long classId = item.classId, instanceId = item.instanceId; //Loop through all inventory items and find the asset id for the item long assetId = 0; foreach (var inventoryItem in rgInventory) { var value = inventoryItem.Value; long tAssetId = value.id, tClassId = value.classid, tInstanceId = value.instanceid; if (tClassId == classId && tInstanceId == instanceId) { //Check if this assetId has already been added to the trade if (alreadyAddedToWinnerTrade.Contains (tAssetId)) { continue; //This is for when there are 2 of the same weapon, but they have different assetIds } assetId = tAssetId; break; } } //Log.Success ("Adding item to winner trade offer. Asset ID: " + assetId); winnerTradeOffer.Items.AddMyItem (730, 2, assetId, 1); alreadyAddedToWinnerTrade.Add (assetId); } //Send trade offer to winner if (itemsToGive.Count > 0) { string winnerTradeOfferId, winnerMessage = "Congratulations, you have won on CSGO Win Big! Here are your items."; winnerTradeOffer.SendWithToken (out winnerTradeOfferId, winnerTradeToken, winnerMessage); Log.Success ("Offer sent to winner."); } else { Log.Info ("No items to give... strange"); } } } else { if (offer.Decline ()) { Log.Error ("Minimum deposit not reached, offer declined."); } } } else { Log.Error ("Server deposit request failed, declining trade. Error message:\n" + responseJsonObj.errMsg); offer.Decline (); } }
private bool evaluateTradeRequest(GameState gamestate, TradeOffer trade) { bool acceptTradeRequest = false; if (!isAI) { // Allow player to accept / reject / modify trade } else { List <AIEngine.Objective> objectives = AIEngine.GetObjectives(this, gamestate.getGamestateBoard(), gamestate); foreach (AIEngine.Objective objective in objectives) { PlayerHand thisPlayerNeedResources = objective.GetCardDifferential(); PlayerHand thisPlayerGiveResources = trade.convertGetResourcesToPlayerHand(); // tradeHost gets the resources that this Player gives PlayerHand thisPlayerGetResources = trade.convertGiveResourcesToPlayerHand(); // tradeHost gives the resources that this Player gets if (debugMessages) { GameEngine.print(objective.GetObjectiveScore() + ": OBJECTIVE SCORE"); GameEngine.print("PLAYER " + this.id + " GIVES TO TRADEHOST:" + "GIVE " + trade.getBrick + " BRICK, " + "GIVE " + trade.getOre + " ORE, " + "GIVE " + trade.getWood + " WOOD, " + "GIVE " + trade.getGrain + " GRAIN, " + "GIVE " + trade.getSheep + " SHEEP"); GameEngine.print("FOR " + trade.giveBrick + " BRICK, " + "FOR " + trade.giveOre + " ORE, " + "FOR " + trade.giveWood + " WOOD, " + "FOR " + trade.giveGrain + " GRAIN, " + "FOR " + trade.giveSheep + " SHEEP"); int[] x = thisPlayerNeedResources.ToArray(); GameEngine.print("PLAYER " + this.id + " (SELLER) NEEDS:" + x[0] + " BRICK, " + x[1] + " ORE, " + x[2] + " WOOD, " + x[3] + " GRAIN, " + x[4] + " SHEEP"); } bool resourcesNeededOverlapsWithResourcesReceived = false; // Compare Cards Received with Cards Needed for (int i = 0; i < 5; i++) { if (thisPlayerNeedResources.GetResourceQuantity(i) < 0 && thisPlayerGetResources.GetResourceQuantity(i) > 0) { resourcesNeededOverlapsWithResourcesReceived = true; } } bool resourcesNeededOverlapsWithResourcesGiven = false; for (int i = 0; i < 5; i++) { if (thisPlayerNeedResources.GetResourceQuantity(i) >= 0 && thisPlayerNeedResources.GetResourceQuantity(i) - thisPlayerGiveResources.GetResourceQuantity(i) < 0) { resourcesNeededOverlapsWithResourcesGiven = true; } } if (debugMessages) { // If any resources needed and received overlap && any resources needed and given do not overlap GameEngine.print("NEEDS OVERLAPS WITH GET?: " + resourcesNeededOverlapsWithResourcesReceived + "(-true-), " + "NEEDS OVERLAPS WITH GIVE?: " + resourcesNeededOverlapsWithResourcesGiven + " (-false-)"); } if (resourcesNeededOverlapsWithResourcesReceived && !resourcesNeededOverlapsWithResourcesGiven) { if (debugMessages) { GameEngine.print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ GET NEEDED RESOURCES & ONLY TRADE SURPLUS RESOURCES @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"); } if (trade.IsFairTrade() || trade.isGoodTradeForSeller()) { acceptTradeRequest = true; } else { System.Random rand = new System.Random(); if (rand.Next(100) < 25) // 25% Chance to accept an unfair trade (technically could be better for them, but sometimes worse for them) { acceptTradeRequest = true; } } } if (acceptTradeRequest) { if (debugMessages) { GameEngine.print("# # # # # # # # # # # # # # # # # # # # # # # # # # # ACCEPT TRADE # # # # # # # # # # # # # # # # # # # # # # # # # # #"); } break; } } } return(acceptTradeRequest); }
public void TradeOfferRouter(TradeOffer offer) { if (offer.OfferState == TradeOfferState.TradeOfferStateActive) { GetUserHandler(offer.PartnerSteamId).OnNewTradeOffer(offer); } }
public override void OnNewTradeOffer(TradeOffer offer) { var escrow = Bot.GetEscrowDuration(offer.TradeOfferId); Log.Success(escrow.DaysMyEscrow + " | " + escrow.DaysTheirEscrow); //Code for limiting pot for only specific users /* if (offer.PartnerSteamId.ConvertToUInt64() != 76561198020620333 && offer.PartnerSteamId.ConvertToUInt64() != 76561197995164153) { * if (offer.Decline ()) { * Log.Error ("Not one of the 2 verified accounts."); * return; * } * } */ if (escrow.DaysMyEscrow != 0) { doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("This bot has not been using the Mobile Authenticator for 7 days or has turned off trade confirmations, offer declined."); } }); } else if (escrow.DaysTheirEscrow != 0) { doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("User has not been using the Mobile Authenticator for 7 days or has turned off trade confirmations, offer declined."); } }); } else { //Get password from bot configuration file string pass = Bot.BotDBPassword; //Get items in the trade, and ID of user sending trade var theirItems = offer.Items.GetTheirItems(); var myItems = offer.Items.GetMyItems(); bool shouldDecline = false; //Check if they are trying to get items from the bot if (myItems.Count > 0 || theirItems.Count == 0) { //shouldDecline = true; Log.Error("Offer declined because the offer wasn't a gift; the user wanted items instead of giving."); } //Check to make sure all items are for CS: GO. foreach (TradeAsset item in theirItems) { if (item.AppId != 730) { shouldDecline = true; Log.Error("Offer declined because one or more items was not for CS: GO."); } } //Check if there are more than 10 items in the trade if (theirItems.Count > 10) { shouldDecline = true; Log.Error("Offer declined because there were more than 10 items in the deposit."); } if (shouldDecline) { doWebWithCatch(1, () => { if (offer.Decline()) { Log.Error("Offer declined."); } }); return; } Log.Success("Offer approved, accepting."); //Send items to server and check if all items add up to more than the minimum deposit. //If they do, accept the trade. If they don't, decline. if (timerTime <= 15) { acceptTrade(offer); } else { Log.Success("Offer sent within 15 seconds of round end, delaying to next round."); System.Timers.Timer acceptDelayTimer = new System.Timers.Timer(); acceptDelayTimer.Interval = 20000; //20 seconds acceptDelayTimer.Elapsed += delegate { acceptTrade(offer); acceptDelayTimer.Stop(); }; acceptDelayTimer.Start(); } } }
/// <summary> /// Called when a new trade offer is received /// </summary> /// <param name="offer"></param> public virtual void OnNewTradeOffer(TradeOffer offer) { }
private void CreateTradeOffer(Bot bot, GameServerRequest gsr) { float tradeValue = -1; string message = gsr.Arguments; //STEAM_0:1:42047781/2514414967/NULL/999900.00 //TOOOOOOOOO DOOOOOOOOOOOOOO string[] assetIDs = null; string[] myAssetIDs = null; string[] steamIDitems = message.Split('/'); SteamID steamid = GetSteamIDFromString(steamIDitems[0]); TradeOffer to = bot.TradeOfferManager.NewOffer(steamid); GameServer gameServer = bot.Manager.GetServerByID(gsr.ServerID); if (steamIDitems[1].Length > 1 && steamIDitems[1] != "NULL") { assetIDs = steamIDitems[1].Split(','); List <long> contextId = new List <long>(); contextId.Add(2); bot.OtherGenericInventory.load((int)Games.CSGO, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(assetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.OtherGenericInventory.load((int)Games.TF2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(assetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.OtherGenericInventory.load((int)Games.Dota2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(assetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } } if (steamIDitems[2].Length > 1 && steamIDitems[2] != "NULL") { myAssetIDs = steamIDitems[2].Split(','); List <long> contextId = new List <long>(); contextId.Add(2); bot.MyGenericInventory.load((int)Games.CSGO, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(myAssetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.MyGenericInventory.load((int)Games.TF2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(myAssetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } bot.MyGenericInventory.load((int)Games.Dota2, contextId, steamid); foreach (GenericInventory.Item item in bot.OtherGenericInventory.items.Values) { if (Array.IndexOf(myAssetIDs, item.assetid.ToString()) > -1) { GenericInventory.ItemDescription description = bot.OtherGenericInventory.getDescription(item.assetid); to.Items.AddTheirItem(item.appid, item.contextid, (long)item.assetid); } } } if (steamIDitems[3] != "NULL") { tradeValue = float.Parse(steamIDitems[3], CultureInfo.InvariantCulture); } string offerId; to.Send(out offerId, String.Format("\"{0}\" the {1}@{2}", gameServer.Name, DateTime.Now.ToString("dd/MM/yyyy"), DateTime.Now.ToString("HH:mm"))); if (offerId != "") { bot.Manager.Send(gsr.ServerID, gsr.ModuleID, NetworkCode.ASteambotCode.CreateTradeOffer, offerId); bot.TradeoffersGS.Add(offerId, gsr.ModuleID + "|" + tradeValue); bot.TradeOfferValue.Add(offerId, tradeValue); bot.AcceptMobileTradeConfirmation(offerId); } else { bot.Manager.Send(gsr.ServerID, gsr.ModuleID, NetworkCode.ASteambotCode.CreateTradeOffer, "-1"); } }