c++cocos2d-x-3.x

How to create new function and excute it while the game is running?


I'm making a game with Cocos2d-x v3.17.

I want player write their code in the game scene, then they press Submit and the game execute it.

I think about save their code to a file and call a function from it, so I create 2 files like this:

//PlayerCode.h
#pragma once
int PlayerFunction(int a, int b);

//PlayerCode.cpp
#include "PlayerCode.h"
int PlayerFunction(int a, int b){ return 0;}

And I run the game.

In the main scene, when the player press Submit, I rewrite the .cpp file depend on what they code, assume it become:

//PlayerCode.cpp
#include "PlayerCode.h"
int PlayerFunction(int a, int b){ return a+b;}

Then run this to excute player code

try{
    int result = PlayerFunction(2,3);
    CCLOG("%d",result);
}
catch (string somethingError){
    CCLOG("%s",somethingError);
}

But regardless what player write, result is always 0. Even if the .cpp file change each time they press Submit, program just run code from the first old file.

That's all my problem, please help me solve it, or guide me if you know other way to do this feature.

Thank you.


Solution

  • C++ is a compiled language meaning that you are not directly reading any source file at runtime. It doesn't matter if you change the source code when the application is running since you haven't compiled it.

    One thing you could try is to use a scripting language and make it embedded in your c++. Then the player can script in that language and you can run the script.

    The popular choice for scripting in a game is the LUA language.

    I suggest you look at a book for writing games with C++ such as Game Coding Complete, Fourth Edition