public void TestRetreat() { using (var consoleOutput = new ConsoleOutput()) { var state = new GameState(32, 32, int.MaxValue, 100, 25, 5, 1); var bot = new MyBot(); state.StartNewTurn(); state.AddAnt(16, 15, 0); state.AddAnt(12, 16, 1); state.AddAnt(12, 15, 1); state.AddAnt(12, 17, 1); var initDist = state.EnemyAnts.Select(x => state.GetDistance(state.MyAnts[0], x)).ToList(); bot.DoTurn(state); ApplyTurn(state, consoleOutput.GetOuput()); consoleOutput.Clear(); var finalDist = state.EnemyAnts.Select(x => state.GetDistance(state.MyAnts[0], x)).ToList(); for (int i = 0; i < initDist.Count; i++) { Assert.Greater(finalDist[i], initDist[i]); } } }
public override void Run() { if (MyBot.RadarTurnRemaining == 0.0) { MyBot.SetTurnRadarRightRadians(2 * Math.PI); } }
private void banButton_Click(object sender, EventArgs e) { string usernameToBan = string.Empty; try { usernameToBan = userList.SelectedItem.ToString().ToUpper(); } catch (NullReferenceException) { _errorMessage = "Error: Did you select someone?"; Console.WriteLine(_errorMessage); errorLabel.Text = _errorMessage; } var channel = this.e.Server.FindChannels(MOD_LOGS_CHANNEL, ChannelType.Text).FirstOrDefault(); var userToBan = this.e.Channel.Users.FirstOrDefault(input => input.Name.ToUpper() == usernameToBan); if (!userToBan.HasRole((this.e.Server.FindRoles("Mod").FirstOrDefault()))) { this.e.Server.Ban(userToBan); MyBot.Log(this.e.User.Name + " tried to ban " + userToBan.Name); channel.SendMessage(this.e.User.Name + " banned " + userToBan.Name); } else { errorLabel.Text = "Error: Can't ban a Mod or Owner"; } }
private async void purgeButton_Click(object sender, EventArgs e) { int amnt = int.TryParse(purgeTextBox.Text, out amnt) ? int.Parse(purgeTextBox.Text) : 5; string logMessage; if (amnt <= 100) { var messagesToDelete = await this.e.Channel.DownloadMessages(amnt); await this.e.Channel.DeleteMessages(messagesToDelete); await this.e.Channel.SendMessage(amnt + " messages deleted."); logMessage = this.e.User.Name + " on " + this.e.Server.Name + " in " + this.e.Channel.Name + " purged " + amnt + " messages."; MyBot.Log(logMessage); _channel = this.e.Server.FindChannels(MOD_LOGS_CHANNEL, ChannelType.Text).FirstOrDefault(); await _channel.SendMessage(logMessage); } else if (amnt > 100) { logMessage = this.e.User.Name + " on " + this.e.Server.Name + " tried to purged " + amnt + " messages but the limit is 100."; MyBot.Log(logMessage); await this.e.Channel.SendMessage(this.e.User.Mention + ",The maximum purge amount is 100."); } else { logMessage = this.e.User.Name + " on " + this.e.Server.Name + " tried to purged " + amnt + " messages but it was an invalid parameter."; MyBot.Log(logMessage); await this.e.Channel.SendMessage("Invalid amount."); } }
public void PerformanceIssue() { Assert.Fail(); GameState state = new GameState(10, 10, 1, 1, 1, 5, 1); state.Set(new Tile[, ] { { _, _, _, _, _, _, _, _, _, _ }, { _, _, a, a, a, a, a, a, _, _ }, { _, _, a, a, w, a, a, a, _, _ }, { _, _, a, a, w, a, a, a, _, _ }, { _, _, a, a, f, a, a, a, _, _ }, { _, _, a, a, a, A, a, a, _, _ }, { _, _, a, a, a, a, a, a, _, _ }, { _, _, _, _, _, _, _, _, _, _ }, { _, _, _, _, _, _, _, _, _, _ }, { _, _, _, _, _, _, _, _, _, _ }, }); Bot dut = new MyBot(); dut.Initialize(state); dut.DoTurn(state); }
//public ushort treshold = 20; public static void Main(string[] args) { //Log.Setup(@"C:\Users\phili\Desktop\Coveo-Blitz-2018\CSharp\log.txt"); Console.SetIn(Console.In); Console.SetOut(Console.Out); ushort myID; Map map = Networking.getInit(out myID); MyBot bot = new MyBot(myID); bot.map = map; /* ------ * Do more prep work, see rules for time limit * ------ */ bot.Analyze(); Networking.SendInit(MyBotName); // Acknoweldge the init and begin the game while (true) { Networking.getFrame(ref map); // Update the map to reflect the moves before this turn bot.map = map; List <Move> moves; bot.ComputeMove(out moves); Networking.SendMoves(moves); // Send moves } }
private void RadarAdjust(ScannedRobotEvent e) { //http://robowiki.net/wiki/One_on_One_Radar double radarAngleToTurn = MyBot.HeadingRadians - MyBot.RadarHeadingRadians + e.BearingRadians; MyBot.SetTurnRadarRightRadians(Utils.NormalRelativeAngle(radarAngleToTurn)); }
//byte[] msg1; //string toSend; // Use this for initialization public void Start() { MyBot bot = new MyBot(data); ThreadStart tcpThreadS = new ThreadStart(bot.Update1); Thread tcpThread = new Thread(tcpThreadS); tcpThread.Start(); }
public override void Init() { MyBot.SetColors(Utilities.GetTeamColor(), Color.Red, Color.DarkCyan); MyBot.IsAdjustGunForRobotTurn = true; MyBot.IsAdjustRadarForGunTurn = true; MyBot.TurnRadarRightRadians(2 * Math.PI); }
public void TestNoCollision1() { GameState state = new GameState(10, 10, 1, 1, 1, 5, 1); state.Set(new Tile[, ] { { _, _, _, _, _, _, _, _, _, _ }, { _, _, a, a, a, a, a, a, _, _ }, { _, _, a, a, w, a, a, a, _, _ }, { _, _, a, a, w, a, a, a, _, _ }, { _, _, a, a, f, a, a, a, _, _ }, { _, _, a, a, a, a, a, a, _, _ }, { _, _, a, a, a, a, a, a, _, _ }, { _, _, _, _, _, _, _, _, _, _ }, { _, _, _, _, _, _, _, _, _, _ }, { _, _, _, _, _, _, _, _, _, _ }, }); MyBot dut = new MyBot(); dut.Initialize(state); for (int i = 0; i < 10; i++) { dut.Cook(state); } dut.DoTurn(state); bool takeFood = false; foreach (Ant a in state.MyAnts) { Assert.IsTrue(a.hasMoved); Vector2i dst = a.position + Vector2i.AllDirections[(int)a.direction]; if (state.map[dst.x, dst.y].isFood) { takeFood = true; } } Assert.IsTrue(takeFood); for (int i = 0; i < state.MyAnts.Count; i++) { Ant a = state.MyAnts[i]; Vector2i aPos = a.position + Vector2i.AllDirections[(int)a.direction]; for (int j = 0; j < i; j++) { Ant b = state.MyAnts[j]; Vector2i bPos = b.position + Vector2i.AllDirections[(int)b.direction]; Assert.AreNotEqual(aPos, bPos); } } }
public AudioManager(MyBot myBot) { this.myBot = myBot; _client = myBot.discord; this.webClient = new WebClient(); myBot.discord.UsingAudio(x => { x.Mode = AudioMode.Outgoing; }); }
public override void OnScannedRobot(ScannedRobotEvent e) { if (MyBot.IsTeammate(e.Name)) { return; } currentTarget = e.Name; Move(e); RadarAdjust(e); Fire(e); }
public override void OnScannedRobot(ScannedRobotEvent e) { var closestEnemy = MyBot.GetClosestTarget(); if (!MyBot.IsTeammate(e.Name) && closestEnemy != null && closestEnemy.Name == e.Name) { double absBearing = e.BearingRadians + MyBot.HeadingRadians; Move(e, absBearing); RadarAdjust(e); Fire(e, absBearing); } }
private void Fire(ScannedRobotEvent e) { var bullerPower = MyBot.Energy > 10 ? 400 / e.Distance : 0.1; //http://robowiki.net/wiki/Linear_Targeting double absoluteBearing = MyBot.HeadingRadians + e.BearingRadians; MyBot.SetTurnGunRightRadians(Utils.NormalRelativeAngle(absoluteBearing - MyBot.GunHeadingRadians + (e.Velocity * Math.Sin(e.HeadingRadians - absoluteBearing) / Rules.GetBulletSpeed(bullerPower)))); MyBot.SetFire(bullerPower); }
static void Main(string[] args) { MyBot.Start(); Console.WriteLine(MyBot.HelpCommand()); foreach (var item in MyBot.helpFunctions) { Console.WriteLine(item.Name); } while (true) { Console.WriteLine(MyBot.ExecuteCommand(Console.ReadLine())); } }
private async Task Add(Discord.Commands.CommandEventArgs e) { await e.Message.Delete(); if (playing && e.User.VoiceChannel != voiceChannel) { await e.Channel.SendMessage("Join vc NOW :angry:"); return; } var param = e.GetArg("param"); if (param.Length <= 0) { await e.Channel.SendMessage("I cannot add nothing to the queue"); return; } try { var youTube = Client.For(YouTube.Default); // starting point for YouTube actions var video = youTube.GetVideo(e.GetArg("param")); // gets a Video object with info about the video var vidfile = Path.Combine(Environment.CurrentDirectory, "Music", video.FullName); Console.WriteLine(vidfile); var mp3file = Path.Combine(Environment.CurrentDirectory, "Music", video.Title + ".mp3"); if (!File.Exists(mp3file)) { byte[] bytes = await video.GetBytesAsync(); File.WriteAllBytes(vidfile, bytes); songcounter++; videoconverter.ConvertMedia(vidfile, mp3file, "mp3"); File.Delete(vidfile); } queue.Add(new Song(mp3file, video.Title, e.User.Name)); await e.Channel.SendMessage("**" + video.Title + "** has been added to the queue by *" + e.User.Name + "*!"); MyBot.Log(DateTime.Now.ToUniversalTime().ToShortTimeString() + " - " + e.Channel.Name + ") Song added: " + video.FullName, e.Channel.Name + "_log"); } catch (Exception ex) { await e.Channel.SendMessage("I could not download that..."); Console.WriteLine(ex.StackTrace); return; } await Play(e); }
private void Fire(ScannedRobotEvent e, double absoluteBearing) { absoluteBearing = MyBot.HeadingRadians + e.BearingRadians; //Finding the heading and heading change. double enemyHeading = e.HeadingRadians; double enemyHeadingChange = enemyHeading - _oldEnemyHeading; _oldEnemyHeading = enemyHeading; // Circular Targeting http://robowiki.net/wiki/Circular_Targeting /*This method of targeting is know as circular targeting; you assume your enemy will * keep moving with the same speed and turn rate that he is using at fire time.The * base code comes from the wiki. */ double deltaTime = 0; double predictedX = MyBot.X + e.Distance * Math.Sin(absoluteBearing); double predictedY = MyBot.Y + e.Distance * Math.Cos(absoluteBearing); PointD point = new PointD(MyBot.X, MyBot.Y); while ((++deltaTime) * _bulletSpeed < point.Distance(predictedX, predictedY)) { //Add the movement we think our enemy will make to our enemy's current X and Y predictedX += Math.Sin(enemyHeading) * e.Velocity; predictedY += Math.Cos(enemyHeading) * e.Velocity; //Find our enemy's heading changes. enemyHeading += enemyHeadingChange; //If our predicted coordinates are outside the walls, put them 18 distance units away from the walls as we know //that that is the closest they can get to the wall (Bots are non-rotating 36*36 squares). predictedX = Math.Max(Math.Min(predictedX, MyBot.BattleFieldWidth - 18), 18); predictedY = Math.Max(Math.Min(predictedY, MyBot.BattleFieldHeight - 18), 18); } //Find the bearing of our predicted coordinates from us. double aim = Utils.NormalAbsoluteAngle(Math.Atan2(predictedX - MyBot.X, predictedY - MyBot.Y)); var bullerPower = 400 / e.Distance; //Aim and fire. MyBot.SetTurnGunRightRadians(Utils.NormalRelativeAngle(aim - MyBot.GunHeadingRadians)); MyBot.SetFire(bullerPower); MyBot.SetTurnRadarRightRadians(Utils.NormalRelativeAngle(absoluteBearing - MyBot.RadarHeadingRadians) * 2); }
private void Move(ScannedRobotEvent e, double absoluteBearing) { // 90o to enemy double turn = absoluteBearing + Math.PI / 2; //This formula is used because the 1/e.Distance means that as we get closer to the enemy, we will turn to them more sharply. //We want to do this because it reduces our chances of being defeated before we reach the enemy robot. turn -= Math.Max(0.5, (1 / e.Distance) * 100) * _dir; MyBot.SetTurnRightRadians(Utils.NormalRelativeAngle(turn - MyBot.HeadingRadians)); //This line makes us slow down when we need to turn sharply. MyBot.MaxVelocity = (400 / MyBot.TurnRemaining); MyBot.SetAhead(100 * _dir); }
public override void OnScannedRobot(ScannedRobotEvent e) { var closestEnemy = MyBot.GetClosestTarget(); if (closestEnemy != null && closestEnemy.Name == e.Name) { var bullerPower = 300 / e.Distance; //simplest linear targeting algorithm - http://robowiki.net/wiki/Linear_Targeting double absoluteBearing = MyBot.HeadingRadians + e.BearingRadians; MyBot.SetTurnGunRightRadians(Utils.NormalRelativeAngle(absoluteBearing - MyBot.GunHeadingRadians + (e.Velocity * Math.Sin(e.HeadingRadians - absoluteBearing) / Rules.GetBulletSpeed(bullerPower)))); MyBot.SetFire(bullerPower); } }
public void TestRegroup() { using (var consoleOutput = new ConsoleOutput()) { var state = new GameState(32, 32, int.MaxValue, 100, 25, 5, 1); var bot = new MyBot(); state.StartNewTurn(); state.AddAnt(18, 15, 0); state.AddAnt(16, 16, 0); state.AddAnt(18, 17, 0); state.AddAnt(12, 15, 1); state.AddAnt(12, 17, 1); {//Extra test for platoon + BuildFrontLine List <Ant> Platoon = new List <Ant>(); Battle.BuildPlatoon(state, Platoon, new Ant(16, 16, 0)); Assert.AreEqual(3, Platoon.Count); List <Ant> EPlatoon = new List <Ant>(); Battle.BuildPlatoon(state, EPlatoon, new Ant(12, 15, 1)); Assert.AreEqual(2, EPlatoon.Count); var AllyDist = Battle.BuildFrontline(state, Platoon, EPlatoon, out int qty, out int distance); Assert.AreEqual(1, qty); Assert.AreEqual(6, AllyDist[Platoon.IndexOf(new Ant(18, 15, 0))]); Assert.AreEqual(5, AllyDist[Platoon.IndexOf(new Ant(16, 16, 0))]); Assert.AreEqual(5, distance); var EnemyDist = Battle.BuildFrontline(state, EPlatoon, Platoon, out int Eqty, out int Edistance); Assert.AreEqual(2, Eqty); } bot.DoTurn(state); consoleOutput.originalOutput.Write(consoleOutput.GetOuput()); ApplyTurn(state, consoleOutput.GetOuput()); consoleOutput.Clear(); Assert.Contains(new Ant(17, 15, 0), state.MyAnts); Assert.Contains(new Ant(16, 16, 0), state.MyAnts); Assert.Contains(new Ant(17, 17, 0), state.MyAnts); } }
static void Main(string[] args) { var options = new CommandLineOptions(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { try { MyBot bot = new MyBot(); BotClient client = new BotClient(options, bot); while (true) { try { client.Run(); } catch (TimeoutWebException) { //Eat the timeout exception CoreHelpers.OutputLine("Timed out while searching for game."); } if (options.EndlessMode) { CoreHelpers.OutputLine("Sleeping for 15 seconds before starting again..."); Thread.Sleep(15 * 1000); } else { //End the program return; } } } catch (Exception ex) { CoreHelpers.OutputLine(ex.ToString()); throw; } } }
public async Task SendAudio(Channel channel, Song song) { try { MyBot.Log(DateTime.Now.ToUniversalTime().ToShortTimeString() + " - " + channel.Name + ") Song playing: " + song.path, channel.Name + "_log"); var channelCount = discordClient.GetService <AudioService>().Config.Channels; // Get the number of AudioChannels our AudioService has been configured to use. var OutFormat = new WaveFormat(48000, 16, 2); // Create a new Output Format, using the spec that Discord will accept, and with the number of channels that our client supports. using (var MP3Reader = new Mp3FileReader(song.path)) // Create a new Disposable MP3FileReader, to read audio from the filePath parameter using (var resampler = new MediaFoundationResampler(MP3Reader, OutFormat)) // Create a Disposable Resampler, which will convert the read MP3 data to PCM, using our Output Format { resampler.ResamplerQuality = 60; // Set the quality of the resampler to 60, the highest quality int blockSize = OutFormat.AverageBytesPerSecond / 50; // Establish the size of our AudioBuffer byte[] buffer = new byte[blockSize]; int byteCount; await channel.SendMessage("Playing *" + song.user + "'s* song **" + song.title + "** now!"); MyBot.Log("Playing *" + song.user + "'s* song **" + song.title + "** now!", "music_log"); while (playing && !skipped && (byteCount = resampler.Read(buffer, 0, blockSize)) > 0) // Read audio into our buffer, and keep a loop open while data is present { if (byteCount < blockSize) { // Incomplete Frame for (int i = byteCount; i < blockSize; i++) { buffer[i] = 0; } } discordAudio.Send(buffer, 0, blockSize); // Send the buffer to Discord } if (skipped) { skipped = false; } } } catch (Exception e) { await channel.SendMessage("Something went teribly wrong.. ABORT ABORT \\o/"); Console.WriteLine(e.StackTrace); } }
public void TestFindClosest() { const int mapSize = 32; var state = new GameState(mapSize, mapSize, int.MaxValue, 100, 25, 5, 1); var start1 = new Location(16, 16); var target1 = new Location(16, 18); var testCollection1 = new List <Location>(); testCollection1.Add(target1); var testCollection2 = new[] { new Location(1, 1), new Location(mapSize, mapSize), new Location(mapSize, 1), new Location(1, mapSize), target1, }.ToList(); var tests = new[] { new { start = start1, target = target1, dist = 20, resultIsNull = false, set = testCollection1 }, new { start = start1, target = target1, dist = 1, resultIsNull = true, set = testCollection1 }, new { start = start1, target = target1, dist = 20, resultIsNull = false, set = testCollection2 }, }; foreach (var test in tests) { var result = MyBot.FindClosest(state, test.start, x => test.set.Contains(x) ? test.set[test.set.IndexOf(x)]: null, test.dist); if (test.resultIsNull) { Assert.IsNull(result); } else { Assert.NotNull(result); Assert.AreEqual(test.target, result.Target); } } }
public void GetFood() { using (var consoleOutput = new ConsoleOutput()) { var state = new GameState(32, 32, int.MaxValue, 100, 25, 5, 1); var bot = new MyBot(); state.StartNewTurn(); state.AddAnt(16, 16, 0); state.AddFood(17, 16); Func <Location, Ant> test = x => state.MyAnts.Select(ant => (x.Row == ant.Row && x.Col == ant.Col) ? ant : null).Where(y => y != null).FirstOrDefault(); Assert.NotNull(test(state.MyAnts[0])); Assert.NotNull(test(new Ant(16, 16, 0))); Assert.NotNull(test(new Location(16, 16))); var result = MyBot.FindClosest(state, state.FoodTiles[0], test); Assert.NotNull(result); bot.DoTurn(state); Assert.AreEqual("o 16 16 s\r\n", consoleOutput.GetOuput()); consoleOutput.Clear(); state.StartNewTurn(); state.AddAnt(16, 16, 0); state.AddFood(15, 16); bot.DoTurn(state); Assert.AreEqual("o 16 16 n\r\n", consoleOutput.GetOuput()); } }
private string ExecuteHelpCommand(string command) { string result = ""; if (!(command.Contains("(") && command.Contains(")"))) { Console.WriteLine(command); result = Console.ReadLine(); } else { string[] str = command.Split(new char[] { '(' }); string commandName = str[0]; List <string> parameters = new List <string>(); str[1] = str[1].Replace(" ", ""); if (str[1].Length < 3) { result = MyBot.ExecuteHelpFunction(commandName, parameters.ToArray()); } else { string[] parametersQuestion = str[1].Split(new char[] { ',' }); parametersQuestion[parametersQuestion.Length - 1] = parametersQuestion[parametersQuestion.Length - 1].Trim(new char[] { ')' }); foreach (var item in parametersQuestion) { Console.WriteLine(item); parameters.Add(Console.ReadLine()); } result = MyBot.ExecuteHelpFunction(commandName, parameters.ToArray()); } } return(result); }
private void Move(ScannedRobotEvent e) { //http://mark.random-article.com/weber/java/robocode/lesson5.html - closing in movement if (MyBot.DistanceRemaining == 0.0) { moveDirection *= -1; //revert body direction turnDirection *= -1; //revert turn direction MyBot.SetAhead(randomDistance * moveDirection); } var turnAngle = e.BearingRadians + Math.PI / 2;// 90o to enemy double randomClosingInAngle = Math.PI / turnFactor; turnFactor++; if (turnFactor >= 7) { turnFactor = 5; } randomClosingInAngle = randomClosingInAngle * moveDirection; // turn close to enemy randomClosingInAngle = randomClosingInAngle * (e.Distance > 50 ? 1 : -1); // move out when too close MyBot.SetTurnRightRadians(turnAngle - randomClosingInAngle); }
public bool ShouldMineInsteadOfDropoff(Ship ship, List <Ship> bucket, Dictionary <Position, List <Ship> > buckets) { // verified... if (ship.CellHalite < 10) { return(false); } if (ship.CellHalite * .15 + ship.halite > 1000) { return(false); } if (ship.CurrentMapCell.IsThreatened) { return(false); } if (!Safety.IsSafeMove(ship, Direction.STILL)) { return(false); } if (!MyBot.ShouldSpawnShip(0) && MyBot.ShouldSpawnShip(ship.halite) /* and not 2 ships same dist from drop */) { return(false); } if (bucket.Count > 1 && bucket[1].DistanceToMyDropoff - 1 <= ship.DistanceToMyDropoff) { return(false); } foreach (var b in buckets.Where(x => x.Value != bucket)) { if (b.Value.First().DistanceToMyDropoff <= ship.DistanceToMyDropoff) { return(false); } } return(true); }
private void ForceMoving() { PointD nextPosition = MyBot.Position; _recentForces.Clear(); _recentForces = GetRecentForced(); // Adjust position by forces for (int i = 0; i < _recentForces.Count; i++) { nextPosition = _recentForces[i].Force(nextPosition); } //Prevent wall var wallMargin = 36 / 2 + 1; if (nextPosition.X <= wallMargin) { nextPosition.X = wallMargin; } if (nextPosition.X >= 1000 - wallMargin) { nextPosition.X = 1000 - wallMargin; } if (nextPosition.Y <= wallMargin) { nextPosition.Y = wallMargin; } if (nextPosition.Y >= 1000 - wallMargin) { nextPosition.Y = 1000 - wallMargin; } //Move in the direction of our resolved force. MyBot.GotoPoint(nextPosition); }
private void Bossfight() { try { rpgchannel = client.FindServers(serverName).First().FindChannels(channelName).FirstOrDefault(); } catch { Console.WriteLine("Finding rpg channel failed"); return; } var blevel = 1; var boss = new RPGMonster(blevel * 100, blevel * 10, blevel * 15, blevel * 5); if (bossFightPlayers.Count() <= 0) { MyBot.Log(DateTime.Now.ToUniversalTime().ToShortTimeString() + ") Bossfight cancelled, noone showed up", "rpggame"); return; } // Resolve boss battle rpgchannel.SendMessage("BOSSFIGHT!!\n*Wait wut... Not even implemented? smh*"); MyBot.Log(DateTime.Now.ToUniversalTime().ToShortTimeString() + ") Bossfight!! " + bossFightPlayers.Count() + " warriors ready", filename); bossFightPlayers = new List <RPGPlayer>(); }
public override void Run() { ForceMoving(); MyBot.SetTurnRadarLeftRadians(2 * Math.PI); MyBot.Execute(); }