Robocode

    Tagline RobocodeThe habrasociety has supported the idea of ​​writing game reviews for programmers, so I continue this series of articles. Let me remind you, the last time I told you about the games Colobot and Ceebot .

    Today you will learn about the excellent Robocode game. It is intended for advanced Java training, and has great functionality, despite the apparent external simplicity.

    Robocode is an open source educational game developed by Mathew Nelson and Flemming Larsen. Its sole purpose was to facilitate the study of the Java programming language.



    The game



    The main driving element in training was to become competition. Each participant writes code in Java, which controls a small tank, and fights with other such tanks.

    Your goal is to destroy all other tanks on the field. No compromise. Your tank must achieve absolute superiority, and show what pathetic losers your friends are.

    The developers strongly draw your attention to the fact that there is no blood in Robocode, no people and no politics. There are explosions in the game, but if you care about your own mental health, they can be easily turned off.

    Tanks have great opportunities: they can move around the playing field, shoot, find out the location of each other, crash into walls and other robots, find out where the flying bullets are and use the full power of the Java language.

    Battle of tanks


    Naturally, there is no simple strategy for winning. There are a huge number of different tactics, each of which has its own advantages and disadvantages. The code size for various tanks ranges from a dozen lines to several thousand. Some even manage to resort to statistical analysis and neural programming.

    Interestingly approached the writing of the robot in St. Petersburg ITMO. The tank was developed using SWITCH technology (a mixture of automated and object-oriented programming), and serious project documentation is attached to the project.

    You can download it and the tank source codes absolutely free on the project page .

    Game installation



    On the official website of the project is a huge amount of various materials. If you want to start training, this is the best place to start.

    Install Robocode


    The game itself is distributed as a jar archive, which can be downloaded from the game download page .

    The game is cross-platform, as it is written in Java. It can be played on Windows, Linux, FreeBSD, and on any other system on which the Java machine is ported.

    Java


    Before installing the game, do not forget to install Java .

    Your first robot



    Ready to create your first robot? I am sure it will be easy, entertaining and just interesting!

    Creating a robot is very simple. But to make him a winner is not.

    Robocode Logo


    Built-in editor



    The developers included their own editor in the game. Therefore, you already have a ready-made development environment with syntax highlighting.

    This program is called Robot Editor, and it is available in the Robot -> Editor menu.

    Robocode editor


    Let's now create a robot blank. To do this, go to the menu item File -> New Robot. Create a name for your future robot and enter your initials (nickname).

    Voila! Now you see a draft code of your future robot.

    Note: If you want to use Eclipse or another IDE, you can easily find the appropriate guide for integrating with Robocode on the Internet.

    New robot



    In its simplest form, the code should look like this:

    // Используем пакет с Вашими инициалами. Это сделано для избежания конфликтов имен.
    package v673;

    // Указывает Java, что мы собираемся использовать объекты Robocode в нашей программе.
    import robocode.*;

    // Указывает Java: "Класс, описываемый ниже, является расширением класса Robot.
    // И называется MyFirstRobot".
    public class MyFirstRobot extends Robot
    {
       // Игры вызывает метод run(), когда начинается битва.
       public void run()
       {
         // Здесь идет непосредственно код Вашего робота.

       }

       // Существует и другие методы, которые мы рассмотрим позже.
    }



    It's time to do something already!



    Let's make our robot do something. Add the following lines to the run () method:

    // while (true) означает то, что код в скобках будет выполнятся до тех пор, пока игра не прервется.
    while (true)
    {
       // Робот проедет вперед на 100 пикселей.
       ahead(100);

       // Робот повернет свою пушку на 360 градусов.
       turnGunRight(360);

       // Робот вернется назад на 100 пикселей.
       back(100);

       // Робот снова повернет свою пушку на 360 градусов.
       turnGunRight(360);

       // После чего код начинает выполняться снова.
    }



    Our robot will perform these actions over and over until it dies. Not bad, huh?

    Fire!



    When the tank’s radar finds an enemy robot, we start firing:

    public void onScannedRobot(ScannedRobotEvent e)
    {
       fire(1);
    }


    As you can see, in the function of the object is sent ScannedRobotEvent , which contains information about the enemy (or friendly) robot - much as his health, where he is the speed with which moves, etc.

    But since we have a simple robot - we will not devote much time to this.

    Robot compilation



    First of all, save your work: File -> Save .

    Now compile the robot: Compiler -> Compile .

    Compilation


    If your robot compiled without errors, you can start the battle. Start a new battle by choosing Battle -> New in the game menu . If you do not see your own robot - update the list by pressing F5. Add your robot to the battle along with another robot. For example, along with the Sample tank .

    New battle


    Start the battle by clicking Start Battle .

    Enjoy!

    Robot anatomy



    We just created our own robot. Let's now take a closer look at the design features of the tanks.

    The tank consists of three parts: the body of the tank, the gun and the radar.

    Robot anatomy


    Each of these parts can move independently of each other. The tank moves most slowly, the gun moves faster, and the radar is the fastest element of the robot.

    Battleground



    The battlefield is a rectangle. Moreover, its size is set when creating a battle.

    Coordinate system:

    Coordinate system


    Note that even if you execute ahead (50,000), the team will stop execution the moment the robot crashes into a wall.

    In RoboWiki you can learn more about game physics .

    Deflection angle



    It is sometimes convenient to use a relative angle. For example, to turn to another robot, you can use the following command:

    turnRight(event.getBearing());


    That is, getBearing () indicates how many degrees you need to deviate from the current position in order to see, for example, an enemy tank.

    Deflection angle


    Note: If you pass a negative value to the turnRight () function, the robot will turn left.

    Robot feelings



    No, we will not talk about the vulnerable soul of the tank. We will consider the functions by which the robot can recognize the influence of external factors.

    Your robot knows when:
    • He hits the wall: onHitWall ()
    • An enemy bullet hits it: onHitByBullet ()
    • It crashes into another robot: onHitRobot ()
    • And also a number of exotic functions, for example, when your bullet hits the bullet of an enemy robot.


    All robots in Robocode are built on the basis of these functions. You can get acquainted with all the functions in more detail in the API documentation .

    What's next?



    Most of the training material is collected on the official website of the game .

    Unfortunately, there are not so many Russian materials about Robocode. But I hope that English is not a big problem for you.

    I recommend that you take a look at the Robocode course from Mark Whitley: CS 3230 - Robocode Project . By the way, there is a collective Russian translation thanks to the translated.by project . But, unfortunately, it has not yet been issued in a separate PDF file, there are no pictures. Therefore, at the moment, I advise you to study the original.

    There are also two great articles from Sing Li about Robocode: Rock 'em, sock' em Robocode! Round 1 , Rock 'em, sock' em Robocode! Round 2

    OnRoboWiki has collected a huge amount of high-quality material about RoboCode. Starting from simple guides, and ending with an explanation of various subtle points.

    In addition, on the official website you will find many links to other excellent articles about Robocode.

    You can even read articles about using genetic algorithms in RoboCode .

    The RoboCode repository contains a huge number of different robots. Some of them have source codes.

    There is an official developer blog: robo-code.blogspot.com .

    On this, I would like to finish our review.

    If you are interested in my articles, then there is a hack that allows you to read them before the release on habrahabr: subscribe to my blog , or on twitter .

    I wish you success in understanding the intricacies of Robocode!

    Also popular now: