text:
Risk, the Warlight Way
Introduction
In this game, players use their armies to fight other players' armies, capture territories, and become the last man standing. Each turn, players receive a base number of armies to use at their disposal. By capturing territories in certain regions, however, players can increase this number to give them a potential advantage later in the game. (This is essentially the same as Warlight).
All bots should be written in Java , C, or C++ (I would include other languages but don't have the software or experience for them). It is not necessary for your submission to extend a class, and you may create functions, classes, interfaces, or whatever else is necessary, and use any package or class in the standard APIs. If you are planning on creating a class or interface, please consider using an inner class or inner interface.
Please do not attempt to programmatically alter the controller or other submissions in this competition.
Gameplay
Overview
A 10x10 two-dimensional array will simulate the board, each element/cell representing a "territory". There will be 20 rounds and up to 1000 turns per round. Each turn, players will first deploy the armies they have to any of the territories they own, and then be given the opportunity to transport their armies to nearby territories in an attempt to capture their opponents' territories by attacking the armies in them. Players must deploy all their armies, but they do not have to move them if desired.
Attacking/Transferring armies
If the player desires, he/she can send armies from one territory to any of the eight adjacent ones. The board "wraps around", i.e. if a player's territory is on one side, armies from it can be transferred to an adjacent territory on the other side. When moving armies from a territory, there should still be at least one army left in that territory. For example, if a territory contains five armies, no more than four can be moved to a different territory; if a territory contains one, that army cannot move.
If a player sends n armies from one territory to another that they own, that territory will receive n armies.
Say a player sends n armies from his/her territory to an opposing territory with o armies in it. o will decrease by n * .6 rounded to the nearest integer; however, at the same time, n will decrease by o * .7 rounded to the nearest integer. The following rules dealing with whether or not the opposing territory has been captured will apply:

If o reaches zero AND n is greater than 0, the player will take over the territory, which will have n armies in it.
If both n and o become zero, o will automatically be set to 1 and the territory will not be captured.
If o remains greater than 0, the number of armies in the player's territory will increase by n and the opposing territory will not be captured.

Bonuses
A group of territories will be chosen to represent a bonus; if one player owns all the territories that are part of the group, that player will receive an extra amount of armies per turn.
Bonuses have id numbers to denote different ones and values that represent the extra number of armies that a player can receive. Each round, a bonus's value will be a random number between 5 and 10, inclusive, and ten bonuses will be available on the field, each with ten territories included in the bonus.
For example, if a player that receives 5 armies per turn owns all the territories that make up a bonus with a value of 8, the player will receive 13 armies the next turn and subsequent turns. If, however, the player loses one or more of the territories that make up the bonus, he or she will receive just 5 armies per turn.
Input/Output
Your program should take input through command-line arguments, which will have the following format:
[id] [armies] [territories (yours and all adjacent ones)] [bonuses] ["X" (if first turn)]

id and armies are both whole numbers. id is your id, and armies is the number of armies you need to deploy to your territories. You must deploy all the armies given to you -- no more and no less.
territories is a series of strings representing the territories you own and the territories that you do not own that are adjacent to yours. The strings are in this format:
[row],[col],[bonus id],[player id],[armies]

row and col indicate the row and column of the board where the territory is, bonus id is the id of the bonus that this territory is a part of, player id is the id of the player who owns the territory, and armies is the number of armies contained in the territory. These are all numbers.
bonuses is a series of strings representing the bonuses on the board that you can take advantage of. The strings are in this format:
[id],[armies],[territories left]

id is the id of the bonus, armies is the number of extra armies you can receive by owning all the territories in this bonus, and territories left is the number of territories in the bonus that you need to capture to receive the extra armies.

Please note that a fifth argument, an "X", will appear if it is the first turn of a round and can be used for convenience reasons.
An example of input on the first turn:
0 5 "7,6,7,-1,2 8,7,7,-1,2 7,7,7,0,5 6,6,7,-1,2 8,8,9,-1,2 6,7,7,-1,2 7,8,9,-1,2 6,8,9,-1,2 8,6,7,-1,2" "0,5,10 1,5,10 2,9,10 3,9,10 4,9,10 5,5,10 6,5,10 7,6,9 8,7,10 9,7,10" X

Your program must output two strings separated by a newline, the first of which lists the rows and columns of the territories which you want to add armies to and the number of armies you want to add to it, and the second of which lists the rows and columns of the territories you want to send armies to and the number of armies you want to send. The output may contain trailing spaces.
To specify a territory you want to add armies to, your output should follow this format:
[row],[col],[armies]

row and col are the row and column of the board where the territory you want to add armies to is, and armies is the number of armies you want to add to the territory.
To specify which territories you want to send armies to, your output should follow this format:
[srow],[scol],[drow],[dcol],[armies]

srow and scol are the row and column of the board where the territory you want to transport armies from is, drow and dcol are the row and column of the board where the territory you want to send armies to is, and armies is the number of armies you want to send. Note that if you do not want to move any armies, your program should print a space.
A sample output may be this:
0,0,5
0,0,0,1,3 0,0,1,0,3 0,0,1,1,3

In this case, the player deploys five armies to the territory at 0,0 and moves three armies from 0,0 to 0,1; three from 0,0 to 1,0; and three from 0,0 to 1,1.
Rounds and Turns
At the start of each round, all players will be given one territory located in a random spot on the board (it is possible for two or more players to start next to each other). The territories that make up a bonus may also change.
On the first turn, each player will have one territory containing five armies, and they will receive five armies they can use (this is the minimum that they can receive). All the other territories will be owned by NPCs that do not attack; each of these contain two armies and have an id of -1.
Each turn your program will be run, and both pieces of output will be collected. The controller will apply the first piece of output, adding armies to territories, immediately; however, the controller will wait until all players have given their second piece of output, their attack/transfer commands. Once this has been completed, the commands will be shuffled randomly and then executed. Your program must provide output and terminate in one second or less in order to participate in the turn.
Scoring and Winning
For any given round, if one player remains, that player will earn 100 points. Otherwise, if 1000 turns pass and there are still multiple players, the 100 points will be divided evenly between the remaining players (i.e. 3 players remaining yields 33 points each). Whichever player has the most points at the end of the 20 rounds will win.
Submissions
Your post should include a name for the bot, the language it is written in, a brief description of it, and the code used to run it. A sample bot will be posted here as an example and will be used in the contest. You may submit as many as you wish.
Other
Your program may create, write to, and read from a file as long as the file's name is the same as the name you used for your submission. These files will be deleted prior to the beginning of a tournament but not in between rounds.
Your turn will be skipped if:

you are eliminated (have no territories);
your program does not print anything;
your program does not terminate within one second;
you deploy too few armies to your territories (deploying armies to territories you do not own will count toward this) or too many armies; or
your output causes the controller to throw an exception.

Your attack/transfer command will not be executed if:

your program does not give correct output;
you choose a territory to move armies from that is not yours;
you move zero or a negative number of armies from your territory;
you move too many armies from your territory; or
you choose a territory to send armies to that is not adjacent to the territory you chose to move armies from.

You can find the controller and a sample bot here. The bot will participate in the game, but it probably won't win any rounds (unless it's really lucky).
Results
Running the controller after pushing a bug fix to it, WeSwarm continues to be a force to be reckoned with. It'll take a bot with a great strategy to have a chance against it.
As of 25-08-15, 04:40 UTC

1: WeSwarm           1420
2: java Player        120
   java LandGrab      120
   java Hermit        120
   java Castler       120
6: java RandomHalver   80

Notice!
A bug discovered by Zsw causing territories that deployed their armies after others to have a potential advantage in the game has been fixed. An edit was been pushed to the controller, so please use the existing version found using the link above.

JavaScript? It can be run in any browser console

Sorry, but no; I want the submissions to be in any of the three languages above.

Not sure if it is a bug in your controller or your player bot, but if i put three instances of your bot in the simulation by themselves, the console outputs:  Invalid command by java Player: no output

@Moogie Does this happen for each bot? Does it output consistently (each turn) or periodically (every few turns)? And are you using "java Player" in the array three times or did you create separate classes?

@TNT ok it is my problem... we actually the IDE's problem :P changed the command to "java -cp bin Player" and it is all good. sorry for that.

@Moogie No problem, good to know that you resolved the issue. :)

It may be beneficial to explicitly state that each turn, you recieve 5 armies (+ what ever bonus armies) to deploy... this was not explained. I had to look at the code to determine this fact

@Moogie Thanks. I added an example to demonstrate that fact.

Although you can gleam it from the example, maybe just explicitly say that unoccupied territories have an id of -1

@Cain I did. Look under Rounds and Turns.

You are completely correct, my bad

@TNT i have modified your controller for the optional use of same VM for java entries which is a massive speed improvement and have developed a visualisation of the simulation. This is handy for potential bot makers. It can also output an animated Gif. If you want, i can push it into your git repo.

@Moogie Sounds good! Go ahead.

@TNT will do... i assume that I have push privileges. Also, since the playing field is fixed, the more bots there are the more contention for territories and that may lead to stale mates and so there may not actually be a winner. It may be a bit late to change to make the area more dynamic...

@TNT not sure how to send a private message... I cannot push the visualizer code to your git repo... i do not have permission.

@Moogie Would adding you as a collaborator work?

@TNT i believe so. my github handle is klana001

@TNT thanks, i have pushed it into a new branch: visualiser

@TNT thanks for initiating the challenge :) was fun.

Is it just me, or does the gif only display 7/10 bonuses?

@TNT I am pretty sure this is an oversight in the controller. The controller would report to each bot the number of armies in each territory after the adding phase only for bots placed above them in the array list of bots. This means that the first bot only got the number of armies in each territory after the conclusion of the last round, while the last bot knew the number of armies in each territory after each bot has added theirs in. This actually affects my bot a lot. Could you confirm what the intended behavior is? Please see my updated answer for more details.

@Zsw This is, in fact, an oversight. Thanks for pointing it out. I'll fix it when I get the chance.

@TNT are you still updating the rounds? And if so, when do submissions close?

@thefistopher I'll always accept submissions. Whenever someone enters a bot, I'll run the controller and update the results.

Castler - Java 8
He just wants to make a square castle... and if left to his own devices will do just that. Albeit that he gets bored with a small castle so makes it bigger and bigger. This will inevitably mean conflict with other players and so the battling ensues. However he never forgets his most desired shape... the square.

Click image for animated gif (15 meg) of a full 20x 1000 turn simulation.
Castler scored 1700 and the other players scored 100 each.
import java.util.*;
import java.util.stream.Collectors;

/**
 * Wants to make an expanding square castle... however if opponents interfere then will reluctantly make an odd-shaped castle
 */
public class Castler {
    private static final int MAP_SIZE = 10;
    private int ownId;
    private int deployableArmyCount;
    private List<Territory> territories;
    private Territory[][] map;
    private Map<Territory,Territory> territoryHashMap;
    List<Territory> ownedTerritories;
    public int minRow;
    public int minCol;

    public static void main(String[] args)
    {
        new Castler(args);
    }

    Castler(String[] args)
    {
        ownId = Integer.parseInt(args[0]);
        deployableArmyCount = Integer.parseInt(args[1]);

        territories = new ArrayList<Territory>();
        map = new Territory[MAP_SIZE][MAP_SIZE];

        territoryHashMap = new HashMap<Territory,Territory>();

        for (String s : args[2].split(" ")) {
            Territory territory = new Territory(s.split(","));
               territories.add(territory);
            territoryHashMap.put(territory, territory);
            map[territory.col][territory.row]=territory;
        }

        ownedTerritories = territories.stream().filter(t->t.id==ownId).collect(Collectors.toList());

        minRow=Integer.MAX_VALUE;
        minCol=Integer.MAX_VALUE;

        //find top left territory that is the corner of our castle :)
        int largestArea=0;
        for (Territory territory : ownedTerritories)
        {
            int area=countRightDownConnected(territory,new int[MAP_SIZE][MAP_SIZE]);
            if (area>largestArea)
            {
                largestArea=area;
                minRow=territory.row;
                minCol=territory.col;
            }
        }

        // the average army size per owned territory
           int meanArmySize=0;
           for (Territory territory : ownedTerritories)
           {
               meanArmySize+=territory.armies;
           }
           meanArmySize/=ownedTerritories.size();

        int squareSideLength = (int) Math.ceil(Math.sqrt(ownedTerritories.size()));

        // if we own all territories inside the square of our castle, or we have stalled but have the numbers to expand... make the length of side of the square larger to allow expansion
        if (squareSideLength*squareSideLength == ownedTerritories.size() || meanArmySize>squareSideLength)
        {
            squareSideLength++;
        }

        // lets collate all the enemy territories within the area of our desired castle square and marke them as candidates to be attacked.
        List<Territory> attackCandidates = new ArrayList<>();
        for (int y=minRow;y<minRow+squareSideLength;y++)
        {
            for (int x=minCol;x<minCol+squareSideLength;x++)
            {
                Territory territory = map[x%MAP_SIZE][y%MAP_SIZE];
                if (territory!=null && territory.id!=ownId)
                {
                    attackCandidates.add(territory);
                }
            }
        }

        // sort in ascending defensive army size.
        attackCandidates.sort((a,b)->a.armies-b.armies);

        List<Territory> unCommandedTerritories = new ArrayList<>(ownedTerritories);
        List<Move> moves = new ArrayList<>();
        Set<Territory> suicideAttackCandidate = new HashSet<>();

        // command owned territories to attack any territories within the area of the prescribed square if able to win.
        for (int i=0;i<unCommandedTerritories.size();i++)
        {
            Territory commandPendingTerritory =unCommandedTerritories.get(i);
            List<Territory> neighbours = getNeighbours(commandPendingTerritory,map);
            List<Territory> attackCandidatesCopy = new ArrayList<>(attackCandidates);

            // remove non-neighbour attackCandidates
            attackCandidatesCopy.removeIf(t->!neighbours.contains(t));

            for (Territory attackCandidate : attackCandidatesCopy)
            {
                Battle battle = battle(commandPendingTerritory,attackCandidate);
                if (battle.attackerWon)
                {
                    attackCandidates.remove(attackCandidate);
                    suicideAttackCandidate.remove(attackCandidate);
                    unCommandedTerritories.remove(i--);

                    Territory[][] futureMap = cloneMap(map);
                    futureMap[attackCandidate.col][attackCandidate.row].id=ownId;

                    // default to sending the required armies to win + half the difference of the remainder
                    int armiesToSend = battle.minArmiesRequired + (commandPendingTerritory.armies-battle.minArmiesRequired)/2;

                    // but if after winning, there is no threat to the current territory then we shall send most of the armies to attack
                    if (!underThreat(commandPendingTerritory, futureMap))
                    {
                        armiesToSend = commandPendingTerritory.armies-1;
                    }
                    moves.add(new Move(commandPendingTerritory,attackCandidate,armiesToSend));

                    break;
                }
                else
                {
                    // we can't win outright, add it to a list to attack kamikaze style later if needed.
                    suicideAttackCandidate.add(attackCandidate);
                }
            }
        }

        // Find edge territories.
        // A territory is deemed an edge if at least one of its neighbours are not owned by us.
        List<Territory> edgeTerritories = new ArrayList<>();
        ownedTerritories.forEach(owned->
            getNeighbours(owned,map).stream().filter(neighbour->
                neighbour.id!=ownId).findFirst().ifPresent(t->
                edgeTerritories.add(owned)));

        // All edge territories that have not yet had orders this turn...
        List<Territory> uncommandedEdgeTerritories = edgeTerritories.stream().filter(t->unCommandedTerritories.contains(t)).collect(Collectors.toList());

        // Find edges that are under threat by hostile neighbours
        List<Territory> threatenedEdges = edgeTerritories.stream().filter(edge->underThreat(edge,map)).collect(Collectors.toList());

        // All threatened edge territories that have not yet had orders this turn...
        List<Territory> uncommandedThreatenedEdges = threatenedEdges.stream().filter(t->unCommandedTerritories.contains(t)).collect(Collectors.toList());

        // unthreatened edges
        List<Territory> unThreatenedEdges = edgeTerritories.stream().filter(edge->!threatenedEdges.contains(edge)).collect(Collectors.toList());
        List<Territory> uncommandedUnThreatenedEdges = unThreatenedEdges.stream().filter(t->unCommandedTerritories.contains(t)).collect(Collectors.toList());

        // map that describes the effect of moves. Ensures that we do not over commit on one territory and neglect others
        Territory[][] futureMap = cloneMap(map);

        //sort the threatened edges in ascending order of defense
        threatenedEdges.sort((a,b)->a.armies-b.armies);

        int meanThreatenedEdgeArmySize = Integer.MAX_VALUE;
        if (!threatenedEdges.isEmpty())
        {
            // calculate the average defense of the threatened edges
            int[] total = new int[1];
            threatenedEdges.stream().forEach(t->total[0]+=t.armies);
            meanThreatenedEdgeArmySize = total[0]/threatenedEdges.size();

            // command any unthreatened edges to bolster weak threatened edges.
            out:
            for (int i=0;i<uncommandedUnThreatenedEdges.size();i++)
            {
                Territory commandPendingTerritory = uncommandedUnThreatenedEdges.get(i);

                // the unthreatened edge has spare armies
                if (commandPendingTerritory.armies>1)
                {
                    for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
                    {
                        for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
                        {
                            if (!(x==MAP_SIZE && y==MAP_SIZE))
                            {
                                int xx=commandPendingTerritory.col+x;
                                int yy=commandPendingTerritory.row+y;
                                Territory territory = futureMap[xx%MAP_SIZE][yy%MAP_SIZE];

                                // if the current threatened edge has less than average defensive army then send all spare troops to from the uncommanded unthreatened edge.
                                if (territory!=null && territory.armies<meanThreatenedEdgeArmySize && threatenedEdges.contains(territory))
                                {
                                    // update future map
                                    Territory clonedTerritory = (Territory) territory.clone();
                                    clonedTerritory.armies+=commandPendingTerritory.armies-1;
                                    futureMap[xx%MAP_SIZE][yy%MAP_SIZE]=clonedTerritory;

                                    moves.add(new Move(commandPendingTerritory,territory,commandPendingTerritory.armies-1));

                                    unCommandedTerritories.remove(commandPendingTerritory);
                                    uncommandedUnThreatenedEdges.remove(i--);
                                    uncommandedEdgeTerritories.remove(commandPendingTerritory);
                                    continue out;
                                }
                            }
                        }
                    }
                }
            }

            // command any stronger threatened edges to bolster weak threatened edges.
            out:

            for (int i=0;i<uncommandedThreatenedEdges.size();i++)
            {
                Territory commandPendingTerritory = uncommandedThreatenedEdges.get(i);

                // the threatened edge has more than average edge armies
                if (commandPendingTerritory.armies>meanThreatenedEdgeArmySize)
                {
                    for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
                    {
                        for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
                        {
                            if (!(x==MAP_SIZE && y==MAP_SIZE))
                            {
                                int xx=commandPendingTerritory.col+x;
                                int yy=commandPendingTerritory.row+y;
                                Territory territory = futureMap[xx%MAP_SIZE][yy%MAP_SIZE];

                                // if the current threatened edge has less than average defensive army then send the excess troops larger than the average edge armies amount from the uncommanded threatened edge.
                                if (territory!=null && territory.armies<meanThreatenedEdgeArmySize && threatenedEdges.contains(territory))
                                {
                                    // update future map
                                    Territory clonedTerritory = (Territory) territory.clone();
                                    clonedTerritory.armies+=commandPendingTerritory.armies-meanThreatenedEdgeArmySize;
                                    futureMap[xx%MAP_SIZE][yy%MAP_SIZE]=clonedTerritory;
                                    moves.add(new Move(commandPendingTerritory,territory,commandPendingTerritory.armies-meanThreatenedEdgeArmySize));

                                    unCommandedTerritories.remove(commandPendingTerritory);
                                    uncommandedThreatenedEdges.remove(i--);
                                    uncommandedEdgeTerritories.remove(commandPendingTerritory);
                                    continue out;
                                }
                            }
                        }
                    }
                }
            }
        }

        // for any uncommanded non-edge territories, just move excess armies to the right or down
           unCommandedTerritories.stream().filter(t->
               t.armies>1 && !edgeTerritories.contains(t)).forEach(t->
                   moves.add(new Random().nextFloat()>0.5? (new Move(t,map[(t.col+1)%MAP_SIZE][t.row],t.armies-1)):(new Move(t,map[t.col][(t.row+1)%MAP_SIZE],t.armies-1))));

           // lets perform suicide attacks if we are in a good position to do so... hopefully will whittle down turtling enemies.
        for (Territory target : suicideAttackCandidate)
        {
            List<Territory> ownedNeighbours = getNeighbours(target, map).stream().filter(neighbour->neighbour.id==ownId).collect(Collectors.toList());

            for (Territory ownedTerritory : ownedNeighbours)
            {
                // if the edge has yet to be commanded and the territory has more than three times the average armies then it is likely that we are in a power struggle so just suicide attack!
                if (uncommandedEdgeTerritories.contains(ownedTerritory) && ((ownedTerritory.armies)/3-1)>meanArmySize)
                {
                    uncommandedEdgeTerritories.remove(ownedTerritory);
                    unCommandedTerritories.remove(ownedTerritory);
                    moves.add(new Move(ownedTerritory,target,ownedTerritory.armies-meanArmySize));
                }
            }
        }

        // deploy troops to the weakest threatened edges
        int armiesToDeploy =deployableArmyCount;

        Map<Territory,Integer> deployTerritories = new HashMap<>();
        while (armiesToDeploy>0 && threatenedEdges.size()>0)
        {
            for (Territory threatenedEdge : threatenedEdges)
            {
                Integer deployAmount = deployTerritories.get(threatenedEdge);
                if (deployAmount==null)
                {
                    deployAmount=0;
                }
                deployAmount++;
                deployTerritories.put(threatenedEdge,deployAmount);
                armiesToDeploy--;
                if (armiesToDeploy==0) break;
            }
        }

        // no threatened edges needing deployment, so just add them to the "first" edge
        if (armiesToDeploy>0)
        {
            deployTerritories.put(edgeTerritories.get(new Random().nextInt(edgeTerritories.size())),armiesToDeploy);
        }

        // send deploy command
        StringBuilder sb = new StringBuilder();
        deployTerritories.entrySet().stream().forEach(entry-> sb.append(entry.getKey().row + "," + entry.getKey().col + "," + entry.getValue()+" "));
        sb.append(" ");
        System.out.println(sb);

        StringBuilder sb1 = new StringBuilder();

        // send move command
        moves.stream().forEach(move-> sb1.append(move.startTerritory.row + "," + move.startTerritory.col + "," + move.endTerritory.row + "," + move.endTerritory.col + "," + move.armies+" "));
        sb1.append(" ");
        System.out.println(sb1);

    }

    /**
     *    Recursive method that attempts to count area the territories in the square with the given territory as the top left corner
     */
    private int countRightDownConnected(Territory territory,int[][] visited) {

        int count=0;
        if (visited[territory.col][territory.row]>0) return visited[territory.col][territory.row];
        if (visited[territory.col][territory.row]<0) return 0;
        visited[territory.col][territory.row]=-1;

        if (territory!=null && territory.id==ownId)
        {
            if (visited[territory.col][territory.row]>0) return visited[territory.col][territory.row];

            count++;
            count+=countRightDownConnected(map[territory.col][(territory.row+1)%MAP_SIZE],visited);
            count+=countRightDownConnected(map[(territory.col+1)%MAP_SIZE][territory.row],visited);
            visited[territory.col][territory.row]=count;
        }
        return count;
    }

    /**
     *    Performs a deep clone of the provided map
     */
    private Territory[][] cloneMap(Territory[][] map)
    {
        Territory[][] clone = new Territory[MAP_SIZE][MAP_SIZE];
        for (int x=0;x<MAP_SIZE;x++)
        {
            for (int y=0;y<MAP_SIZE;y++)
            {
                Territory territory = map[x][y];
                clone[x][y] = territory==null?null:territory.clone();
            }
        }
        return clone;
    }

    /**
     * Simulates a battle between an attacker and a defending territory
     */
    private Battle battle(Territory attacker, Territory defender)
    {
        Battle battle = new Battle();
        battle.attackerWon=false;
        battle.loser=attacker;
        battle.winner=defender;

        for (int i=0;i<attacker.armies;i++)
        {
            int attackerArmies = i;
            int defenderArmies = defender.armies;
            defenderArmies -= (int) Math.round(attackerArmies * .6);
            attackerArmies -= (int) Math.round(defenderArmies * .7);
            if (defenderArmies <= 0) {
                if (attackerArmies > 0) {
                    defenderArmies = attackerArmies;
                    battle.attackerWon=true;
                    battle.loser=defender;
                    battle.winner=attacker;
                    battle.minArmiesRequired=i;
                    break;
                }
            }
        }
        return battle;
    }

    /**
     * returns true if the provided territory is threatened by any hostile neighbours using the provided map
     */
    private boolean underThreat(Territory territory,Territory[][] map)
    {
        return !getNeighbours(territory,map).stream().filter(neighbour->neighbour.id!=ownId && neighbour.id!=-1).collect(Collectors.toList()).isEmpty();
    }

    /**
     * returns the neighbours of the provided territory using the provided map
     */
    private List<Territory> getNeighbours(Territory territory,Territory[][] map) {

        List<Territory> neighbours = new ArrayList<>();
        for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
        {
            for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
            {
                if (!(x==MAP_SIZE && y==MAP_SIZE))
                {
                    Territory t = map[(x+territory.col)%MAP_SIZE][(y+territory.row)%MAP_SIZE];
                    if (t!=null) neighbours.add(t);
                }
            }
        }
        return neighbours;
    }

    static class Battle {
        public int minArmiesRequired;
        Territory winner;
        Territory loser;
        boolean attackerWon;
    }

    static class Move
    {
        public Move(Territory startTerritory, Territory endTerritory, int armiesToSend)
        {
            this.endTerritory=endTerritory;
            this.startTerritory=startTerritory;
            this.armies=armiesToSend;
        }
        Territory startTerritory;
        Territory endTerritory;
        int armies;
    }

    static class Territory implements Cloneable
    {
        public int id, row, col, armies;

        public Territory clone()
        {
            try {
                return (Territory) super.clone();
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(e);
            }
        }

        public Territory(String[] data) {
            id = Integer.parseInt(data[3]);
            row = Integer.parseInt(data[0]);
            col = Integer.parseInt(data[1]);
            armies = Integer.parseInt(data[4]);
        }

        void add(Territory territory)
        {
            row+=(territory.row);
            col+=(territory.col);
        }

        @Override
        public int hashCode()
        {
            return row*MAP_SIZE+col;
        }

        @Override
        public boolean equals(Object other)
        {
            Territory otherTerritory = (Territory) other;
            return row == otherTerritory.row && col == otherTerritory.col;
        }

    }
}

Hermit - Java
Just keeps adding his armies to the same town. I don't think it can be taken down without getting bonus armies.
public class Hermit {
    public static void main(String[] args) {
        int myId = Integer.parseInt(args[0]);

        for (String s : args[2].split(" ")) {
            String[] data = s.split(",");
            int id = Integer.parseInt(data[3]);
            int row = Integer.parseInt(data[0]);
            int col = Integer.parseInt(data[1]);

            if (id == myId) {
                System.out.println(row + "," + col + "," + args[1]);
                break;
            }
        }
        System.out.println();
    }
}

The simplicity is surprisingly effective! :) very nicely done.

WeSwarm - C++11 [v2.2]
Updated to v2.2 as of August 25, 2015.
v2.2 - adjusted due to a change in the way the controller reports armies.
v2.1 - TNT was having trouble compiling my code, so I stopped using stoi.
v2.0 - a code refactor along with a few bug fixes.

Welcome to the swarm. Our strength is in numbers. Our eternal will is to collect all your bonuses in order to maximize our spawns. Do not stand in our way, lest you wish to be overwhelmed. Do not try to defeat us, for every one you kill, three more will take it's place. You may force us to make sacrifices, but you will never force us to surrender!
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <cmath>
#include <algorithm>
#include <map>

using namespace std;

/// http://stackoverflow.com/questions/236129/split-a-string-in-c
vector<string> &split(const string &s, char delim, vector<string> &elems)
{
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

/// http://stackoverflow.com/questions/236129/split-a-string-in-c
vector<string> split(const string &s, char delim)
{
    vector<string> elems;
    split(s, delim, elems);
    return elems;
}

enum Allegiance { MINE, ENEMY, HOSTILE, NPC, ANY };

class Bonus
{
public:
    Bonus(int id, int armies, int territoriesLeft)
    {
        this->id = id;
        this->armies = armies;
        this->territoriesLeft = territoriesLeft;
    }

    int getId()
    {
        return id;
    }

    int getArmies()
    {
        return armies;
    }

    int getTerritoriesLeft()
    {
        return territoriesLeft;
    }

private:
    /// id of the bonus.
    int id;

    /// number of extra armies that this bonus gives.
    int armies;

    /// number of territories in the bonus that still needs to be captured.
    int territoriesLeft;
};

class Territory
{
public:
    Territory(int row, int col, Bonus* bonus, int playerId, int armies, Allegiance allegiance)
    {
        this->row = row;
        this->col = col;
        this->bonus = bonus;
        this->armies = armies;
        this->allegiance = allegiance;
        this->toAdd = 0;
        this->toRemove = 0;
    }

    Territory(Territory *territory)
    {
        this->row = territory->getRow();
        this->col = territory->getCol();
        this->bonus = territory->getBonusPtr();
        this->armies = territory->getArmies();
        this->allegiance = ANY;
        this->toAdd = 0;
        this->toRemove = 0;
    }

    /// Ensures uniqueness
    bool operator<(const Territory& other) const
    {
        return row < other.row && + col < other.col;
    }

    /// Return the minimum number of armies needed to conquer this territory.
    int conquerNeeded()
    {
        /*
        Say a player sends n armies from his/her territory to an opposing territory with o armies in it.
        o will decrease by n * .6 rounded to the nearest integer;
        however, at the same time, n will decrease by o * .7 rounded to the nearest integer.
        The following rules dealing with whether or not the opposing territory has been captured will apply:

        If o reaches zero AND n is greater than 0, the player will take over the territory, which will have n armies in it.
        If both n and o become zero, o will automatically be set to 1 and the territory will not be captured.
        If o remains greater than 0, the number of armies in the player's territory will increase by n and the opposing territory will not be captured.
        */

        int o = this->armies; // Given o.
        int n; // Solve for n.
        int n1;
        int n2;

        if (this->allegiance != NPC) {
            o = o + 5; // To account for potential reinforcement.
        }

        // resulto = o - 0.6n
        // resultn = n - 0.7o
        //
        // We want a result of o = 0 and n = 1.
        // 0 = o - 0.6n
        // 1 = n - 0.7o
        //
        // Isolate n
        // 0.6n = o
        // n = o / 0.6
        n1 = (int)ceil(o / 0.6);
        // 0.7o = n - 1
        // 0.7o + 1 = n
        n2 = (int)ceil(0.7 * o + 1);

        // Take the bigger of the two to guarantee o <= 0 and n >= 1
        n = max(n1, n2);
        return n;
    }

    /// Returns the minimum number of armies that must be added to this territory
    /// to ensure that the territory cannot be taken over by an attack with n armies.
    int reinforceNeeded(int n)
    {
        int o = this->armies; // Number of armies we already have.
        int add = 0; // Solve for number of armies we need to add.

        // resulto = o - 0.6n
        // resultn = n - 0.7o
        //
        // We want a result of o = 1 at the very least.
        // 1 = o - 0.6n
        // 1 + 0.6n = o

        int needed = (int)ceil(1 + 0.6 * n);

        // We only need to reinforce if we don't have enough.
        if (o < needed) {
            add = needed - o;
        }

        return add;
    }

    void add(int toAdd)
    {
        if (toAdd > 0) {
            this->toAdd = this->toAdd + toAdd;
        }
    }

    void remove(int toRemove)
    {
        if (toRemove > 0) {
            this->toRemove = this->toRemove + toRemove;
        }
    }

    void deploy()
    {
        this->armies = this->armies + this->toAdd - this->toRemove;
        this->toAdd = 0;
        this->toRemove = 0;
    }

    int getRow()
    {
        return row;
    }

    int getCol()
    {
        return col;
    }

    int getArmies()
    {
        return armies;
    }

    int getAvaliableArmies()
    {
        return armies - 1 - toRemove;
    }

    int getToAdd()
    {
        return toAdd;
    }

    bool isToBeDefended()
    {
        return toAdd > 0;
    }

    Bonus getBonus()
    {
        if (bonus != nullptr) {
            return *bonus;
        }

        return Bonus(-1, 1, 100);
    }

    Bonus *getBonusPtr()
    {
        return bonus;
    }

    bool isMine()
    {
        return allegiance == MINE;
    }

    bool isNPC()
    {
        return allegiance == NPC;
    }

private:
    /// Row number of this territory.
    int row;

    /// Column number of this territory.
    int col;

    /// The bonus that this territory is a part of.
    Bonus* bonus;

    /// number of armies contained in the territory.
    int armies;

    /// number of armies to add or send to the territory.
    int toAdd;

    /// number of armies to remove from this territory.
    int toRemove;

    /// Who this territory belongs to.
    Allegiance allegiance;

};

/// Return whether Territory a is a neighbour of Territory b.
bool isNeighbour(Territory *a, Territory *b)
{
    /*
    n n n
    n x n
    n n n
    */

    // A neighbouring territory is where either:
    // row - 1 , col - 1
    // row - 1 , col + 0
    // row - 1 , col + 1
    // row + 0 , col - 1
    // row + 0 , col + 1
    // row + 1 , col - 1
    // row + 1 , col + 0
    // row + 1 , col + 1

    int rowA = a->getRow();
    int colA = a->getCol();
    int rowB = b->getRow();
    int colB = b->getCol();

    // The row and column is the same, so they're the same territory, but not neighbours.
    if (rowA == rowB && colA == colB) {
        return false;
    }

    // The difference of row : row and column : column is no more than 1.
    // e.g. a territory at row 7 will have neighbour at row 6 and 8.
    if (abs(rowA - rowB) <= 1 && abs(colA - colB) <= 1) {
        return true;
    }

    // Special case for wrapping.

    int checkRow = -1;
    int checkCol = -1;

    // Row is at 0. We need to check for 9 and 1.
    // 1 is already covered by 0 - 1. Explicitly check the 0 - 9 case.
    if (rowB == 0) {
        checkRow = 9;
    }

    // Row is at 9. We need to check for 0 and 8.
    // 8 is already covered by 9 - 9. Explicitly check the 9 - 0 case;
    if (rowB == 9) {
        checkRow = 0;
    }

    // Same thing for column
    if (colB == 0) {
        checkCol = 9;
    }

    if (colB == 9) {
        checkCol = 0;
    }

    if ((rowA == checkRow && abs(colA - colB) <= 1) ||
        (abs(rowA - rowB) <= 1 && colA == checkCol) ||
        (rowA == checkRow && colA == checkCol)) {
        return true;
    }

    return false;
}

/// Verify that territory has the correct allegiance.
bool isOfAllegiance(Territory *territory, Allegiance allegiance)
{
    if (allegiance == MINE && territory->isMine()) {
        return true;
    }
    else if (allegiance == ENEMY && !territory->isMine()) {
        // Enemy means NOT mine, which includes NPCs.
        return true;
    }
    else if (allegiance == HOSTILE && !territory->isMine() && !territory->isNPC()) {
        // Specifically enemy PLAYERS.
        return true;
    }
    else if (allegiance == NPC && territory->isNPC()) {
        return true;
    }
    else if (allegiance == ANY) {
        return true;
    }

    return false;
}

/// Return all neighbouring territories of a particular territory,
/// where the neighbouring territories fits the given allegiance.
set<Territory *> getNeighbours(Territory *territory, Allegiance allegiance, set<Territory *> territories)
{
    set<Territory *> neighbours;

    for (Territory *neighbour : territories) {

        if (isNeighbour(neighbour, territory) && isOfAllegiance(neighbour, allegiance)) {
            neighbours.insert(neighbour);
        }

    }

    return neighbours;
}

/// Return the total number of armies near a particular territory that can be mobilized.
int getAvaliableArmiesNear(Territory *territory, Allegiance allegiance, set<Territory *> territories)
{
    int armies = 0;

    set<Territory *> neighbour = getNeighbours(territory, allegiance, territories);

    for (Territory *near : neighbour) {
        armies = armies + near->getAvaliableArmies();
    }

    return armies;
}

/// Return a set of all territories of a particular allegiance.
set<Territory *> getAllTerritories(Allegiance allegiance, set<Territory *> territories)
{
    set<Territory *> t;

    for (Territory *territory : territories) {
        if (isOfAllegiance(territory, allegiance)) {
            t.insert(territory);
        }
    }

    return t;
}

/// Returns the priority of attacking this particular territory.
/// The lower the priority, the better. It is calculated based on
/// the number of territories left to claim a bonus, the number
/// of armies required to take it over, and the number of armies
/// getting this bonus will give us.
int calculateAttackPriority(Territory *territory)
{
    Bonus bonus = territory->getBonus();
    int territoriesLeft = bonus.getTerritoriesLeft();
    int armiesNeeded = territory->conquerNeeded();
    int armiesGiven = bonus.getArmies();
    return (int)round(territoriesLeft * armiesNeeded / armiesGiven);
}

/// Return a map of int, Territories where int represent priority
/// and Territory is the territory to be attacked.
///
/// Higher priority = LESS important.
///
/// ALL territories that can be attacked will appear in the set.
map<int, Territory *> getAttackCandidates(set<Territory *> territories)
{
    map<int, Territory *> attack;

    set<Territory *> opponents = getAllTerritories(ENEMY, territories);

    for (Territory *territory : opponents) {
        int priority = calculateAttackPriority(territory);

        // Check if the territory is already inserted.
        auto findTerritory = attack.find(priority);
        bool inserted = findTerritory != attack.end();

        // Already inserted, so we decrease the priority until we can insert it.
        while (inserted) {
            priority = priority + 1;
            findTerritory = attack.find(priority);
            inserted = findTerritory != attack.end();
        }

        attack.insert({ priority, territory });

    }

    return attack;
}

/// Returns the priority of defending this particular territory.
/// The lower the priority, the better. It is calculated based on
/// whether or not we have this bonus, number of armies that can
/// potentially take it over, and the number of armies
/// getting this bonus will give us.
int calculateDefendPriority(Territory *territory, set<Territory *> territories)
{
    Bonus bonus = territory->getBonus();
    set<Territory *> enemies = getNeighbours(territory, ENEMY, territories);

    int territoriesLeft = bonus.getTerritoriesLeft();
    int armiesNeeded = territory->reinforceNeeded(getAvaliableArmiesNear(territory, HOSTILE, territories));
    int armiesGiven = bonus.getArmies();

    return (int)round((1 + territoriesLeft) * armiesNeeded / armiesGiven);
}

/// Return a map of int, pair<int, Territory> where int represent priority
/// and Territory is the territory to be defended.
///
/// Again, the higher the priority, the LESS important it is.
///
/// ALL territories that can be defended will appear in the set.
map<int, Territory *> getDefendCandidates(set<Territory *> territories)
{
    map<int, Territory *> defend;

    set<Territory *> mine = getAllTerritories(MINE, territories);

    for (Territory *territory : mine) {
        int priority = calculateDefendPriority(territory, territories);

        // Check if the territory is already inserted.
        auto findTerritory = defend.find(priority);
        bool inserted = findTerritory != defend.end();

        // Already inserted, so we decrease the priority until we can insert it.
        while (inserted) {
            priority = priority + 1;
            findTerritory = defend.find(priority);
            inserted = findTerritory != defend.end();
        }

        defend.insert({ priority, territory });

    }

    return defend;
}

/// Determine which territories to add armies to, and add to them accordingly.
/// Return a set which specifically lists the Territories that will have armies
/// added to them.
///
/// set<Territory> territories is a set of territories that are visible to us.
/// int armies is the number of armies we can add.
set<Territory *> getAdd(set<Territory *> territories, int armies)
{
    set<Territory *> add;

    // First we check whether there are any territories worth defending - i.e. we have bonus.
    map<int, Territory *> defend = getDefendCandidates(territories);

    for (auto pairs : defend) {

        if (armies <= 0) {
            break;
        }

        Territory *territory = pairs.second;

        Bonus bonus = territory->getBonus();

        int need = territory->reinforceNeeded(getAvaliableArmiesNear(territory, HOSTILE, territories));

        // Make sure that we actually need to defend this, and it actually can be defended.
        if (need > 0 && need <= armies + getAvaliableArmiesNear(territory, MINE, territories) + territory->getArmies()) {

            if (need < armies) {
                armies = armies - need;
                territory->add(need);
                add.insert(territory);
            }
            else {
                // Do we really want to use up all our armies
                // if it doen't even give us a bonus?
                if (bonus.getTerritoriesLeft() != 0) {
                    continue;
                }
                territory->add(armies);
                armies = 0;
                add.insert(territory);
            }

        }

    }

    // Attacking is much easier. We simply allocate all the armies
    // to a place beside where we wish to attack.
    map<int, Territory *> attack = getAttackCandidates(territories);

    for (auto pairs : attack) {

        if (armies <= 0) {
            break;
        }

        Territory *territory = pairs.second;

        // Determine where to allocate.
        set<Territory *> neighbours = getNeighbours(territory, MINE, territories);

        // We'll just arbitrarily pick the first one that is an ally, though any one will work.
        for (Territory *my : neighbours) {

            // I am almost certain I messed up my logic somewhere around here.
            // I'm supposed to initiate an attack if I got a good surround near a territory.
            // However, it isn't working so I removed it and opted for a simpler logic.
            // So far, it is doing well as is. If I start loosing I'll reimplement this ;)
            //int need = territory->conquerNeeded() - getAvaliableArmiesNear(territory, MINE, territories);
            int need = territory->conquerNeeded();
            int a = territory->conquerNeeded();
            int b = getAvaliableArmiesNear(territory, MINE, territories);
            int c = my->getAvaliableArmies();

            if (need <= 0) {
                continue;
            }

            if (need < armies) {
                armies = armies - need;
                my->add(need);
                add.insert(my);
            }
            else {
                my->add(armies);
                armies = 0;
                add.insert(my);
            }
            break;
        }
    }

    // Check if there are any armies left over,
    // because we must add all our armies.
    if (armies > 0) {

        // This means that we are in a perfect position and it doesn't matter where we add it.
        // So we'll just pick a random territory and put it there.
        if (add.size() < 1) {
            set<Territory *> mine = getAllTerritories(MINE, territories);
            auto first = mine.begin();
            Territory *random = *first;
            random->add(armies);
            add.insert(random);
        }
        else {
            // In this case, we just throw it to the highest priority.
            auto first = add.begin();
            Territory *t = *first;
            t->add(armies);
        }

    }

    return add;
}

/// Return a set of set of Territories.
/// Each set have [0] as source and [1] as destination.
/// Number of armies to send will be in destination.
/// add is a list of territories with armies added to them.
set<pair<Territory *, Territory *>> getSend(set<Territory *> territories)
{
    set<pair<Territory *, Territory *>> send;

    // Attacking is much easier. We simply allocate all the armies
    // to a place beside where we wish to attack.
    map<int, Territory *> attack = getAttackCandidates(territories);

    for (auto pairs : attack) {

        Territory *territory = pairs.second;

        int needed = territory->conquerNeeded();
        set<Territory *> mine = getNeighbours(territory, MINE, territories);

        // Find all our territories avaliable for attack.
        for (Territory *my : mine) {

            // We need to make sure we actually have enough!
            int avaliable = my->getAvaliableArmies();

            // We send all our attacking army from a single territory,
            // So this one territory must have enough.
            if (needed > 0 && avaliable >= needed) {
                // Attack!
                territory->add(needed); // represents number of armies to send.
                my->remove(needed);

                pair<Territory *, Territory *> attackOrder(my, territory); // src -> dst.
                send.insert(attackOrder);
                break;
            }
        }
    }

    // First we check whether there are any territories worth defending - i.e. we have bonus.
    map<int, Territory *> defend = getDefendCandidates(territories);

    for (auto pairs : defend) {

        Territory *territory = pairs.second;

        // Number of armies that will potentially attack.
        int threat = getAvaliableArmiesNear(territory, HOSTILE, territories);

        // The number of armies needed to reinforce this attack.
        int needed = territory->reinforceNeeded(threat);

        if (needed <= 0) {
            continue;
        }

        // Check that we have enough to actually defend.
        int avaliable = getAvaliableArmiesNear(territory, MINE, territories);
        set<Territory *> neighbours = getNeighbours(territory, MINE, territories);

        if (avaliable < needed) {
            // Not enough, retreat!
            for (Territory *my : neighbours) {

                int retreat = territory->getAvaliableArmies();
                if (retreat > 0) {
                    // Retreat!

                    // Remove from the territory in defense candidate.
                    territory->remove(retreat);

                    // Add to territory else where.
                    my->add(retreat);

                    pair<Territory *, Territory *> defendOrder(territory, my); // src -> dst.
                    send.insert(defendOrder);
                }
                // We retreat to a single territory.
                // So we break as soon as we find a territory.
                // If there is no territory, this loop won't run.
                break;
            }
        }
        else {

            // Track how many we still need to add.
            int stillneed = needed;

            // Reinforce!
            for (Territory *my : neighbours) {

                // Do we need more?
                if (stillneed <= 0) {
                    break;
                }

                // Check that it's not about to be reinforced.
                // Otherwise, it is senseless to take armies away from a
                // territory we intend to defend!
                if (!my->isToBeDefended()) {
                    int canSend = my->getAvaliableArmies();
                    if (canSend > 0) {
                        // Reinforce!

                        // We create a copy of the territory when adding.
                        // Why? Because in this case, the destination Territory
                        // is only meant as a place holder territory simply
                        // for the purpose of having the toAdd value read.
                        Territory *territoryAdd = new Territory(territory);
                        territoryAdd->add(canSend);

                        // Remove from the territory we are sending from.
                        my->remove(canSend);

                        stillneed = stillneed - canSend;

                        pair<Territory *, Territory *> defendOrder(my, territoryAdd); // src -> dst.
                        send.insert(defendOrder);
                    }
                }
            }
        }

    }

    return send;
}

/// Rules of Engagement:
/// 1. Collect Bonuses.
/// 2. Attack Weak Territories whenever possible.
///
/// Rules of Defense:
/// 1. Reinforce if possible.
/// 2. Otherwise, retreat and live to fight another day
///
/// For a given territory, we will prioritze attacking over
/// defending if we do not have the bonus yet for that territory.
/// If we have the bonus, we will prioritze defending over attacking.
int main(int argc, char* argv[])
{
    // Note: cannot use stoi because of compilation problems.

    int id = atoi(argv[1]);
    int armies = atoi(argv[2]);
    string territoriesIn = argv[3];
    string bonusesIn = argv[4];

    // First seperate by space, then seperate by comma.
    vector<string> territoriesData = split(territoriesIn, ' ');
    vector<string> bonusesData = split(bonusesIn, ' ');

    set<Territory *> territories;
    map<int, Bonus *> bonuses;

    for (string data : bonusesData) {
        // [id],[armies],[territories left]
        vector<string> bonus = split(data, ',');
        int id = atoi(bonus[0].c_str());
        int armies = atoi(bonus[1].c_str());
        int territoriesLeft = atoi(bonus[2].c_str());

        Bonus *b = new Bonus(id, armies, territoriesLeft);

        bonuses.insert({ id, b });
    }

    for (string data : territoriesData) {
        // [row],[col],[bonus id],[player id],[armies]
        vector<string> territory = split(data, ',');

        int row = atoi(territory[0].c_str());
        int col = atoi(territory[1].c_str());
        int bonusId = atoi(territory[2].c_str());
        int playerId = atoi(territory[3].c_str());
        int armies = atoi(territory[4].c_str());

        // We can assume that each territory always belongs to a bonus.
        auto findBonus = bonuses.find(bonusId);
        Bonus *bonus;

        if (findBonus != bonuses.end()) {
            bonus = findBonus->second;
        }
        else {
            bonus = nullptr;
        }

        Allegiance allegiance = ENEMY;
        if (playerId == id) {
            allegiance = MINE;
        }
        else if (playerId == -1) {
            allegiance = NPC;
        }

        Territory *t = new Territory(row, col, bonus, playerId, armies, allegiance);

        territories.insert(t);

    }

    // Here we output our desire to add armies.
    set<Territory *> add = getAdd(territories, armies);

    string delimiter = "";
    for (Territory *t : add) {
        cout << delimiter << t->getRow() << "," << t->getCol() << "," << t->getToAdd();
        delimiter = " ";

        // Move added army to actual army.
        t->deploy();
    }

    cout << endl;

    // Here we output our desire to send armies.
    set<pair<Territory *, Territory *>> send = getSend(territories);

    delimiter = "";

    // Note that if you do not want to move any armies, your program should print a space.
    if (send.size() == 0) {
        cout << " ";
    }
    else {
        for (auto location : send) {
            Territory *source = location.first;
            Territory *destination = location.second;

            cout << delimiter << source->getRow() << "," << source->getCol() << "," << destination->getRow() << "," << destination->getCol() << "," << destination->getToAdd();
            delimiter = " ";
        }
    }

    cout << endl;

    return 0;
}

Animated GIF

Archived:
v2.1: https://drive.google.com/uc?export=download&id=0B-BtKdd4FDDEU3lkNzVoTUpRTG8
v1.0: https://drive.google.com/uc?export=download&id=0B-BtKdd4FDDEVzZUUlFydXo2T00

Thanks! Unfortunately I am unable to compile your program due to stoi not being resolved despite having C++11. There have been consistent issues with resolving it which I have yet to figure out how to do, so could you provide an alternate solution that does not use stoi?

@TNT Ahh that sucks. I'm still new to C++, but I'm sure I can figure something out.

@TNT Please see if you can compile it now.

It compiles and runs just fine. Thanks!

@Zsw WeSwarm is very strong. good work! I'll have to see if I can come up with a counter-strategy :P

I've pushed an edit to the controller. Please check if it works now. Thanks again!

@TNT No problem! I added a change to my bot to naively expect armies to be added. It reduces the effectiveness slightly but still seem to perform well enough to get a high score.

LandGrab - Java
The more land the better. Targets exclusively free territories if there are any, then with the leftover armies begins building up and taking out the enemy one tile at a time.
import java.util.Arrays;
import java.util.LinkedList;

public class LandGrab {
    public static void main(String[] args) {

        //Init
        int id = Integer.parseInt(args[0]);
        int armies = Integer.parseInt(args[1]);
        LinkedList<Territory> myTerritories = new LinkedList<Territory>();
        LinkedList<Territory> enemyTerritories = new LinkedList<Territory>();
        LinkedList<Territory> freeTerritories = new LinkedList<Territory>();
        for (String s : args[2].split(" ")) {
            Territory t = new Territory(s.split(","));
            if (t.id == id)
                myTerritories.add(t);
            else if(t.id == -1)
                freeTerritories.add(t);
            else
                enemyTerritories.add(t);
        }

        LinkedList<int[]> deploy = new LinkedList<int[]>();
        LinkedList<int[]> move = new LinkedList<int[]>();

        //Boost up territories next to free ones
        for(Territory mine : myTerritories){
            if(armies <= 0) break;
            LinkedList<Territory> neighbors = getNeighbors(mine, freeTerritories);
            int depArm = 0;
            while(neighbors.peek() != null && armies * 0.6 >= neighbors.peek().armies){
                Territory x = neighbors.pop();
                int needed = x.armies * 2;
                depArm += needed;
                mine.armies += needed;
                armies -= needed;
                int[] temp = {mine.row, mine.col, x.row, x.col, needed};
                move.add(temp);
            }
            int[] temp = {mine.row, mine.col, depArm};
            if(depArm > 0) deploy.add(temp);
        }

     /* //Take any freebies we can
        for(Territory mine : myTerritories){
            LinkedList<Territory> neighbors = getNeighbors(mine, freeTerritories);
            while(neighbors.peek() != null){
                Territory x = neighbors.pop();
                if((mine.armies - 1) > x.armies * 2){
                    int needed = x.armies * 2;
                    move += mine.row + "," + mine.col + "," + x.row + "," + x.col + "," + (needed) + " ";
                    mine.armies -= needed;
                }
            }
        }
       */
        //Choose a single enemy army and crush it
        if(enemyTerritories.size() > 0 && armies > 0){
            Territory x = enemyTerritories.pop();
            Territory y = largest(getNeighbors(x, myTerritories));
            int[] temp = {y.row, y.col, armies};
            deploy.add(temp);
            int armSize = y.armies + armies - 1;
            if(armSize * 0.6 > x.armies){
                int[] attack = {y.row, y.col, x.row, x.col, armSize};
                move.add(attack);
            }
            armies = 0;
        }

        //Deploy leftover armies wherever
        if(armies > 0){
            Territory rand = myTerritories.getFirst();
            int[] temp = {rand.row, rand.col, armies};
            deploy.add(temp);
        }

        //Consolidate
        String deployString = consolidate(deploy);
        String moveString = "";
        for(int[] command : move){
            moveString += Arrays.toString(command).replace(" ", "").replace("[", "").replace("]", "") + " ";
        }
        if(moveString == "") moveString = " ";

        //Return
        System.out.println(deployString);
        System.out.println(moveString);

    }

    private static Territory largest(LinkedList<Territory> l){
        Territory largest = l.getFirst();
        for(Territory t : l){
            if(t.armies > largest.armies) largest = t;
        }
        return largest;
    }

    public static String consolidate(LinkedList<int[]> list){
        LinkedList<int[]> combined = new LinkedList<int[]>();
        for(int[] t : list){
            boolean dup = false;
            for(int[] existing : combined){
                if(t[0] == existing[0] && t[1] == existing[1]){
                    existing[2] += t[2];
                    dup = true;
                }

            }
            if(!dup) combined.add(t);
        }

        String result = "";
        for(int[] dep : combined){
            result += Arrays.toString(dep).replace(" ", "").replace("[", "").replace("]", "") + " ";

        }
        return result;
    }

    private static LinkedList<Territory> getNeighbors(Territory t, LinkedList<Territory> possibles){
        LinkedList<Territory> neighbors = new LinkedList<Territory>();
        for(Territory x : possibles){
            if(Math.abs(x.row - t.row) <= 1 && Math.abs(x.col - t.col) <= 1){
                neighbors.add(x);
            }
        }
        return neighbors;
    }

    static class Territory {
        int id, row, col, armies;

        public Territory(String[] data) {
            id = Integer.parseInt(data[3]);
            row = Integer.parseInt(data[0]);
            col = Integer.parseInt(data[1]);
            armies = Integer.parseInt(data[4]);
        }
    }
}

I have added a correction to your bot to protect against index out of bounds exception. Please feel to accept or disregard the correction

Hey, thanks for the concern, but in my testing been an issue. y should never be null, because the only territories it gets passed are those adjacent to one I own, so any enemy territory has at least one neighbor in myTerritories.

Tenacious! Your bot is able to recover from loss of territories proficiently. good work.

Random Halver - Java 8
A very simple bot that simply moves half its armies in each territory to a random neighbouring territory. Does not matter if the neighbour is friend or foe...
While it cannot compete with Castler, it does surprisingly well against the Player and other bots.
import java.util.*;
import java.util.stream.Collectors;

/**
 * Sends half its force to a random territory around itself.
 */
public class RandomHalver {
    private static final int MAP_SIZE = 10;
    private int ownId;
    private int deployableArmyCount;
    private List<Territory> territories;
    private Territory[][] map;
    private Map<Territory,Territory> territoryHashMap;
    List<Territory> ownedTerritories;
    public int minRow;
    public int minCol;

    public static void main(String[] args)
    {
        new RandomHalver(args);
    }

    RandomHalver(String[] args)
    {
        ownId = Integer.parseInt(args[0]);
        deployableArmyCount = Integer.parseInt(args[1]);

        territories = new ArrayList<Territory>();
        map = new Territory[MAP_SIZE][MAP_SIZE];

        territoryHashMap = new HashMap<Territory,Territory>();

        for (String s : args[2].split(" ")) {
            Territory territory = new Territory(s.split(","));
            territories.add(territory);
            territoryHashMap.put(territory, territory);
            map[territory.col][territory.row]=territory;
        }

        ownedTerritories = territories.stream().filter(t->t.id==ownId).collect(Collectors.toList());

        List<Move> moves = new ArrayList<>();

        ownedTerritories.stream().forEach(t->moves.add(new Move(t, getNeighbours(t,map).get(new Random().nextInt(getNeighbours(t,map).size())),t.armies/2)));
        Map<Territory,Integer> deployTerritories = new HashMap<>();
        deployTerritories.put(ownedTerritories.get(new Random().nextInt(ownedTerritories.size())),deployableArmyCount);

        // send deploy command
        StringBuilder sb = new StringBuilder();
        deployTerritories.entrySet().stream().forEach(entry-> sb.append(entry.getKey().row + "," + entry.getKey().col + "," + entry.getValue()+" "));
        sb.append(" ");
        System.out.println(sb);

        StringBuilder sb1 = new StringBuilder();

        // send move command
        moves.stream().filter(m->m.armies>0).forEach(move-> sb1.append(move.startTerritory.row + "," + move.startTerritory.col + "," + move.endTerritory.row + "," + move.endTerritory.col + "," + move.armies+" "));
        sb1.append(" ");
        System.out.println(sb1);

    }

    /**
     * returns the neighbours of the provided territory using the provided map
     */
    private List<Territory> getNeighbours(Territory territory,Territory[][] map) {

        List<Territory> neighbours = new ArrayList<>();
        for (int x=MAP_SIZE-1;x<=MAP_SIZE+1;x++)
        {
            for (int y=MAP_SIZE-1;y<=MAP_SIZE+1;y++)
            {
                if (!(x==MAP_SIZE && y==MAP_SIZE))
                {
                    Territory t = map[(x+territory.col)%MAP_SIZE][(y+territory.row)%MAP_SIZE];
                    if (t!=null) neighbours.add(t);
                }
            }
        }
        return neighbours;
    }

    static class Battle {
        public int minArmiesRequired;
        Territory winner;
        Territory loser;
        boolean attackerWon;
    }

    static class Move
    {
        public Move(Territory startTerritory, Territory endTerritory, int armiesToSend)
        {
            this.endTerritory=endTerritory;
            this.startTerritory=startTerritory;
            this.armies=armiesToSend;
        }
        Territory startTerritory;
        Territory endTerritory;
        int armies;
    }

    static class Territory implements Cloneable
    {
        public int id, row, col, armies;

        public Territory clone()
        {
            try {
                return (Territory) super.clone();
            } catch (CloneNotSupportedException e) {
                throw new RuntimeException(e);
            }
        }

        public Territory(String[] data) {
            id = Integer.parseInt(data[3]);
            row = Integer.parseInt(data[0]);
            col = Integer.parseInt(data[1]);
            armies = Integer.parseInt(data[4]);
        }

        void add(Territory territory)
        {
            row+=(territory.row);
            col+=(territory.col);
        }

        @Override
        public int hashCode()
        {
            return row*MAP_SIZE+col;
        }

        @Override
        public boolean equals(Object other)
        {
            Territory otherTerritory = (Territory) other;
            return row == otherTerritory.row && col == otherTerritory.col;
        }

    }
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Lossy ASCII art compression
Background
PICASCII is a neat tool that converts images into ASCII art.
It achieves different degrees of brightness by using the following ten ASCII characters:
@#+';:,.`

We'll say that these charxels (character elements) have brightnesses from 1 (at-sign) to 10 (space).
Below, you can see the results of converting a little code, the Welsh flag, an overhanded fractal, a large trout and a little golf, displayed with the correct font:

Your can see the images in this fiddle and download them from Google Drive.
Task
While the end results of PICASCII are visually pleasing, all five images combined weigh 153,559 bytes. How much could these images be compressed if we are willing to sacrifice part of their quality?
Your task is to write a program that accepts an ASCII art image such as the above ones and a minimum quality as input and prints a lossy compression of the image – in form of a full program or a function returning a single string – that satisfies the quality requirement.
This means that you do not get to write a separate decompressor; it must be built-in into each of the compressed images.
The original image will consist of charxels with brightnesses between 1 and 10, separated by linefeeds into lines of the same length. The compressed image must have the same dimensions and use the same set of characters.
For an uncompressed image consisting of n charxels, the quality of a compressed version of the image is defined as

where ci is the brightness of the ith charxel of the compressed image's output and ui the brightness of the ith charxel of the uncompressed image.
Scoring
Your code will be run with the five images from above as input and minimum quality settings of 0.50, 0.60, 0.70, 0.80 and 0.90 for each of the images.
Your score is the geometric mean of the sizes of all compressed images, i.e., the twenty-fifth root of the product of the lengths of all twenty-five compressed images.
The lowest score wins!
Additional rules

Your code has to work for arbitrary images, not just the ones used for scoring.
It is expected that you optimize your code towards the test cases, but a program that does not even attempt to compress arbitrary images won't get an upvote from me.

Your compressor may use built-in byte stream compressors (e.g., gzip), but you have to implement them yourself for the compressed images.
Bulit-ins normally used in byte stream decompressors (e.g., base conversion, run-length decoding) are allowed.

Compressor and compressed images do not have to be in the same language.
However, you must pick a single language for all compressed images.

For each compressed image, standard code golf rules apply.

Verification
I've made a CJam script to easily verify all quality requirements and calculate a submission's score.
You can download the Java interpreter from here or here.
e# URLs of the uncompressed images.
e# "%s" will get replaced by 1, 2, 3, 4, 5.

"file:///home/dennis/codegolf/53199/original/image%s.txt"

e# URLs of the compressed images (source code).
e# "%s-%s" will get replaced by "1-50", "1-60", ... "5-90".

"file:///home/dennis/codegolf/53199/code/image%s-%s.php"

e# URLs of the compressed images (output).

"file:///home/dennis/codegolf/53199/output/image%s-%s.txt"

e# Code

:O;:C;:U;5,:)
{
    5,5f+Af*
    {
        C[IQ]e%g,X*:X;
        ISQS
        [U[I]e%O[IQ]e%]
        {g_W=N&{W<}&}%
        _Nf/::,:=
        {
            {N-"@#+';:,.` "f#}%z
            _::m2f#:+\,81d*/mq1m8#
            _"%04.4f"e%S
            @100*iQ<"(too low)"*
        }{
            ;"Dimension mismatch."
        }?
        N]o
    }fQ
}fI
N"SCORE: %04.4f"X1d25/#e%N

Example

Bash → PHP, score 30344.0474
cat

Achieves 100% quality for all inputs.
$ java -jar cjam-0.6.5.jar vrfy.cjam
1 50 1.0000
1 60 1.0000
1 70 1.0000
1 80 1.0000
1 90 1.0000
2 50 1.0000
2 60 1.0000
2 70 1.0000
2 80 1.0000
2 90 1.0000
3 50 1.0000
3 60 1.0000
3 70 1.0000
3 80 1.0000
3 90 1.0000
4 50 1.0000
4 60 1.0000
4 70 1.0000
4 80 1.0000
4 90 1.0000
5 50 1.0000
5 60 1.0000
5 70 1.0000
5 80 1.0000
5 90 1.0000

SCORE: 30344.0474

I'm having some trouble understanding this part: If someone chooses q=0.5, then each char in the input file should be replaced by the char with half the brightness in the output, right? Obviously excluding the whitespace since that would mess up the entire image.

Its all too confusing and loopholey.  How do you stop a http://www.mattmahoney.net/dc/barf.html entry?  Can the decompressor read any file other than the compressed image too?  Can you provide a python script or something that actually checks the quality an image and calculates a score so there can be no quibbles on that front too?  Etc.

@Will Confusing? Maybe. But I don't think it's loopholey. Each compressed image has to be a program or function, so unfunny jokes like BARF are automatically excluded. I don't know Python, but I'll think of something to verification simple.

"I've made a CJam script to easily verify all quality requirements and calculate a submission's score." Do people really use this thing to do normal scripts? Dear lord...

Java → CJam, score ≈4417.89
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import net.aditsu.cjam.CJam;

public class Compress {
    protected static final char[] DIGITS = "0123456789ABCDEFGHIJK".toCharArray();
    protected static final String CHARS = "@#+';:,.` ";
    protected static final char[] CHR = CHARS.toCharArray();

    private static class Img {
        public final int rows;
        public final int cols;
        public final int[][] a;

        public Img(final int rows, final int cols) {
            this.rows = rows;
            this.cols = cols;
            a = new int[rows][cols];
        }

        public Img(final List<String> l) {
            rows = l.size();
            cols = l.get(0).length();
            a = new int[rows][cols];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    a[i][j] = CHARS.indexOf(l.get(i).charAt(j));
                }
            }
        }

        public static Img read(final Reader r) {
            try {
                final BufferedReader br = new BufferedReader(r);
                final List<String> l = new ArrayList<>();
                while (true) {
                    final String s = br.readLine();
                    if (s == null || s.isEmpty()) {
                        break;
                    }
                    l.add(s);
                }
                br.close();
                return new Img(l);
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public static Img read(final File f) {
            try {
                return read(new FileReader(f));
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public Img scaleDown(final int fr, final int fc) {
            final int r1 = (rows + fr - 1) / fr;
            final int c1 = (cols + fc - 1) / fc;
            final Img x = new Img(r1, c1);
            final int[][] q = new int[r1][c1];
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[i / fr][j / fc] += a[i][j];
                    q[i / fr][j / fc]++;
                }
            }
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] /= q[i][j];
                }
            }
            return x;
        }

        public Img scaleUp(final int fr, final int fc) {
            final int r1 = rows * fr;
            final int c1 = cols * fc;
            final Img x = new Img(r1, c1);
            for (int i = 0; i < r1; ++i) {
                for (int j = 0; j < c1; ++j) {
                    x.a[i][j] = a[i / fr][j / fc];
                }
            }
            return x;
        }

        public Img crop(final int r, final int c) {
            if (r == rows && c == cols) {
                return this;
            }
            final Img x = new Img(r, c);
            for (int i = 0; i < r; ++i) {
                for (int j = 0; j < c; ++j) {
                    x.a[i][j] = a[i][j];
                }
            }
            return x;
        }

        public Img rescale(final int fr, final int fc) {
            return scaleDown(fr, fc).scaleUp(fr, fc).crop(rows, cols);
        }

        public double quality(final Img x) {
            if (x.rows != rows || x.cols != cols) {
                throw new IllegalArgumentException();
            }
            double t = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    final int y = a[i][j] - x.a[i][j];
                    t += y * y;
                }
            }
            t /= 81 * rows * cols;
            t = 1 - Math.sqrt(t);
            return Math.pow(t, 8);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    sb.append(CHR[a[i][j]]);
                }
                sb.append('\n');
            }
            return sb.toString();
        }

        public Array toArray() {
            final Array x = new Array(rows * cols);
            int k = 0;
            for (int i = 0; i < rows; ++i) {
                for (int j = 0; j < cols; ++j) {
                    x.a[k++] = a[i][j];
                }
            }
            return x;
        }

        public String compress(final double quality) {
            int bi = 1;
            int bj = 1;
            int bs = rows * cols;
            Img bx = this;

            for (int i = 1; i < 3; ++i) {
                for (int j = 1; j < 3; ++j) {
                    Img x = rescale(i, j);
                    if (quality(x) >= quality) {
                        x = scaleDown(i, j);
                        if (x.rows * x.cols < bs) {
                            bi = i;
                            bj = j;
                            bs = x.rows * x.cols;
                            bx = x;
                        }
                    }
                }
            }

            Array a = bx.toArray();
            int bf = 0;
            for (int i = 1; i <= 20; ++i) {
                final int t = a.rle11(i).n;
                if (t < bs) {
                    bs = t;
                    bf = i;
                }
            }

            int b = 10;
            if (bf > 0) {
                b = 11;
                a = a.rle11(bf);
            }

            String s = null;
            for (int i = 92; i < 97; ++i) {
                for (char c = ' '; c < '$'; ++c) {
                    final String t = a.cjamBase(b, i, c);
                    boolean ok = true;
                    for (int j = 0; j < t.length(); ++j) {
                        if (t.charAt(j) > '~') {
                            ok = false;
                            break;
                        }
                    }
                    if (!ok) {
                        continue;
                    }
                    if (s == null || t.length() < s.length()) {
                        s = t;
                    }
                }
            }

            if (bf > 0) {
                s += "{(_A={;()";
                if (bf > 1) {
                    s += DIGITS[bf] + "*";
                }
                s += "\\(a@*}&\\}h]e_";
            }
            if (bi * bj == 1) {
                return s + '"' + CHARS + "\"f=" + cols + "/N*";
            }
            s += bx.cols + "/";
            if (bi > 1) {
                s += bi + "e*";
                if (rows % 2 == 1) {
                    s += "W<";
                }
            }
            if (bj > 1) {
                s += bj + "fe*";
                if (cols % 2 == 1) {
                    s += "Wf<";
                }
            }
            return s + '"' + CHARS + "\"ff=N*";
        }

        public void verify(final String s, final double quality) {
            final String t = CJam.run(s, "");
            final Img x = read(new StringReader(t));
            final double q = quality(x);
            if (q < quality) {
                throw new RuntimeException(q + " < " + quality);
            }
//          System.out.println(q + " >= " + quality);
        }
    }

    private static class Array {
        public final int[] a;
        public final int n;

        public Array(final int n) {
            this.n = n;
            a = new int[n];
        }

        public Array(final int[] a) {
            this.a = a;
            n = a.length;
        }

        public String join() {
            final StringBuilder sb = new StringBuilder();
            for (int x : a) {
                sb.append(x).append(' ');
            }
            sb.setLength(sb.length() - 1);
            return sb.toString();
        }

//      public String cjamStr() {
//          final StringBuilder sb = new StringBuilder("\"");
//          for (int x : a) {
//              sb.append(DIGITS[x]);
//          }
//          sb.append("\":~");
//          return sb.toString();
//      }

        public String cjamBase(final int m, final int b, final char c) {
            final boolean zero = a[0] == 0;
            String s = join();
            if (zero) {
                s = "1 " + s;
            }
            s = CJam.run("q~]" + m + "b" + b + "b'" + c + "f+`", s);
            s += "'" + c + "fm" + b + "b" + DIGITS[m] + "b";
            if (zero) {
                s += "1>";
            }
            return s;
        }

        public Array rle11(final int f) {
            final int[] b = new int[n];
            int m = 0;
            int x = -1;
            int k = 0;
            for (int i = 0; i <= n; ++i) {
                final int t = i == n ? -2 : a[i];
                if (t == x && m < 11 * f) {
                    m++;
                }
                else {
                    if (m >= f && m > 3) {
                        b[k++] = 10;
                        b[k++] = m / f - 1;
                        b[k++] = x;
                        for (int j = 0; j < m % f; ++j) {
                            b[k++] = x;
                        }
                    }
                    else {
                        for (int j = 0; j < m; ++j) {
                            b[k++] = x;
                        }
                    }
                    m = 1;
                    x = t;
                }
            }
            return new Array(Arrays.copyOf(b, k));
        }
    }

    private static void score() {
        double p = 1;
        for (int i = 1; i < 6; ++i) {
            final File f = new File("image" + i + ".txt");
            final Img img = Img.read(f);
            final int n = (int) f.length();
            for (int j = 5; j < 10; ++j) {
                final double q = j / 10.0;
                final String s = img.compress(q);
                System.out.println(f.getName() + ", " + q + ": " + n + " -> " + s.length());
                img.verify(s, q);
                p *= s.length();
            }
        }
        System.out.println(Math.pow(p, 1 / 25.0));
    }

    public static void main(final String... args) {
        if (args.length != 2) {
            score();
            return;
        }
        final String fname = args[0];
        final double quality = Double.parseDouble(args[1]);
        try {
            final Img img = Img.read(new File(fname));
            final String s = img.compress(quality);
            img.verify(s, quality);
            final FileWriter fw = new FileWriter(fname + ".cjam");
            fw.write(s);
            fw.close();
        }
        catch (IOException e) {
            throw new RuntimeException();
        }
    }
}

Requires the CJam jar in the classpath. If you give it 2 command line arguments (file name and quality), it appends ".cjam" to the file name and writes the compressed image there. Otherwise it calculates its score on the 5 test images, which are assumed to be in the current directory. The program also verifies every compressed image automatically. You may want to double-check the score calculation in case there's any discrepancy.
The techniques used (so far) are: scaling to half (horizontally, vertically or both) if it doesn't reduce the quality too much, a custom-coded RLE, and base conversion to pack more data into each character while remaining in the printable ASCII range.

Could you give me a brief overview on how to run this? I compiled it (successfully, I think) with javac -cp cjam-0.6.5.jar Compress.java, but java -cp cjam-0.6.5.jar Compress says Error: Could not find or load main class Compress and java Compress doesn't find the CJam class.

@Dennis You need to add the directory that contains Compress.class to the  classpath (-cp). If it's in the current directory, use -cp .:cjam-0.6.5.jar (in windoze I think you need a semicolon instead of a colon)

That did the trick, thank you.

Python 3.5 (main and output) (currently noncompeting)
Happy Birthday, Challenge! Here's your present: an answer!
EDIT: Converted output to python code, improved compression rate (slightly)
EDIT2: Made it print raw when size is 1. Improved score, but score needs to be calculated again.
EDIT3: @Dennis pointed out that I still haev bugs to fix, so I marked the answer as noncompeting
Code:
import sys
LIST = [' ','`','.',',',':',';',"'",'+','#','@']

def charxel_to_brightness(charxel):
    return LIST.index(charxel)

def brightness_to_charxel(bright):
    return LIST[bright]

def image_to_brightness(imagetext):
    return [list(map(charxel_to_brightness,line)) for line in imagetext.split("\n")]

def brightness_to_image(brightarray):
    return '\n'.join([''.join(map(brightness_to_charxel,line)) for line in brightarray])

def split_into_parts(lst,size):
    return [lst[x:x+size] for x in range(0, len(lst), size)]

def gen_updown(startxel,endxel,size):
    return [[int((size-r)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_leftright(startxel,endxel,size):
    return [[int((size-c)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_tlbr(startxel,endxel,size):
    return [[int((2*size-r-c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_bltr(startxel,endxel,size):
    return [[int((size-r+c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_block(code,startxel,endxel,size):
    if code==0:return gen_updown(startxel,endxel,size)
    if code==1:return gen_leftright(startxel,endxel,size)
    if code==2:return gen_bltr(startxel,endxel,size)
    if code==3:return gen_tlbr(startxel,endxel,size)

def vars_to_data(code,startxel,endxel):
    acc=endxel
    acc+=startxel<<4
    acc+=code<<8
    return acc

def data_to_vars(data):
    code=data>>8
    startxel=(data>>4)&15
    endxel=data&15
    return code,startxel,endxel

def split_into_squares(imgarray,size):
    rows = split_into_parts(imgarray,size)
    allsquares = []
    for rowblock in rows:
        splitrows = []
        for row in rowblock:
            row = split_into_parts(row,size)
            splitrows.append(row)
        rowdict = []
        for row in splitrows:
            for x in range(len(row)):
                if len(rowdict)<=x:
                    rowdict.append([])
                rowdict[x].append(row[x])
        allsquares.append(rowdict)
    return allsquares

def calc_quality(imgarray,comparray):
    acc=0
    for row in range(len(imgarray)):
        for col in range(len(imgarray[row])):
            acc+=pow(imgarray[row][col]-comparray[row][col],2)
    return (1-(acc/81.0/sum([len(row) for row in imgarray]))**.5)**8

def fuse_squares(squarray):
    output=[]
    counter=0
    scounter=0
    sqrow=0
    while sqrow<len(squarray):
        if scounter<len(squarray[sqrow][0]):
            output.append([])
            for square in squarray[sqrow]:
                output[counter].extend(square[scounter])
            scounter+=1
            counter+=1
        else:
            scounter=0
            sqrow+=1
    return output

def main_calc(imgarray,threshold):
    imgarray = image_to_brightness(imgarray)
    size = 9
    quality = 0
    compimg=[]
    datarray=[]
    testdata = [vars_to_data(c,s,e) for c in range(4) for s in range(10) for e in range(10)]
    while quality<threshold:
        squares = split_into_squares(imgarray,size)
        compimg = []
        datarray = []
        testblock = [gen_block(c,s,e,size) for c in range(4) for s in range(10) for e in range(10)]
        for row in squares:
            comprow = []
            datrow=[]
            for square in row:
                quality_values = [calc_quality(square,block) for block in testblock]
                best_quality = quality_values.index(max(quality_values))
                comprow.append(testblock[best_quality])
                datrow.append(testdata[best_quality])
            compimg.append(comprow)
            datarray.append(datrow)
        compimg = fuse_squares(compimg)
        quality = calc_quality(imgarray,compimg)
        print("Size:{} Quality:{}".format(size,quality))
        size-=1
    return brightness_to_image(compimg),datarray,size+1

template = '''def s(d,s,e,z):
 x=range(z)
 return d<1 and[[int((z-r)*(e-s)/z+s)for c in x]for r in x]or d==1 and[[int((z-c)*(e-s)/z+s)for c in x]for r in x]or d==2 and[[int((2*z-r-c)/2*(e-s)/z+s)for c in x]for r in x]or d>2 and[[int((z-r+c)/2*(e-s)/z+s)for c in x] for r in x]
i=lambda a:'\\n'.join([''.join(map(lambda r:" `.,:;'+#@"[r],l))for l in a])
def f(a):
 o=[];c=0;s=0;r=0
 while r<len(a):
  if s<len(a[r][0]):
   o.append([])
   for q in a[r]:
    o[c].extend(q[s])
   s+=1;c+=1
  else:
   s=0;r+=1
 return o
t={};z={}
print(i(f([[s(D>>8,(D>>4)&15,D&15,z)for D in R]for R in t])))'''

template_size_1 = '''print("""{}""")'''

def main(filename,threshold):
    print(filename+" "+str(threshold))
    file = open(filename,'r')
    compimg,datarray,size = main_calc(file.read(),threshold)
    file.close()
    textoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".txt",'w')
    textoutput.write(compimg)
    textoutput.close()
    compoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".py",'w')
    datarray = str(datarray).replace(" ","")
    code = ""
    if size==1:
        code = template_size_1.format(compimg)
    else:
        code= template.format(datarray,str(size))
    compoutput.write(code)
    compoutput.close()
    print("done")

if __name__ == "__main__":
    main(sys.argv[1],float(sys.argv[2]))

This answer could use a lot of improvements, so I'll probably be working on it more over the weekend.
How this works:

Divide image into blocks of size size.
Find best matching block

Blocks can have gradient now!

Calculate quality (according to formula) for entire image.
If correct, write zipped image to file.
Otherwise, decrement size and try again.

This algorithm works well for low quality (0.5, 0.6) but doesn't work too well on the higher quality images (actually inflates). It is also really slow.
Here I have all the generated files, so you won't have to re-generate them again.

Finally, an answer! It's technically non-competing though, since I created Bubblegum after posting this challenge... I'll run the scoring script later and maybe port it to a less esoteric language.

@Dennis Ah, well it shouldn't be too hard to port the output to a python script. Thanks for the heads-up

I just re-read my challenge (after a year, I was a little fuzzy on the details), and it says Your compressor may use built-in byte stream compressors (e.g., gzip), but you have to implement them yourself for the compressed images. That means Bubblegum is out anyway.

I finally remembered I had promised to score this; sorry for the delay. Your code seems to have a typo (comping should be compimg), which I fixed to run the program. Unless I made a mistake when running your code, the dimensions of some of the generated images are incorrect (e.g., image2.txt has 33,164 bytes, but image2-50.0.txt has 33,329) and other do not generate the same file when running the generated programs (image3-50.0.txt has a quality of 0.5110, but running the generated program results in a quality of 0.4508).

Addendum: I downloaded image3-50.0.py from your Dropbox and it matches the file I generated.

@Dennis Oh! Sorry, I forgot about adding the dimensions to the template. Will fix. As for having different generated images, I might know what is causing it (function s in the template), and will look into it.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/