Creating "artificial life" on the computer

  • Tutorial
Hello. In this article I want to describe my experiment on creating “artificial life” on a computer.

What does it look like?

The image is clickable.

A virtual environment with its own rules is created on the computer and the first simple animal is released. I will call them bots. Bots can die or survive and give offspring. A descendant may differ slightly from the ancestor.

And then evolution and natural selection are taken to work .

And I can only observe the development of the world.

The more unexpected for the creator and the more varied the options for the development of the world, the more successful the experiment can be considered.

The behavior of the bots is controlled by the code written in them.

That code is the genome that is responsible for the behavior of the bot and which will change in the process of evolution.

The internal structure of the code is the most interesting in the project.

The code should be simple and withstand various modifications (random change of any element in the code) over itself without syntax errors.

We will return to the code later, first describe the world itself.

Description of the "world of bots"

The world is a two-dimensional, divided into squares field. Horizontally, it is closed in a circle, that is, if the bot goes beyond the left edge, it will appear on the right side. From above and below the movement is limited by a wall. The world, according to the idea - is a section of the reservoir, the higher, the more energy can be obtained from the sun. In the lower half of the energy of the sun is no longer available. Actually, this is enough. I started experiments with this world.

Then added "minerals" at the bottom of which you can get energy. The deeper, the more "minerals" the bot can get. After that, the lower part of the world also became populated.

Bots can move in eight directions and probe adjacent cells.
Bots can eat other bots that are on a nearby cage.

Bots save energy and when they accumulate a given amount, their clone buds off from them.
The same program is written to the clone as the parent, but in one case out of four, one byte in the program changes randomly. This may not affect the clone's behavior in any way, since not all commands in the genome program are executed, a large part of the genome may not be involved. It can also cause a deterioration or improvement in the ability of a bot to survive in this world. In the first case, the bot will either die or will not be able to leave many descendants. In the case of improving the abilities of the bot, he is more likely to leave more offspring, which will displace less successful neighbors.

Bots do not die of old age. A bot can die if its reserves of energy become below zero, if another bot eats it, and if it has accumulated the maximum amount of energy, it should budge a descendant, but is surrounded on all sides and cannot do it. After death, if it was not eaten, the bot turns into organic matter, which begins to sink until it encounters an obstacle. After that, the organic remains in limbo. Organics can eat other bots.

Here I gave a brief idea of ​​the virtual world of bots, sufficient to understand the further material. Actually the world itself is not so important, you can experiment with different worlds. Much more interesting how the code-genome works

Gene coding

A cod-genome is a chain of numbers. Each number is some kind of command (in the simplest case). There is also a pointer to the current command (hereinafter UTK ), which shows which command will now be executed and after the command is executed, the pointer moves to the next command. If the pointer goes beyond the edge of the chain, then it appears on the opposite side, that is, the chain of commands is closed in a circle. Initially, I chose a chain size of 64 cells and assigned the first commands to some numbers. If the number does not correspond to any team, then this number is an unconditional transition . When the TCA points to a cell with a similar number, it will increase (go forward in the chain of commands) to that number. The fact that a number without an assigned command isunconditional transition is very convenient. When experimenting, you can safely assign a new command to the free numbers or remove the old one. Since I have a chain length of 64 cells, the available numbers are also 64 (from 0 to 63).

The figure schematically depicts the genome of the first bot in the form of a tape closed in a circle. All cells are clogged with command 23 . This is the "photosynthesis" command . After its execution, the bot receives energy in an amount depending on the depth where the bot is located. The figure also shows the execution of the code. It is worth noting that the team, in addition to performing the main function, is also responsible for changing the TC . After executing such a simple command as "photosynthesis" , UTKincreases by one. In this example, all commands in the code-genome will be executed sequentially.

Suppose that when a new bot appeared, a mutation occurred and the number 63 was recorded in the cell number 1 . After the appearance of the new bot, its UTK is 0, the “photosynthesis” command is executed , the UTK is increased by 1. Now the number from cell 1 is read - this is the number 63 . This number is not assigned to any team, so this is an unconditional transition . We move UTK on 63 cells forward and now UTK again points to the "photosynthesis" commandin the zero cell. This will be repeated in a circle. Note that the external behavior of the bot will not differ from the parent, but only two of the 64 cells will be used.

Now consider the more complex commands that require parameters.

There are eight directions in the world of bots. If we need the rotation function, we can use 8 teams, one command for each direction.

But we have only 64 numbers (0..63) and there are simply not enough numbers for all the necessary commands. Therefore, we will use the parameters.

For example, we assigned the command “turn” to the number 25 . When UTK will point to the cell with the number 25(turn), then we also take the following number. From this number, we learn where to turn. The number can be from 0 to 63, and there are 8 directions. To find out the direction, we divide the parameter by 8 and take the remainder of the division. Get one of the 8 values ​​(0..7) - this is the direction to turn. The number of available numbers (64) is a multiple of 8. Therefore, the probability of choice is the same for all directions. After executing the command, UTC moves not by one cell, but by two, jumping over the parameter.

It is worth noting that the UTK can come to the cell, which at another time served as a parameter. Now the value from this cell will be the command. This greatly complicates the analysis of the code by man, but the “virtual machine” that executes the bot code is very simple to implement.

Suppose we need the command “how much energy do I have?” When executing this command, if there is more energy than received in a parameter, then we go to one address, if less, then to another. The energy can be from 1 to 1000, and the parameter from 0 to 63. To circumvent this limitation, when executing this command, the parameter is multiplied by 15. We get the following options:

0, 15, 30, 45, 60 ...... 945.

With the obtained option, we compare the energy level and, by comparison, add to the TCA bias. The offset value is taken from the following cells after the parameter.

Detailed interpretation of the picture above
Указатель текущей команды (УТК) равен 10.

Берём число из ячейки №10. Это 33, команда «сколько энергии?».
Берём число из следующей ячейки (УТК+1), это параметр, из него вычисляем число для сравнения.


Если энергии у бота больше или равно 210, то берется число по адресу УТК+2.
Там у нас число 23. Это число прибавляется к УТК.


То есть УТК теперь равно 33 и следующей командой будет команда из ячейки №33

Если энергии у бота меньше, чем 210, то берется число по адресу УТК+3.
Там у нас число 8. Это число прибавляется к УТК.


То есть УТК теперь равно 18 и следующей командой будет команда из ячейки №18

Some commands, such as “see” , “make a step” , “eat” , “share energy” are splitters. Depending on what was in the cage to which the action was directed, the further execution of the code will go along different branches.

Detailed interpretation of the picture above
Указатель текущей команды (УТК) равен 7.
Берём число из ячейки №7. Это 26, команда «шагнуть».
Берём число из следующей ячейки (УТК+1), это параметр, из него вычисляем направление для шага.

18 % 8 = 2

Если клетка, куда шагает бот, была пуста, то берется число по адресу УТК+2.
Там у нас число 0. Это число прибавляется к УТК.


То есть УТК опять указывает на ячеёку №7. Бот будет двигаться в этом направлении, пока на пути не встретит препятствие.

Получился цикл.

Если на клетке была стена, то берется число по адресу УТК+3.
Там у нас число 3. Это число прибавляется к УТК.


То есть УТК теперь равно 10 и следующей командой будет команда из ячейки №10 То есть число в этой ячейке только что было ссылкой, а теперь будет выполняться, как команда.

Если на клетке была органика, то берется число по адресу УТК+4.
Там у нас число 43. Это число прибавляется к УТК.

7+43=50. То есть УТК теперь равно 50 и следующей командой будет команда из ячейки №50
Если на клетке был чужой бот, то берется число по адресу УТК+5. Там у нас число 24. Это число прибавляется к УТК. 7+24=31.

То есть УТК теперь равно 31 и следующей командой будет команда из ячейки №31

Если на клетке была родня, то берется число по адресу УТК+6.
Там у нас число 59. Это число прибавляется к УТК.


То есть УТК теперь равно 66. Указатель вышел за диапазон возможных адресов, вычитаем из него 64 и получаем 2 Следующей командой будет команда из ячейки №2

In reality, a bot can take a step only if the cell was empty, otherwise the bot will remain in place. Well that's all. Thus, the bot receives information about its surrounding cells. And the behavior of the bot is now not linear, but depends on the environment.

Bots distinguish a stranger from its own, if the code-gene differs by more than one byte. This is a resource-intensive operation, but after the introduction of this possibility, colonies with clear boundaries began to appear.

A few more points.

All bots in the memory of the operative memory are connected in a circular chain and control in turn is transferred from one bot to another. The bot code is executed until the final command is executed. These teams include: “step” , “eat” , “photosynthesis” ,“Share energy” and so on. The remaining commands ( unconditional transition , “see” , “turn” , “how much energy?” And so on) can be performed up to 15 times, after which control is transferred to another bot.

When a new bot buds, it is built into the chain of bots in front of the ancestor.

What is the result?

Well, now screenshots of what happened. I note that the pictures are not so interesting to watch, like a video where you can see the dynamics of the development of the world. Many interesting phenomena, such as “flamefish” and “ghosts” on static photos, do not look very photogenic, but they are fascinating in video. For the video, I used a screenshot from every 25 turns. At the same time, unfortunately, some curious moments can be lost, such as short cyclical movements of bots.

Screenshots are made at different stages of development. Where the background changes from white to blue, I haven’t introduced “minerals” yet .

Two display modes are shown here.

In standard modecolor depends on the way of obtaining energy. Fans of photosynthesis turn green, fans of “minerals” turn blue, and meat eaters turn red.
Omnivores may have an intermediate color.

In the energy display mode , the more energy, the redder the bot, the less energy, the yellower the bot.

The very beginning. Appear "Labyrinth" , a chain of bots

are beginning to appear the first colony

The colonies have formed. You can see pink and blue-green lovers of a varied diet.

Curious diagonal predator settlements.

Curious chess arrangement of organic (corpses of bots) in the middle of the colony.
The view of the world has changed, but the "chess"order maintained. I suspect that the bots used only 4 directions out of 8. The

newly born bot receives its color from the parent. Then, depending on the diet, the color may change.

Here are visible red clusters of bots. They do not eat anyone and do not receive energy from the Sun, otherwise they would have turned green.

Energy they receive from the distribution of energy in the colony. A kind of parasite. When the colony begins to have problems, the parasites die quickly.

The mode of displaying energy opens up new sides of the world. It can be seen how the energy inside the colonies is distributed in different ways. The central colony has clear boundaries from the left, but it does not on the right side of the border. Also visible from the edges of the colony, where energy goes diagonally(since the world is horizontally closed in a circle, it is one and the same colony) .

If in the standard mode the colony looks uniform, then in the energy display mode it can be distinguished that structures living according to their own rules can exist in the colony. A sort of second level colony.

The beginning of a mass extinction. Red bots are overflowing with energy and they have to otchibach the descendant, but there is no free space and they die. Eats bots organic also ceased. As a result, organic (pale pink) filled the entire upper part of the world.

The size of the created world is small, since most of the work and experiments were carried out on a 7-inch tablet, but for such experiments, the larger the world, the better. The first photo in the article used a screenshot from a clone of my project, rewrittenRomanoBruno in Java . Here is another scale and speed of work is higher. Link to this project at the end of the article.

The world is rapidly developing within a few hours, then the speed drops, the world finds a stable state in it and remains. Most likely, the small size of the world and the scarcity of opportunities affect it.

I decided to cheer up a world that has not changed for a long time and made a "solar flare" . In this case, every second bot in the code-genome randomly changes random bytes.

State of the world before the flash

Passed 21 turn after the flash. The world is pretty ruined, most of the bots are dead.

Another 347 moves passed, the world is returning to life.

It took more than 2,000 moves and the world returns to the previous form, which came as a surprise to me. I expected that the world would no longer be the same. Apparently, none of the provoked mutations made the bot better and all the mutants died over time.

Note that a small colony of blue bots in the center on the right side did not seem to notice the catastrophe.

What's next

Now I have partially written, but temporarily frozen due to lack of time, the project of a new world.

Energy can be obtained by eating the "grass" . You can eat all the "grass" in a certain place and it will only appear there growing from those places where it remained.
The amount of energy, respectively, will inversely depend on the number of bots and bots will not be able to flood the whole world. This will create a larger world with natural isolation of different groups of bots. Bots will be forced to move in search of affordable food.

Code-genome will work on the same principles, but some additional features will be added.

  • Registers and operations with them.
  • Interrupts , sibling stack and ret command
  • Ways of communication between bots.

business project
<шутка> В будущем собираюсь выпустить чашки, поверхность которых выполнена в виде экрана, на котором отображается искусственный мир. Мир получает энергию, когда в чашку налит напиток правильного производителя. Если долго не поступало энергии, то мир чахнет и умирает.</шутка>


Unlike the genetic algorithm , there is no division into generations, the bot may not die at all and live to the end of the centuries (turning off the computer). There is no clearly defined fitness function that determines which bot is better and which is worse, all the more it can change along with the changing world. There is no sense, no purpose, only natural selection in a changing world.

If you are hooked by the idea of ​​creating your own world and experimenting with it, then join, try to create your own world.

The principle of constructing a genome code, which I described, is simple to implement and can be easily modified for different worlds.


This project is not the only one on this subject, but at the time of its creation I knew only one thing. I read about him in 93 in the magazine "Technology Youth". The article caught me. At that time I didn’t have a computer and I didn’t think that I would ever be able to do this.
Link to the article

Video , where you can see different options for the development of the world.

The project is written on the Pixilang interpreter

The project is also rewritten by RomanoBruno in Java and posted on GitHub .

Also popular now: