Friday, May 20, 2016

Colobot: Robot switching Power Cells by itself

If you have discovered Colobot: Gold Edition, you've been missing a great game.  It's free as in open source and is available on all operating systems.

The main feature is the possibility to program your robots with real code.  The syntax does look like Java or C# and is quite easy to master.  I've created a little program that will find the best available power cell in the area and will let the robot find it and use it as it's new power source.

Here's the code:
extern void object::FindEnergy()
{
while(true){
object newcell = FindCell();
if (newcell !=null){
message("New cell found!");
turn(direction(newcell.position));
moveToPosition(position,newcell.position);
replaceCell();
} else {
message("Cannot find another cell...");
break;
}
}
}
void moveToPosition(point p1,point p2){
errmode(0);
int err = move(distance(p1,p2)-1.5);
while (err != 0){
turn(45);
move(5);
err = move(distance(p1,p2)-1.5);
}
}
object FindCell(){
message("Scanning for cell...");
int minDist = 5;
object cell = radar(PowerCell,0,360,5);
object otherCell= cell;
while (otherCell != null ){
minDist += 1;
otherCell = radar(PowerCell,0,360,minDist);
if (otherCell != null){
if (otherCell.energyLevel > cell.energyLevel){
cell = otherCell;
}
}
}
if (cell.energyLevel == 0){
cell = null;
return cell;
}
void replaceCell(){
message("Replacing cell...");
grab(EnergyCell);
drop(Behind);
grab(InFront);
drop(EnergyCell);
grab(Behind);
drop(InFront);
turn(-90);
move(4);
}
 
See it in action:


Have fun!