Learning Java programming through advanced robot combat simulation engine more interesting than ever
Robocode is a very easy-to-use robot combat emulator that can be run on all platforms that support Java 2. You created a robot and put it on the battlefield and let it fight against the robot opponents created with other developers. There are some pre-dated robots in Robocode to get started, but once you no longer need them, you can join the robots you created in your own alliance that is formating around the world to go to the world's strongest hand.
Each Robocode participant must use Java language elements to create his or her robot, so that you can participate in this recreational event from beginners to high-level hackers. The primary Java developers can learn some basic knowledge: call API code, read Javadoc, inherit, internal class, event processing, etc. Senior developers can improve their programming skills in building a "best variety" software robot global competition. In this article, we will introduce Robocode and guide you from building your first Robocode robot to conquer the world. We will also look at the charming "background" mechanism, which is it to make Robocode works.
Download and install RobocodoBocode is the wisdom of Mathew Nelson, and he is a software engineer of IBM Internet Department Advanced Technology. Please first access the IBM AlphaWorks Robocode page. On this page, you can find the latest executable of the Robocode system. This packet is a self-contained installation file. After downloading the packet, you can use the following command line to install this package on your system (of course, we assume that Java VM has been predicted on your machine. (JDK 1.3.x):
Java-Jar Robocode-setup.jar
During the installation process, Robocode will ask you to compile the robot using this external Java VM. You can also choose the JIKES compiler that is provided as part of the Robocode distribution package.
After the installation is complete, you can start the Robocode system via the Icons (Robocode.bat) or icons on the desktop. At this point, the battlefield will appear. Here you can call Robot Editor and Compiler through the menu.
Robocode System Components When you activate Robocode, you will see two-related GUI windows, which forms Robocode IDE:
Battlefield Robot Editor
Figure 1 shows the battlefield and Robot Editor in the working state.
Figure 1. RobOcode IDE
The battlefield is a battle between the robots until the venue of the victory. The main simulation engine is placed thereto, and allows you to create battle, save battles, and open new or existing battles. Through the controls in the interface area, you can suspend or continue fighting, terminate the battle, eliminate any robot individuals or get statistical data for any robot. In addition, you can activate Robot Editor on this screen.
Robot Editor is a custom text editor that can be used to edit the Java source file generated by generating robots. The Java compiler (for compiling robot code) and custom Robot packer are integrated in its menu. All robots created by Robot Editor and successfully compiled are in the battlefield on a deployment.
Each robot in Robocode is composed of one or more Java classes. These classes can be compressed into a JAR package. To this end, the latest version of Robocode provides "Robot packager" that can be activated in the battlefield GUI window. Detailed analysis of the Robocode robot is written in this article, the Robocode robot is a graphical tank. Figure 2 is a diagram of a typical Robocode robot.
Figure 2. Detailed analysis of Robocode robots
Please note that the robot has a rotatable gun, and the radar on the machine can also be rotated. Vehicle, guns and radar can rotate separately, that is, at any time, robot tanks, guns, and radar can be turned to different directions. By default, these directions are consistent, all point to the direction of the tank movement.
Robot Commands Robocode robots are included in the Robocode API JavaDoc. You will find that these commands are public methods for the Robocode.Robot class. In this part, we will classify each available command.
Mobile robots, guns and radar let us start from the basic order of mobile robots and their equipment:
Turnright (double deterree) and turns (double deterree) turn the robot to a specified angle. Ahead (double distance) and back (double distance) make the robot to move the specified pixel point distance; the two methods are completed when the robot comes from the wall or another robot. Turngunright (Double Degree) and Turngunleft (Double Degree) can be rotated in the direction of the tank. Turnradarright (Double Degree) and TurnRadarleft (Double Degree) rotate the radar above the gun, the direction of rotation is also independent of the direction of the gun (and the direction of the tank).
These commands are also given to the program after executing. In addition, when turning the tank, the direction of the gun (and radar) will be moved by calling the following methods.
SetadjustGunForrobotturn (Boolean Flag): If Flag is set to True, then the tank rotates, the gun keeps the original direction. SetadjustRadarForrobotturn (Boolean Flag): If Flag is set to true, the radar will maintain the original direction when the tank is turned to TRUE. SetadjustRadarforgunturn (Boolean Flag): If Flag is set to true, the radar will maintain the original direction when the gun is turned. Moreover, the action it performs is like called SetAdjustRadarForrobotturn (TRUE).
Getting information about robots There are many ways to get information about robots. The following is simple to list commonly used methods calls:
Getx () and getY () can capture the current coordinates of the robot. GetHeading (), getGunHeading () and getRadarheading () can draw the current direction of tanks, guns or radars, which is expressed in an angle. GetBattlefieldWidth () and getBattlefieldHeight () can get the current round battlefield size.
Shooting Order Once you have mastered the mobile robots and related weapons and equipment methods, you should consider the task of shooting and controlling damage. Each robot has a default "energy level" at the beginning. When its energy level is reduced to zero, we think that the robot has been eliminated. When shooting, the robot can use up to three energy units. The more energy supplied to the shell, the greater the damage caused by the target robot. Fire (Double Power) and Firebullt (Double Power) are used to transmit the designated energy (firepower). The called FireBullet () version returns a reference to the Robocode.Bullet object, which can be used for advanced robots. Events whenever the robot is moving or rotated, the radar is always in an active state. If the radar detects that there is a robot, an event is triggered. As a robot creator, you have the right to select a variety of events that may occur in the battle. The basic ROBOT class includes all of these events default procedures. However, you can overwrite any of the "nothing" default handler, then implement your own custom behavior. Here are some of the more common events:
ScannedRobotevent. The method is called by overlying the onscannedrobot () method; when the radar detects the robot, the method is called. Hitbybulletevent. This method is called by overlying the onhitbybullet () method; when the robot is hit by the shells. Hitrobotevent. The method is called by overlying the onhitrobot () method; when your robot hits another robot, you call this method. Hitwallevent. Hitwallevent is processed by overlying the OnHitwall () method; the method is called when your robot hits the wall.
We only need to know that you can create some fairly complicated robots. You can access the remaining Robocode API in Javadoc through the Battlefield Help menu or the Help menu of the Robot Editor.
Now, we should put the knowledge learned into practice.
Creating a robot To create a new robot, launch Robot Editor and select File-> New-> Robot. The system will prompt you to enter the name of the robot, which will become a Java class name. Please enter dwstraight at the prompt. Next, the system will also prompt you to enter a unique package prefix that will be used as the name of the package that stores the robot (which may have a related java file). Enter DW at this prompt.
Robot Editor will display the Java code you want to control this robot. Listing 1 is an example of the code you will see:
Listing 1. RoboT code generated by Robocode
Package dw;
Import robocode. *;
/ **
* DWSTRAIGHT - A ROBOT BY (DeveloperWorks)
* /
Public Class DWstraight Extends Robot
{
... // << Area 1 >>
/ **
* Run: DWSTRAIGHT'S Default Behavior
* /
Public void run () {
... // << Area 2 >>
While (true) {
... // << Area 3 >>
}
}
... // << Area 4 >>
Public void onscannedrobot (ScannedRobotevent E) {
Fire (1);
}
Highlighting the area is where we add a control robot's code:
Area 1 We can declare the role domain variables in this blank and set the value of these variables. These variables can be used within the robot's RUN () method and other other helper methods you might create.
Area 2 Combat Manager Call the Run () method to activate the robot. Typically, the RUN () method includes two regions (i.e., Area 2 and Area 3 pointed out in Listing 1, you can add code in both blank. The code you join in Area 2 is run once every robot instance. This part of the code is usually used to make the robot first in a preset state, then start performing repetitive behavior.
Area 3 This is a second part of a typical RUN () method implementation. Here, we will program the repetitive behavior of the robot possible within the infinite While cycle.
Area 4 You can add robots to the Run () logic in this area. You can also add any event handlers you want to overwrite. For example, the code in Listing 1 processes the scannedRobot event. Whenever the radar detects the robot, it is only directly transmitting the shell directly.
Our update to the code of the first robot (DWSTRAIGHT) is shown in the red tag in Listing 2.
Listing 2. Addition of DWSTraight robot code
Package dw;
Import robocode. *;
Public Class DWstraight Extends Robot
{
Public void run () {
Turnft (GetHeading ());
While (true) {
Ahead (1000);
TurnRight (90);
}
}
Public void onscannedrobot (ScannedRobotevent E) {
Fire (1);
}
Public void onhitbybullet (HitbybulleTevent E) {
Turnft (180);
}
}
Below we describe what the first robot will do inquate:
Area 1 We did not specify any type of scope variable in this robot.
Area 2 In order to make the robot in a known state, we turn it to 0 degrees through Turnft (GetHeading ()).
Area 3 In this repetitive part, we use statements ahead (1000) to allow the robot to move forward to the farthest place. When the robot hits the wall or other robots, it will stop. Next, we turn it right through TurnRight (90). When this line is repeated, the robot is basically moved in a clockwise direction along the wall.
Area 4 here, in addition to processing the automatically generated scannedRobot event and directly shooting it directly, we also detect Hitbybullet events, and let the robot turn 180 degrees in the shot (clockwise or inverse Hetorous direction).
Compilation and Test Robots Select Compiler-> Compile on the Robot Editor menu to compile your robot code. Now we can try the first round of fighting. Switch back to the battlefield and select Battle-> New on the menu, there will be a dialog that is similar to that shown in Figure 3.
Figure 3. New Battle dialog
Please add our robot DW.dwstraight to the battle, then add a rim robot, such as Sample.SittingDuck. Click Finish, starting. It is undeniable that it is not interesting to fight with SITTINGDUCK, but you can see this robot called DWSTraight in the default behavior. Try other robots in the Sample folder to see how DWSTraight's fighting situation with these robots. When you are ready to start studying the code of another robot, let's take a look at the code of the DW.DWROTATER machine that is provided with the code packet in the reference material. By default, this robot will:
Move to the battlefield center, I have been turning it until it detects that the robot is detected at a different angle to shoot in front of the detected robot. Whenever it is hit by another robot, it will come back and forth. mobile
This code is easy to understand, so we don't have analyze here, but I encourage you to test. The SAMPLE package in Robocode also provides a lot of other robots.
Additional Robot Support With the improvement of the level of your design robot, the robot's code subject will be fully grown. A modular processing method for these codes is to decompose the code into a separate Java class, then package these Java classes into a separate package (JAR file) through the package, and include it in your robot distribution package . Robocode will automatically find the Robot class in the package under its robots directory.
Other Robot subclasses can create Robot subclasses and add new features used to build robots. Robocode provides a Robot subclass called AdvanceDrobot, which allows asynchronous API calls. Although the description of the AdvanceDrobot class beyond the scope of this article, I encouraged you to test this advanced class after you have the basic Robot class.
The purpose of the design Robocode I met with the founder of Robocode, Mathew Nelson, asked him to create the original design purpose of Robocode. Mat said: "Part of the purpose of writing Robocode is to prove to the world: icon 'Java is slower' and 'Java can not be used to write games' and the arguments such as' Java is no longer correct. I think I have proven this. "
The architecture of the combat emulator analyzes Robocode through "in the background", we find that complex simulation engines have both high performance (in order to generate flexibility in reality), flexibility (enabling complex robot logic does not have obstacles) . Special thanks to the founder of Robocode Mathew Nelson, selfless, providing internal information of the simulation engine architecture.
The simulation engine shown in Figure 4 is used in the design of the Java platform to utilize the non-seizuated thread technology provided by most modern Java VMs and combined with the generated functionality provided by the JDK GUI and 2D graphics libraries.
Figure 4. Robocode Simulation Engine Architecture
Note that each robot simulated is on its own Java thread, which can use the VM local thread mapping mechanism in any applicable place. The combat manager thread is a system controller: it arranges simulation and drive graphical generated subsystems. The graphical generated subsystem itself is based on Java 2D and AWT.
Loose thread coupled to reduce the possible problems that the shared resource may bring (and the deadlock or blocking simulation engine), the coupling between the combat manager thread and the robot thread should be very loose. In order to achieve this loose coupling, each robot thread will have its own event queue. Getting and handling these events are done in each robot's own thread. This thread-based queue effectively eliminates anything that may exist between combat manager threads and robot threads (or robot threads themselves). Robocode internal structure You can view the Robocode emulator engine as an emulator program that uses some plugins (custom robots) at runtime; these plugins can utilize existing APIs (Robocode.Robot classes). In fact, each robot is a separate Java thread, and the RUN () method contains logic to be executed on each thread.
At any time, the robot thread can call the API provided by its parent class Robocoode.Robot. Typically, this will block the robot thread by calling Object.wait ().
Combat Manager Thread Combat Manager Thread Managers, shells and their buildings on the battlefield. The simulation "clock" is marked according to the number of frames generated on the battlefield. The user can adjust the speed of the real frame.
In a typical turn, the combat manager thread wakes up each robot thread, then waits for the robot to complete its round battle (ie, call a blocking API again). Waiting time is usually tens of milliseconds, even the most complex robot, using the currently typical system speed, as long as 1 to 2 milliseconds.
The following is a logical pseudo code executed by the combat manager thread:
Listing 3. Fighting manager's logic pseudo code
While (round is not over) do
Call The Rendering Subsystem to Draw Robots, Bullets, Explosions
For Each Robot DO
Wake up the robot
Wait for it to make a blocking call, Up to a max time interval
End for
Clear All Robot Event Queue
Move Bullets, And Generate Event Into Robots' Event Queue IF Applicable
Move Robots, And Generate Event Into Robots' Event Queue IF Applicable
Do Battle Housekeeping and Generate Event Into Robots' Event Queue
IF Applicable
DELAY for Frame Rate if Necessary
End DO
Note that in the For loop, the wait time of the combat manager thread will not exceed the maximum time interval. If the robot thread does not call the blocked API in time (typically due to some application logic errors or infinite loops), it will continue to fight. Generate a skippedturnevent and add it to the robot event queue to notify the advanced robot.
Alternative Generated Subsystem AWT and Java 2D threads are the generated subsystem in the current implementation, which acquires commands from the combat manager and generates battlefields. It is completely separated from the rest of the system. We can foresee that in this revision of this generated subsystem, it can be replaced (for example, with a 3-D generator). In the current implementation, as long as the Robocode application is minimized, generating is disabled, which can simulate faster. The future of Robocode is a discussion group on the AlphaWorks Robocode site (see Resources), Mathew Nelson can maintain close feedback to the Robocode user community. Many feedbacks are incorporated into the real code. Mathew has planned some improvements to be on:
Customize the battlefield map based on different objects and obstacles to the team-based battle to the League or alliance integrated support users can choose tank body / gun / radar / weapon style
The Robocode trend that uncomfortable is in front of the project in front of the public from July 12, 2001, and the name of Robocode is simply surprised. Although the latest available version is less than 1.0 (which is version 0.98.2 when writing this article), it is already a popular recreational event on the university campus and the company's PC. The Robocode Alliance (or Roboleagues) appeared like a spring, in these alliances, people made their custom works with each other through the Internet. The University professors have been excavating the educational characteristics of Robocode and has included it into a computer science course in the university. On the Internet, the Robocode user group, discussion list, FAQ, tutorials, and WebRing are everywhere.
Obviously, Robocode has filled the blank of publicized entertaining in the field - it provides simple, interesting, non-stressful way to compete for students and staying up late, release their creativity, and it is possible to achieve them Conquer the dream of the world.