E
E
ent1k13372022-03-03 23:47:38
C++ / C#
ent1k1337, 2022-03-03 23:47:38

How to execute pseudocode?

I am developing a game on unity in which you need to compose an algorithm from the available commands (the mechanics of compiling an algorithm are taken from these games: 7 Billion Humans or Human Resource Machine). When building an algorithm, the pseudocode of the algorithm is written to the file; it contains both methods, loops and branches. How to execute this pseudocode in c#.

6221290a141ec043755231.jpeg

a:
if s != worker or
 sw != worker:
  step s
  jump a
endif
b:
takefrom s
if myitem < 50:
  giveto sw
  step e
  jump b
else:
  step w
  step w
endif
c:
step n
jump c

PS If you have any ideas how you can transfer the algorithm from the game to the code avoiding pseudocode, please share.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vindicar, 2022-03-04
@Vindicar

Use the Composite + Interpreter pattern from the Gang of Four pattern set.
You describe the basic interface for the runtime and for the command:

//окружение хранит текущее состояние программы плюс предоставляет средства взаимодействия с "окружающим миром".
public interface IProgramEnvironment
{
    Dictionary<str, int> Variables {get;} //хранилище переменных
    IProgramOperator CurrentOperator {get; set;} //текущая команда - нужно для переходов
    //ну и что там ещё тебе может потребоваться? Операции ввода-вывода, и т.п.
}
//просто составной оператор
public interface ICompoundOperator: IList<IProgramOperator>
{
    void ExecuteAll(IProgramEnvironment env); //выполнить дочерние команды
    string ToString(); //для отладки
}
//абстрактный оператор, его будут реализовывать классы операторов
public interface IProgramOperator
{
    int LineNumber; //номер строки, для удобства обозначения
    IReadOnlyList<ICompoundOperator> ChildrenBlocks {get;} //списки дочерних команд, если они есть
    void Execute(IProgramEnvironment env);  //выполняем команду в окружении. Может потребоваться возвращать значение
    string ToString(); //для отладки
    void Render(); //для отображения на экране?
}

Then you describe individual commands as separate classes that implement IProgramOperator.
If the statement is compound, then its ChildrenBlocks will not be empty, but will contain lists of nested commands. For example, a loop will have 2 such lists (condition and body), and a branch will have 3 (condition if, otherwise).
Then, when executed, the operator executes its Execute () method, and, if necessary, executes certain child operators.
Accordingly, you will get a tree of command objects. The root of the tree will be ICompoundOperator - the body of the program. As part of the execution of the program, you, in fact, bypass this tree in depth.
There will be some problems with the implementation of stepping, but this can be solved by turning the Execute() method into a generator that will pause its execution after each command. At the same time, the question of the "last calculated value" will be solved - it will be possible to simply yield the results of calculations.
IEnumerable<object> Execute(IProgramEnvironment env)

R
Roman, 2022-03-04
@yarosroman

Dig towards ANTLR (antlr.org) or Gold Parcer ( www.goldparser.org )

V
Vasily Bannikov, 2022-03-04
@vabka

How to execute this pseudocode in c#.

Well, you need to parse and execute it :)
For parsing, in addition to the named ANTLR, you can also use Irony or Yoakke
If you have any ideas how you can transfer the algorithm from the game to the code avoiding pseudocode, please share.

Use some real-life embeddable language like lua

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question