Classic Robocode Example Code

zhaozj2021-02-16  74

Classic Robocode Example Code

Author: Alisdair // * -------------------------------------------- -------------------------------------------------- ------------------ * ///// * Translation: Tianyi. Li (Skyala.Li) // * Copyright: alisdair /// *权 权: Robocode China Union WWW . Robochina.org // * Please contact Skyala.li in relation to Skyala.li: roboccode@tang.com // * Reprint, please keep this file head @ 2002.10 31 All Rights reserved // * ------- -------------------------------------------------- -------------------------------------------------- ----- * // Classic Robocode novice entry example, including mobile, radar, and barrel. . . After watching it and apply it, keep you Robocode thousands of miles away. Note: The translation style has changed, some did not translate, some have added the experience of Skyala.li. We only pay attention to principles, not heavy form. Everyone can take a look at the part that has no translation, just learn foreign languages! Finally, About Duelist is introduced to a paragraph of the world's first robot development process. This thing is on the day, look good to the collection! Source code can also be downloaded (Skyala.li)

package wind; import robocode *; import java.awt.Color;. / ** * SnippetBot - a robot by Alisdair Owens * This bot includes all sorts of useful snippets It is not * designed to be a good fighter (although it does. well 1v1), * just to show how certain things are done * Bits of code lifted from Nicator and Chrisbot * Conventions in this bot include: Use of radians throughout * Storing absolute positions of enemy bots rather than relative ones * Very little code in events * These are all good programming practices for robocode * There may also be methods that arent used; these might just be useful for you * / public class SnippetBot extends AdvancedRobot {/ ** * run:. SnippetBot's default behavior * / Enemy target; / / OUR CURRENT Enemy Represents to the opponent, including all useful parameters of the opponent Final Double Pi = Math.pi; // Just a constant int direction = 1; // Direction we are heading ... 1 = forward, -1 = backwards / / Our direction of the tank head Double FirePowe R; // the power of the shot we will be using - set by do firepower () Set our fire power public void run () {target = new enemy (); // instantiated enemy () Target.distance = 100000 ; // initialise the distance suwe can select a target setcolors (color.red, color.blue, color.green); // sets the colors of the robot // the next two lines mean That the Turns of the robot, Gun and Radar are independant // Let Gun, Radar is independent of tank car setAdjustGunForrobotturn (TRUE); setJustRadarforgunturn (TRUE); Turnradarrightradians (2 * pi);

// Turns The Radar Right Around To Get A View of The Field Calculates Rotation One Week WHILE (TRUE) {Domovement (); // Move The BOT Mobile Robot DofirePower (); // Select The Fire Power To Use Select Fire Doscanner (); // oscillate the scanner over the BOT scan DOGUN (); //move the gun to predict where the Enemy Will BE predicts the enemy, adjusting the artillery Out.println (Target.distance); Fire (FirePower); // After all the actions are completed, fire execute (); // Execute All Commands Top Used above the non-blocking call // control in the AdvanceDrobot class is in us, all here use of blocking methods to return to control to robots}} / * * this Simple .. function calculates the fire power to use (from 0.1 to 3) * based on the distance from the target We will investigate the data structure * holding the target data later * / void doFirePower () {firePower = 400 / target.distance; // selects a bullet power based on o UR distance approay from the target // Select firepower according to the enemy, because it is advanced, back to 300, so firepower will not be too large} / * * this is the movememnt function. it will cause us * to circle Strafe THEMY ( ie move back and forward, * circling the enemy. if you do not know what strafing means * play more quake. * The direction variable is global to the class. Passing a * negative number to setAhead causes the bot to go backwards * to Target main center Round swing * / void Domovement () {if (getTime ()% 20 == 0) //? The multiple time of 20 inversion direction {// Every TWENTY 'TICKS' DIRECTION * = -1;

// REVERSE DIRECTION setahead (Direction * 300); //move in what timection}); // every Turn Move To Circle Strafe The Enemy // Each time period is enemy Center Round Movement} / * * This Scanner Method Allows Us To make Our scanner TRACK OUR TARGET. * IT WILL TRACK to WHEREURE TARGET IS AT The Moment, and some further * in case the target HAS MOVED. THIS WAY WE ALWAYS GET Up to the minute * information on our target Radar lock target * / void doscanner () {double radaroffset; // radar offset IF (gettime () - target.ctime> 4) // ??? Why is coming 4 The round did not sweep to mean the goal, and then sweep it again {// if we haven't seen anybody for a bit .... Radaroffset = 360; // rotate the Radar to find a target} else {//// Next is the amount we need to rotary the radar by to scan where the target is now // The radar rotation is determined by scanning the radar rotation, "see the basic principle direction analysis and target lock www.robochina.or g ". Radar radar curvature - enemy angle Get the difference between the difference is Radaroffset = getradarheadingradians () - AbsBearing (Getx (), getY (), target.x, target.y); // this adds or subtracts small Amounts from the Adds or Subtracts Small Amounts from Bearing for the radar to produce the wobbling // and make Sure We don't lose the target // Add or minus a point in the resulting angle, make the radar in a small range without losing the target IF (Radaroffset <0 Radaroffset - = pi / 8; //(0.375) Else Radaroffset = pi / 8;} // Turn The Radar setTurnRadarleftradians (NormaliseBearing (Radaroffset);

// Left adjustment rotation angle to pi} / * * this Simple method Moves the gun to the bearing That We prefer the gun to be by the time ou ly, get there, * the 'absbearing' method can be found in the helper functions section * the nextX and nextY method can be found in the 'Enemy' class description * / void doGun () {// works out how long it would take a bullet to travel to where the enemy is * now * // This is the best estimation we have // ​​Calculate the length of time for bullets to reach the target Speed ​​= 20 - 3 * power; there is a calculation formula, the distance except speed = time long time = getTime () (int) (Target.distance / (20 - (3 * firepower))))))); // offsets the gun by the angle to the next shot based on linear targeting provided by the first minear target // The angle of the next time the bullet is launched in a straight line. (This makes the chance of bullet emption to decrease.

But there is a problem with the mutual movement of the robot that does not move and makes a circular motion) //target.guessx (), target.guesy () Double gunoffset = getGunHeadingradians (), Target.guesx (Time), Target.Guesy (Time)); setTurngunleFTradians (NormaliseBearing (Gunoffset)); // Adjust relative angle to 2pi} / * * this set of helper methods. You May Find Several of these Very Useful * THEY INCLUDE The Ability To Find The Angle To a point. * / // if a bearing is not with the --pi to pi ing, alters it to pi} {ix {ix {ix {ix {ix (ang> pi) ang {ix - = 2 * pi; if (Ang <-pi) ang = 2 * pi; returnon;} // if a heading is not with the 0 to 2Pi Range, Alters It to provide the Shortest Angle Double NormaliseHeading (Double Ang ) {IF (Ang> 2 * pi) Ang - = 2 * pi; if (Ang <0) Ang = 2 * pi; return ang;} // Returns the distance between Two x, y coordinates '**' / / Squeezing between two sides with opponents PUBLIC DOUBLE GetRange (Double X1, Double Y1, Double X2, Double Y2) {Double XO = X2-x1; Double YO = Y2-Y1; Double H = Math.SQRT (XO * XO YO * YO); Return H;} / / GETS THE ABSOLUTE Bearing Between To X, Y Coordinates // According to the absolute angle according to the coordinates of X, Y, see "Coordinate lock" uses a right angle coordinate system to reverse the angle.

? ? ? Public Double Absbearing (Double X1, Double Y1, Double X2, Double Y2) {Double XO = X2-x1; Double YO = Y2-Y1; Double H = GetRange (x1, y1, x2, y2); if (xo> 0 && yo> 0) {// Anti-sicrosion definition, except for the arc of the side. Refer to the absolute direction and coordinate system in Robocode, Y, Y is 0-90, X Positive Y The lower corner is 90-180, x, y negative left corner 180-270, x negative, Y positive upper right corner 270-360 // This is to understand that the absolute angle in Robocode is 0, and the lower 180, if the center is Distinguishing quadrant gets the following result Return Math.asin (XO / H);} if (xo> 0 && yo <0) {return math.pi - math.asin (XO / h); // x is positive, Y is a negative second quadrant angle} if (XO <0 ​​&& yo <0) {return math.pi math.asin (-xo / h); // Third quadrant 180 angle} IF (XO <0 ​​&& YO> 0) {RETURN 2.0 * Math.pi - math.asin (-xo / h); // 4 quadrant 360-angle} Return 0;} / ** * OnscannedRobot: What to do when You see Another Robot * Scan Event, also the process of initializing target data * / public void onscannedRobot (ScannedRobotevent E) {//iff we have found acloser robot .... IF ((E.GetDistance ()

// Works out the x coordinate of where the target is target.y = getY () math.cos (absbearing_rad) * E.GETDISTANCE (); // Works out the y coordinate of where the target is target.bearing = e Target.Bearing = E .getBearingradians (); target.head = E.getHeadingradians (); target.ctime = gettime (); // Game Time At Which this scan .speed scanned to robots Target.Speed ​​= E.GETVELOCICITY (); / / Get the enemy speed target.distance = E.GetDistance ();}} public void onrobotdeath (effect e) {if (E.GETName () == target.name) target.distance = 10000; // this will effectively make it it search for a new target}} / ** This class holds scan data so that we can remember where enemies were * and what they were doing when we last scanned then. * You could make a hashtable (with the name of the enemy bot as Key) * OR a Vector of these So That You Can Remember Where All of Your Enemies Are * in relation to you. * this class als o holds the guessX and guessY methods. These return where our targeting * system thinks they will be if they travel in a straight line at the same speed * as they are travelling now. You just need to pass the time at which you want to know * Where the will be. * Save all useful data for the target we scanned, or use the HashTable, Vector method to process all the Guessx, the guessy method for the middle of the target data (for group war) * is to do linear Speed ​​Sports Robot A Policy * / Class Enemy {/ * * OK, We Should Really Be Using Accessors and Mutators Here, * (IE getName () and setname ()) BUT Life's Too Short. * / String Name; Public Double Bearing; Public Double Head; Public Long Ctime; // Game Time That The Scan Was Produced Public Double Speed; Public Double X, Y;

Public Double Distance; Public Double Guessx (long when) {// Time difference between the bullet arrives at * Maximum speed = distance, then use the opponent's coordinates to get the moving coordinates to get the enemy moved after the moving coordinate long Diff = When - CTIME; Return X Math.sin (HEAD) * SPEED * DIFF; // Objective Moved Coordinate} Public Double Guesy (Long When) {Long DIFF = WHEN - CTIME; RETURN Y MATH.COS (HEAD) * SPEED * DIFF }}

/ *** About Duelist I started Duelist as a general purpose bot, based off of SnippetBot by Alisdair Owens. I quickly realized that melee and duel matches were two completely different ball games and for a time my code was riddled with if (duel) statements. Eventually I decided that I would focus on duels since they present a much simpler and more elegant problem than melee, to me at least, and Duelist was born. Duelist uses many common concepts found in the top bots. Among them, it fires virtual bullets, the idea made famous by SandboxLump (written by Paul Evans). Duelist also uses anti-gravity for movement, though it has been thoroughly overhauled to eliminate the problems with anti-gravity, such as getting stuck in a local minimum. I also keep statistics on how well my various targetting methods are doing in a data structure that persists from round to round, so that I can learn which methods work the best without having to guess randomly at the start of each round. Some things I thin k I'm the only bot out there doing: Conduct my initial radar sweep by turning the body, gun, and radar before setting them to move independantly This saves about 3 turns in the beginning Firing virtual bullets ONLY when I fire a real.. one. Although this slows down my learning, there's no better way to learn the movement of bots that attempt bullet dodging. Since they move when I fire, I learn only their dodging movement. Changing bullet power based on how hard the enemy is to hit As Well as The Current Range. it's silly to fire a .5 Power Bullet At SittingDuck Just Because HE'S 900 Units Away from You. I'm Sure Some Else Is Doing this But I don't know of any personally sol I '

转载请注明原文地址:https://www.9cbs.com/read-18377.html

New Post(0)