private static void LoadSprockets(Bot bot) { bot.AddSprocket(new Jabbot.Sprockets.auto_stache()); bot.AddSprocket(new Jabbot.Sprockets.Github.Issues()); bot.AddSprocket(new Jabbot.Sprockets.Github.Issue()); bot.AddSprocket(new Jabbot.Sprockets.Github.Members()); }
public static void HandleShortcutBarRefreshMessage(Bot bot, ShortcutBarRefreshMessage message) { if (message.barType == (int)bot.Character.GeneralShortcuts.BarType) bot.Character.GeneralShortcuts.Update(message); else bot.Character.SpellShortcuts.Update(message); }
public override String run(CommandInfo cmdInfo, Bot bot) { String output = "Here are the items you have duplicates of:"; dynamic json = Util.CreateSteamRequest(String.Format("http://api.steampowered.com/ITFItems_440/GetPlayerItems/v0001/?key=" + bot.apiKey + "&SteamID={0}&format=json",cmdInfo.getSteamid().ConvertToUInt64()),"GET"); int limit = cmdInfo.getArg(0, 2); Dictionary<int, MutableInt> freq = new Dictionary<int, MutableInt>(); foreach (dynamic i in json.result.items.item) { int defindex = i.defindex; if (freq.ContainsKey(defindex)) { freq[defindex].increment(); } else { freq.Add(defindex, new MutableInt()); } } List<KeyValuePair<int, MutableInt>> myList = freq.ToList(); myList.Sort((firstPair,nextPair) => { return firstPair.Value.CompareTo(nextPair.Value); } ); foreach (KeyValuePair<int, MutableInt> entry in myList) { if (entry.Value.get() < limit) { break; } ItemInfo itemInfo = Util.getItemInfo(entry.Key); output += "\n" + itemInfo.getName() + " x" + entry.Value.get(); } return output; }
public override void Initialize(Bot Bot) { mSelfBot = Bot; mCurrentAction = PetBotAction.Idle; mActionStartedTimestamp = UnixTimestamp.GetCurrent(); mPossibleTricks = PetDataManager.GetTricksForType(Bot.PetData.Type); }
public static void cmd_cycle(Bot bot, String ns, String[] args, String msg, String from, dAmnPacket packet) { var chan = ""; if (args.Length > 1 && args[1].StartsWith("#")) { chan = args[1]; } else { chan = ns; } String cpns = Tools.FormatNamespace(chan, Types.NamespaceFormat.Packet).ToLower(); if (!Core.ChannelData.ContainsKey(cpns)) { bot.Say(ns, "<b>» It doesn't look like I'm in that channel.</b>"); return; } lock (CommandChannels["part"]) { CommandChannels["part"].Add(ns); } lock (CommandChannels["join"]) { CommandChannels["join"].Add(ns); } bot.Part(cpns); bot.Join(cpns); }
public void FriendRun(SteamFriends.FriendMsgCallback callback, Bot bot, object[] args = null) { List<string> strings = new List<string>(callback.Message.Split(' ')); strings.RemoveAt(0); string company = String.Join(" ", strings.ToArray()); bot.FriendMessage(callback.Sender, Util.GetYahooStocks(company)); }
public void GroupRun(SteamFriends.ChatMsgCallback callback, Bot bot, object[] args = null) { List<string> strings = new List<string>(callback.Message.Split(' ')); strings.RemoveAt(0); string company = String.Join(" ", strings.ToArray()); bot.ChatroomMessage(bot.chatRoomID, Util.GetYahooStocks(company)); }
public override System.Collections.Generic.IEnumerator<string> Run(Bot bot) { string danceButton = ""; int danceDuration = 0; var rnd = random.NextDouble(); if (rnd > .9) { danceButton = "2"; danceDuration = 1 + random.Next(_maxCrouch); } else if (rnd > .65 && Math.Abs(bot.myState.XDistance) < _targetDistance) { danceButton = "4"; danceDuration = 1 + random.Next(_maxBackward); } else { danceButton = "6"; danceDuration = 1 + random.Next(_maxForward); } while (danceDuration-- > 0) { bot.pressButton(danceButton); yield return "Dancing"; } }
/// <summary> /// Constructor. /// </summary> /// <param name="chatroomName">Chatroom name.</param> /// <param name="bot">Bot reference.</param> /// <param name="uiThread">The thread for the currently running UI.</param> public UIChat(string chatroomName, Bot bot, dAmnNET dAmn, Thread uiThread) : base(chatroomName, bot) { this.dAmn = dAmn; this.UIThread = uiThread; Messages = new ObservableCollection<string>(); }
static public IEnumerable<ITaskParam> Resolve( this ShipModuleActivateParam Param, Bot Bot) { var Module = Param?.Module; var Target = Param?.Target; if (null != Target) { var TargetMeasurementLast = Bot?.SequenceStepLastState()?.MemoryMeasurement?.Wert?.Target?.FirstOrDefault(Candidate => Candidate?.Id == Target?.Id); if (null == TargetMeasurementLast) { yield return new ToClientStatusParam("requested Target not present", TaskStatusEnum.Failed); } if (!(TargetMeasurementLast?.Active ?? false)) { yield return new MouseClickUIElementParam(TargetMeasurementLast, BotEngine.Motor.MouseButtonIdEnum.Left); } } // Sensor Data is noisy and will sometimes report an active module as inactive. // Therefore activation is only attempted when multiple sensor measurements have shown inactivity. if (Bot?.SequenceInstantOfAccuEntityReversed(Module) ?.Take(ShipModuleActivateParam.NoiseSupressionThresholdStepCount) ?.Any(ModuleInstant => ModuleInstant?.LastInstant?.Wert?.Module?.RampActive ?? false) ?? false) { // module was active in the last NoiseSupressionThresholdStepCount steps. yield break; } yield return new ShipModuleActivityToggleParam(Module); }
static public ITaskParam TravelInfoPanelRouteConditional(Bot Bot) { var MemoryMeasurement = Bot?.SequenceStepLastState()?.MemoryMeasurement?.Wert; var InfoPanelRoute = MemoryMeasurement.InfoPanelRoute(); // from the set of Waypoint markers in the Info Panel pick the one that represents the next Waypoint/System. // We assume this is the one which is nearest to the topleft corner of the Screen which is at (0,0) var WaypointMarkerNext = InfoPanelRoute?.WaypointMarker ?.OrderByCenterDistanceToPoint(new Vektor2DInt(0, 0)) ?.FirstOrDefault(); if (null == WaypointMarkerNext) { return new ToClientStatusParam("no route in InfoPanel.", TaskStatusEnum.Idle); } if ((Bot?.LastOcurrenceAge(BotInstant => (BotInstant.ShipState()?.ManeuverType?.Docked() ?? false)) ?? int.MaxValue) < TravelInfoPanelRouteParam.ShipTransitionSettlingTime) { return new ToClientStatusParam("char is docked, no action required.", TaskStatusEnum.Idle); } return new SequentialParam( new ITaskParam[] { new WaitUntilShipManeuverPossible(), new MenuPathParam(WaypointMarkerNext, new[] { TravelInfoPanelRouteParam.MenuEntryRegexPattern }).ContainerRateLimitEqualByTime(TravelInfoPanelRouteParam.InputNextManeuverDistanceMin), }); }
public Tell(Bot bot) : base(bot) { Bot.OnChannelMessage+=new IrcEventHandler(Bot_OnMessage); Bot.OnQueryMessage += new IrcEventHandler(Bot_OnMessage); Bot.OnJoin += new JoinEventHandler(Bot_OnJoin); }
public void UpdateBot(Bot bot) { var healthSlider = gameObject.GetComponentInChildren<Slider>(); healthSlider.minValue = 0; healthSlider.maxValue = bot.PhysicalHealth.Maximum; healthSlider.value = bot.PhysicalHealth.Current; }
public Dig(Bot bot) : base(bot) { resetDigHardness(); playerSaveStopwatch = new Stopwatch(); playerSaveStopwatch.Start(); }
public static void cmd_act(Bot bot, String ns, String[] args, String msg, String from, dAmnPacket packet) { if (args.Length < 2) { bot.Say(ns, String.Format("<b>» Usage:</b> {0}act <i>[#channel]</i> msg", bot.Config.Trigger)); } else { String chan, mesg; if (!args[1].StartsWith("#")) { chan = ns; mesg = msg.Substring(4); } else { chan = args[1]; mesg = msg.Substring(5 + args[1].Length); } lock (CommandChannels["send"]) { CommandChannels["send"].Add(ns); } bot.Act(chan, mesg); } }
public void OnDisconnect(object sender, string reason, Bot bot) { lock (tasks) { while (tasks.Count > 0) { Task task = tasks.Dequeue().task; if (BotUtility.isTaskRunning(task)) task.Dispose(); } } lock (subBots) { foreach (SubBot o in subBots.Values) { if (o != null) { o.onDisconnect(sender, reason, bot); o.onDisable(bot); bot.form.Invoke(new Action(() => { if (o.HasForm) o.Form.Close(); })); } } System.Threading.Thread.Sleep(500); subBots.Clear(); bot.form.Invoke(new Action(() => bot.form.subbotCheckedListBox.Items.Clear() )); } }
public static void cmd_disconnects(Bot bot, String ns, String[] args, String msg, String from, dAmnPacket packet) { if (Program.Disconnects == 0) bot.Say(ns, "<b>» I have not disconnected since startup.</b>"); else bot.Say(ns, String.Format("<b>» I have disconnected {0} time{1} since startup.</b>", Program.Disconnects, Program.Disconnects == 1 ? "" : "s")); }
public override void SetData(string key, string value, Bot bot, Player player) { switch (key) { case "chance": { chances.Clear(); totalChance = 0; string[] temp = value.Split(','); for (int i = 0; i < temp.Length; i++) { string[] percentBlock = temp[i].Split('%'); int percent = 0; int block = 0; int.TryParse(percentBlock[0], out percent); if (percentBlock.Length > 1) int.TryParse(percentBlock[1], out block); if (percent != 0 && !chances.ContainsKey(block)) chances.Add(block, percent); totalChance += percent; } bot.connection.Send("say", player.name + ": Chance set. Total: " + chances.Count); } return; } base.SetData(key, value, bot, player); }
public static void evt_recv_action(Bot bot, dAmnPacket packet) { // Don't display DataShare messages. if (!Program.NoDisplay.Contains(Tools.FormatNamespace(packet.Parameter.ToLower(), Types.NamespaceFormat.Channel))) { ConIO.Write(String.Format("* {0} {1}", packet.Arguments["from"], packet.Body), Tools.FormatChat(packet.Parameter)); lock (BDS._seen_database) { if (BDS._seen_database.ContainsKey(packet.Arguments["from"].ToLower())) { BDS._seen_database[packet.Arguments["from"].ToLower()].Channel = packet.Parameter; BDS._seen_database[packet.Arguments["from"].ToLower()].Type = (byte)Types.SeenType.Talking; BDS._seen_database[packet.Arguments["from"].ToLower()].Timestamp = Bot.EpochTimestamp; } else { BDS._seen_database.Add(packet.Arguments["from"].ToLower(), new SeenInfo() { Name = packet.Arguments["from"], Channel = packet.Parameter, Type = (byte)Types.SeenType.Talking, Timestamp = Bot.EpochTimestamp }); } } } }
public static void HandleGameMapMovementMessage(Bot bot, GameMapMovementMessage message) { if (bot.Character.Context == null) { logger.Error("Context is null as processing movement"); return; } var actor = bot.Character.Context.GetContextActor(message.actorId); if (actor == null) logger.Error("Actor {0} not found", message.actorId); // only a log for the moment until context are fully handled else { var path = Path.BuildFromServerCompressedPath(bot.Character.Map, message.keyMovements); if (path.IsEmpty()) { logger.Warn("Try to start moving with an empty path"); return; } var movement = new MovementBehavior(path, actor.GetAdaptedVelocity(path)); movement.Start(DateTime.Now + TimeSpan.FromMilliseconds(EstimatedMovementLag)); actor.NotifyStartMoving(movement); } }
public override void DrawArea(Bot bot, Player player, WorldEdit worldEdit, string arg = "") { if (worldEdit.bothPointsSet) { for (int x = worldEdit.editBlock1.X; x <= worldEdit.editBlock2.X; x++) { for (int y = worldEdit.editBlock1.Y; y <= worldEdit.editBlock2.Y; y++) { int random = r.Next(totalChance); int block = 0; int current = 0; foreach (KeyValuePair<int, double> pair in chances) { int blabla = current + (int)Math.Round((pair.Value / totalChance) * totalChance); if (random >= current && random <= blabla) { block = pair.Key; bot.room.DrawBlock(Block.CreateBlock(block >= 500 ? 1 : 0, x, y, block, player.id)); break; } current += (blabla - current); } } } } }
public static void HandleGameEntitiesDispositionMessage(Bot bot, GameEntitiesDispositionMessage message) { if (!bot.Character.IsFighting()) logger.Error("Received GameEntitiesDispositionMessage but character is not in fight !"); else bot.Character.Fight.Update(message); }
public override void onEnable(Bot bot) { blockMap = new List<Block>[2][,]; blockQueue = new Queue<Block>(); blockRepairQueue = new Queue<Block>(); blockSet = new HashSet<Block>(); }
public override System.Collections.Generic.IEnumerator<string> Run(Bot bot) { var r = new Random(); var chosenCombo = (from combo in bot.getComboList() where combo.Score > 0 && combo.Type.HasFlag(ComboType.GROUND) orderby combo.Score descending select combo).Take(5); if (chosenCombo.Count() == 0) { _reason = "No combos?"; yield break; } var c = chosenCombo.ElementAt(r.Next(chosenCombo.Count())); var timer = 0; while(Math.Abs(bot.myState.XDistance) > c.XMax || bot.enemyState.ActiveCancelLists.Contains("REVERSAL") || bot.enemyState.ScriptName.Contains("UPWARD")) { bot.pressButton("6"); if (timer++ > 10) { _reason = "Rerolling"; yield break; } yield return "Getting in range"+timer; } var substate = new SequenceState(c.Input); while(!substate.isFinished()) yield return substate.Process(bot); }
public override void onCommand(object sender, string text, string[] args, Player player, bool isBotMod, Bot bot) { switch (args[0]) { case "rsize": lock (blockSet) { bot.connection.Send("say", "Size: " + blockSet.Count); } break; case "getplacer": { if (blockMap[0][player.blockX, player.blockY].Count > 0) { Block b = blockMap[0][player.blockX, player.blockY].Last(); int id = -1; if (b != null) id = b.b_userId; if (id != -1 && bot.playerList.ContainsKey(id)) bot.connection.Send("say", "Block is placed by " + bot.playerList[id].name); else bot.connection.Send("say", "Block is placed by undefined/server"); } else bot.connection.Send("say", "There is no block there."); } break; } }
private static void Main(string[] args) { using (var bot = new Bot()) { bot.Run(); } }
public static void cmd_part(Bot bot, String ns, String[] args, String msg, String from, dAmnPacket packet) { var c = ns; if (args.Length != 2) { // Ignore this for now. //bot.Say(ns, String.Format("<b>» Usage:</b> {0}part #channel", bot.Config.Trigger)); } else { if (!args[1].StartsWith("#")) { bot.Say(ns, "<b>» Invalid channel!</b> Channels should start with a #"); return; } c = args[1]; } lock (CommandChannels["part"]) { CommandChannels["part"].Add(ns); } bot.Part(c); }
static public ITaskParam Resolve( this ShipUndockParam Param, Bot Bot) { var MemoryMeasurement = Bot?.SequenceStepLastState()?.MemoryMeasurement?.Wert; if (false == MemoryMeasurement.ShipState()?.Docked()) { return null; } var WindowStationLobby = MemoryMeasurement.WindowStationLobby?.FirstOrDefault(); var ButtonUndock = WindowStationLobby?.ButtonUndock; if (WindowStationLobby?.UnDocking() ?? false) { return new ToClientStatusParam("waiting for undock to complete", TaskStatusEnum.WaitingForTransition); } if (null == ButtonUndock) { return new ToClientStatusParam("button to undock not available", TaskStatusEnum.Failed); } return new MouseClickUIElementParam(ButtonUndock, MouseButtonIdEnum.Left); }
public bool IsCommandExecutionAllowed(Command command, Bot bot, string hostMask) { var users = bot.GetAuthenticatedUsers(); var user = users.GetUserByHostMask(hostMask); return user.SecurityLevel >= (int)command.GetRequiredSecurityLevel(); }
public static void HandleGameFightHumanReadyStateMessage(Bot bot, GameFightHumanReadyStateMessage message) { if (!bot.Character.IsFighting()) logger.Error("Received GameFightHumanReadyStateMessage but character is not in fight !"); else bot.Character.Fight.Update(message); }
public void ApplyMultiplier(Bot _bot) { _bot.damageMultiplier_Rock *= (1f / defenseRock); _bot.damageMultiplier_Paper *= (1f / defensePaper); _bot.damageMultiplier_Scissors *= (1f / defenseScissors); }
private bool RedoerEffect() { List <ClientCard> enemy = Enemy.GetMonstersInMainZone(); List <int> units = Card.Overlays; if (Duel.Phase == DuelPhase.Standby && (AI.Executor.Util.GetStringId(XYZs.TimeThiefRedoer, 0) == ActivateDescription)) { return(true); } try { if (Bot.HasInSpellZone(Traps.XyzReborn)) { return(false); } if (Bot.HasInSpellZone(Traps.XyzExtreme)) { return(false); } for (int i = 0; i < enemy.Count; i++) { _totalAttack += enemy[i].Attack; } foreach (var t in Bot.GetMonsters()) { _totalBotAttack += t.Attack; } if (_totalAttack > Bot.LifePoints + _totalBotAttack) { return(false); } foreach (var t in enemy) { if (t.Attack < 2400 || !t.IsAttack()) { continue; } try { AI.SelectCard(t.Id); AI.SelectCard(t.Id); } catch {} return(true); } } catch {} if (Bot.UnderAttack) { //AI.SelectCard(Util.GetBestEnemyMonster()); return(true); } return(false); }
public async Task <StartGameView> Start(string playerName, int countOfBots) { if (string.IsNullOrEmpty(playerName)) { throw new CustomServiceException("Player name cannot be null"); } var player = await _database.Players.GetByName(playerName); if (player == null) { throw new CustomServiceException("Player does not exist"); } var isActiveGame = await _database.Games.GetActiveByPlayerId(player.Id); var game = new Game(); if (isActiveGame != null) { game = isActiveGame; } else { game = new Game() { PlayerId = player.Id, Player = player, GameState = (GameStateType)GameStateTypeEnumView.Unknown }; await _database.Games.Create(game); var playerSteps = new List <PlayerStep> { CreatePlayerStep(player, game), CreatePlayerStep(player, game) }; await _database.PlayerSteps.Create(playerSteps); } var bots = new List <Bot>(); bots = (isActiveGame != null) ? await _database.Bots.GetAllBotsByGameId(isActiveGame.Id) : await _database.Bots.GetAllBotsByGameId(game.Id); if (bots == null || bots.Count == 0) { var stepsOfAllBots = new List <BotStep>(); var countOfAlreadyExistBots = await _database.Bots.Count() + 1; var createdBots = new List <Bot>(); if (countOfBots > 0) { for (int i = 0; i < countOfBots; i++) { var bot = new Bot() { Balance = 1000, Bet = 0, Name = $"Bot {countOfAlreadyExistBots}" }; createdBots.Add(bot); countOfAlreadyExistBots += 1; stepsOfAllBots.Add(CreateBotStep(bot, game)); stepsOfAllBots.Add(CreateBotStep(bot, game)); } } await _database.Bots.Create(createdBots); await _database.BotSteps.Create(stepsOfAllBots); } await _database.Players.Update(player); var result = new StartGameView() { Id = game.Id, GameState = (GameStateTypeEnumView)game.GameState, CountOfBots = countOfBots, Player = new PlayerStartGameView() { PlayerId = game.Player.Id, UserName = game.Player.UserName, Balance = game.Player.Balance, Bet = game.Player.Bet } }; return(result); }
private void chkFpsCounter_CheckedChanged(object sender, EventArgs e) { Bot.CallGameFunction("world.toggleFPS"); }
private void btnSetFpsCap_Click(object sender, EventArgs e) { Bot.SetGameObject("stage.frameRate", (int)numFpsCap.Value); }
public static void Go(string[] args) { Console.SetIn(new StreamReader(Console.OpenStandardInput(512))); //from http://theaigames.com/languages/cs while (true) { var line = Console.ReadLine(); if (line == null) { break; } line = line.Trim(); if (line.Length == 0) { continue; } var parts = line.Split(' '); if (parts[0] == "pick_starting_region") { if (PickedTerritories == null) { LatestTurnStanding = DistributionStanding; //during picking, LatestStanding and DistributionStanding are the same thing InitBot(); PickedTerritories = Bot.GetPicks(); AILog.Log("AIGamesParser", "Bot picked " + PickedTerritories.Select(o => o.ToString()).JoinStrings(" ")); } var timeout = long.Parse(parts[1]); // pick which territories you want to start with var pickableStartingTerritories = parts.Skip(2).Select(o => (TerritoryIDType)int.Parse(o)).ToHashSet(false); var pick = PickedTerritories.Where(o => pickableStartingTerritories.Contains(o)).ToList(); if (pick.Count > 0) { Console.Out.WriteLine(pick[0]); } else { AILog.Log("AIGamesParser", "None of bot's picks are still available, picking random"); Console.Out.WriteLine(pickableStartingTerritories.Random()); } } else if (parts[0] == "go") { var timeout = long.Parse(parts[2]); Assert.Fatal(parts.Length == 3); NumberOfTurns++; // we need to do a move var output = new StringBuilder(); if (parts[1] == "place_armies") { AILog.Log("AIGamesParser", "================= Beginning turn " + NumberOfTurns + " ================="); //Re-create the bot before every turn. This is done to simulate how the bot will run in production -- it can't be active and maintaining state for the entirety of a multi-day game, since those can take months or years. Instead, it will be created before each turn, ran once, then thrown away. InitBot(); CompletedOrders = Bot.GetOrders(); // place armies foreach (var move in CompletedOrders.OfType <GameOrderDeploy>()) { output.Append(GetDeployString(move) + ","); } } else if (parts[1] == "attack/transfer") { foreach (var move in CompletedOrders.OfType <GameOrderAttackTransfer>()) { output.Append(GetAttackString(move) + ","); } } else { throw new Exception("Unexpected " + parts[1]); } if (output.Length > 0) { Console.Out.WriteLine(output); } else { Console.Out.WriteLine("No moves"); } } else if (parts[0] == "settings" && parts[1] == "starting_regions") { foreach (var terrID in parts.Skip(2).Select(o => (TerritoryIDType)int.Parse(o))) { DistributionStanding.Territories[terrID].OwnerPlayerID = TerritoryStanding.AvailableForDistribution; } } else if (parts.Length == 3 && parts[0] == "settings") { UpdateSettings(parts[1], parts[2]); // update settings } else if (parts[0] == "setup_map") { SetupMap(parts); // initial full map is given } else if (parts[0] == "update_map") { PreviousTurnStanding = LatestTurnStanding; LatestTurnStanding = ReadMap(parts); } else if (parts[0] == "opponent_moves") { ReadOpponentMoves(parts); // all visible opponent moves are given } else { throw new Exception("Unable to parse line \"" + line + "\""); } } }
protected bool Equals(Bot other) { return Position.Equals(other.Position) && SignalRadius == other.SignalRadius; }
private void InitializeMainForm() { dateLB.Text = DateTime.Now.ToString("dd/MMM/yyyy-HH:mm "); timer1.Start(); //Timer to control clock and DDE connection status update winNameLB.Text = Program.appName + " - V" + Program.appVersion.Major + "." + Program.appVersion.Minor; //Retrieve app name from Program.cs and set into UI versionLB.Text = $"Version: {Program.appVersion.ToString()}"; //updateRSI = false; this.client = new DdeClient(dashB.app, dashB.service); this.clientVWAP = new DdeClient(dashB.app, dashB.service); this.clientHOR = new DdeClient(dashB.app, dashB.service); clientHOR.Disconnected += OnDisconnected; clientVWAP.Disconnected += OnDisconnected; client.Disconnected += OnDisconnected; #region Set native Font PomBot.LoadFont(this); #endregion #region BOTs initialization //TODO -> If not possible to instantiate more than 1 bot, remove list and create just one object Bot bot1 = new Bot(); botsList.Add(bot1); //connect this form with all bots so bot have access to its directly foreach (Bot bot in botsList) { bot.mainForm = this; } //BOT forms initialization BOTsInit(); #endregion #region MenuItems and UI elements menuItems.Add(dashboardPN); menuItems.Add(bot1PN); menuItems.Add(bot2PN); menuItems.Add(bot2PN); menuItems.Add(bot3PN); menuItems.Add(bot4PN); menuItems.Add(helpPN); menuItems.Add(aboutPN); foreach (Panel item in menuItems) { item.Location = new Point(166, 67); item.Visible = false; } dashboardBT.Focus(); dashboardPN.Visible = true; #endregion ReadSavedData(); //DDE Connection ConnectDDE(); //ConnectDDETask(); //DDEupdateStatusAsync(); DDEupdateStatus(); UpdateDDEStrategy(); //Delegates StartMultiThread(); //Keys Bindings InitializeKeys(); calibrationBot1Bar.Maximum = 100; //Check for application Update Updater(); }
public override void OnStart(Bot bot) { bot.TaskManager = new TaskManager(); }
public async override Task Execute(Bot bot, DiscordUser user, DiscordMessage message, string[] args) { if (!Directory.Exists("out")) { Directory.CreateDirectory("out"); } var assoc = new ColoredRoleAssociations(); if (File.Exists(colorsPath)) { while (true) { try { assoc = JsonConvert.DeserializeObject <ColoredRoleAssociations>(File.ReadAllText(colorsPath)); break; } catch (IOException e) { Log.Warn("Waiting for file lock READ on " + colorsPath + "\n" + e.ToString()); await Task.Delay(100); } } } string colorName = args[0]; string roleName = args.Length > 1 ? string.Join(" ", args.Skip(1)) : colorName; DiscordColor color; try { color = new DiscordColor(colorName); } catch (Exception e) { await message.RespondAsync("Wrong color given! [" + colorName + "] is not a valid color. Use a #AABBCC format."); Log.Warn("When an user tried to set a color:\n" + e.ToString()); return; } var guildMember = await message.Channel.Guild.GetMemberAsync(user.Id); var fetchedRoles = guildMember.Roles.Where(o => o.Id == assoc[user.Id]?.roleId); DiscordRole currentRole; if (fetchedRoles.Count() > 0) { currentRole = fetchedRoles.ElementAt(0); await guildMember.Guild.UpdateRoleAsync(currentRole, roleName, hoist : false, color : color); } else { currentRole = await guildMember.Guild.CreateRoleAsync(roleName, DSharpPlus.Permissions.None, color, hoist : false, mentionable : false); } await guildMember.GrantRoleAsync(currentRole); assoc.ClearFor(user.Id); assoc.Add(new ColoredRoleAssociation() { roleId = currentRole.Id, userId = user.Id }); while (true) { try { File.WriteAllText(colorsPath, JsonConvert.SerializeObject(assoc)); break; } catch (IOException e) { Log.Warn("Waiting for file lock WRITE on " + colorsPath + "\n" + e.ToString()); await Task.Delay(100); } } await message.CreateReactionAsync(Extensions.ToDiscordEmoji("✅", bot)); Log.Info("Done creating role!"); }
public override void OnFrame(Bot bot) { if (NaturalProbe != null) { bool naturalProbeAlive = false; int probePos = -1; int i = 0; foreach (Agent agent in Units) { if (agent == NaturalProbe) { probePos = i; naturalProbeAlive = true; break; } i++; } if (!naturalProbeAlive) { NaturalProbe = null; } if (NaturalProbe != null && !DedicatedNaturalProbe && probePos >= 0) { Bot.Main.DrawText("Removing natural probe."); bool alreadyAssigned = false; foreach (BuildRequest request in BuildRequests) { if (request.worker == NaturalProbe) { alreadyAssigned = true; break; } } if (!alreadyAssigned) { DebugUtil.WriteLine("Clearing natural probe."); ClearAt(probePos); NaturalProbe = null; } else { Bot.Main.DrawText("Natural probe already assigned."); } } } if (DedicatedNaturalProbe && NaturalProbe != null) { bool alreadyAssigned = false; foreach (BuildRequest request in BuildRequests) { if (request.worker == NaturalProbe) { alreadyAssigned = true; } } if (!alreadyAssigned) { BuildRequest pickedRequest = null; foreach (BuildRequest request in UnassignedRequests) { if (request.Base == Bot.Main.BaseManager.Natural) { pickedRequest = request; } } if (pickedRequest != null) { pickedRequest.worker = NaturalProbe; pickedRequest.LastImprovementFrame = Bot.Main.Frame; pickedRequest.Closest = NaturalProbe.DistanceSq(pickedRequest.Pos); BuildRequests.Add(pickedRequest); UnassignedRequests.Remove(pickedRequest); alreadyAssigned = true; } } if (!alreadyAssigned && NaturalProbe != null && NaturalProbe.DistanceSq(bot.BaseManager.Natural.OppositeMineralLinePos) >= 4 * 4) { NaturalProbe.Order(Abilities.MOVE, bot.BaseManager.Natural.OppositeMineralLinePos); } } while (unassignedAgents.Count > 0 && UnassignedRequests.Count > 0) { UnassignedRequests[UnassignedRequests.Count - 1].worker = unassignedAgents[unassignedAgents.Count - 1]; UnassignedRequests[UnassignedRequests.Count - 1].LastImprovementFrame = Bot.Main.Frame; UnassignedRequests[UnassignedRequests.Count - 1].Closest = unassignedAgents[unassignedAgents.Count - 1].DistanceSq(UnassignedRequests[UnassignedRequests.Count - 1].Pos); BuildRequests.Add(UnassignedRequests[UnassignedRequests.Count - 1]); UnassignedRequests.RemoveAt(UnassignedRequests.Count - 1); unassignedAgents.RemoveAt(unassignedAgents.Count - 1); } for (int i = BuildRequests.Count - 1; i >= 0; i--) { BuildRequest buildRequest = BuildRequests[i]; bool completed = false; if (buildRequest.worker != null) { float newDist = buildRequest.worker.DistanceSq(buildRequest.Pos); if (newDist < buildRequest.Closest) { buildRequest.Closest = newDist; buildRequest.LastImprovementFrame = Bot.Main.Frame; } else if (Bot.Main.Frame - buildRequest.LastImprovementFrame >= 448) { UnassignedRequests.Add(buildRequest); BlockedWorkers.Add(buildRequest.worker.Unit.Tag); BuildRequests[i] = BuildRequests[BuildRequests.Count - 1]; BuildRequests.RemoveAt(BuildRequests.Count - 1); IdleTask.Task.Add(buildRequest.worker); units.Remove(buildRequest.worker); } else if (UnitTypes.ResourceCenters.Contains(buildRequest.Type)) { bool closeEnemy = false; int closeEnemyWorkerCount = 0; foreach (Unit enemy in Bot.Main.Enemies()) { if (!UnitTypes.CanAttackGround(enemy.UnitType)) { continue; } if (UnitTypes.WorkerTypes.Contains(enemy.UnitType)) { if (buildRequest.worker.DistanceSq(enemy) <= 4 * 4) { closeEnemyWorkerCount++; } continue; } if (buildRequest.worker.DistanceSq(enemy) <= 8 * 8) { closeEnemy = true; break; } } if (closeEnemy || closeEnemyWorkerCount > 1) { ExpandingBlockedUntilFrame = Bot.Main.Frame + 224; BuildRequests[i] = BuildRequests[BuildRequests.Count - 1]; BuildRequests.RemoveAt(BuildRequests.Count - 1); if (buildRequest.worker != NaturalProbe) { IdleTask.Task.Add(buildRequest.worker); units.Remove(buildRequest.worker); } DebugUtil.WriteLine("Base blocked, cancelling base. BuildRequest length: " + BuildRequests.Count); continue; } } } foreach (Agent agent in bot.UnitManager.Agents.Values) { if ((agent.Unit.UnitType == buildRequest.Type || (UnitTypes.GasGeysers.Contains(agent.Unit.UnitType) && UnitTypes.GasGeysers.Contains(buildRequest.Type))) && SC2Util.DistanceSq(agent.Unit.Pos, buildRequest.Pos) <= 1) { completed = true; agent.Base = buildRequest.Base; agent.AroundLocation = buildRequest.AroundLocation; agent.Exact = buildRequest.Exact; break; } } if (completed) { BuildRequests[i] = BuildRequests[BuildRequests.Count - 1]; BuildRequests.RemoveAt(BuildRequests.Count - 1); if (buildRequest.worker != NaturalProbe) { IdleTask.Task.Add(buildRequest.worker); units.Remove(buildRequest.worker); } } else if (!bot.UnitManager.Agents.ContainsKey(buildRequest.worker.Unit.Tag)) { buildRequest.worker = null; UnassignedRequests.Add(buildRequest); BuildRequests[i] = BuildRequests[BuildRequests.Count - 1]; BuildRequests.RemoveAt(BuildRequests.Count - 1); } else if (CancelBlockedBuildings && Unbuildable(buildRequest)) { BuildRequests[i] = BuildRequests[BuildRequests.Count - 1]; BuildRequests.RemoveAt(BuildRequests.Count - 1); if (buildRequest.worker != NaturalProbe) { IdleTask.Task.Add(buildRequest.worker); units.Remove(buildRequest.worker); } } else if (buildRequest.worker.Unit.Orders.Count == 0 || buildRequest.worker.Unit.Orders[0].AbilityId != BuildingType.LookUp[buildRequest.Type].Ability || (buildRequest.worker.Unit.Orders[0].TargetWorldSpacePos != null && buildRequest.worker.Unit.Orders[0].TargetWorldSpacePos.X != buildRequest.Pos.X) || (buildRequest.worker.Unit.Orders[0].TargetWorldSpacePos != null && buildRequest.worker.Unit.Orders[0].TargetWorldSpacePos.Y != buildRequest.Pos.Y) || (buildRequest is BuildRequestGas && ((BuildRequestGas)buildRequest).Gas.Tag != buildRequest.worker.Unit.Orders[0].TargetUnitTag)) { Bot.Main.ReservedMinerals += BuildingType.LookUp[buildRequest.Type].Minerals; Bot.Main.ReservedGas += BuildingType.LookUp[buildRequest.Type].Gas; if (buildRequest is BuildRequestGas) { bot.DrawLine(buildRequest.worker, ((BuildRequestGas)buildRequest).Gas.Pos); } else { bot.DrawLine(buildRequest.worker, SC2Util.Point(buildRequest.Pos.X, buildRequest.Pos.Y, buildRequest.worker.Unit.Pos.Z)); } if (bot.Observation.Observation.PlayerCommon.Minerals < BuildingType.LookUp[buildRequest.Type].Minerals || bot.Observation.Observation.PlayerCommon.Vespene < BuildingType.LookUp[buildRequest.Type].Gas || buildRequest.worker.DistanceSq(buildRequest.Pos) >= 5) { Point2D target = buildRequest is BuildRequestGas?SC2Util.To2D(((BuildRequestGas)buildRequest).Gas.Pos) : buildRequest.Pos; if (buildRequest.worker.DistanceSq(target) > 3 * 3) { buildRequest.worker.Order(Abilities.MOVE, new PotentialHelper(target, 1).To(buildRequest.worker.Unit.Pos).Get()); continue; } } if (buildRequest is BuildRequestGas) { Unit gas = ((BuildRequestGas)buildRequest).Gas.Unit; foreach (Unit unit in bot.Observation.Observation.RawData.Units) { if (SC2Util.DistanceSq(unit.Pos, ((BuildRequestGas)buildRequest).Gas.Pos) > 2 * 2) { continue; } gas = unit; break; } buildRequest.worker.Order(BuildingType.LookUp[buildRequest.Type].Ability, gas.Tag); } else { buildRequest.worker.Order(BuildingType.LookUp[buildRequest.Type].Ability, buildRequest.Pos); } } } foreach (BuildRequest request in UnassignedRequests) { Bot.Main.DrawText("BuildRequest: " + UnitTypes.LookUp[request.Type].Name + " " + request.Pos); } foreach (BuildRequest request in BuildRequests) { Bot.Main.DrawText("BuildRequest: " + UnitTypes.LookUp[request.Type].Name + " " + request.Pos); } }
public override void Produce(Bot bot, Agent agent) { }
static void Main(string[] args) { Bot bot = new Bot(@"config.xml", "there should be your bot token"); bot.ActivateBot().GetAwaiter().GetResult(); }
private void ConnectBot(Bot bot, Server server) { var credentials = new Credentials("USER Bottii 0 * :Botti", "IrcBotNM"); bot.ConnectToServer(server, credentials); }
private bool ShootingRiserDragonEffect() { if (ActivateDescription == -1 || (ActivateDescription == Util.GetStringId(CardId.ShootingRiserDragon, 0))) { int targetLevel = 8; if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == targetLevel - 5 && card.IsFaceup() && !card.IsTuner()) && Bot.GetRemainingCount(CardId.MechaPhantomBeastOLion, 2) > 0) { AI.SelectCard(CardId.MechaPhantomBeastOLion); } else if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == targetLevel - 4 && card.IsFaceup() && !card.IsTuner())) { AI.SelectCard(new[] { CardId.ScrapRecycler, CardId.RedRoseDragon }); } else if (Bot.MonsterZone.IsExistingMatchingCard(card => card.Level == targetLevel - 3 && card.IsFaceup() && !card.IsTuner())) { AI.SelectCard(new[] { CardId.ScrapBeast, CardId.PhotonThrasher, CardId.Goblindbergh, CardId.WorldCarrotweightChampion, CardId.WhiteRoseDragon, CardId.RaidenHandofTheLightsworn, CardId.AngelTrumpeter, CardId.PerformageTrickClown, CardId.MaskedChameleon }); } else { FoolishBurialEffect(); } return(true); } else { if (Duel.LastChainPlayer == 0 || ShootingRiserDragonCount >= 10) { return(false); } ShootingRiserDragonCount++; AI.SelectCard(new[] { CardId.BlackRoseMoonlightDragon, CardId.ScrapDragon, CardId.PSYFramelordOmega }); return(true); } }
public static void HandleChatMessage(Bot bot, ChatClientMultiMessage message) { if (message.content == ".help") { message.BlockNetworkSend();// do not send this message to the server bot.Character.SendInformation(".dump spells"); bot.Character.SendInformation(".dump all"); bot.Character.SendInformation(".FF ? => Show all plugins running"); bot.Character.SendInformation(".FF on or .FF auto => Starts experimental AI fight in automatic mode"); bot.Character.SendInformation(".FF fol => Put the experimental AI fight in follower mode"); bot.Character.SendInformation(".FF gat => Put the experimental AI fight in gathering mode (not implemented yet)"); bot.Character.SendInformation(".FF off or .FF man => Disable experimental AI fight (manual mode)"); bot.Character.SendInformation(".FF stats => gives some stats"); bot.Character.SendInformation(".FF all => Starts experimental AI fight on all Bots"); bot.Character.SendInformation(".FF /all => Stops experimental AI fight on all Bots"); bot.Character.SendInformation("message <Level> => Filters the messages received from the bot to the Dofus client. <Level> is a bit field (4 bits, so values range from 0 to 7)"); } else if (message.content == ".dump all") { message.BlockNetworkSend();// do not send this message to the server XmlDumper.DumpAll(); } else if (message.content == ".dump spells") { message.BlockNetworkSend();// do not send this message to the server XmlDumper.SpellsDumper("_Spells.xml"); } if (message.content.StartsWith(".FF")) { message.BlockNetworkSend();// do not send this message to the server if (message.content == ".FF ?") { int BotNo = 0; int FrameNo = 0; foreach (Bot subBot in BotManager.Instance.Bots) { BotNo++; foreach (IFrame frame in subBot.Frames) { FrameNo++; bot.Character.SendInformation("Bot {0} ({3}) Frame {1} : {2}", BotNo, FrameNo, frame.GetType().Name, subBot.Character); } } } else if (message.content == ".FF all") { bot.Character.SendInformation("Experimental AI fight started for all played characters (set to follower mode for non-leaders of parties)"); foreach (Bot subBot in BotManager.Instance.Bots) { if (subBot.AddFrame(new FFight(subBot))) { subBot.Character.SendInformation("Experimental AI fight started"); bot.Character.SendInformation("FF started for {0}", bot.Character); } else { subBot.Character.SendInformation("Can't start FF"); bot.Character.SendInformation("Can't start FF for {0}", bot.Character); } } } else if (message.content == ".FF /all") { bot.Character.SendInformation("Experimental AI fight stopped for all played characters (set to manual mode)"); foreach (Bot subBot in BotManager.Instance.Bots) { if (subBot.RemoveFrame <FFight>()) { subBot.Character.SendInformation("Experimental AI fight stopped"); bot.Character.SendInformation("FF stopped for {0}", bot.Character); } else { subBot.Character.SendInformation("Failed to stop Experimental AI fight. Probably not running ?"); bot.Character.SendInformation("Can't stop FF for {0}", bot.Character); } } } else if (message.content.StartsWith(".FF fol", StringComparison.InvariantCultureIgnoreCase)) { SetFrame(bot, Mode.Follower); } else if (message.content.StartsWith(".FF gat", StringComparison.InvariantCultureIgnoreCase)) { SetFrame(bot, Mode.Ressources); } else if (message.content.StartsWith(".FF auto", StringComparison.InvariantCultureIgnoreCase) || message.content.StartsWith(".FF on", StringComparison.InvariantCultureIgnoreCase)) { SetFrame(bot, Mode.AutomaticFight); } else if (message.content.StartsWith(".FF man", StringComparison.InvariantCultureIgnoreCase) || message.content.StartsWith(".FF off", StringComparison.InvariantCultureIgnoreCase)) { SetFrame(bot, Mode.Manual); } else if (message.content == ".FF stats") { if (!bot.HasFrame <FFight>()) { bot.Character.SendInformation("Experimental AI fight is NOT running"); } else { FFight fightBot = bot.GetFrame <FFight>(); bot.Character.SendInformation("Experimental AI fight IS running in mode {0}", fightBot.Mode); fightBot.Dump(); } } } PlayedCharacter PC = bot.Character; if (message.content == "?") { message.BlockNetworkSend();// do not send this message to the server PC.SendInformation(String.Format("Position : NF{0} - F{1}", PC.Cell, PC.Fighter != null ? PC.Fighter.Cell.ToString() : "N/A")); /*PC.ResetCellsHighlight(); * if (PC.Fighter != null) * { * PC.HighlightCells(PC.Fight.BlueTeam.FightersAlive.Select(fighter => fighter.Cell), Color.Blue); * PC.HighlightCells(PC.Fight.RedTeam.FightersAlive.Select(fighter => fighter.Cell), Color.Red); * PC.HighlightCell(PC.Fighter.Cell, Color.Pink); * } * else * PC.HighlightCell(PC.Cell, Color.Pink);*/ } if (message.content.StartsWith("message")) { message.BlockNetworkSend();// do not send this message to the server string sdbgLevel = message.content.Replace("message", "").Trim(); PlayedCharacter.MessageLevel dbgLevel = PC.InformationLevel; if (PlayedCharacter.MessageLevel.TryParse(sdbgLevel, out dbgLevel)) { PC.SendMessage(String.Format("MessageLevel was {0}, it is now {1}", PC.InformationLevel, dbgLevel)); PC.InformationLevel = dbgLevel; } else { PC.SendMessage(String.Format("MessageLevel is {0}", PC.InformationLevel)); } } }
private bool WorldCarrotweightChampionEffect() { return(!Bot.HasInMonstersZone(L4NonTuners)); }
public ReachAnyTarget(DeluxeState state, Bot bot, Func <IEnumerable <Vec> > getTargets) : base(state, bot) { this.getTargets = getTargets; }
private bool ScrapRecyclerSummonFirst() { return(Bot.GetRemainingCount(CardId.ScrapGolem, 2) > 0 && Bot.GetRemainingCount(CardId.MechaPhantomBeastOLion, 2) > 0 && Bot.GetRemainingCount(CardId.JetSynchron, 2) > 0); }
private bool ScrapGolemSummon() { return(Bot.GetMonsterCount() <= 2 && Bot.HasInMonstersZoneOrInGraveyard(CardId.ScrapRecycler)); }
protected BotStrategy(DeluxeState state, Bot bot) : base(state) { this.bot = bot; }
private bool OtherTunerSummonFirst() { return(Bot.HasInMonstersZone(L4NonTuners, faceUp: true)); }
public void StartPlugin(RadegastInstance inst) { Instance = inst; Instance.ClientChanged += new EventHandler <ClientChangedEventArgs>(Instance_ClientChanged); if (!Instance.GlobalSettings.Keys.Contains("plugin.alice.enabled")) { Instance.GlobalSettings["plugin.alice.enabled"] = OSD.FromBoolean(Enabled); } else { Enabled = Instance.GlobalSettings["plugin.alice.enabled"].AsBoolean(); } if (!Instance.GlobalSettings.Keys.Contains("plugin.alice.disableOnStart")) { Instance.GlobalSettings["plugin.alice.disableOnStart"] = OSD.FromBoolean(DisableOnStart); } else { DisableOnStart = Instance.GlobalSettings["plugin.alice.disableOnStart"].AsBoolean(); } if (DisableOnStart) { Enabled = false; } btn_DisableOnStart = new ToolStripMenuItem("Disable on start", null, (sender, e) => { DisableOnStart = btn_DisableOnStart.Checked = !DisableOnStart; Instance.GlobalSettings["plugin.alice.disableOnStart"] = OSD.FromBoolean(DisableOnStart); }); btn_DisableOnStart.Checked = DisableOnStart; EnabledButton = new ToolStripMenuItem("Enabled", null, (sender, e) => { Enabled = SetEnabled(!Enabled); EnabledButton.Checked = MenuButton.Checked = Enabled; Instance.GlobalSettings["plugin.alice.enabled"] = OSD.FromBoolean(Enabled); }); if (!Instance.GlobalSettings.Keys.Contains("plugin.alice.respondWithoutName")) { Instance.GlobalSettings["plugin.alice.respondWithoutName"] = OSD.FromBoolean(respondWithoutName); } else { respondWithoutName = Instance.GlobalSettings["plugin.alice.respondWithoutName"].AsBoolean(); } respondWithoutNameButton = new ToolStripMenuItem("Respond without name", null, (sender, e) => { respondWithoutName = respondWithoutNameButton.Checked = !respondWithoutName; Instance.GlobalSettings["plugin.alice.respondWithoutName"] = OSD.FromBoolean(respondWithoutName); }); if (!Instance.GlobalSettings.Keys.Contains("plugin.alice.respondRange")) { Instance.GlobalSettings["plugin.alice.respondRange"] = respondRange; } else { respondRange = Instance.GlobalSettings["plugin.alice.respondRange"]; } distance_5m = new ToolStripMenuItem("5m range", null, (sender, e) => { distance_5m.Checked = !distance_5m.Checked; if (distance_5m.Checked) { respondRange = 5; distance_10m.Checked = false; distance_15m.Checked = false; distance_20m.Checked = false; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } else if (!distance_10m.Checked && !distance_15m.Checked && !distance_20m.Checked) { respondRange = -1; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } }); distance_10m = new ToolStripMenuItem("10m range", null, (sender, e) => { distance_10m.Checked = !distance_10m.Checked; if (distance_10m.Checked) { respondRange = 10; distance_5m.Checked = false; distance_15m.Checked = false; distance_20m.Checked = false; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } else if (!distance_5m.Checked && !distance_15m.Checked && !distance_20m.Checked) { respondRange = -1; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } }); distance_15m = new ToolStripMenuItem("15m range", null, (sender, e) => { distance_15m.Checked = !distance_15m.Checked; if (distance_15m.Checked) { respondRange = 15; distance_5m.Checked = false; distance_10m.Checked = false; distance_20m.Checked = false; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } else if (!distance_5m.Checked && !distance_10m.Checked && !distance_20m.Checked) { respondRange = -1; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } }); distance_20m = new ToolStripMenuItem("20m range", null, (sender, e) => { distance_20m.Checked = !distance_20m.Checked; if (distance_20m.Checked) { respondRange = 20; distance_5m.Checked = false; distance_10m.Checked = false; distance_15m.Checked = false; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } else if (!distance_5m.Checked && !distance_10m.Checked && !distance_15m.Checked) { respondRange = -1; Instance.GlobalSettings["plugin.alice.respondRange"] = OSD.FromReal(respondRange); } }); if (!Instance.GlobalSettings.ContainsKey("plugin.alice.shout2shout")) { Instance.GlobalSettings["plugin.alice.shout2shout"] = OSD.FromBoolean(shout2shout); } else { shout2shout = Instance.GlobalSettings["plugin.alice.shout2shout"].AsBoolean(); } btn_shout2shout = new ToolStripMenuItem("Shout response to Shout", null, (sender, e) => { shout2shout = btn_shout2shout.Checked = !shout2shout; Instance.GlobalSettings["plugin.alice.shout2shout"] = OSD.FromBoolean(shout2shout); }); if (!Instance.GlobalSettings.ContainsKey("plugin.alice.whisper2whisper")) { Instance.GlobalSettings["plugin.alice.whisper2whisper"] = OSD.FromBoolean(whisper2whisper); } else { whisper2whisper = Instance.GlobalSettings["plugin.alice.whisper2whisper"].AsBoolean(); } btn_whisper2whisper = new ToolStripMenuItem("Whisper response to Whisper", null, (sender, e) => { whisper2whisper = btn_whisper2whisper.Checked = !whisper2whisper; Instance.GlobalSettings["plugin.alice.whisper2whisper"] = OSD.FromBoolean(whisper2whisper); }); MenuButton = new ToolStripMenuItem("ALICE chatbot", null, (sender, e) => { Enabled = SetEnabled(!Enabled); EnabledButton.Checked = MenuButton.Checked = Enabled; Instance.GlobalSettings["plugin.alice.enabled"] = OSD.FromBoolean(Enabled); }); btn_enableDelay = new ToolStripMenuItem("Enable random delay", null, (sender, e) => { btn_enableDelay.Checked = !btn_enableDelay.Checked; Instance.GlobalSettings["plugin.alice.enable_delay"] = EnableRandomDelay = btn_enableDelay.Checked; }); btn_enableDelay.Checked = EnableRandomDelay = Instance.GlobalSettings["plugin.alice.enable_delay"]; Instance.MainForm.PluginsMenu.DropDownItems.Add(MenuButton); Instance.MainForm.PluginsMenu.Visible = true; MenuButton.DropDownItems.Add(EnabledButton); MenuButton.Checked = EnabledButton.Checked = Enabled; MenuButton.DropDownItems.Add(respondWithoutNameButton); MenuButton.DropDownItems.Add(distance_5m); MenuButton.DropDownItems.Add(distance_10m); MenuButton.DropDownItems.Add(distance_15m); MenuButton.DropDownItems.Add(distance_20m); MenuButton.DropDownItems.Add(btn_shout2shout); MenuButton.DropDownItems.Add(btn_whisper2whisper); respondWithoutNameButton.Checked = respondWithoutName; if (respondRange == 5.0) { distance_5m.Checked = true; } else if (respondRange == 10.0) { distance_10m.Checked = true; } else if (respondRange == 15.0) { distance_15m.Checked = true; } else if (respondRange == 20.0) { distance_20m.Checked = true; } btn_shout2shout.Checked = shout2shout; btn_whisper2whisper.Checked = whisper2whisper; MenuButton.DropDownItems.Add(btn_enableDelay); MenuButton.DropDownItems.Add(btn_DisableOnStart); MenuButton.DropDownItems.Add("Reload AIML", null, (sender, e) => { Alice = null; GC.Collect(); LoadALICE(); }); SetEnabled(Enabled); // Events RegisterClientEvents(Client); }
public override void OnFrame(Bot bot) { BalanceGas(); if (ProxyPylon && ProxyTask.Task.UnitCounts.ContainsKey(UnitTypes.PYLON) && ProxyTask.Task.UnitCounts[UnitTypes.PYLON] > 0) { ProxyPylon = false; ProxyTask.Task.Stopped = true; ProxyTask.Task.Clear(); } IdleTask.Task.AttackMove = true; bot.TargetManager.CloseTo = null; bot.TargetManager.PrefferDistant = true; foreach (Agent agent in bot.UnitManager.Agents.Values) { if (agent.Unit.UnitType == UnitTypes.MOTHERSHIP) { bot.TargetManager.CloseTo = SC2Util.To2D(agent.Unit.Pos); bot.TargetManager.PrefferDistant = false; bot.TargetManager.IncludeAllEnemies = true; break; } } if (WorkerScoutTask.Task.BaseCircled()) { WorkerScoutTask.Task.Stopped = true; WorkerScoutTask.Task.Clear(); } if (!ProxyDetected && Defensive) { float proxyDist = 100 * 100; foreach (Unit enemy in bot.Enemies()) { if (enemy.UnitType == UnitTypes.PYLON) { float dist = SC2Util.DistanceSq(enemy.Pos, bot.MapAnalyzer.StartLocation); if (dist < proxyDist) { ProxyDetected = true; } } } } ForceFieldRampTask.Task.Stopped = !ProxyDetected || Completed(UnitTypes.STALKER) >= 20; if (ForceFieldRampTask.Task.Stopped) { ForceFieldRampTask.Task.Clear(); } if (TotalEnemyCount(UnitTypes.ZEALOT) + TotalEnemyCount(UnitTypes.PHOTON_CANNON) > 0) { HuntProxyTask.Task.Stopped = true; HuntProxyTask.Task.Clear(); } if ((ProxyDetected) && Completed(UnitTypes.STALKER) < 15) { foreach (Agent agent in bot.Units()) { if (agent.Unit.UnitType != UnitTypes.NEXUS) { continue; } if (agent.Unit.BuildProgress >= 0.99) { continue; } agent.Order(Abilities.CANCEL); } } BlinkForwardController.Stopped = !EnemyTempestOpener || Completed(UnitTypes.MOTHERSHIP) > 0; if (TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.ROBOTICS_BAY) > 0) { EnemyStargateOpener = false; EnemyTempestOpener = false; EnemyVoidRayOpener = false; } if (!StalkerAggressionSuspected && Defensive && bot.Frame >= 22.4 * 60 * 4.5 && Expanded.Get().Detected && TotalEnemyCount(UnitTypes.STARGATE) + TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.ROBOTICS_BAY) + TotalEnemyCount(UnitTypes.IMMORTAL) + TotalEnemyCount(UnitTypes.FLEET_BEACON) + +TotalEnemyCount(UnitTypes.VOID_RAY) + TotalEnemyCount(UnitTypes.TEMPEST) == 0) { StalkerAggressionSuspected = true; } if (TotalEnemyCount(UnitTypes.STARGATE) + TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.ROBOTICS_BAY) + TotalEnemyCount(UnitTypes.IMMORTAL) + TotalEnemyCount(UnitTypes.FLEET_BEACON) + +TotalEnemyCount(UnitTypes.VOID_RAY) + TotalEnemyCount(UnitTypes.TEMPEST) > 0) { StalkerAggressionSuspected = false; } if (!EnemyStargateOpener && Defensive && TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.ROBOTICS_BAY) == 0 && TotalEnemyCount(UnitTypes.STARGATE) + TotalEnemyCount(UnitTypes.VOID_RAY) + TotalEnemyCount(UnitTypes.FLEET_BEACON) + TotalEnemyCount(UnitTypes.TEMPEST) > 0 && bot.Frame <= 22.4 * 60 * 4.5) { EnemyStargateOpener = true; } if (!EnemyVoidRayOpener && !EnemyTempestOpener && EnemyStargateOpener && (TotalEnemyCount(UnitTypes.VOID_RAY) > 0 || Expanded.Get().Detected) && TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.ROBOTICS_BAY) == 0) { EnemyVoidRayOpener = true; } if (!EnemyVoidRayOpener && !EnemyTempestOpener && EnemyStargateOpener && TotalEnemyCount(UnitTypes.TEMPEST) + TotalEnemyCount(UnitTypes.FLEET_BEACON) > 0 && TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.ROBOTICS_BAY) == 0) { EnemyTempestOpener = true; } ObserverScoutTask.Task.Priority = 6; ArmyObserverTask.Task.IgnoreAllyUnitTypes.Add(UnitTypes.DARK_TEMPLAR); if (TotalEnemyCount(UnitTypes.STARGATE) + TotalEnemyCount(UnitTypes.DARK_SHRINE) + TotalEnemyCount(UnitTypes.ROBOTICS_FACILITY) + TotalEnemyCount(UnitTypes.VOID_RAY) == 0 && !ProxyDetected) { foreach (Agent agent in bot.Units()) { if (agent.Unit.UnitType != UnitTypes.SENTRY) { continue; } if (agent.Unit.Energy < 75) { continue; } // Hallucinate scouting phoenix. agent.Order(154); } } ScoutTask.Task.ScoutType = UnitTypes.PHOENIX; if (Completed(UnitTypes.PHOENIX) == 0) { ScoutTask.Task.Target = bot.TargetManager.PotentialEnemyStartLocations[0]; } else { foreach (Agent agent in bot.UnitManager.Agents.Values) { if (agent.Unit.UnitType != UnitTypes.PHOENIX) { continue; } if (bot.TargetManager.PotentialEnemyStartLocations.Count == 0 || agent.DistanceSq(bot.TargetManager.PotentialEnemyStartLocations[0]) >= 10 * 10) { continue; } ScoutTask.Task.Target = bot.MapAnalyzer.GetEnemyNatural().Pos; break; } } bot.NexusAbilityManager.Stopped = Completed(UnitTypes.PYLON) == 0; bot.NexusAbilityManager.PriotitizedAbilities.Add(1006); SaveWorkersTask.Task.Stopped = bot.Frame >= 22.4 * 60 * 7 || EnemyCount(UnitTypes.CYCLONE) == 0 || !Natural.UnderAttack; if (SaveWorkersTask.Task.Stopped) { SaveWorkersTask.Task.Clear(); } DefenseTask.GroundDefenseTask.IncludePhoenixes = true; if (TimingAttackTask.Task.Units.Count > 0) { DefenseTask.AirDefenseTask.IgnoreEnemyTypes.Add(UnitTypes.OBSERVER); } else { DefenseTask.AirDefenseTask.IgnoreEnemyTypes.Remove(UnitTypes.OBSERVER); } WorkerTask.Task.EvacuateThreatenedBases = true; TimingAttackTask.Task.DefendOtherAgents = false; if (EnemyVoidRayOpener && Completed(UnitTypes.TEMPEST) + Completed(UnitTypes.CARRIER) < 10) { TimingAttackTask.Task.RetreatSize = 15; TimingAttackTask.Task.RequiredSize = 45; } else if (TotalEnemyCount(UnitTypes.PHOTON_CANNON) > 0 && ProxyDetected && Completed(UnitTypes.IMMORTAL) >= 4) { TimingAttackTask.Task.RetreatSize = 6; TimingAttackTask.Task.RequiredSize = 15; } else if (Completed(UnitTypes.MOTHERSHIP) == 0 || Completed(UnitTypes.TEMPEST) + Completed(UnitTypes.CARRIER) < 6) { TimingAttackTask.Task.RetreatSize = 15; TimingAttackTask.Task.RequiredSize = 35; } else if (Completed(UnitTypes.MOTHERSHIP) == 1 && Completed(UnitTypes.TEMPEST) + Completed(UnitTypes.CARRIER) >= 8) { TimingAttackTask.Task.RetreatSize = 0; TimingAttackTask.Task.RequiredSize = 8; } else { TimingAttackTask.Task.RetreatSize = 10; TimingAttackTask.Task.RequiredSize = 25; } if (ProxyDetected && TotalEnemyCount(UnitTypes.PHOTON_CANNON) > 0 && Completed(UnitTypes.IMMORTAL) < 3) { DefenseTask.GroundDefenseTask.ExpandDefenseRadius = 18; DefenseTask.GroundDefenseTask.MainDefenseRadius = 18; DefenseTask.GroundDefenseTask.MaxDefenseRadius = 120; DefenseTask.GroundDefenseTask.DrawDefenderRadius = 80; DefenseTask.GroundDefenseTask.BufferZone = 0; DefenseTask.AirDefenseTask.ExpandDefenseRadius = 18; DefenseTask.AirDefenseTask.MainDefenseRadius = 18; DefenseTask.AirDefenseTask.MaxDefenseRadius = 120; DefenseTask.AirDefenseTask.DrawDefenderRadius = 80; DefenseTask.AirDefenseTask.BufferZone = 0; } else if (EnemyTempestOpener || TotalEnemyCount(UnitTypes.TEMPEST) > 0) { DefenseTask.GroundDefenseTask.ExpandDefenseRadius = 30; DefenseTask.GroundDefenseTask.MainDefenseRadius = 30; DefenseTask.GroundDefenseTask.MaxDefenseRadius = 120; DefenseTask.GroundDefenseTask.DrawDefenderRadius = 80; DefenseTask.AirDefenseTask.ExpandDefenseRadius = 30; DefenseTask.AirDefenseTask.MainDefenseRadius = 30; DefenseTask.AirDefenseTask.MaxDefenseRadius = 120; DefenseTask.AirDefenseTask.DrawDefenderRadius = 80; } else { DefenseTask.GroundDefenseTask.ExpandDefenseRadius = 20; DefenseTask.GroundDefenseTask.MainDefenseRadius = 20; DefenseTask.GroundDefenseTask.MaxDefenseRadius = 120; DefenseTask.GroundDefenseTask.DrawDefenderRadius = 80; DefenseTask.AirDefenseTask.ExpandDefenseRadius = 20; DefenseTask.AirDefenseTask.MainDefenseRadius = 20; DefenseTask.AirDefenseTask.MaxDefenseRadius = 120; DefenseTask.AirDefenseTask.DrawDefenderRadius = 80; } }
private bool SpellSet() { int count = 0; foreach (ClientCard check in Bot.Hand) { if (check.IsCode(CardId.CardOfDemise)) { count++; } } if (count == 2 && Bot.Hand.Count == 2 && Bot.GetSpellCountWithoutField() <= 2) { return(true); } if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) { return(false); } if (Card.IsCode(CardId.AntiSpellFragrance) && Bot.HasInSpellZone(CardId.AntiSpellFragrance)) { return(false); } if (CardOfDemiseeff_used) { return(true); } if (Card.IsCode(CardId.EvenlyMatched) && (Enemy.GetFieldCount() - Bot.GetFieldCount()) < 0) { return(false); } if (Card.IsCode(CardId.AntiSpellFragrance) && Bot.HasInSpellZone(CardId.AntiSpellFragrance)) { return(false); } if (Card.IsCode(CardId.MacroCosmos) && Bot.HasInSpellZone(CardId.MacroCosmos)) { return(false); } if (Duel.Turn > 1 && Duel.Phase == DuelPhase.Main1 && Bot.HasAttackingMonster()) { return(false); } if (Card.IsCode(CardId.InfiniteImpermanence)) { return(Bot.GetFieldCount() > 0 && Bot.GetSpellCountWithoutField() < 4); } if (Card.IsCode(CardId.Scapegoat)) { return(true); } if (Card.HasType(CardType.Trap)) { return(Bot.GetSpellCountWithoutField() < 4); } if (Bot.HasInSpellZone(CardId.AntiSpellFragrance, true)) { if (Card.IsCode(CardId.UpstartGoblin, CardId.PotOfDesires, CardId.PotOfDuality)) { return(true); } if (Card.IsCode(CardId.CardOfDemise) && Bot.HasInSpellZone(CardId.CardOfDemise)) { return(false); } if (Card.HasType(CardType.Spell)) { return(Bot.GetSpellCountWithoutField() < 4); } } return(false); }
public static async Task UpdateClientStatusOnVoiceStateUpdated(DiscordClient client, VoiceStateUpdateEventArgs e) { await Bot.UpdateBotStatusAsync(client, e.Guild); }
private bool EvenlyMatchedeff() { return(Enemy.GetFieldCount() - Bot.GetFieldCount() > 1); }
public static void Start(Update u, string[] args) { if (u.Message.Chat.Type == ChatType.Private) { if (u.Message.From != null) { using (var db = new WWContext()) { var p = GetDBPlayer(u.Message.From.Id, db); if (p == null) { var usr = u.Message.From; p = new Player { UserName = usr.Username, Name = (usr.FirstName + " " + usr.LastName).Trim(), TelegramId = usr.Id, Language = "English" }; db.Players.Add(p); db.SaveChanges(); p = GetDBPlayer(u.Message.From.Id, db); } #if RELEASE p.HasPM = true; #elif RELEASE2 p.HasPM2 = true; #elif BETA p.HasDebugPM = true; #endif db.SaveChanges(); if (String.IsNullOrEmpty(args[1])) { var msg = $"Hi there! I'm @{Bot.Me.Username}, a clone of @werewolfbot, and I moderate games of Werewolf." + $"\nUse /setlang to set PM language and /config after you added me into a group." + $"\nFor role information, use /rolelist." + $"\nBe sure to stop by <a href=\"https://telegram.me/greywolfsupport\">Werewolf Support</a> for any questions, and subscribe to @greywolfdev for updates from the developer." + $"\nMore infomation can be found <a href=\"https://www.tgwerewolf.com/?referrer=start\">here</a>!"; Bot.Send(msg, u.Message.Chat.Id); } /* * else * { * var uid = args[1]; * * * * * * //check the database for that user * { * var aspuser = db.AspNetUsers.Find(uid); * * //we have the asp user, let's find the player * var user = db.Players.FirstOrDefault(x => x.TelegramId == u.Message.From.Id); * if (user == null) * return; * user.WebUserId = uid; //linked! * db.SaveChanges(); * Send($"Your telegram account is now linked to your web account - {aspuser.Email}", u.Message.From.Id); * } * } */ } } } }
private bool GoToBattlePhase() { return(Bot.HasInHand(CardId.EvenlyMatched) && Duel.Turn >= 2 && Enemy.GetFieldCount() >= 2 && Bot.GetFieldCount() == 0); }
private bool EaterOfMillionssp() { if (Bot.MonsterZone[0] == null) { AI.SelectPlace(Zones.z0); } else { AI.SelectPlace(Zones.z4); } if (Enemy.HasInMonstersZone(CardId.KnightmareGryphon, true)) { return(false); } if (Bot.HasInMonstersZone(CardId.InspectBoarder) && !eater_eff) { return(false); } if (Util.GetProblematicEnemyMonster() == null && Bot.ExtraDeck.Count < 5) { return(false); } if (Bot.GetMonstersInMainZone().Count >= 5) { return(false); } if (Util.IsTurn1OrMain2()) { return(false); } AI.SelectPosition(CardPosition.FaceUpAttack); IList <ClientCard> targets = new List <ClientCard>(); foreach (ClientCard e_c in Bot.ExtraDeck) { targets.Add(e_c); if (targets.Count >= 5) { AI.SelectCard(targets); /*AI.SelectCard(new[] { * CardId.BingirsuTheWorldChaliceWarrior, * CardId.TopologicTrisbaena, * CardId.KnightmareCerberus, * CardId.KnightmarePhoenix, * CardId.KnightmareUnicorn, * CardId.BrandishMaidenKagari, * CardId.HeavymetalfoesElectrumite, * CardId.CrystronNeedlefiber, * CardId.FirewallDragon, * CardId.BirrelswordDragon, * CardId.RaidraptorUltimateFalcon, * });*/ AI.SelectPlace(Zones.z4 | Zones.z0); return(true); } } Logger.DebugWriteLine("*** Eater use up the extra deck."); foreach (ClientCard s_c in Bot.GetSpells()) { targets.Add(s_c); if (targets.Count >= 5) { AI.SelectCard(targets); return(true); } } return(false); }