Thursday, February 25, 2010

Robocode with C++/CLI

Recently I spotted question if it's possible to create robot in C++. Here is the answer. Ok, I know, it's not like real C++ with pointers etc, this is managed version of C++, which is safe enough to be runnable in Robocode.
  • Download VS 2008 Express C++
  • Create new CLR-> Class Library (DLL) project
  • Go to project properties, Common Properties, Add New Reference, and add robocode.dll from lib folder of your robocode installation.
  • Go to project properties, Configuration properties, General, Common Language Runtime support and set it to Safe MSIL (/clrsafe)
  • Go to AssemblyInfo.cpp and delete line with [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
  • Go to [myCppRobot].h and insert code below
  • Compile it, drop the DLL into Robocode and enjoy!
#pragma once
using namespace System;
using namespace Robocode;
namespace myCppR {
    public ref class MyCplusplusRobot : Robot {
    public:
        virtual void Run() override {
            while(true) {
                Ahead(100);
                TurnLeft(100);
            }
        }
    };
}

2 comments:

Nat Pavasant said...

Actually I think I raise this question on RoboWiki some time ago =)

What I was thinking is to create a Robot API through JNI and write a C sandbox for it (which I know is possible on Linux, still experimenting on Windows). That way we can write "true" C/C++

Pavel Šavara said...

You are right that you could use JNI and that would work on any platform, but the problem is that it would be not secure. You can't verify that binary .dll/.so file doesn't hack your system or cheat in the game. It would be possible to isolate such robot as process, but that would be probably slow. Another problem is that 'real' C++ compiles into native code, which is not platform independent.

We could as well relax the security of CLR sandbox and that would allow for 'real' C++ features as well. But the impact is the same as with your solution.

Definitely interesting, but probably not worth of (my) time.