# Battle for the Petri Dish

In this challenge, you must design a species of single-celled organisms to fight to the death in the petri-dish arena. The arena is represented as a rectangular grid, where each cell occupies one space:

.....x....
...x...o..
...x.c..o.
.......o..


## Attributes

Every cell has three attributes. When specifying your cell species at the start of the game, you allocate 12 points among these attributes.

• Hit Points (HP): If a cell's HP falls to zero, it dies. New cells have full HP.
• When a cell dies, it leaves behind a corpse which can be eaten by other cells for energy.
• A cell cannot regain lost HP, but it can create a new cell with full HP by dividing.
• Energy: Most actions a cell can take require energy. By actively resting, a cell can regain lost energy up to it species' maximum.
• A cell species with less than 5 energy is likely to fail, because it cannot divide to create new cells.
• A cell cannot regain energy beyond its species' maximum value.
• A newly created cell has an initial energy value copied from its parent (and a max value dictated by its species specification).
• Acidity: If a cell chooses to explode, the cell's acidity level is used in calculating damage to adjacent cells.

## Actions

Each turn, every cell can take one action:

• Move: The cell moves one space in any direction (N/S/E/W/NE/NW/SE/SW) at a cost of 1 energy.

• A cell cannot move onto a space occupied by another living cell.
• A cell cannot move off of the grid.
• Moving onto a cell corpse destroys the corpse.
• Attack: A cell attacks an adjacent cell, dealing 1 to 3 damage, by expending 1 to 3 energy points.

• A cell can attack in any direction (N/S/E/W/NE/NW/SE/SW).
• It is legal to attack friendly cells.
• Divide: The cell divides and creates a new cell on an adjacent space, at a cost of 5 energy.

• A cell can divide in any direction (N/S/E/W/NE/NW/SE/SW).
• The new cell has full HP according to your original cell specification.
• The new cell has as much energy as its parent cell does after subtracting division cost. (For example, a parent cell with an initial 8 energy points will be reduced to 3 energy and produce a child cell with 3 energy).
• A new cell cannot act until your next turn.
• A cell cannot divide into an space occupied by a living cell, but it can divide into a space occupied by a dead cell corpse (this destroys the corpse).
• Eat: A cell eats an adjacent cell corpse, gaining 4 energy.

• A cell can eat in any direction (N/S/E/W/NE/NW/SE/SW).
• Rest: A cell does nothing for one turn, regaining 2 energy.

• Explode: When a cell has 3 or fewer HP and more energy than HP, it may choose to explode, dealing damage to all eight adjacent cells.

• Damage to each adjacent cell is (exploding cell HP) + (explodng cell acidity)
• An exploded cell dies and leaves behind a corpse, as do any cells killed in the explosion.

## Protocol

### Setup

Your program will run with the string BEGIN provided on stdin. Your program must write to stdout a space-separated list of 3 non-negative integers, representing HP, energy, and acidity for your cell species: e.g., 5 6 1. The numbers must sum to 12. Acidity may be 0, if you wish. (Other attributes may also be zero, but doing so functionally forfeits the game!)

You begin with one cell, in the northwest or southeast corner, one space away from either edge. The beginning cell has full HP and energy.

### Every cells acts

Every turn, your program will be invoked once for every cell alive on your team (except cells just created this turn) so that cell can act. Your program is provided with data on stdin that includes the petri dish state and information about this particular cell:

10 4
..........
..xx.c....
...c...o..
......o...

6 3 5 7


The first two numbers indicate arena width and height: here, there is a 10-by-4 arena.

• The o cells are yours; the x cells are your enemies. (This is always true; each player always sees their own cells as o.)
• The . spaces are empty.
• The c spaces represent edible cell corpses.

• The first two numbers are x,y coordinates, indexed from 0,0 in the top left (so 6 3 here refers to the south-most o cell).
• The third number is the cell's HP; the fourth number is the cell's energy.

Your program should output (to stdout) an action. In the examples below, we'll use N as an example direction, but it can be any direction legal for that action (N/S/E/W/NE/NW/SE/SW). All program output is case-insensitive, but examples will use uppercase. Any output action that is invalid (either because it has invalid syntax or attempts an illegal action) is ignored and results in the cell RESTing (and thus gaining 2 energy).

• MOVE N
• DIVIDE N
• EAT N
• ATTACK N 2 - the number represents the strength of the attack (1 - 3)
• REST
• EXPLODE

Your team's turn consists of all your cells being given an opportunity to act, one by one. All of your cells act before any of the opponent's cells act. Once all of your cells act, your turn ends, and your opponent's turn begins. Once all your opponent's cells act, your turn begins again. Within your turn, each cell is given priority to act based on its age: the oldest cells on your team act first before younger cells.

## Example

Here's how a program might behave. Input from stdin is denoted here with leading > arrows (separated from actual input by a clarifying space) and output on stdout has < arrows.

> BEGIN
< 5 6 1


Then, the program is invoked again:

> 10 4
> ..........
> .o........
> ........x.
> ..........
>
> 1 1 5 6
< DIVIDE SE


After your opponent's turn (who decided to DIVIDE W with the single starting cell), your program is invoked twice, once for each cell:

> 10 4
> ..........
> .o........
> ..o....xx.
> ..........
>
> 1 1 5 1
< MOVE E


For the second invocation on your turn:

> 10 4
> ..........
> ..o.......
> ..o....xx.
> ..........
>
> 2 2 5 1
< MOVE SE


Note this second cell sees the updated board state based on the other cell's movement earlier in your turn. Also note this cell has been created with 1 energy, because the parent cell had 6 energy when it performed division last turn (so the original 6, minus the 5-energy cost of division, created a child cell with 1 energy).

Now your turn is over and your opponent's turn begins. The two opposing cells will be given a chance to act, and then your next turn begins.

## Victory

You can win by either:

• Destroying all opposing cells, or
• Having more cells than your opponent after each player has completed 150 turns

Scoring will be based on number of wins in 100 games against each other submission. In half of the simulations, your program will be allowed to go first.

Tie games (i.e. exactly the same number of cells after 150 turns, or the only remaining cells are killed together in an explosion) are not counted in either player's win totals.

## Other information

• Your program should not attempt to maintain state (beyond using the state of the Petri dish): monocellular organisms do not have a very good memory and react to the world moment by moment. In particular, writing to a file (or other data store), communicating with a remote server, or setting environment variables are explicitly disallowed.
• Submissions will be run/compiled on Ubuntu 12.04.4.
• The specifics of the 100 scoring games are not yet confirmed, but they will likely involve multiple arena sizes (for example, 50 runs on a small arena and 50 runs on a larger arena). For a larger arena, I may increase the max turn count to ensure that a proper battle can take place.

## Resources

Here is the driver code that runs the simulation, written for Node.js, called by node petri.js 'first program' 'second program'. For example, pitting a Python-written cell against a Java-written cell might look like node petri.js 'python some_cell.py' 'java SomeCellClass'.

Additionally, I understand that reading and parsing multiple lines on stdin can be a huge pain, so I've drafted a few complete sample cells in different languages which you are free to build upon, completely overhaul, or ignore entirely.

Of course you are free to write a cell in a different language; these are simply three languages I decided to write boilerplate code for as a time-saving aid.

If you have any problems running the driver, feel free to ping me in the chat room I've created for this challenge. If you don't have sufficient reputation for chat, then just leave a comment.

• @Ryan You'll need to specify a fully runnable command like 'node c:/cell/cell_template.js' for each argument, just as you'd need to specify 'java CellTemplate' for the Java code. I'll make that clearer in the challenge text. If you're stil having trouble, we (and anyone else with technical issues) can continue this discussion in a chat room I've just made. – apsillers Jul 12 '14 at 13:47
• @Moogie Only 2 opponents per game. – apsillers Jul 14 '14 at 7:18
• Man, the examples are great! – CommonGuy Jul 14 '14 at 10:33
• @apsillers we asked you in chat but forgot to ping you so you might not have noticed: we were wondering when are you planning on running the game? – plannapus Jul 24 '14 at 6:54
• @Manu Finally, yes! I apologize for the very long delay. I have the matchmaking/scorekeeping code set up and I'm now clearing up any problems with the submissions in my attempt to get everyone's code to run. After that, I'll let it run on my server for a day or so to complete the rounds. – apsillers Aug 22 '14 at 12:27

Here's my relatively simple bot, which I programmed in Ruby. Basically, it prioritizes dividing first, and attempts to divide towards enemies in order to gain control over the field. Its second priority is eating, and third is attacking. It easily beat the sample Python cell.

def surroundingCells(x, y)
result = Hash.new
if x >= 1
if y >= 1
# northwest
result["NW"] = $petriDish[x - 1][y - 1] end if y < ($sizeY - 1) # $sizeY - 1 is the farthest south square # southwest result["SW"] =$petriDish[x - 1][y + 1]
end
# west
result["W"] = $petriDish[x - 1][y] end if x < ($sizeX - 1)
if y >= 1
# northeast
result["NE"] = $petriDish[x + 1][y - 1] end if y < ($sizeY - 1)
# southeast
result["SE"] = $petriDish[x + 1][y + 1] end # east result["E"] =$petriDish[x + 1][y]
end
# north
result["N"] = $petriDish[x][y - 1] if y >= 1 # south result["S"] =$petriDish[x][y + 1] if y < ($sizeY - 1) return result end def directionTowardsEnemies(locX, locY) totalXDirections = 0 totalYDirections = 0 totalTargetsFound = 0 # enemies or corpses optimalDirections = [] for x in 0..($petriDish.length - 1)
for y in 0..($petriDish.length - 1) if$petriDish[x][y] == 'c' or $petriDish[x][y] == 'x' totalXDirections += (x - locX) totalYDirections += (y - locY) totalTargetsFound += 1 end end end if totalXDirections == 0 if totalYDirections > 0 optimalDirections << "S" << "SE" << "SW" else optimalDirections << "N" << "NE" << "NW" end return optimalDirections end if totalYDirections == 0 if totalXDirections > 0 optimalDirections << "E" << "NE" << "SE" else optimalDirections << "W" << "NW" << "SW" end return optimalDirections end if totalXDirections > 0 if totalYDirections > 0 optimalDirections << "SE" if totalYDirections > totalXDirections optimalDirections << "S" << "E" else optimalDirections << "E" << "S" end else optimalDirections << "NE" if -totalYDirections > totalXDirections optimalDirections << "N" << "E" else optimalDirections << "E" << "N" end end return optimalDirections end if totalXDirections < 0 if totalYDirections > 0 optimalDirections << "SW" if totalYDirections > -totalXDirections optimalDirections << "S" << "W" else optimalDirections << "W" << "S" end else optimalDirections << "NW" if -totalYDirections > -totalXDirections optimalDirections << "N" << "W" else optimalDirections << "W" << "N" end end end return optimalDirections end firstLine = gets if firstLine == "BEGIN" puts "5 7 0" exit 0 end$sizeX, $sizeY = firstLine.split(' ').to_i, firstLine.split(' ').to_i$petriDish = Array.new($sizeX) { Array.new($sizeY) }
for y in 0..($sizeY - 1) line = gets chars = line.split('').reverse.drop(1).reverse # this gets every character but the last for x in 0..(chars.length - 1)$petriDish[x][y] = chars[x]
end
end
gets # blank line
info = gets
locX = info.split(' ').to_i
locY = info.split(' ').to_i
hp = info.split(' ').to_i
energy = info.split(' ').to_i

# dividing is our first priority
if(energy >= 5)
# try to divide towards enemies
dirs = directionTowardsEnemies(locX, locY)
directions = { "N" => [0, -1], "NE" => [1, -1], "E" => [1, 0],
"SE" => [1, 1], "S" => [0, 1], "SW" => [-1, 1],
"W" => [-1, 0], "NW" => [-1, -1] }
for dir in dirs
potentialNewX = locX + directions[dir]
potentialNewY = locY + directions[dir]
if $petriDish[potentialNewX][potentialNewY] == '.' puts "DIVIDE #{dir}" exit 0 end end # otherwise, just divide somewhere. surroundingCells(locX, locY).each do |k, v| if v == '.' puts "DIVIDE #{k}" exit 0 end end end # next, eating surroundingCells(locX, locY).each do |k, v| if v == 'c' puts "EAT #{k}" exit 0 end end # next, attacking surroundingCells(locX, locY).each do |k, v| attackStrength = 0 if (energy > 5) then # we want to save energy for dividing attackStrength = [(energy - 5), 3].min else attackStrength = [energy, 3].min end if v == 'x' puts "ATTACK #{k} #{attackStrength}" exit 0 end end # otherwise, rest puts "REST"  • I'm no Ruby programmer, so I wonder why some variables are normal and some start with a $. – seequ Jul 14 '14 at 11:59
• \$ is used to indicate a global variable. Yes, they're evil, but in this small program, it doesn't matter too much. – Alex Jul 14 '14 at 14:27
• Global variables are evil only in production code. Who minds them in scripts like this? – seequ Jul 14 '14 at 14:59
• Is my cell really the only one whose ability spread isn't 4-8-0? – Alex Jul 14 '14 at 15:36
• This is the best contender for my CoordinatedBacteria so far! I built my strategy based on the test result on your single-cell-organism. =) – justhalf Aug 27 '14 at 9:13

# Amoeba

First splits into four and then tries to get to the middle ground to limit the opponents replication space. Then starts replicating. When moving or replicating, finds the optimal path to the closest enemy, and moves or divides towards it, to try to cut off the enemy available space.

If an enemy is adjacent or one space away, will always attack or move towards it, allowing the row behind doing nothing to fill any empty spaces.

I haven't tested this against any other submissions so have no idea how well it will do.

var MAX_HP = 2;
var MAX_ENERGY = 10;
var ACIDITY = 0;

function PathfindingNode(_x, _y, _prevNode, _distance, _adjacentEnemies) {
this.x = _x;
this.y = _y;
this.prevNode = _prevNode;
this.distance = _distance;
}

PathfindingNode.prototype.GetDistance = function()
{
return this.distance;
}

var evaluatedNodes = {};
var initialNode = {};
var firstEval = true;

function evaluateNode(x, y, arena)
{
//get surrounding reachable nodes that havent already been checked

//if this node is adjacent to the start node - special case because the start node isnt an empty
if (firstEval)
adjacentEmpties.push({ 'x': initialNode.x, 'y': initialNode.y });

//find the optimal node to reach this one
var prevNode = null;
{
{

if (!prevNode) {
prevNode = currentNode;
}
else {
if(currentNode.GetDistance() < prevNode.GetDistance())
{
prevNode = currentNode;
}
}
}
}

var newNode = new PathfindingNode(x, y, prevNode, prevNode.GetDistance() + 1, adjacentEnemies.length);
evaluatedNodes[x + "," + y] = newNode;
}

function evaluateNeighbours(arena) {
//breadth first search all reachable cells
var nodesToEvaluate = [];
for (var i in evaluatedNodes) {
var emptyNodes = arena.getAdjacentMatches(arena.get(evaluatedNodes[i].x, evaluatedNodes[i].y), [".", "c"]);
//only ones that havent already been eval'd
for (var j in emptyNodes)
if (!evaluatedNodes[emptyNodes[j].x + "," + emptyNodes[j].y])
nodesToEvaluate.push(emptyNodes[j])
}

//have all available nodes been evaluated
if (nodesToEvaluate.length === 0)
return false;

for (var i in nodesToEvaluate)
{
evaluateNode(parseInt(nodesToEvaluate[i].x), parseInt(nodesToEvaluate[i].y), arena)
}

firstEval = false;
return true;
}

function getAllReachableNodes(arena, cell) {
//return a list of all reachable cells, with distance and optimal path
evaluatedNodes = {};

//add the first node to get started
var newNode = new PathfindingNode(parseInt(cell.x), parseInt(cell.y), null, 0, adjacentEnemies.length);
evaluatedNodes[cell.x + "," + cell.y] = newNode;
initialNode.x = parseInt(cell.x);
initialNode.y = parseInt(cell.y);
firstEval = true;

while (evaluateNeighbours(arena))
;

return evaluatedNodes;
}

function passedMiddleGround(arena)
{
for (var i = (parseInt(arena.width) / 2) - 1; i < parseInt(arena.width); i++)
{
for(var j = 0; j < parseInt(arena.height); j++)
{
if (arena.get(i, j).symbol == "o")
return true;
}
}
return false;
}

function decide(arena, cell, outputCallback) {

var nearbyEmpties = arena.getAdjacentMatches(cell.point, [".", "c"]);

if (nearbyEnemies.length > 4 && cell.energy >= cell.hp && cell.hp <= 3) {
outputCallback("EXPLODE");
return;
}

//attack whenever we get the chance. leave the replication to the cells doing nothing
if (cell.energy > 0 && nearbyEnemies.length > 0){
outputCallback("ATTACK " + arena.getDirection(cell, nearbyEnemies[(nearbyEnemies.length * Math.random()) | 0]) + " " + Math.min(cell.energy, 3));
return;
}

//if we are close to an enemy, move towards it. let the back line fill the new space
if (cell.energy > 2) {
for (var i = 0; i < nearbyEmpties.length; ++i) {
var space = nearbyEmpties[i];
outputCallback("MOVE " + arena.getDirection(cell, space));
return;
}
}
}

//yum
if (nearbyCorpses.length > 0) {
outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length * Math.random()) | 0]));
return;
}

//until we pass the middle ground, just keep moving into tactical position. afterwards we can start replication
if (passedMiddleGround(arena) && cell.energy < 5 && nearbyEmpties.length > 0)
{
outputCallback("REST");
return;
}

//try to block the opponent cells - interrupt their replication
//if we have enough energy to move, choose the best spot
if (nearbyEmpties.length > 0 && ((cell.energy >= 2 && nearbyEnemies.length == 0) || cell.energy >= 5)) {

var nextMove = null;

if (nearbyEmpties.length === 1) {
nextMove = nearbyEmpties;
}
else {
var reachableNodes = getAllReachableNodes(arena, cell);

//select nodes that have an adjacent enemy
var enemyNodesReachable = false;
for (var node in reachableNodes) {
if (reachableNodes.hasOwnProperty(node) && reachableNodes[node].adjacentEnemies > 0) {
enemyNodesReachable = true;
}
}

if (enemyNodesReachable)
{
//if there are any then select the closest one
var closest = null;
for (var node in enemyAdjacentNodes) {
if(!closest)
{
}
else{
{
}
}

}

//select the first move of the nodes path
//trace the selected node back to the first node to select the first move towards the cell.
while (closest.prevNode != null && closest.prevNode.prevNode != null)
{
closest = closest.prevNode;
}
nextMove = arena.get(closest.x, closest.y);
}
}

//a path to the enemy was found
if(nextMove)
{
//do this until we get half way across the board, then we just replicate
if (!passedMiddleGround(arena)) {
if (cell.energy >= 5) {
outputCallback("DIVIDE " + arena.getDirection(cell, nextMove));
return;
}

outputCallback("MOVE " + arena.getDirection(cell, nextMove));
return;
}
else {
outputCallback("DIVIDE " + arena.getDirection(cell, nextMove));
return;
}

}

}

//if theres no path to an enemy available, just divide anywhere
if (cell.energy >= 5 && nearbyEmpties.length > 0) {
outputCallback("DIVIDE " + arena.getDirection(cell, nearbyEmpties[(nearbyEmpties.length * Math.random()) | 0]));
return;
}

outputCallback("REST");
return;
}

var input = "";
// quiet stdin EPIPE errors
process.stdin.on("error", function(err) {
log("slight error: " + err);
});
process.stdin.on("data", function(data) {
input += data;
});
process.stdin.on("end", function() {
if(input == "BEGIN") {
// output space-separated attributes
process.stdout.write([MAX_HP, MAX_ENERGY, ACIDITY].join(" "));
clearLog();
} else {
// read in arena and decide on an action
var arena = new Arena();
var lines = input.split("\n");
var dimensions = lines.split(" ").map(function(d) { return parseInt(d); });
arena.width = dimensions;
arena.height = dimensions;
for(var y=1; y<=dimensions; ++y) {
for(var x=0; x<lines[y].length; ++x) {
arena.set(x, y-1, lines[y][x]);
}
}

var stats = lines[dimensions+2].split(" ");
var cell = { x: stats, y: stats, hp: stats, energy: stats, point: arena.get(stats, stats) };

// decide on an action and write the action to stdout
decide(arena, cell, function(output) { process.stdout.write(output); })
}
});

var Arena = function() {
this.dict = {};
};
Arena.prototype = {
// get Point object
get: function(x,y) {
if(!this.dict[x+","+y])
return 'w';
return this.dict[x+","+y];
},

// store Point object
set: function(x,y,d) {
this.dict[x+","+y] = new Point(x,y,d);
},

// get an array of all Points adjacent to this one whose symbol is contained in matchList
// if matchList is omitted, return all Points
var result = [];
for(var i=-1; i<=1; ++i) {
for(var j=-1; j<=1; ++j) {
var inspectedPoint = this.get(point.x+i, point.y+j);
if(inspectedPoint &&
(i!=0 || j!=0) &&
(!matchList || matchList.indexOf(inspectedPoint.symbol) != -1)) {
result.push(inspectedPoint);
}
}
}
return result;
},

// return the direction from point1 to point2
getDirection: function(point1, point2) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
dx = Math.abs(dx) / (dx || 1);
dy = Math.abs(dy) / (dy || 1);

c2d = { "0,0":"-",
"0,-1":"N", "0,1":"S", "1,0":"E", "-1,0":"W",
"-1,-1":"NW", "1,-1":"NE", "1,1":"SE", "-1,1":"SW" };

return c2d[dx + "," + dy];
}
}

var Point = function(x,y,d) {
this.x = x;
this.y = y;
this.symbol = d;
}
Point.prototype.toString = function() {
return "(" + this.x + ", " + this.y + ")";
}

• This is actually quite a good strategy, if only you make it less risk-taking by considering the number of neighboring friends before moving, otherwise other rushers can easily break through your thin defense line in early game (and hence only applicable in small boards) – justhalf Aug 28 '14 at 13:18
• Btw, this doesn't seem to work as intended if it's player 2. – justhalf Aug 28 '14 at 14:17

Simple cell done in node.js. Tested it agains examples node cell and against Kostronor it beats them.

Update

Still fairly simple, try to move towards enemy or divide.

// used in defining cell spec
var MAX_HP = 4;
var MAX_ENERGY = 8;
var ACIDITY = 0;

function decide(arena, cell, outputCallback) {

var nearbyEmpties = arena.getAdjacentMatches(cell.point, [".", "c"]);

if (nearbyFriends.length >= 8) {
outputCallback("REST");
return;
}

if (nearbyFriends.length >= 7 && nearbyEnemies.length < 0 && nearbyCorpses.length > 0 && energy < MAX_ENERGY) {
outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length*Math.random())|0]));
return;
}

// if you have two or more nearby enemies, explode if possible
if(nearbyEnemies.length >= 1
&& cell.energy >= cell.hp
&& cell.hp <= 1
&& nearbyEnemies.length > nearbyFriends.length) {
outputCallback("EXPLODE");
return;
}

// if you have two or more nearby enemies, explode if possible
if(nearbyEnemies.length >= 3 && cell.energy >= cell.hp && nearbyEnemies.length > nearbyFriends.length) {
outputCallback("EXPLODE");
return;
}

// if you have the energy and space to divide, do it
if(cell.energy >= 5 && nearbyEmpties.length > 0) {
var ed = arena.getEnemyDirection(cell);
if (nearbyEmpties.indexOf(ed) >= 0 && Math.random() < 0.5){
outputCallback("DIVIDE " + ed);
} else{
outputCallback("DIVIDE " + arena.getDirection(cell, nearbyEmpties[(nearbyEmpties.length*Math.random())|0]));
}
return;
}

// if at least one adjacent enemy, attack if possible
if(cell.energy > 0 && nearbyEnemies.length > 0) {
outputCallback("ATTACK " + arena.getDirection(cell, nearbyEnemies[(nearbyEnemies.length*Math.random())|0]) + " " + Math.min(cell.energy, 3));
return;
}

if (Math.random() < 0.5) {
for(var i=0; i<nearbyEmpties.length; ++i) {
outputCallback("MOVE " + arena.getEnemyDirection(cell));
return;
}
}

if (nearbyEmpties.length > 0 && nearbyEnemies.length <= 6) {
outputCallback("REST"); // because next turn is divide time
return;
}

// if there's a nearby corpse, eat it if your energy is below max
if(nearbyCorpses.length > 0) {
outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length*Math.random())|0]));
return;
}

outputCallback("REST");
return;
}

var input = "";
// quiet stdin EPIPE errors
process.stdin.on("error", function(err) {
console.log("slight error: " + err);
});
process.stdin.on("data", function(data) {
input += data;
});
process.stdin.on("end", function() {
if(input == "BEGIN") {
// output space-separated attributes
process.stdout.write([MAX_HP, MAX_ENERGY, ACIDITY].join(" "));
} else {
// read in arena and decide on an action
var arena = new Arena();
var lines = input.split("\n");
var dimensions = lines.split(" ").map(function(d) { return parseInt(d); });
arena.width = dimensions;
arena.height = dimensions;
for(var y=1; y<=dimensions; ++y) {
for(var x=0; x<lines[y].length; ++x) {
arena.set(x, y-1, lines[y][x]);
}
}

var stats = lines[dimensions+2].split(" ");
var cell = { x: stats, y: stats, hp: stats, energy: stats, point: arena.get(stats, stats) };

// decide on an action and write the action to stdout
decide(arena, cell, function(output) { process.stdout.write(output); })
}
});

var Arena = function() {
this.dict = {};
};
Arena.prototype = {
// get Point object
get: function(x,y) {
return this.dict[x+","+y];
},

// store Point object
set: function(x,y,d) {
this.dict[x+","+y] = new Point(x,y,d);
},

// get an array of all Points adjacent to this one whose symbol is contained in matchList
// if matchList is omitted, return all Points
var result = [];
for(var i=-1; i<=1; ++i) {
for(var j=-1; j<=1; ++j) {
var inspectedPoint = this.get(point.x+i, point.y+j);
if(inspectedPoint &&
(i!=0 || j!=0) &&
(!matchList || matchList.indexOf(inspectedPoint.symbol) != -1)) {
result.push(inspectedPoint);
}
}
}
return result;
},

// return the direction from point1 to point2
getDirection: function(point1, point2) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
dx = Math.abs(dx) / (dx || 1);
dy = Math.abs(dy) / (dy || 1);

c2d = { "0,0":"-",
"0,-1":"N", "0,1":"S", "1,0":"E", "-1,0":"W",
"-1,-1":"NW", "1,-1":"NE", "1,1":"SE", "-1,1":"SW" };

return c2d[dx + "," + dy];
},

getEnemyDirection: function(p) {
for (var i = 0; i < this.width; i++) {
for (var j = 0; j < this.height; j++) {
var found = this.get(i,j);
if (found != null && found.symbol == "x") {
return this.getDirection(p, found);
}
}
}
return "N"; //should never happen
}
}

var Point = function(x,y,d) {
this.x = x;
this.y = y;
this.symbol = d;
}
Point.prototype.toString = function() {
return "(" + this.x + ", " + this.y + ")";
}

• justhalf has identified a few serious bugs in the driver program (MOVE was cost-free and EXPLODE didn't account for acidity). If you're interested in retesting against the updated driver code and updating your submission, please let me know. If not, that's perfectly fine, too. – apsillers Aug 28 '14 at 13:27

# Evolution

This submission has evolved and is no longer a simple singe-cell organism! It tries to attack/explode whenever possible, otherwise it divides or moves towards the enemy. Moving should solve the problem of a cell surrounded by friendly cells with max energy, unable to do something useful.
After moving there is always 3 energy left to hit the enemy as hard as possible.

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class Evolution {
public static final int MAX_HP = 4;
public static final int MAX_ENERGY = 8;
public static final int ACIDITY = 0;

// given arena state and cell stats, return an action string (e.g., "ATTACK NW 2", "DIVIDE S")
public static String decide(Arena arena, Point cell, int hp, int energy) {

// more than 1 enemy around => explode if possible and worth it
if(nearbyEnemies.size() > 1 && energy > hp && hp <= 3 && nearbyEnemies.size() > nearbyFriends.size()) {
return "EXPLODE";
}

// enemies around => always attack with max strength
if(energy > 0 && nearbyEnemies.size() > 0) {
int attackStrength = Math.min(energy, 3);
Point enemy = nearbyEnemies.get(0);
return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength;
}

// safe spot => divide if possible
if(energy >= 5 && nearbyEmpty.size() > 0) {
Point randomEmpty = nearbyEmpty.get((int)Math.floor(nearbyEmpty.size()*Math.random()));
return "DIVIDE " + arena.getDirection(cell, randomEmpty);
}

// nearby corpse and missing energy => eat
if(nearbyCorpses.size() > 0 && energy < MAX_ENERGY) {
Point corpse = nearbyCorpses.get(0);
return "EAT " + arena.getDirection(cell, corpse);
}

// move towards enemy => constant flow of attacks
if(energy == 4) {
return "MOVE " + arena.getEnemyDirection(cell);
}

return "REST";
}

public static void main(String[] args) throws IOException {

String firstLine;

if(firstLine.equals("BEGIN")) {
System.out.println(MAX_HP + " " + MAX_ENERGY + " " + ACIDITY);
} else {
String[] dimensions = firstLine.split(" ");
int width = Integer.parseInt(dimensions);
int height = Integer.parseInt(dimensions);
Point[][] arena = new Point[height][];
String input;
int lineno = 0;

String[] charList = input.substring(1).split("");
arena[lineno] = new Point[width];
for(int i=0; i<charList.length; ++i) {
arena[lineno][i] = new Point(i, lineno, charList[i]);
}
lineno++;
}

int x = Integer.parseInt(stats);
int y = Integer.parseInt(stats);
int hp = Integer.parseInt(stats);
int energy = Integer.parseInt(stats);

Arena arenaObj = new Arena(arena, width, height);
System.out.print(decide(arenaObj, arenaObj.get(x,y), hp, energy));
}
}

public static class Arena {
public Point[][] array;
public HashMap<String, String> c2d;
public int height;
public int width;

public Arena(Point[][] array, int width, int height) {
this.array = array;
this.width = width;
this.height = height;

this.c2d = new HashMap<String, String>();
this.c2d.put("0,0", "-");
this.c2d.put("0,-1", "N");
this.c2d.put("0,1", "S");
this.c2d.put("1,0", "E");
this.c2d.put("-1,0", "W");
this.c2d.put("-1,-1", "NW");
this.c2d.put("1,-1", "NE");
this.c2d.put("-1,1", "SW");
this.c2d.put("1,1", "SE");
}

// get the character at x,y
// or return empty string if out of bounds
public Point get(int x, int y) {
if(y < 0 || y >= this.array.length){
return null;
}

Point[] row = this.array[y];

if(x < 0 || x >= row.length) {
return null;
}

return row[x];
}

// get arraylist of Points for each adjacent space that matches the target string
public ArrayList<Point> getAdjacentMatches(Point p, String match) {
ArrayList<Point> result = new ArrayList<Point>();
for(int i=-1; i<=1; ++i) {
for(int j=-1; j<=1; ++j) {
Point found = this.get(p.x+i, p.y+j);
if((i!=0 || j!=0) && found != null && found.symbol.equals(match)) {
}
}
}
return result;
}

// get the direction string from point 1 to point 2
public String getDirection(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
dx = Math.abs(dx) / (dx==0?1:dx);
dy = Math.abs(dy) / (dy==0?1:dy);

return this.c2d.get(dx + "," + dy);
}

public String getEnemyDirection(Point p) {
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
Point found = this.get(x,y);
if (found != null && found.symbol.equals("x")) {
return getDirection(p, found);
}
}
}
return "N"; //should never happen
}
}

public static class Point {
int x, y;
String symbol;

public Point(int x, int y, String sym) {
this.x=x;
this.y=y;
this.symbol=sym;
}
}
}

• justhalf has identified a few serious bugs in the driver program (MOVE was cost-free and EXPLODE didn't account for acidity). If you're interested in retesting against the updated driver code and updating your submission, please let me know. If not, that's perfectly fine. – apsillers Aug 28 '14 at 13:32

## Berserker

Because I used Clojure, which has some limitations, mainly the huge startup time, I took a little liverty. When the program is given BEGIN it outputs 4 6 2 LOOP, indicating that it doesn't stop. Then it takes the inputs as a continuous stream and ends with END. It doesn't save any state, which is made clear by not using any global variables or reusing return values. Because the implementation for this loopy action hasn't been done yet, I couldn't fully test the code (I hope the code is clear enough).

The cell gained it's name from it's nature of exploding whenever possible (and thus having acidity) and by prioritising attacking right after dividing.

I uploaded the generated jar-file to my Dropbox. Run with java -jar petridish-clojure.jar

Just to clarify:

> BEGIN
< 4 6 2 LOOP
> 10 4
> ..........
> ..xx.c....
> ...c...O..
> ......o...
>
> 3 4 6
< DIVIDE NW
> 10 4
> ..........
> ..xx.c....
> ...c.o.o..
> ......o...
>
> 5 2 4 1
< EAT N
> END

(ns petridish.core
(:require [clojure.string :as s])
(:gen-class))

(def ^:const maxhp     4)
(def ^:const maxenergy 6)
(def ^:const acidity   2)

(defn str->int
[x]
(if (empty? x)
0
(Integer. (re-find #"\d+" x))))

(defn sum-vectors [vec1 vec2]
(vec (map #(vec (map + % vec2)) vec1)))

(defn find-adjacent [[width height] board pos target]
(let [cells (sum-vectors [[-1 -1] [0 -1] [1 -1]
[-1  0]        [1  0]
[-1  1] [0  1] [1  1]]
pos)
directions ["NW" "N" "NE"
"W"      "E"
"SW" "S" "SE"]]
(for [cell cells
:when (and (> width  (cell 0) -1)
(> height (cell 1) -1)
(= target (get-in board (reverse cell))))]
(directions (.indexOf cells cell)))))

(defn decide [size board [x y hp energy]]
(let [friends (find-adjacent size board [x y] \o)
enemies (find-adjacent size board [x y] \x)
corpses (find-adjacent size board [x y] \c)
empty   (find-adjacent size board [x y] \.)]
(cond
(and (<= hp 3) (> energy hp) (seq enemies))
"EXPLODE"
(and (>= energy 5) (seq empty))
(str "DIVIDE " (first empty))
(and (>= energy 3) (seq enemies))
(str "ATTACK " (first enemies) " " (min 3 energy))
(and (< energy maxenergy) (seq corpses))
(str "EAT " (first corpses))
(or (and (<= 5 energy maxenergy) (not (seq empty))) (< energy 5))
"REST"
(seq empty)
(str "MOVE " (rand-nth empty)))))

(let [result (vec (for [i (range height)]
(read-line) ; Skip the empty line
result))

(loop []
(when (not= firstline "END")
(println
(if (= firstline "BEGIN")
(str maxhp " " maxenergy " " acidity " LOOP")
(let [size   (map str->int (s/split firstline #"\s+"))
status (map str->int (s/split (read-line) #"\s+"))]
(decide size board status))))
(recur)))))

(defn -main []


Update log

1. Fixed the logic a little and removed redundancies.

• Nice use of acidity- in fact, I think this is the only bot that uses acidity at all. – Alex Jul 16 '14 at 19:10
• @Alex We'll see how it works out, but I think this should be able to clear out the Amoeba. What do you think of the code? I'm so new to clojure. – seequ Jul 16 '14 at 19:36
• In your example, how can the newly spawned cell move? I thought you need to wait for one more turn? – justhalf Aug 27 '14 at 5:13
• @justhalf Eh, cells do not know how old they are. – seequ Aug 27 '14 at 6:53
• Yes, but the controller knows, right? It's not supposed to give a turn to the newly formed cell. – justhalf Aug 27 '14 at 7:53

## Hungry, hungry bot

Here is an entry in R. I hope I understood correctly what were the technical specs on how to communicate with your program. Should be triggered with Rscript Hungryhungrybot.R.
If it has at least 6 of energy it divides, preferentially in the direction of the enemy. Otherwise it eats whatever's next to it or whatever's reachable. If no food is reachable then it will either explode when there is more enemies around than sister cells, or fight with nearby enemies. Rests only if energy is 0 and nothing to eat is available.

infile <- file("stdin")
open(infile)
if(input1=="BEGIN"){
out <- "4 7 1"
}else{
nr <- as.integer(strsplit(input1," ")[])
nc <- as.integer(strsplit(input1," ")[])
arena <- do.call(rbind,strsplit(input2[1:nr],""))
stats <- strsplit(input2[nr+2]," ")[]
coords <- as.integer(stats[2:1])+1
hp <- as.integer(stats)
nrj <- as.integer(stats)
closest <- function(coords,arena,object){
a <- which(arena==object,arr.ind=TRUE)
if(length(a)){
d <- apply(a,1,function(x)max(abs(x-coords)))
b <- which.min(d)
f <- a[b,]
dir <- f-coords
where <- ""
if(dir<0)where <- paste(where,"N",sep="")
if(dir>0)where <- paste(where,"S",sep="")
if(dir<0)where <- paste(where,"W",sep="")
if(dir>0)where <- paste(where,"E",sep="")
dist <- d[b]
}else{dist <- NA; where <- ""}
list(dist,where)
}
near <- expand.grid((coords-1):(coords+1),(coords-1):(coords+1))
near <- near[near[,1]<=nr&near[,2]<=nc,]
w <- matrix(c('NW','N','NE','W','','E','SW','S','SE'),nr=3,byrow=TRUE)
if(coords==1) w <- w[-1,]
if(coords==nr) w <- w[-3,]
if(coords==1) w <- w[,-1]
if(coords==nc) w <- w[,-3]
if(any(arena=="c")){food <- closest(coords,arena,"c")}else{food <- list(nrj+2,"")}
enemies <- closest(coords,arena,"x")
if(nrj>=6){
if(!length(empties)){
out <- "EXPLODE"
}else{out <- "REST"}
}else if(enemies[]%in%empties & enemies[]!=1){
out <- paste("DIVIDE", enemies[])
}else{
out <- paste("DIVIDE", empties)
}
}else{
out <- "REST"
}else{
}else if(any(arena=="c") & food[]<=(nrj+1)){
out <- paste("MOVE",food[])
out <- "EXPLODE"
}else{
out <- paste("MOVE", enemies[])
}
}
}
}
cat(out)
flush(stdout())

• I'm (finally) trying to run the challenge, and I keep getting Error: unexpected 'else' in "else" in your code. I afraid I don't know R at all, so I can't begin to solve this error. For reference, I get this error both when I run it in the driver and when I simply run the program and manually type BEGIN. – apsillers Aug 21 '14 at 22:35
• @apsillers arf i added a newline where i shouldn t have: it should work now. – plannapus Aug 22 '14 at 7:15
• That fixed that error so we can get through cell init; now I'm getting another one when the game actually starts: Error in if (dir < 0) where <- paste(where, "N", sep = "") : missing value where TRUE/FALSE needed – apsillers Aug 23 '14 at 0:13
• Now the first turn runs fine, but subsequent turns produce Error: object 'food' not found (when facing off against Alex's Ruby submission, possibly others) – apsillers Aug 26 '14 at 0:31
• You cell now runs just fine, thanks! :) However, justhalf has identified a few serious bugs in the driver program (MOVE was cost-free and EXPLODE didn't account for acidity). If you're interested in retesting against the updated driver code and updating your submission, please let me know. If not, that's perfectly fine. – apsillers Aug 28 '14 at 13:33

### Coordinated Bacteria

I hope I'm not too late.

Win against other opponents (and always by killing them all -- after many rounds), in my tests, and the battle will never end if it faces itself, an evidence that the strategy is strong. Always win within the 150 rounds limit, and if continued indefinitely will always kill all.

When you are single-celled, you can memorize previous state, but you can exploit your own position to behave differently! =)

This will divide the bacteria into divider and mover, and in doing so will keep more bacteria useful instead of just the front line, while keeping the defense line up.

It also coordinates its attacks to focus on specific enemy, so that enemies get killed faster (this is to face my other single-cell which focuses on HP).

In mid-game, which is detected by the number of cells on the board, they will try to shove into enemy territory by out-flanking them. This is the key winning strategy.

This has the highest growth rate compared to all other opponents currently, but it has a slow start, so this works better on large arena.

Run it with java CoordinatedBacteria

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class CoordinatedBacteria {
public static final int MAX_HP = 6;
public static final int MAX_ENERGY = 6;
public static final int ACIDITY = 0;

// given arena state and cell stats, return an action string (e.g., "ATTACK NW 2", "DIVIDE S")
public static String decide(final Arena arena, Point cell, int hp, int energy) {
// empty and corpses are free for movement and division
final Point2D enemyCenter = arena.getCenterOf("x");
final Point2D ourCenter = arena.getCenterOf("o");
final int moverPos = (enemyCenter.x <= ourCenter.x || enemyCenter.y <= ourCenter.y) ? (arena.width+arena.height+1)%2 : 1;
final int attackPos = (enemyCenter.x <= ourCenter.x || enemyCenter.y <= ourCenter.y) ? (arena.width+arena.height)%2 : 1;

int selfCount = arena.count("o");
boolean isMidWay = selfCount > (arena.width*arena.height/2-1);

if(!isMidWay){
if(enemyCenter.x < ourCenter.x){
enemyCenter.x = 0;
enemyCenter.y = 0;
ourCenter.x = arena.width;
ourCenter.y = arena.height;
} else {
enemyCenter.x = arena.width;
enemyCenter.y = arena.height;
ourCenter.x = 0;
ourCenter.y = 0;
}
}
Collections.sort(nearbyEmpty, new Comparator<Point>(){
@Override
public int compare(Point o1, Point o2) {
+ distance(o1.x, o1.y, enemyCenter.x, enemyCenter.y)*100;
+ distance(o1.x, o1.y, enemyCenter.x, enemyCenter.y)*100;
return Double.compare(score2, score1);
}
});
Collections.sort(nearbyEnemies, new Comparator<Point>(){
@Override
public int compare(Point o1, Point o2) {
*10
+ (isAtBoundary(o1, arena)?1000:0)
+ (o1.x + o1.y + attackPos + 1)%2;
*10
+ (isAtBoundary(o2, arena)?1000:0)
+ (o2.x + o2.y + attackPos + 1)%2;
return Integer.compare(score2, score1);
}
});
Collections.sort(nearbyCorpses, new Comparator<Point>(){
@Override
public int compare(Point o1, Point o2) {
return Integer.compare(score1, score2);
}
});

for(Point empty: nearbyEmpty){
if(nearbyFriends.size()>=2 && energy >= 1 && arena.getAdjacentMatches(empty, "x").size()==3 && isAtBoundary(empty, arena)){
return "MOVE "+arena.getDirection(cell, empty);
}
}

for(Point empty: nearbyCorpses){
if(nearbyFriends.size()>=2 && energy >= 1 && arena.getAdjacentMatches(empty, "x").size()==3 && isAtBoundary(empty, arena)){
return "MOVE "+arena.getDirection(cell, empty);
}
}

if ((cell.x+cell.y)%2 == moverPos && energy >= 1 && energy <= 5){
if(nearbyEmpty.size()>0){
Point foremost = nearbyEmpty.get(0);
if(nearbyFriends.size() >= 4){
return "MOVE "+arena.getDirection(cell, foremost);
}
}
if(nearbyCorpses.size() > 0) {
Point corpse = nearbyCorpses.get(0);
return "EAT " + arena.getDirection(cell, corpse);
}

if(energy > 0 && nearbyEnemies.size() > 0) {
int attackStrength = Math.min(energy, 3);
Point enemy = nearbyEnemies.get(0);
return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength;
}

if(nearbyFriends.size() >= 4 && nearbyEmpty.size() > 0){
Point movePoint = getBestPointToDivide(arena, nearbyEmpty);
return "MOVE " + arena.getDirection(cell, movePoint);
}
}

if(energy >= 5 && nearbyEmpty.size() > 0) {
Point divisionPoint = getBestPointToDivide(arena, nearbyEmpty);
if(energy == MAX_ENERGY && nearbyFriends.size() >= 5
&& distance(enemyCenter.x, enemyCenter.y, cell.x, cell.y) > distance(enemyCenter.x, enemyCenter.y, divisionPoint.x, divisionPoint.y)){
return "MOVE " + arena.getDirection(cell, divisionPoint);
}
return "DIVIDE " + arena.getDirection(cell, divisionPoint);
}

if(nearbyCorpses.size() > 0) {
Point corpse = nearbyCorpses.get(0);
if (energy < MAX_ENERGY){
return "EAT " + arena.getDirection(cell, corpse);
} else {
return "DIVIDE " + arena.getDirection(cell, corpse);
}
}

if(energy >= 5 && nearbyCorpses.size() > 0) {
Point divisionPoint = getBestPointToDivide(arena, nearbyCorpses);
if(energy == MAX_ENERGY && nearbyFriends.size() >= 5
&& distance(enemyCenter.x, enemyCenter.y, cell.x, cell.y) < distance(enemyCenter.x, enemyCenter.y, divisionPoint.x, divisionPoint.y)){
return "MOVE " + arena.getDirection(cell, divisionPoint);
}
return "DIVIDE " + arena.getDirection(cell, divisionPoint);
}

// if at least one adjacent enemy, attack if possible
if(energy > 0 && nearbyEnemies.size() > 0) {
int attackStrength = Math.min(energy, 3);
Point enemy = nearbyEnemies.get(0);
return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength;
}

return "REST";

}

public static boolean isAtBoundary(Point point, Arena arena){
return point.x==0 || point.x==arena.width-1 || point.y==0 || point.y==arena.height-1;
}

public static double distance(double x1, double y1, double x2, double y2){
return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);
}

public static Point getBestPointToDivide(Arena arena, List<Point> nearbyEmpty){
Point result = null;
double minDist = 100000;
List<Point> mostEmpty = new ArrayList<Point>();
int max = -1000;
List<Point> neighbor = nearbyEmpty;
for(Point point: neighbor){
if(emptyNeighborScore > max){
mostEmpty = new ArrayList<Point>();
max = emptyNeighborScore;
} else if(emptyNeighborScore == max){
}
}
for(Point point: mostEmpty){
Point2D enemyCenter = arena.getCenterOf("x");
double dist = Math.pow(point.x-enemyCenter.x, 2) + Math.pow(point.y-enemyCenter.y, 2);
if(dist < minDist){
minDist = dist;
result = point;
}
}
return result;
}

public static void main(String[] args) throws IOException {

String firstLine;

if(firstLine.equals("BEGIN")) {
System.out.println(MAX_HP + " " + MAX_ENERGY + " " + ACIDITY);
} else {
String[] dimensions = firstLine.split(" ");
int width = Integer.parseInt(dimensions);
int height = Integer.parseInt(dimensions);
Point[][] arena = new Point[height][];
String input;
int lineno = 0;

char[] charList = input.toCharArray();
arena[lineno] = new Point[width];
for(int i=0; i<charList.length; ++i) {
arena[lineno][i] = new Point(i, lineno, charList[i]);
}
lineno++;
}

int x = Integer.parseInt(stats);
int y = Integer.parseInt(stats);
int hp = Integer.parseInt(stats);
int energy = Integer.parseInt(stats);

Arena arenaObj = new Arena(arena, width, height);
System.out.print(decide(arenaObj, arenaObj.get(x,y), hp, energy));
}
}

public static class Arena {
public Point[][] array;
public HashMap<String, String> c2d;
public int height;
public int width;

public Arena(Point[][] array, int width, int height) {
this.array = array;
this.width = width;
this.height = height;

this.c2d = new HashMap<String, String>();
this.c2d.put("0,0", "-");
this.c2d.put("0,-1", "N");
this.c2d.put("0,1", "S");
this.c2d.put("1,0", "E");
this.c2d.put("-1,0", "W");
this.c2d.put("-1,-1", "NW");
this.c2d.put("1,-1", "NE");
this.c2d.put("-1,1", "SW");
this.c2d.put("1,1", "SE");
}

// get the character at x,y
// or return empty string if out of bounds
public Point get(int x, int y) {
if(y < 0 || y >= this.array.length){
return null;
}

Point[] row = this.array[y];

if(x < 0 || x >= row.length) {
return null;
}

return row[x];
}

// get arraylist of Points for each adjacent space that matches the target string
public ArrayList<Point> getAdjacentMatches(Point p, String match) {
ArrayList<Point> result = new ArrayList<Point>();
for(int i=-1; i<=1; ++i) {
for(int j=-1; j<=1; ++j) {
Point found = this.get(p.x+i, p.y+j);
if((i!=0 || j!=0) && found != null && found.symbol.equals(match)) {
}
}
}
return result;
}

ArrayList<Point> result = new ArrayList<Point>();
for(int i=-1; i<=1; ++i) {
for(int j=-1; j<=1; ++j) {
Point found = this.get(p.x+i, p.y+j);
if((i!=0 || j!=0) && found != null) {
}
}
}
return result;
}

public int count(String sym){
int result = 0;
for(int y=0; y<array.length; y++){
for(int x=0; x<array[y].length; x++){
Point cur = this.get(x, y);
if(cur!=null && cur.symbol.equals(sym)){
result++;
}
}
}
return result;
}

// get the direction string from point 1 to point 2
public String getDirection(Point p1, Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
dx = Math.abs(dx) / (dx==0?1:dx);
dy = Math.abs(dy) / (dy==0?1:dy);

return this.c2d.get(dx + "," + dy);
}

public Point2D getCenterOf(String sym){
Point2D result = new Point2D(0,0);
int count = 0;
for(int y=0; y<array.length; y++){
for(int x=0; x<array[y].length; x++){
if(this.get(x,y).symbol.equals(sym)){
result.x += x;
result.y += y;
count++;
}
}
}
result.x /= count;
result.y /= count;
return result;
}

}

public static class Point {
int x, y;
String symbol;

public Point(int x, int y, String sym) {
this.x=x;
this.y=y;
this.symbol=sym;
}

public Point(int x, int y, char sym){
this(x, y, ""+sym);
}
}

public static class Point2D{
double x,y;
public Point2D(double x, double y){
this.x = x;
this.y = y;
}
}
}


I think i will post my submission, since you are so generous to add the boilerplate logic...

There was a problem in your logic, where the eat-action would issue an ATTACK instead of an EAT and would waste the corpse.

I have modified your gist just as much to have a working solution, that should perform relatively well. It starts with 4 hp and 8 energy, so after a split and a rest, both cells can split again. It will try to multiply itself, attack enemies, eat corpses and rest, in this order. So inner cells will store their 8 energy points, to quickly replace killed outer cells and leave them 3 energy points to make a 3 point attack or multiply themselves after one turn rest. The 4 hp are to survive at least one full force attack.

acid seems to be a waste of points for me so i kept it out...

I did not tested the submission, as it was a 2 minute thing ;)

here is my code:

/*
Sample code for a "Battle for the Petri Dish" cell

Released under the terms of the WTF Public License
No warranty express or implied is granted, etc, etc.

I just hacked this together very quickly; improvements are welcome, so please fork the Gist if you like.

used this code for a submission @kostronor

*/

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class SlimeCell {
public static final int MAX_HP = 4;
public static final int MAX_ENERGY = 8;
public static final int ACIDITY = 0;

// given arena state and cell stats, return an action string (e.g., "ATTACK NW 2", "DIVIDE S")
public static String decide(final Arena arena, final Point cell, final int hp, final int energy) {
// empty and corpses are free for movement and division

// if you have energy and space to divide, divide into a random space
if((energy >= 5) && (nearbyEmpty.size() > 0)) {
Point randomEmpty = nearbyEmpty.get((int)Math.floor(nearbyEmpty.size()*Math.random()));
return "DIVIDE " + arena.getDirection(cell, randomEmpty);
}

// if at least one adjacent enemy, attack if possible
if((energy > 0) && (nearbyEnemies.size() > 1)) {
int attackStrength = Math.min(energy, 3);
Point enemy = nearbyEnemies.get((int)Math.floor(nearbyEnemies.size()*Math.random()));
return "ATTACK " + arena.getDirection(cell, enemy) + " " + attackStrength;
}

// if there's a nearby corpse, eat it if your energy is below max
if(nearbyCorpses.size() > 0) {
Point corpse = nearbyCorpses.get((int)Math.floor(nearbyCorpses.size()*Math.random()));
return "EAT " + arena.getDirection(cell, corpse);
}

return "REST";

}

public static void main(final String[] args) throws IOException {

String firstLine;

if(firstLine.equals("BEGIN")) {
System.out.println(MAX_HP + " " + MAX_ENERGY + " " + ACIDITY);
} else {
String[] dimensions = firstLine.split(" ");
int width = Integer.parseInt(dimensions);
int height = Integer.parseInt(dimensions);
Point[][] arena = new Point[height][];
String input;
int lineno = 0;

String[] charList = input.substring(1).split("");
arena[lineno] = new Point[width];
for(int i=0; i<charList.length; ++i) {
arena[lineno][i] = new Point(i, lineno, charList[i]);
}
lineno++;
}

int x = Integer.parseInt(stats);
int y = Integer.parseInt(stats);
int hp = Integer.parseInt(stats);
int energy = Integer.parseInt(stats);

Arena arenaObj = new Arena(arena, width, height);
System.out.print(decide(arenaObj, arenaObj.get(x,y), hp, energy));
}
}

public static class Arena {
public Point[][] array;
public HashMap<String, String> c2d;
public int height;
public int width;

public Arena(final Point[][] array, final int width, final int height) {
this.array = array;
this.width = width;
this.height = height;

this.c2d = new HashMap<String, String>();
this.c2d.put("0,0", "-");
this.c2d.put("0,-1", "N");
this.c2d.put("0,1", "S");
this.c2d.put("1,0", "E");
this.c2d.put("-1,0", "W");
this.c2d.put("-1,-1", "NW");
this.c2d.put("1,-1", "NE");
this.c2d.put("-1,1", "SW");
this.c2d.put("1,1", "SE");
}

// get the character at x,y
// or return empty string if out of bounds
public Point get(final int x, final int y) {
if((y < 0) || (y >= this.array.length)){
return null;
}

Point[] row = this.array[y];

if((x < 0) || (x >= row.length)) {
return null;
}

return row[x];
}

// get arraylist of Points for each adjacent space that matches the target string
public ArrayList<Point> getAdjacentMatches(final Point p, final String match) {
ArrayList<Point> result = new ArrayList<Point>();
for(int i=-1; i<=1; ++i) {
for(int j=-1; j<=1; ++j) {
Point found = this.get(p.x+i, p.y+j);
if(((i!=0) || (j!=0)) && (found != null) && found.symbol.equals(match)) {
}
}
}
return result;
}

// get the direction string from point 1 to point 2
public String getDirection(final Point p1, final Point p2) {
int dx = p2.x - p1.x;
int dy = p2.y - p1.y;
dx = Math.abs(dx) / (dx==0?1:dx);
dy = Math.abs(dy) / (dy==0?1:dy);

return this.c2d.get(dx + "," + dy);
}

}

public static class Point {
int x, y;
String symbol;

public Point(final int x, final int y, final String sym) {
this.x=x;
this.y=y;
this.symbol=sym;
}
}
}


Since you so kindly provided boilerplate code, I decided to make my own simple cell; This cell has 4 acidity, only 1 hp and 7 energy. It tries to get out of range of friendlies and then waits there (or eats if possible) until it gets the chance to blow up or replicate. Attacks only if it's the only option.

It's a pretty ballsy strategy and will probably perform badly, but I'm curious to see how it does. I'll test it and improve it later today, maybe.

/*
Sample code for a "Battle for the Petri Dish" cell

Released under the terms of the WTF Public License,
No warranty express or implied is granted, etc, etc.

I just hacked this together very quickly; improvements are welcome, so please fork the Gist if you like.
*/

// used in defining cell spec
var MAX_HP = 1;
var MAX_ENERGY = 7;
var ACIDITY = 4;

/*
The decide function takes an Arena object (see below for prototype methods), a cell object,
and an outputCallback, which accepts a command string to output
*/
function decide(arena, cell, outputCallback) {
var nearbyEmpties = arena.getAdjacentMatches(cell.point, [".", "c"]);

//attempt to move away from friendlies if possible
if(nearbyFriendlies.length>1 && cell.energy>0)
{
for(var i=0; i<nearbyEmpties.length; ++i)
{
var space = nearbyEmpties[i];
{
outputCallback("MOVE " + arena.getDirection(cell,space));
return;
}
}
}

// Explode if there are two more adjacent enemies than friendlies or enemies and no friendlies.
if((nearbyEnemies.length - nearbyFriendlies.length > 1 || (nearbyEnemies.length>0 && nearbyFriendlies.length == 0))
&& cell.energy >= cell.hp && cell.hp <= 3)
{
outputCallback("EXPLODE");
return;
}

// if you have the energy and space to divide, and there's a way for the child to get away from friendlies, do it.
if(cell.energy >= 5 && nearbyEmpties.length > 0)
{
for(var i=0; i<nearbyEmpties.length; ++i)
{
var space = nearbyEmpties[i];
for(var i=0; i<possiblePositions.length; ++i)
{
{
outputCallback("DIVIDE " + arena.getDirection(cell,space));
return;
}
}
}
}

// if at least one adjacent enemy, attack if possible
if(cell.energy > 0 && nearbyEnemies.length > 0)
{
outputCallback("ATTACK " + arena.getDirection(cell, nearbyEnemies[(nearbyEnemies.length*Math.random())|0]) + " " + Math.min(cell.energy, 3));
return;
}

// if there's a nearby corpse, eat it if your energy is below max
if(nearbyCorpses.length > 0)
{
outputCallback("EAT " + arena.getDirection(cell, nearbyCorpses[(nearbyCorpses.length*Math.random())|0]));
return;
}

outputCallback("REST");
return;
}

var input = "";
// quiet stdin EPIPE errors
process.stdin.on("error", function(err) {
//console.log("slight error: " + err);
});
process.stdin.on("data", function(data) {
input += data;
});
process.stdin.on("end", function() {
if(input == "BEGIN") {
// output space-separated attributes
process.stdout.write([MAX_HP, MAX_ENERGY, ACIDITY].join(" "));
} else {
// read in arena and decide on an action
var arena = new Arena();
var lines = input.split("\n");
var dimensions = lines.split(" ").map(function(d) { return parseInt(d); });
arena.width = dimensions;
arena.height = dimensions;
for(var y=1; y<=dimensions; ++y) {
for(var x=0; x<lines[y].length; ++x) {
arena.set(x, y-1, lines[y][x]);
}
}

var stats = lines[dimensions+2].split(" ");
var cell = { x: stats, y: stats, hp: stats, energy: stats, point: arena.get(stats, stats) };

// decide on an action and write the action to stdout
decide(arena, cell, function(output) { process.stdout.write(output); })
}
});

var Arena = function() {
this.dict = {};
};
Arena.prototype = {
// get Point object
get: function(x,y) {
return this.dict[x+","+y];
},

// store Point object
set: function(x,y,d) {
this.dict[x+","+y] = new Point(x,y,d);
},

// get an array of all Points adjacent to this one whose symbol is contained in matchList
// if matchList is omitted, return all Points
var result = [];
for(var i=-1; i<=1; ++i) {
for(var j=-1; j<=1; ++j) {
var inspectedPoint = this.get(point.x+i, point.y+j);
if(inspectedPoint &&
(i!=0 || j!=0) &&
(!matchList || matchList.indexOf(inspectedPoint.symbol) != -1)) {
result.push(inspectedPoint);
}
}
}
return result;
},

// return the direction from point1 to point2
getDirection: function(point1, point2) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
dx = Math.abs(dx) / (dx || 1);
dy = Math.abs(dy) / (dy || 1);

c2d = { "0,0":"-",
"0,-1":"N", "0,1":"S", "1,0":"E", "-1,0":"W",
"-1,-1":"NW", "1,-1":"NE", "1,1":"SE", "-1,1":"SW" };

return c2d[dx + "," + dy];
}
}

var Point = function(x,y,d) {
this.x = x;
this.y = y;
this.symbol = d;
}
Point.prototype.toString = function() {
return "(" + this.x + ", " + this.y + ")";
}

• I'm trying to test it but I'm not getting it to run. I installed node.js tried the command line node c:/cells/petri.js 'node c:/cells/bomber.js' 'node c:/cells/sample.js. When I type this in the node application console, I just get three dots, when i try and run it in the windows cmd, I get: 'node' is not recognized as an internal or external command, operable program or batch file. I did save all of the files as .js files in the correct folder. ANy help for a noob? I'd go to the chat or comment somewhere else, but my rep is too low. – overactor Jul 19 '14 at 12:43
• Since I can't test, for now, it's be cool if someone could tell me how my cells do against theirs. I'm second guessing my tactic, or at least thinking it needs refining. – overactor Jul 19 '14 at 18:18
• You seem to have a type on the line if((nearbyEnemies.length - nearbyFriendlies.length > 1 ¦¦  -- those ¦¦ don't seem to be a valid operator and you have mismatched parentheses. I think maybe the code formatting got messed up when you posted it? – apsillers Aug 27 '14 at 22:22
• This performs quite badly according to my tests. You have a lot of assignments (=) when what you want is equality comparison (==). – justhalf Aug 28 '14 at 6:00
• Oh, darn. I was mostly programming in a language where (=) is assignment back when I wrote this, does it run better now? I never expected it to do great though. – overactor Aug 28 '14 at 6:07