110
\$\begingroup\$

Overview

This is a bot battle to see who can survive the longest. These bots increase their power by being attacked, though, so you need to think carefully before you shoot.

Each turn, you can choose a bot to attack, or defend. Attacking will lower its life and increase its power. Last bot standing wins.

Bots

Each bot starts with 1000 life and 10 power.

When attacked:

  • your attacker's power is subtracted from your life
  • your power raises by 1.

So, if on the first turn, you are attacked by two bots, you will have 980 life and 12 power.

If you choose to defend:

  • your power will be lowered by 1
  • all attacks against you this turn will be reduced by half
  • if you are attacked, you will gain 2 power for each attacker instead of 1

So, if you defend on the first turn and are attacked by two bots, you will have 990 life and 13 power. If you defend and are not attacked, you will have 1000 life, but 9 power.

If at the end of a turn your power is below one, it will be set to one. If your life is below 1, you die.

Input/Output

Bots are called once per turn. There is a time limit of one second for each turn.

Initial

The first time your bot is called, it will be given no arguments. Respond with ok. This is done only to make sure your bot responds. If it doesn't, it will not be added to the player list.

Each turn

Each turn, your bot is given information about all bots in the game as command line arguments. An example of these arguments is:

1 0,1000,10,1 1,995,11,D

The first argument is your bot's unique id. Then, a space separated list of bots appears. Each bot is formatted as:

id,life,power,lastAction

lastAction may be an integer representing which bot they attacked, D if they defended, and X if this is the first turn. The others are all integers.

So in the example above, you are bot 1 and defended on your last turn. Bot 0 attacked you and is still at starting health/power.

Output for each turn is very simple. Simply output the bot you want to attack as an integer (eg 0 or 3), or D to defend. Don't attack dead or non-existent bots, as that counts as an invalid command. Any invalid command will result in you losing 1 power.

Tournament Structure

Each game consists of all bots starting at 1000 health and 10 power. Actions by all bots are taken simultaneously. The maximum number of turns for a game is 1000.

If at the end of the turn there is one bot remaining alive (life > 0), it scores one point and another game is started. If the turn limit is reached and there are multiple bots alive, nobody gets a point. If all remaining bots die on the same turn, nobody gets a point.

A tournament consists of 15 games. Whoever has the most points at the end wins! Ties are broken by the sum of life remaining in each won game.

State

Bots may only read from or write to a single file named after itself, in a direct subfolder named state ("Hero" can write to state/hero.whatever). This file should not exceed 10242 bytes in size. Take care to observe the time limit. Your program must terminate within one second to count, not just give a response.

These files will be wiped before each tournament, but will persist game to game. All bot identifiers (id) will also remain the same between games.

Controller

Below is the tournament controller (Stronger.java). By default, it only outputs the final results (sorted list of players, winner on top), which may take quite a while. It's not frozen, just silent. If you'd like a more detailed turn-by turn output, add the -log argument when running.

To add bots, you have two options:

  • add the command as an argument (java Stronger -log "python bot.py")

  • add the command to defaultPlayers[] in the source ("python bot.py")

The bots Hero, Bully, and Coward can be found in this answer, and will be used for scoring purposes.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Stronger {

    static final String[] defaultPlayers = {
                                "java Hero",
                                "java Bully",
                                "java Coward"
                                };
    final int timeout = 1000;
    final int startLife = 1000;
    final int startPower = 10;
    final int numRounds = 15;

    boolean log = false;
    List<Player> players;

    public static void main(String[] args){
        new Stronger().run(args);
    }

    void run(String[] args){
        init(args);
        for(int i=0;i<numRounds;i++){
            Collections.shuffle(players);
            runGame();
        }
        Collections.sort(players);
        for(Player player : players)
            System.out.println(player.toString());
    }

    void runGame(){
        log("Player Count: " + players.size());
        for(Player player : players)
            player.reset();
        int turn = 0;
        while(turn++ < startLife){
            if(aliveCount() < 2)
                break;
            log("Turn " + turn);
            List<Player> clones = new ArrayList<Player>();
            for(Player player : players)
                clones.add(player.copy());
            for(Player player : players){
                if(player.life < 1 || player.timedOut)
                    continue;               
                String[] args = new String[players.size()+1];
                args[0] = "" + player.id;
                for(int i=1;i<args.length;i++)
                    args[i] = players.get(i-1).toArgument();
                String reply = getReply(player, args);
                Player clone = player.findCopyOrMe(clones);
                if(reply.equals("T")){
                    clone.timedOut = true;
                    clone.life = 0;
                }
                clone.lastAction = reply.trim();
            }

            for(Player player : players){
                if(player.life < 1 || player.timedOut)
                    continue;               
                Player clone = player.findCopyOrMe(clones);
                if(clone.lastAction.equals("D")){
                    clone.power--;
                }else{
                    try{
                        int target = Integer.parseInt(clone.lastAction);
                        for(Player t : players)
                            if(t.id == target && t.life < 1)
                                throw new Exception();
                        for(Player tclone : clones){
                            if(tclone.id == target){
                                int atk = player.power; 
                                if(tclone.lastAction.equals("D")){
                                    atk -= player.power / 2;
                                    tclone.power++;
                                }
                                tclone.life -= atk;
                                tclone.power++;
                            }
                        }
                    } catch (Exception e){
                        log(player.cmd + " returned an invalid command: (" + clone.lastAction + ")");
                        clone.power--;
                    }
                }
            }
            players = clones;
            for(Player player : players){
                if(player.power < 1)
                    player.power = 1;
                log(player.life + "\t\t" + player.power + "\t\t(" + player.id + ")\t" + player.cmd);
            }
            log("\n");
        }

        if(aliveCount() == 1)
            for(Player player : players)
                if(player.life > 0){
                    player.scoreRounds++;
                    player.scoreLife += player.life;
                }
    }

    void log(String msg){if(log)System.out.println(msg);}

    String getReply(Player player, String[] args){
        try{
            List<String> cmd = new ArrayList<String>();
            String[] tokens = player.cmd.split(" ");
            for(String token : tokens)
                cmd.add(token);
            for(String arg : args)
                cmd.add(arg);
            ProcessBuilder builder = new ProcessBuilder(cmd);
            builder.redirectErrorStream();
            long start = System.currentTimeMillis();
            Process process = builder.start();
            Scanner scanner = new Scanner(process.getInputStream());
            process.waitFor();          
            String reply = scanner.nextLine();
            scanner.close();
            process.destroy();
            if(System.currentTimeMillis() - start > timeout)
                return "T";
            return reply;
        }catch(Exception e){
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
    }

    void init(String[] args){
        players = new ArrayList<Player>();
        for(String arg : args){
            if(arg.toLowerCase().startsWith("-log")){
                log = true;
            }else{
                Player player = createPlayer(arg);
                if(player != null)
                    players.add(player);
            }
        }
        for(String cmd : defaultPlayers){
            Player player = createPlayer(cmd);
            if(player != null)
                players.add(player);
        }
    }

    Player createPlayer(String cmd){
        Player player = new Player(cmd);
        String reply = getReply(player, new String[]{});
        log(player.cmd + " " + reply);
        if(reply != null && reply.equals("ok"))
            return player;
        return null;
    }

    int aliveCount(){
        int alive = 0;;
        for(Player player : players)
            if(player.life > 0)
                alive++;
        return alive;
    }

    static int nextId = 0;  
    class Player implements Comparable<Player>{
        int id, life, power, scoreRounds, scoreLife;
        boolean timedOut;
        String cmd, lastAction;

        Player(String cmd){
            this.cmd = cmd;
            id = nextId++;
            scoreRounds = 0;
            scoreLife = 0;
            reset();
        }

        public Player copy(){
            Player copy = new Player(cmd);
            copy.id = id;
            copy.life = life;
            copy.power = power;
            copy.scoreRounds = scoreRounds;
            copy.scoreLife = scoreLife;
            copy.lastAction = lastAction;
            return copy;
        }

        void reset(){
            life = startLife;
            power = startPower;
            lastAction = "X";
            timedOut = false;
        }

        Player findCopyOrMe(List<Player> copies){
            for(Player copy : copies)
                if(copy.id == id)
                    return copy;
            return this;
        }

        public int compareTo(Player other){
            if(scoreRounds == other.scoreRounds)
                return other.scoreLife - scoreLife;
            return other.scoreRounds - scoreRounds;
        }

        public String toArgument(){
            return id + "," + life + "," + power + "," + lastAction;  
        }

        public String toString(){
            String out = "" + scoreRounds + "\t" + scoreLife;
            while(out.length() < 20)
                out += " ";
            return out + "(" + id + ")\t" + cmd;
        }
    }
}

Rules

  • You may enter up to two bots. If you want to remove one from play to enter a third, please delete its post.

  • You may not target or otherwise single out a bot by meta-analysis. Use only the information your bot is given. This includes your own bots, so you may not enter two bots that collude.

  • Do not attempt to interfere with the running of the controller or other bots in any way.

  • Your bot may not instantiate or otherwise run the controller or other bots.

Results

(of bots submitted as of of 2015-05-22 00:00:00Z)

This round of play went a bit better, with only two games stalling out at 1000 turns. Kudos to Ralph Marshall's Santayana, which took first place, being the only bot that scored three wins. That wasn't enough, so he also took third place with Tactician. Stormcrow took second with Phantom Menace, a fine first post here. All in all we had a very nice showing by new members, with the top six places going to people with less than five posts. Congratulations, and welcome to the site!

Bots that scored zero wins are not listed to save space. All bots posted before the timestamp above were run, so if you don't see yours, it didn't win anything.

Wins    Life(tiebreaker)  Name

3       561               perl Santayana.pl
2       850               java PhantomMenace
2       692               perl Tactician.pl
2       524               java Wiisniper
1       227               java Tank
1       184               java Velociraptor
1       7                 java Coward
1       3                 java IKnowYou

Sorta sketchy parallelized controller (by Others):

import java.lang.ProcessBuilder.Redirect;
import java.nio.file.FileSystems;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class Stronger {

    static final String[] defaultPlayers = {
                                "java Hero",
                                "java Bully",
                                "java Coward",
                                "java Psycho",
                                "./monte.out",
                                "java Analyst",
                                "java Guardian",
                                "java Revenger",
                                "python precog.py",
                                //"python snappingTurtle.py",
                                "python beserker.py",
                                "./suprise.out",
                                //"python boxer.py",
                                "python defense.py",
                                "java Tank",
                                "java IKnowYou",
                                //"java BroBot",
                                "java Equaliser",
                                "java Velociraptor",
                                //"java AboveAverage",
                                "java PhantomMenace",
                                "java Wiisniper",
                                //"python semiRandom.py",
                                "/usr/bin/perl tactition.pl",
                                "/usr/bin/perl santayana.pl",
                                //"java GlitchUser"
                                "/usr/local/bin/Rscript opportunity.R",
                                "/usr/local/bin/scala Bandwagoner",
                                };
    final int timeout = 5000;
    final int startLife = 1000;
    final int startPower = 10;
    final int numRounds = 20;

    boolean log = true;
    List<Player> players;

    public static void main(String[] args){
        new Stronger().run(args);
    }

    void run(String[] args){
        init(args);
        for(int i=1;i<=numRounds;i++){
            if(log) System.out.println("Begining round "+ i);
            Collections.shuffle(players);
            runGame();
        }
        Collections.sort(players);
        for(Player player : players)
            System.out.println(player.toString());
    }

    void runGame(){
        log("Player Count: " + players.size());
        for(Player player : players)
            player.reset();
        int turn = 0;
        while(turn++ < startLife){
            if(aliveCount() < 2)
                break;
            log("Turn " + turn);
            List<Player> clones = new ArrayList<Player>();
            for(Player player : players)
                clones.add(player.copy());
            AtomicInteger count=new AtomicInteger(players.size());
            for(Player player : players){
                new Thread(() -> {
                    if(player.life >= 1 && !player.timedOut){
                        String[] args = new String[players.size()+1];
                        args[0] = "" + player.id;
                        for(int i=1;i<args.length;i++)
                            args[i] = players.get(i-1).toArgument();
                        String reply = getReply(player, args);
                        Player clone = player.findCopyOrMe(clones);
                        if(reply.equals("T")){
                            clone.timedOut = true;
                            clone.life = 0;
                        }
                        clone.lastAction = reply.trim();
                    }
                    synchronized(count){
                        count.decrementAndGet();
                        count.notify();
                    }
                }).start();
            }
            synchronized(count){
                while(count.get() > 0){
                    //System.out.println(count);
                    try{
                        count.wait();
                    }catch(InterruptedException e){
                    }
                }
            }

            for(Player player : players){
                if(player.life < 1 || player.timedOut)
                    continue;               
                Player clone = player.findCopyOrMe(clones);
                if(clone.lastAction.equals("D")){
                    clone.power--;
                }else{
                    try{
                        int target = Integer.parseInt(clone.lastAction);
                        for(Player t : players)
                            if(t.id == target && t.life < 1)
                                throw new Exception();
                        for(Player tclone : clones){
                            if(tclone.id == target){
                                int atk = player.power; 
                                if(tclone.lastAction.equals("D")){
                                    atk -= player.power / 2;
                                    tclone.power++;
                                }
                                tclone.life -= atk;
                                tclone.power++;
                            }
                        }
                    } catch (Exception e){
                        log(player.cmd + " returned an invalid command: (" + clone.lastAction + ")");
                        clone.power--;
                    }
                }
            }
            players = clones;
            for(Player player : players){
                if(player.power < 1)
                    player.power = 1;
                log(player.life + "\t\t" + player.power + "\t\t" + player.lastAction + "\t\t(" + player.id + ")\t" + player.cmd);
            }
            log("\n");
        }

        if(aliveCount() == 1)
            for(Player player : players)
                if(player.life > 0){
                    player.scoreRounds++;
                    player.scoreLife += player.life;
                }
    }

    void log(String msg){if(log)System.out.println(msg);}

    String getReply(Player player, String[] args){
        try{
            List<String> cmd = new ArrayList<String>();
            String[] tokens = player.cmd.split(" ");
            for(String token : tokens)
                cmd.add(token);
            for(String arg : args)
                cmd.add(arg);
            ProcessBuilder builder = new ProcessBuilder(cmd);
            builder.directory(FileSystems.getDefault().getPath(".", "bin").toFile());
            //builder.redirectError(Redirect.PIPE);
            long start = System.currentTimeMillis();
            Process process = builder.start();
            Scanner scanner = new Scanner(process.getInputStream());
            process.waitFor();          
            String reply = scanner.nextLine();
            scanner.close();
            process.destroy();
            if(System.currentTimeMillis() - start > timeout)
                return "T";
            return reply;
        }catch(Exception e){
            //e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
    }

    void init(String[] args){
        players = new ArrayList<Player>();
        for(String arg : args){
            if(arg.toLowerCase().startsWith("-log")){
                log = true;
            }else{
                Player player = createPlayer(arg);
                if(player != null)
                    players.add(player);
            }
        }
        for(String cmd : defaultPlayers){
            Player player = createPlayer(cmd);
            if(player != null)
                players.add(player);
        }
    }

    Player createPlayer(String cmd){
        Player player = new Player(cmd);
        String reply = getReply(player, new String[]{});
        log(player.cmd + " " + reply);
        if(reply != null && reply.equals("ok"))
            return player;
        return null;
    }

    int aliveCount(){
        int alive = 0;;
        for(Player player : players)
            if(player.life > 0)
                alive++;
        return alive;
    }

    static int nextId = 0;  
    class Player implements Comparable<Player>{
        int id, life, power, scoreRounds, scoreLife;
        boolean timedOut;
        String cmd, lastAction;

        Player(String cmd){
            this.cmd = cmd;
            id = nextId++;
            scoreRounds = 0;
            scoreLife = 0;
            reset();
        }

        public Player copy(){
            Player copy = new Player(cmd);
            copy.id = id;
            copy.life = life;
            copy.power = power;
            copy.scoreRounds = scoreRounds;
            copy.scoreLife = scoreLife;
            copy.lastAction = lastAction;
            return copy;
        }

        void reset(){
            life = startLife;
            power = startPower;
            lastAction = "X";
            timedOut = false;
        }

        Player findCopyOrMe(List<Player> copies){
            for(Player copy : copies)
                if(copy.id == id)
                    return copy;
            return this;
        }

        public int compareTo(Player other){
            if(scoreRounds == other.scoreRounds)
                return other.scoreLife - scoreLife;
            return other.scoreRounds - scoreRounds;
        }

        public String toArgument(){
            return id + "," + life + "," + power + "," + lastAction;  
        }

        public String toString(){
            String out = "" + scoreRounds + "\t" + scoreLife;
            while(out.length() < 20)
                out += " ";
            return out + "(" + id + ")\t" + cmd;
        }
    }
}
\$\endgroup\$
39
  • 2
    \$\begingroup\$ @Tim The bot list is space separated. Each bot's stats are comma separated. \$\endgroup\$
    – Geobits
    Commented May 14, 2015 at 18:32
  • 3
    \$\begingroup\$ @Mark The current bots are about half defensively oriented and half attack. None of the defensive bots have a single win. I agree that it encourages some defense, but the benefit of aggression is that pure defense cannot win any points at all. You only win points if you are the sole survivor. \$\endgroup\$
    – Geobits
    Commented May 15, 2015 at 4:28
  • 8
    \$\begingroup\$ If anyone's curious how the bots stack up now that there's more submissions, here's the result of my "unofficial" test run: 3-809-Hero; 2-593-Velociraptor; 1-471-SurpriseBot; 1-433-Coward; 1-371-Santayana; 1-364-Wiisniper; 1-262-Analyst; 1-230-Bully; 1-132-Equaliser; 1-71-IKnowYou; 0-0 -- precog, Berserker, BroBot, SemiRandom, MonteBot, Tactician, SnappingTurtle, Psycho, Revenger, Opportunity, PhantomMenace, Tank, Boxer, Guardian, AboveAverage, DefensiveBot. Lots of invalid commands from Opportunity, AboveAvg, BroBot, Boxer, and SemiRandom. \$\endgroup\$
    – OJFord
    Commented May 17, 2015 at 18:04
  • 3
    \$\begingroup\$ I have a parallelized version of the controller that runs games faster than the original controller does, if anyone is interested I can post it... \$\endgroup\$
    – Others
    Commented May 17, 2015 at 23:58
  • 3
    \$\begingroup\$ @Manu As long as each bot isn't being executed simultaneously, it shouldn't matter. I assume the parallel version still has all bots finish one turn before moving to the next. Like I said, I'm going to verify before using it if posted. \$\endgroup\$
    – Geobits
    Commented May 18, 2015 at 14:35

31 Answers 31

26
\$\begingroup\$

C++ - MonteBot

Simulates a large number of random games and chooses the move that leads to the greatest chance of not-dying.

Why think of a strategy when you can let the computer create one for you?

Note: Compile this with the -O3 flag for optimal performance.

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>

//Monte Carlo method constants
const unsigned int total_iters=100000; //total number of simulations
double time_limit=0.7; //approximate CPU time the program is allowed to run before outputting the current best solution
const unsigned int check_interval=4096-1;

unsigned int num_players,my_bot;
const int DEFEND=-1,FIRST=-2,DEAD=-3;
struct Bot{
    short int life,power,lastAttack;
    inline bool is_alive(void){
        return life>0;
    }
    inline void damage(short int dmg){
        life-=dmg;
        if(life<0)life=0;
    }
    inline void charge(short int p){
        power+=p;
        if(power<1)power=1;
    }
    inline bool is_attacking(void){
        return lastAttack>=0;
    }
};
int main(int argc,char*argv[]){
    clock_t start=clock();
    if(argc==1){
        printf("ok");
        return 0;
    }

    srand(time(NULL));

    num_players=argc-2;
    sscanf(argv[1],"%u",&my_bot);

    Bot bots[num_players];
    for(unsigned int i=0;i<num_players;++i){
        char buf[16];
        unsigned int id;
        short int life,power;
        sscanf(argv[i+2],"%u,%hd,%hd,%s",&id,&life,&power,buf);
        Bot &cur_bot=bots[id];
        cur_bot.life=life;
        cur_bot.power=power;
        if(strcmp(buf,"D")==0)cur_bot.lastAttack=DEFEND;
        else if(strcmp(buf,"X")==0)cur_bot.lastAttack=FIRST;
        else sscanf(buf,"%hd",&cur_bot.lastAttack);
    }

    //let the other bots kill each other while we accumulate more power
    if(bots[my_bot].life>750){
        printf("D");
        return 0;
    }

    Bot cur_state[num_players];
    unsigned int won[num_players+1],visited[num_players+1];
    for(int i=0;i<num_players+1;++i){
        won[i]=0;
        visited[i]=0;
    }

    //unsigned long long int sim_length=0;
    for(unsigned int iter=0;iter<total_iters;++iter){
        //ensure that we do not exceed the time limit
        if(iter&check_interval==check_interval){
            clock_t cur_time=clock();
            if((double)(cur_time-start)/(double)CLOCKS_PER_SEC>=time_limit){
                break;
            }
        }
        int first_move=FIRST;
        memcpy(cur_state,bots,sizeof(Bot)*num_players);

        //simulate random moves in the game until
        //a. the player dies, or
        //b. the player is the only one alive
        while(true){
            //++sim_length;
            //check if our bot died
            if(!cur_state[my_bot].is_alive()){
                ++visited[first_move+1];
                break;
            }
            //check if our bot is the only bot left alive
            bool others_alive=false;
            for(unsigned int i=0;i<num_players;++i){
                if(i!=my_bot&&cur_state[i].is_alive()){
                    others_alive=true;
                    break;
                }
            }
            if(!others_alive){
                ++won[first_move+1];
                ++visited[first_move+1];
                break;
            }

            Bot new_bots[num_players];
            memcpy(new_bots,cur_state,sizeof(Bot)*num_players);

            //generate random moves for all players
            bool defend[num_players];
            int possible_moves[num_players+2];
            unsigned int num_moves;
            for(unsigned int i=0;i<num_players;++i){
                num_moves=0;
                if(cur_state[i].is_alive()){
                    possible_moves[num_moves++]=DEFEND;
                    for(unsigned int j=0;j<num_players;++j){
                        if(j!=i&&cur_state[j].is_alive()){
                            possible_moves[num_moves++]=j;
                        }
                    }
                    new_bots[i].lastAttack=possible_moves[rand()%num_moves];
                    defend[num_players]=(new_bots[i].lastAttack==DEFEND);
                }else new_bots[i].lastAttack=DEAD;
            }
            if(first_move==FIRST)first_move=new_bots[my_bot].lastAttack;

            //simulate outcome of moves
            for(unsigned int i=0;i<num_players;++i){
                if(cur_state[i].is_alive()&&new_bots[i].is_attacking()){
                    new_bots[i].charge(-1);
                    int victim=new_bots[i].lastAttack;
                    if(defend[victim]){ //if victim is defending
                        new_bots[victim].charge(2);
                        new_bots[victim].damage(cur_state[i].power/2);
                    }else{
                        new_bots[victim].charge(1);
                        new_bots[victim].damage(cur_state[i].power);
                    }
                }
            }
            memcpy(cur_state,new_bots,sizeof(Bot)*num_players);
        }
    }
    //printf("%f\n",(double)sim_length/(double)total_iters);
    double win_rate=-1;
    int best_move=DEFEND;
    for(int i=0;i<num_players+1;++i){
        if(i-1!=my_bot){
            double cur_rate=(double)won[i]/(double)visited[i];
            if(cur_rate>win_rate){
                win_rate=cur_rate;
                best_move=i-1;
            }
        }
    }
    if(best_move==DEFEND)printf("D");
    else printf("%d",best_move);

    //clock_t end=clock();
    //fprintf(stderr,"%f\n",(double)(end-start)/(double)CLOCKS_PER_SEC);

    return 0;
}

C - MonteFaster

Additionally, this bot can be made to run faster by utilizing multithreading. However, as I do not preemptively know how many iterations the bot can evaluate before it times out (on the judging platform), I will not be using this bot (with the code below) for this competition.

The code below is merely for curiosity's sake.

Note: Compile this with the -O3 and -fopenmp flags for optimal performance.

#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_PLAYERS 32

//Monte Carlo method constants
const unsigned int total_iters=60000; //total number of simulations

unsigned int num_players,my_bot;
const int DEFEND=-1,FIRST=-2,DEAD=-3;
struct Bot{
    short int life,power,lastAttack;
};
int main(int argc,char*argv[]){
    clock_t start=clock();
    if(argc==1){
        printf("ok");
        return 0;
    }

    srand(time(NULL));

    num_players=argc-2;
    sscanf(argv[1],"%u",&my_bot);

    struct Bot bots[MAX_PLAYERS];
    int A;
    for(A=0;A<num_players;++A){
        char buf[16];
        unsigned int id;
        short int life,power;
        sscanf(argv[A+2],"%u,%hd,%hd,%s",&id,&life,&power,buf);
        struct Bot *cur_bot=&bots[id];
        cur_bot->life=life;
        cur_bot->power=power;
        if(strcmp(buf,"D")==0)cur_bot->lastAttack=DEFEND;
        else if(strcmp(buf,"X")==0)cur_bot->lastAttack=FIRST;
        else sscanf(buf,"%hd",&cur_bot->lastAttack);
    }

    //let the other bots kill each other while we accumulate more power
    if(bots[my_bot].life>750){
        printf("D");
        return 0;
    }

    struct Bot cur_state[MAX_PLAYERS];
    unsigned int won[MAX_PLAYERS+1],visited[MAX_PLAYERS+1];
    for(A=0;A<num_players+1;++A){
        won[A]=0;
        visited[A]=0;
    }

    //unsigned long long int sim_length=0;
    int iter;
    #pragma omp parallel for //strangely, the code fails to compile if a variable length array is used in the loop
    for(iter=0;iter<total_iters;++iter){
        //note that we cannot break this loop when we use #pragma omp parallel
        //there is therefore no way to check if we're close to exceeding the time limit

        int first_move=FIRST;
        memcpy(cur_state,bots,sizeof(struct Bot)*num_players);

        //simulate random moves in the game until
        //a. the player dies, or
        //b. the player is the only one alive
        int sim_length=0;
        while(1){
            //++sim_length;
            //check if our bot died
            if(cur_state[my_bot].life<=0){
                ++visited[first_move+1];
                break;
            }
            //check if our bot is the only bot left alive
            int others_alive=0;
            int i;
            for(i=0;i<num_players;++i){
                if(i!=my_bot&&cur_state[i].life>0){
                    others_alive=1;
                    break;
                }
            }
            if(!others_alive){
                ++won[first_move+1];
                //won[first_move+1]+=cur_state[my_bot].life;
                ++visited[first_move+1];
                break;
            }

            struct Bot new_bots[MAX_PLAYERS];
            memcpy(new_bots,cur_state,sizeof(struct Bot)*num_players);

            //generate random moves for all players
            char defend[MAX_PLAYERS];
            //int possible_moves[num_players+2];
            int possible_moves[MAX_PLAYERS+2];
            for(i=0;i<num_players;++i){
                if(cur_state[i].life>0){
                    int j,num_moves=0;
                    possible_moves[num_moves++]=DEFEND;
                    for(j=0;j<num_players;++j){
                        if(j!=i&&cur_state[j].life>0){
                            possible_moves[num_moves++]=j;
                        }
                    }
                    new_bots[i].lastAttack=possible_moves[rand()%num_moves];
                    defend[i]=(new_bots[i].lastAttack==DEFEND);
                }else new_bots[i].lastAttack=DEAD;
            }
            if(first_move==FIRST)first_move=new_bots[my_bot].lastAttack;

            //simulate outcome of moves
            for(i=0;i<num_players;++i){
                if(cur_state[i].life>0&&new_bots[i].lastAttack>=0){
                    new_bots[i].power-=1;
                    if(new_bots[i].power<=0)new_bots[i].power=1;
                    int victim=new_bots[i].lastAttack;
                    if(defend[victim]){ //if victim is defending
                        new_bots[victim].power+=2;
                        new_bots[victim].life-=cur_state[i].power/2;
                    }else{
                        new_bots[victim].power+=1;
                        new_bots[victim].life-=cur_state[i].power;
                    }
                    if(new_bots[victim].life<0)new_bots[victim].life=0;
                }
            }
            memcpy(cur_state,new_bots,sizeof(struct Bot)*num_players);
        }
    }
    //printf("%f\n",(double)sim_length/(double)total_iters);
    double win_rate=-1;
    int best_move=DEFEND;
    for(A=0;A<num_players+1;++A){
        if(A-1!=my_bot){
            double cur_rate=(double)won[A]/(double)visited[A];
            if(cur_rate>win_rate){
                win_rate=cur_rate;
                best_move=A-1;
            }
        }
    }
    if(best_move==DEFEND)printf("D");
    else printf("%d",best_move);
    //fprintf(stderr,"%.3f%% chance (based on %d samples)\n",(double)won[best_move+1]/(double)visited[best_move+1]*100.,total_iters);

    //clock_t end=clock();
    //fprintf(stderr,"%f\n",(double)(end-start)/(double)CLOCKS_PER_SEC);

    return 0;
}
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Interesting strategy. Roughly how long does it take to do a simulation with 20ish opponents? \$\endgroup\$ Commented May 15, 2015 at 15:39
  • 2
    \$\begingroup\$ @RalphMarshall It can do 60 thousand simulations rather quickly (from 0.03 seconds to 0.2 seconds) for a few opponents, but quickly becomes extremely slow for 20 opponents (with an average of 10 seconds). Hopefully, terminating the algorithm prematurely will still yield feasible solutions. \$\endgroup\$
    – Potatomato
    Commented May 15, 2015 at 16:33
  • \$\begingroup\$ I'm considering adding multithreading support for this bot to make the program run faster, but I have no idea how many iterations the judging computer will be able to evaluate before the bot times out. I'll probably sacrifice the first game in order to do some profiling so that the bot will be able to run an optimal number of iterations. \$\endgroup\$
    – Potatomato
    Commented May 18, 2015 at 0:57
23
\$\begingroup\$

Java Psycho

There's no telling what this crazed psycho will do - may attack anyone: a dead bot, or even himself.

import java.util.Random;

public class Psycho {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }

        Random rnd = new Random();
        rnd.setSeed( System.currentTimeMillis() );

        String[] tokens = args[ rnd.nextInt(args.length) ].split(",");
        String target = tokens[0];

        System.out.print(target);
    }
}
\$\endgroup\$
1
21
\$\begingroup\$

Scala - Bandwagoner

The Bandwagoner doesn't care about honor, or principles. Bandwagoner lays low, avoiding being the weakest or the strongest. Bandwagoner goes with the crowd, targeting the consensus target, to avoid drawing attention.

import scala.util.Try

object Bandwagoner {
    case class PlayerStatus(life:Int, power:Int, lastAction:Option[Int])

    def main(args:Array[String]):Unit={
        if(args.length==0)
            println("ok")
        else{
            val myId=args(0).toInt
            val everyonesStatus=(for(action <- args.tail) yield{
                val id :: life :: power :: lastAction :: Nil = action.split(",").toList
                (id.toInt, new PlayerStatus(life.toInt, power.toInt, Try(lastAction.toInt).toOption))
            }).toMap
            println(bandwagon(myId, everyonesStatus(myId), everyonesStatus.filter(_._1 != myId)))
        }
    }

    def bandwagon(myId:Int, self:PlayerStatus, opponents:Map[Int, PlayerStatus]):String={
        val alive=opponents.filter(_._2.life > 0)
        //If their is only one opponent left
        if(alive.size==1){
            val (opponentId, opponent)=alive.head
            //Get win projection
            val willWin=opponent.life/(self.power*1.0) <= self.life/(opponent.power*1.0)
            //If I'm stronger attack, otherwise defend
            if(willWin) opponentId.toString() else "D"

        }
        //Otherwise
        else if(alive.size > 0){
            //If I'm the strongest or weakest
            if(alive.map(_._2.life).max < self.life || alive.map(_._2.life).min > self.life){
                //If I have a good opportunity in terms or power, or passivity
                if(alive.map(_._2.power).max * 1.5 < self.power || !alive.exists(_._2.lastAction.isDefined)){
                    //Attack
                    alive.maxBy(_._2.power)._1.toString()
                }
                //Otherwise
                else 
                    //Lay low
                    "D"
            }
            //Otherwise, BANDWAGON
            else{
                //Obviously we dont want to attack dead opponents, or ourself
                val validTargets=opponents.flatMap(_._2.lastAction).filter(alive.contains(_)).filter(_ != myId)
                if(validTargets.size == 0)
                    "D"
                else
                    //Select the most targeted opponent (Sorry)
                    validTargets.groupBy(i => i).mapValues(_.size).maxBy(_._2)._1.toString()
            }
        }
        //Just to be safe..
        else 
            "D"
    }
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Do you have any idea why I would get the silly error "Try is not a member of scala.util" on the very first line? Googling has left me at a loss. I have a standard scala install, 2.9.2 straight from the repository. \$\endgroup\$
    – Geobits
    Commented May 22, 2015 at 0:39
  • \$\begingroup\$ @Geobits thats an older scala version than mine, I'm running 2.11. If upgrading isn't an option, let me know and I'll fix my code to work. \$\endgroup\$
    – Others
    Commented May 22, 2015 at 1:00
  • 3
    \$\begingroup\$ Got it going. I was reading "Since 2.10" in the docs as "Since 2.1.0" and couldn't figure out why it wouldn't be in 2.9.2 :( \$\endgroup\$
    – Geobits
    Commented May 22, 2015 at 1:09
19
\$\begingroup\$

Java Revenger

The Revenger isn't interested in brawling for brawling's sake. But if attacked, revenge will be sought!

public class Revenger {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }

        String me = args[0], target = "D";
        int last_attacker_power = -1;

        for(int i=1; i<args.length; ++i){
            String[] tokens = args[i].split(",");
            int power = Integer.parseInt(tokens[2]);
            int life  = Integer.parseInt(tokens[1]);

            if( tokens[3].equals(me)
             && power>last_attacker_power
             && life>0  ){
                target = tokens[0];
                last_attacker_power = power;
            }
        }

        System.out.print(target);
    }
}
\$\endgroup\$
2
  • 4
    \$\begingroup\$ FYI: This does not stop attacking even after the target is dead. \$\endgroup\$
    – Geobits
    Commented May 14, 2015 at 19:52
  • 27
    \$\begingroup\$ @Geobits Oh but revenge is a dish best served .. already dead? :p Wasn't deliberate; updated. \$\endgroup\$
    – OJFord
    Commented May 14, 2015 at 20:29
18
\$\begingroup\$

Java - Hero, Bully, and Coward

These three bots are included as examples, but they will be playing in the scoring tournament. They all have simplistic behavior.

Hero

Hero simply attacks whoever has the most life on every turn.

public class Hero {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        String me = args[0], target="D";
        int best=0;
        for(int i=1;i<args.length;i++){
            String[] tokens = args[i].split(",");
            int life = Integer.valueOf(tokens[1]);
            if(life > 0 && life >= best && !tokens[0].equals(me)){
                best = life;
                target = tokens[0];
            }
        }
        System.out.print(target);
    }
}

Bully

Meanwhile, Bully attacks whoever has the least life every turn.

public class Bully {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        String me = args[0], target="D";
        int best=Integer.MAX_VALUE;
        for(int i=1;i<args.length;i++){
            String[] tokens = args[i].split(",");
            int life = Integer.valueOf(tokens[1]);
            if(life > 0 && life <= best && !tokens[0].equals(me)){
                best = life;
                target = tokens[0];
            }
        }
        System.out.print(target);
    }
}

Coward

Coward does nothing but defend until his life reaches 500 or lower. He then attacks whoever has the least power each turn.

public class Coward {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        String me = args[0], action="D";
        int best=Integer.MAX_VALUE;
        for(int i=1;i<args.length;i++){
            String[] tokens = args[i].split(",");
            if(tokens[0].equals(me)){
                if(Integer.valueOf(tokens[1]) > 500){
                    System.out.print("D");
                    System.exit(0);
                }
            }
        }       
        for(int i=1;i<args.length;i++){
            String[] tokens = args[i].split(",");
            int power = Integer.valueOf(tokens[2]);
            if(power <= best && !tokens[0].equals(me) && Integer.valueOf(tokens[1]) > 0){
                best = power;
                action = tokens[0];
            }
        }
        System.out.print(action);
    }
}

Enjoy!

\$\endgroup\$
2
  • 7
    \$\begingroup\$ Interesting that Hero's turns out to be highly effective technique; even against more 'sophisticated' bots (e.g. MonteBot, Analyst). Was it just a simple example, or did you base it on some insight? \$\endgroup\$
    – OJFord
    Commented May 17, 2015 at 18:59
  • 1
    \$\begingroup\$ No, I just threw the first three things I thought of as examples. I didn't think it would do very well at all, to be honest. \$\endgroup\$
    – Geobits
    Commented May 18, 2015 at 18:36
16
\$\begingroup\$

Perl - Tactician

This started off as an edit to my Let 'em Fight bot, but I've made enough changes that I've decided to enter it as a new entry. New logic is as follows

  • If nobody attacked in the previous turn, attack the opponent with the highest life value. This should prevent endings where nobody attacks anybody else, at least as long as I'm still alive.
  • If somebody attacked me on the last turn, pick the most powerful such attacker and hit back.
  • If we are down to two bots, or I'm at a below-average strength, attack the opponent with the highest life.
  • If my own power rating is below average make an attack to increase my power to a more reasonable level
  • Otherwise, bide my time

I've tested this locally against the other Java bots that have been entered and managed to get a few wins, but still not a spectacular entry on my part.

#!/usr/bin/perl

use strict;
use warnings;

# First round
if (!@ARGV) {
    print "ok\n";
    exit;
}

my ($self, @rest) = @ARGV;

my ($myAction, $myPower, $myLife,
    $myMaxAttacker, $myMaxAttackerId, 
    $maxLife, $maxLifeId, 
    $maxPower, $maxPowerId,
    $totLife, $totPower, $living, $amWeak, $numAttackers) = ('D');

# First, get a situation report
for (@rest) {
    my ($id, $life, $power, $action) = split(',');

    # Let the dead rest in peace
    next unless $life>0;

    if ($id == $self) {
        # Keep track of my own power and life for later comparison
        $myPower = $power;
        $myLife = $life;
        next;
    }

    $living++;
    $numAttackers++ if ($action ne 'D');
    $totPower += $power;
    $totLife += $life;

    if ($action == $self) {
        # Bastard hit me!
        if ($power > $myMaxAttacker) {
            $myMaxAttacker = $power;
            $myMaxAttackerId = $id;
        }
    }

    # If you're going to pick a fight, go for the biggest
    # guy in the room.
    if ($life > $maxLife) {
        $maxLife = $life;
        $maxLifeId = $id;
    }

    # Or, go for the guy with the biggest gun
    if ($power > $maxPower) {
        $maxPower = $power;
        $maxPowerId = $id;
    }
}

# If I'm being hit any attacks are back at the strongest attacker,
# otherwise simply the healthiest opponent overall
my $preferredTarget = $myMaxAttackerId;
$preferredTarget = $maxLifeId unless defined $preferredTarget;

# Check to see if I have below-average life, in which case it's time to get moving
$amWeak = $myLife < $totLife/$living;

# Now figure out what to do
if (!$numAttackers) {
    # Everybody is standing around, so let's mix it up
    $myAction = $preferredTarget;
} elsif (defined $myMaxAttackerId) {
    # My momma told me never to stand there and be hit
    $myAction = $myMaxAttackerId;
} elsif ($amWeak || $living == 1) {
    # Either we're down to two bots, or I'm fairly weak. Atack!!!
    $myAction = $preferredTarget;
} elsif ($myPower < $totPower/$living) {
    # Just lash out at random so we do not lose all of
    # our power through permanent defense
    $myAction = $preferredTarget;
} else { 
    # Work up some courage/power by drinking beer
    # in the corner. Use the default defensive action in this case.
    # Else clause exists just for debugging.
}

print "$myAction\n";

Perl - Santayana

Those who do not remember history are doomed to die early, or some such. This bot attempts to take advantage of the multi-round nature of the contest by keeping a history of the total strength of each bot over all rounds and always attacking the strongest one. In theory this should keep any bot from going out to a crushing lead, but of course I'm only collecting stats while I'm alive, so if this bot ends up having a short life the stats are not going to be very good.

#!/usr/bin/perl

use strict;
use warnings;

# First round
if (!@ARGV) {
    print "ok\n";
    exit;
}

# Read in our multi-round/multi-game state information
my $state;
if (open STATE, "state/santayana.out") {
    $state = <STATE>;
    close STATE;
}

# Stuff the historical data into a hash keyed by opponent ID
my %state;
my @state = $state ? split(' ', $state) : ();
for (@state) {
    my ($id, $life, $power) = split ',';
    $state{$id} = [$life, $power];
}

my ($self, @rest) = @ARGV;

my ($maxLife, $maxLifeId, $living) = (0, undef, 0);

# First, get a situation report
for (@rest) {
    my ($id, $life, $power, $action) = split(',');

    # Let the dead rest in peace
    next unless $life > 0;

    $living++;

    # Update the historical hash with latest information
    my $aref = $state{$id};
    if ($aref) {
        $$aref[0] += $life * ($action eq 'D' ? 1 : 1.5);
        $$aref[1] += $power;
    } else {
        $state{$id} = [$life, $power];
    }

    next if ($id == $self);

    # Our target is based on the historically
    # strongest opponent, independent of current state,
    # unless they are actually dead
    if ($life > 0 && $state{$id}->[0] > $maxLife) {
        $maxLife = $state{$id}->[0];
        $maxLifeId = $id;
    }
}

# Write out the latest state for next time around
if (open STATE, ">state/santayana.out") {
    print STATE join(" ", map { join ",", $_, $state{$_}->[0], $state{$_}->[1] } sort { $state{$b}->[0] <=> $state{$a}->[0]} keys %state);
    close STATE;
}

# Now figure out what to do
if (defined $maxLifeId) {
    # Should always be defined, but who knows
    print "$maxLifeId\n";
} else {
    print "D\n";
}
\$\endgroup\$
3
  • \$\begingroup\$ Note that I'm pretty sure I deleted my other entry (labelled Let 'em Fight), so I should only have two bots, but if not please ignore that one and only use these two. Thanks. \$\endgroup\$ Commented May 16, 2015 at 1:27
  • 6
    \$\begingroup\$ Congratulations on taking both first and third place in the latest scoreboard :) \$\endgroup\$
    – Geobits
    Commented May 22, 2015 at 3:07
  • \$\begingroup\$ Most excellent! This has been a great challenge. \$\endgroup\$ Commented May 22, 2015 at 10:48
15
\$\begingroup\$

Java Guardian

The Guardian protects the weak. He will attack whoever spent their last turn picking on the now-weakest living bot (besides possibly himself). He's smart enough, though, to not attack:

1) Himself (unless he is the bully, then he feels that he deserves it.)

2) Bots who attack themselves

3) Dead bots

4) Bots with less than ten life left (who have hopefully learned their lessons!)

The Guardian will pick on the same player repeatedly if needed. Ties for "weakest player" and "who picked on him" both go to the first one in the list (which is to say, random).

public class Guardian{
    public static void main (String[] args){
        if(args.length == 0){
            System.out.print("ok");
            System.exit(0);
        }

        String myId = args[0];
        int lowestLife = Integer.MAX_VALUE;
        int life = Integer.MIN_VALUE;
        String[] tokens = {};
        String opposingId = "";
        String weakestOpponent = "";
        String lastTarget = "";

        for(int i=1; i<args.length; i++){
            tokens = args[i].split(",");
            opposingId = tokens[0];
            life = Integer.parseInt(tokens[1]);
            lastTarget = tokens[3];
            if(life < lowestLife && life > 0 &&
                !opposingId.equals(myId) &&
                !opposingId.equals(lastTarget)){
                weakestOpponent = opposingId;
            }
        }

        for(int i=1; i<args.length; i++){
            tokens = args[i].split(",");
            opposingId = tokens[0];
            life = Integer.parseInt(tokens[1]);
            lastTarget = tokens[3];
            if (lastTarget.equals(weakestOpponent) &&
                life > 10){
                System.out.println(opposingId);
                System.exit(0);
            }
        }

        System.out.println("D");
    }
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Please fix the numerous typos and mistakes in this and your other bot. I can compile neither of them as it is. \$\endgroup\$
    – Geobits
    Commented May 15, 2015 at 1:34
  • \$\begingroup\$ I think in case it has been the bully it should think about what it's done, i.e. Defend. \$\endgroup\$ Commented May 15, 2015 at 15:14
  • \$\begingroup\$ Errors fixed. @user3819867, I thought about adding that, but a Guardian will protect the weak at all costs, even at a cost to himself. \$\endgroup\$
    – Xynariz
    Commented May 15, 2015 at 17:18
13
\$\begingroup\$

Java - Analyst

Determines each opponent's threat by multiplying its power by 5 if it attacked and by 25 if it attacked the Analyst. In case of a tie, it attacks the player with least life.

Much of the code was borrowed from Geobits' answer.

public class Analyst {
    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("ok");
            System.exit(0);
        }
        String me = args[0], that = "D";
        int maxThreat = 200;
        for (int i = 1; i < args.length; i++) {
            String[] player = args[i].split(",");
            int threat = Integer.parseInt(player[2]) * 100
                         * (!player[3].equals("D") ? 5 : 1)
                         * (player[3].equals(me) ? 5 : 1)
                         - Integer.parseInt(player[1]);
            if (threat > maxThreat && Integer.parseInt(player[1]) > 0 && !player[0].equals(me)) {
                maxThreat = threat;
                that = player[0];
            }
        }
        System.out.println(that);
    }
}
\$\endgroup\$
0
13
\$\begingroup\$

R - Opportunity

This bot needs to be called using Rscript Opportunity.R. It keeps in memory who did what and it attacks the opponent the less likely to defend itself (i. e. who used D the least in the past) unless he realizes that one of the bot has been attacking him twice in a row in which case it starts defending itself or attacks the attacking bot if it can kill it faster than the attacker can.

args <- commandArgs(TRUE)
if(length(args)){
    myid <- as.integer(args[1])
    data <- as.data.frame(do.call(rbind,strsplit(args[-1],",")),stringsAsFactors=FALSE)
    colnames(data) <- c('id','health','power','last')
    data$id <- as.integer(data$id)
    data$health <- as.integer(data$health)
    data$power <- as.integer(data$power)
    data <- data[order(data$id),]
    if(all(data$last=="X")){
        cat(data$last,file="state/opportunity.txt",sep="\n")
        cat(sample(data$id[data$id!=myid],1))
        }else{
            past <- as.matrix(read.table("state/opportunity.txt",sep=" "))
            lastturn <- data$last
            lastturn[data$health<1] <- "X"
            lastturn[nchar(lastturn)>1] <- "E" #If a bot returned anything else than an integer
            past <- cbind(past,lastturn)
            cat(apply(past,1,paste,collapse=" "),sep="\n",file="state/opportunity.txt")
            who_bully_me <- sapply(apply(past,1,rle),function(x)ifelse(tail(x$v,1)==myid,tail(x$l,1),0))
            if(any(who_bully_me>1)){
                bullyid <- which.max(who_bully_me)-1
                if(data$health[data$id==bullyid]%/%data$power[data$id==myid]<=data$health[data$id==myid]%/%data$power[data$id==bullyid]){
                    cat(bullyid)
                    }else{cat("D")}
                }else{
                    defend <- rowSums(past=="D")
                    defend[past[,ncol(past)]=="X"] <- NA
                    defend[myid+1] <- NA
                    choice <- which(defend%in%min(defend,na.rm=TRUE)) -1
                    if(length(choice)>1) choice <- sample(choice,1)
                    cat(choice)
                }
        }
}else{
    cat("ok")
    }
\$\endgroup\$
3
  • \$\begingroup\$ Nice. I had started a solution in R but this is much better. \$\endgroup\$
    – Alex A.
    Commented May 15, 2015 at 16:31
  • \$\begingroup\$ Well if you can think of a good strategy, do not hesitate to enter a new R bot on the ring (you're welcome to re-use some of my code even if needed)! I would be curious to see a Julia bot though (since you occasionally golf in Julia). \$\endgroup\$
    – plannapus
    Commented May 16, 2015 at 6:43
  • \$\begingroup\$ Perhaps I'll give it a shot in Julia. Thanks for the encouragement. :) \$\endgroup\$
    – Alex A.
    Commented May 16, 2015 at 17:50
12
\$\begingroup\$

Python 2, Snapping Turtle

Hides in its shell, emerges to bite the first person to attack it last turn (unless they're dead), then goes back into its shell again
Run with python snapping_turtle.py <input>

import sys
class snapping_turtle:
    def bitey(self,command):


        if len(command) <=1:
            return 'ok'
        else:
            last_turn = list(command)
            bot_to_bite = -1
            me = last_turn[0]
            for k in xrange(0,len(last_turn)):
                #bot_action = last_turn.split(',')

                if len(last_turn[k]) ==1:
                    pass
                else:
                    bot_action = last_turn[k].split(',')
                    # If they hit me
                    if bot_action[3] == me:
                        # And if they're still alive, hit them
                        if int(bot_action[1]) > 0:
                            bot_to_bite = bot_action[0]
                            break
                        #Otherwise, stay in my shell
                        else:
                            pass

            if bot_to_bite > -1:
                return bot_to_bite
            else:
                return 'D'

print snapping_turtle().bitey(sys.argv[1:])

Python 2, Berserker

Berserker smash! Hits itself until it has enough power, then starts attacking the closest living thing. Also hits itself if it can't work out who it should be hitting, for whatever reason.

EDIT: Changed Berserker's rage threshold from 50 to 25, since otherwise it would take itself out before doing anything...

Runs with python Berserker.py <input>

import sys
class Berserker:
    def rage(self,command):


        if len(command) <=1:
            return 'ok'
        else:
            last_turn = list(command)
            bot_to_smash = -1
            me = last_turn[0]
            my_power = last_turn[int(me)].split(',')[2]
            for k in xrange(0,len(last_turn)):
                #bot_action = last_turn.split(',')

                if len(last_turn[k]) ==1:
                    pass
                else:
                    bot_action = last_turn[k].split(',')
                    if int(my_power) < 25:
                        #Too weak! Need make stronger for smashing!
                        bot_to_smash = me
                        break
                    else:
                        #Now strong! Smash! Not smash broken things!
                        if bot_action[0] != me and bot_action[1] > 0:
                            bot_to_smash = bot_action[0]

            if bot_to_smash > -1:
                return bot_to_smash
            else:
                #Confused! Don't like! MORE POWER!
                return me

print Berserker().rage(sys.argv[1:])
\$\endgroup\$
11
\$\begingroup\$

Python 2 - The Boxer

The Boxer bot will mainly keep its guard up, ducking and weaving. Every now and then it will send a quick jab or cross to a strong opponent that is not defending well, hoping to wear them down over time.

import sys, re, random
if sys.argv[1:]:
    rows = [map(int, re.sub('[DX]', '-1', b).split(',')) for b in sys.argv[2:]]
    bots = dict((r.pop(0),r) for r in rows if r[1]>0 and r[0]!=int(sys.argv[1]))
    target = max(bots, key=lambda b: bots[b][0]-300*(bots[b][2]==-1))
    print target if random.randint(1,100) > 70 else 'D'
else:
    print 'ok'

UPDATE: Fixed a bug that caused some invalid outputs.

\$\endgroup\$
4
  • 4
    \$\begingroup\$ 354 characters? What is this, code golf? ;) \$\endgroup\$ Commented May 15, 2015 at 21:31
  • 1
    \$\begingroup\$ @Darthfett: just because there are many Java submissions around here, doesn't mean everybody needs to litter their code with similar amounts of boilerplate... \$\endgroup\$ Commented May 15, 2015 at 23:43
  • 12
    \$\begingroup\$ The Boxer is lean - he easily meets his fighting weight. He enjoys a healthy diet of comprehensions and lambdas. You won't find him eating a static typing burger, or munching on braces fries. \$\endgroup\$ Commented May 16, 2015 at 3:18
  • 4
    \$\begingroup\$ @CarpetPython Terseness for terseness's sake is just as bad as verbosity. \$\endgroup\$
    – Kroltan
    Commented May 16, 2015 at 4:38
9
\$\begingroup\$

C - SurpriseBot

Assumes the first turn is going to be a mess and defends. After that, attack someone who didn't defend last turn--they'll never see it coming!

This answer is a tad silly, but I wanted to write a rather general platform for building an answer in C, so here you go.

//What doesn't kill me...
//SurpriseBot

#include "stdio.h"
#include "string.h"
#include "stdlib.h"

int myself;

typedef struct s_Bot {
    int id;
    int life;
    int power;
    /* -1 is defending */
    int lastAction;
} Bot;

int compare_bots(const void* a, const void* b) {
    Bot one = *(Bot*)a;
    Bot two = *(Bot*)b;
    
    /* Never, ever target myself */
    if (one.id == myself) {
        return 1;
    }
    else if (two.id == myself) {
        return -1;
    }
    
    /* Also, don't target any bot that is dead */
    if (one.life < 1) {
        return 1;
    }
    else if (two.life < 1) {
        return -1;
    }
    
    /* Prefer those who did not defend last turn */
    /* They'll never see it coming!              */
    if (one.lastAction >= 0 && two.lastAction < 0) {
        return -1;
    }
    else if (one.lastAction < 0 && two.lastAction >= 0) {
        return 1;
    }
    
    /* Try to target the lowest health */
    if (one.life < two.life) {
        return -1;
    }
    else if (one.life > two.life) {
        return 1;
    }
    
    /* Try to target the more powerful bot */
    if (one.power < two.power) {
        return 1;
    }
    else if (one.power > two.power) {
        return -1;
    }
    else return 0;
}

int main(int argc, char** argv) {
    if (argc == 1) {
        printf("ok");
    }
    
    else {
        int quit = 0;
        myself = atoi(argv[1]);
        
        /* Populate a list of all bots */
        int num = argc - 2;
        Bot bots[num];
        
        int i;
        for (i = 0; i < num; i++) {
            char buf[100];
            sscanf(argv[2 + i], "%d,%d,%d,%s", &bots[i].id, &bots[i].life, &bots[i].power, buf);
            switch (buf[0]) {
                case 'X':
                    /* Assume the first turn is a bloodbath and we don't want any part of it */
                    printf("D");
                    quit = 1;
                    break;
                case 'D':
                    bots[i].lastAction = -1;
                    break;
                default:
                    sscanf(buf, "%d", &bots[i].lastAction);
                    break;
            }
            if (quit) {
                goto done;
            }
        }
        
        qsort(bots, num, sizeof(Bot), compare_bots);
        
        printf("%d", bots[0].id);
    }
    
done:
    return 0;
}
\$\endgroup\$
9
\$\begingroup\$

Python 2 - Precog

Precog tries to predict everyone else's moves based on past action frequency, then tries a few simulations and picks one that maximizes its score. It's not particularly reliable, but then... ESP isn't real. :D

import json, sys
from random import choice

#'S'/'W' = attack high/low power (strong/weak)
#'H'/'F'  = attack high/low health (hale/frail)
#'A' = attack defender (armor)
#'R' = attack random (it doesn't know)
#'D' = defend

amin = lambda x: x.index(min(x))
amax = lambda x: x.index(max(x))

def pick(history, ids, action):
    if action == 'D':
        return 'D'
    if action == 'R' or len(history['all'][-1][action]) < 1:
        return choice(ids)
    return choice(history['all'][-1][action])

args = sys.argv
if len(args) == 1:
    print 'ok'
    sys.exit()
me = args[1]

def notme(l):
    tmp = list(l)
    try:
        tmp.remove(me)
    except ValueError:
        pass
    return tuple(tmp)

args = args[2:]
try:
    with open('precog.state') as f:
        history = json.load(f)
except (IOError, ValueError):
    history = {}
if len(history) == 0:
    history = {'all':[]}

args = [a.split(',') for a in args]
ids,hps,pows,acts = zip(*args)
hps,pows = map(int,hps), map(int,pows)

for i,h,p,a in args:
    if a == 'X': #most people will try not to attack armored
        history[i] = {'a':'SWHFRD','health':[],'power':[],'score':[]}
    elif acts == 'D':
        history[i]['a'] += 'D'
    else:
        for x in 'SWHFA':
            if a in history['all'][-1][x]:
                history[i]['a'] += x
                break
        else:
            history[i]['a'] += 'R'
    history[i]['health'] += int(h),
    history[i]['power'] += int(p),
    history[i]['score'] += int(h)*int(p),

history['all'] += {'S':[ids[amax(pows)]],
                   'W':[ids[amin(pows)]],
                   'H':[ids[amax(hps)]],
                   'F':[ids[amin(hps)]],
                   'A':[ids[i] for i in filter(lambda x:acts[x]=='D',range(len(acts)))]},

with open('precog.state','w') as f:
    json.dump(history,f)
      
scores = dict(zip('SWHFRAD',[0]*7))
for _ in range(50):
    for act in 'SWHFRAD':
        _score = {}
        p,h,a = dict(zip(ids,pows)),dict(zip(ids,hps)),{i:0 for i in ids}
        opp = {i:choice(history[i]['a']) for i in ids if i != me}
        opp[me] = act
        m = {o:[1,2][opp[o]=='D'] for o in opp}
        for o in opp:
            if opp[o] != 'D':
                if o == me:
                    target = pick(history, notme(ids), opp[o])
                else:
                    target = pick(history, ids, opp[o])
                h[target] -= p[o]/m[target]
                a[target] += 1
        for o in opp:
            p[o] += m[o] * a[o]
            _score[o] = p[o] * h[o]
        scores[act] += _score.pop(me) - sum(_score.values())

target = pick(history, notme(ids), scores.keys()[amax(scores.values())])
if target == me:
    target = choice(notme(ids))
print target
\$\endgroup\$
1
  • 2
    \$\begingroup\$ This bot seems to occasionally attack other bots which are already dead. It is otherwise a rather strong bot (because it brought my bot down from winning all of the time against the test bots to only 50% of the time when your bot was included in my tests). \$\endgroup\$
    – Potatomato
    Commented May 17, 2015 at 3:12
9
\$\begingroup\$

Java - Phantom Menace

Hi! This is my first post here at the Code Golf. I am a C# guy so pardon my french please. I have used parts of the Hero and Coward sample codes.

My bot is a simple guy with quite a political attitude. Most of the time he just hides himself in the lobby drinking coffee and preparing his schemes. But when the chance arises and the prospect of profit is strong enough he jumps up from his comfortable lobby armchair, throws away the newspaper and goes for the money.

He just defends himself after any harm is done to him. Otherwise he behaves like a true Hero (That is also a political decision as it is quite safe). When he has only three competitors he goes for the win.

He follows a few basic principles. Every serious politician should have some unbreakable principles and a clearly defined profile...

Do not help anyone but yourself! (Egoist)

Glory means death! (Sceptic)

There is nothing after you die! (Atheist)

public class PhantomMenace {
    public static void main(String[] args) {
        if(args.length < 1)
        {
            System.out.print("ok");
            System.exit(0);
        }

           String me = args[0], target="D", secondTarget="D", worstTarget="D";
           int best=0;
           int attackerCount = 0;
           int numBots= 0;
           int secondBest=0;
           int worst=0;

        for(int i=1;i<args.length;i++)
        {
            String[] tokens = args[i].split(",");
            int life = Integer.valueOf(tokens[1]);
            if(life > 0 && life >= best)
            {
                secondBest = best;
                secondTarget = target;
                best = life;
                target = tokens[0];

            }
            else if(life > 0 && life >= secondBest)
            {
                secondBest= life;
                secondTarget = tokens[0];
            }

            if(life > 0 && life <= best)
            {
            worst = life;
            worstTarget = tokens[0];
            }
            // count incoming attacks
            if(tokens[3].equals(me))
            attackerCount++;
            // count living bots
            if(life>0)
            numBots++;
        }

        // activate offensive regime?!
        if(numBots<5)
        {
            if(target.equals(me))
              System.out.print(secondTarget);
            else
              System.out.print(target);
        }
        else
        {
          if(worstTarget.equals(me))
            System.out.print("D");
          if(target.equals(me))
            System.out.print("D");
          else if(attackerCount>0)
            System.out.print("D");
          else
            System.out.print(target);
        }

    }
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Very nice, and currently in second place. Welcome to the site :) \$\endgroup\$
    – Geobits
    Commented May 22, 2015 at 3:07
  • \$\begingroup\$ Oh thanks, although it is a pleasant surprise I have to admit I never stopped believing in my bot :P. \$\endgroup\$
    – Stormcrow
    Commented May 23, 2015 at 12:34
9
\$\begingroup\$

bash - CopyCat

The CopyCat admires the strong, healthy and aggressive ones and attacks the same as they did. When if she has the "impression", that the majority of the bots are attacking here, she starts defending herself or attacking the weak ones unless she gets stronger or the most other bots stop attacking here.

Simply execute it with /bin/bash copycat.sh

#!/bin/bash

if [[ "$1" == "" ]]; then echo "ok"; exit; fi

debug() {
    #echo "$(date): $*" >> copycat.log 
    return;
}

me=$1; shift
meAsTarget=0
myAction="D" #better than an invalid command
topBot=-1
topBotAwe=0
worstBot=-1
worstBotAwe=100
aliveBots=0

myMostWeakAttacker=-1
mmwaAwe=0

if [[ -e "./state/copycat.state" ]]; then
    . ./state/copycat.state
fi

for rawBot 
do
    if [[ "$rawBot" == "" ]]; then continue; fi
    if [[ $(echo $rawBot | grep -Fo ',' | wc -l) -ne 3 ]]; then continue; fi

    bot=(${rawBot//,/ })
    id=${bot[0]}; life=${bot[1]}; power=${bot[2]}; lastAction=${bot[3]}

    printf "%d\n" "$lastAction" > /dev/null 2>&1
    if [[ "$?" -ne 0 && "$lastAction" != "D" ]]; then continue; fi

    if [[ "$life" -le 0 ]]; then continue; fi
    ((aliveBots++))

    awesomeness=$(( 2 * (((life/10) * power) / (life/10 + power)) ))
    if [[ "$id" -eq "$me" ]]; then
        myLastAction="$lastAction"
        myAwe="$awesomeness"
    else
        lastBot=$id
    fi

    if [[ "$awesomeness" -gt "$topBotAwe"
        && "$lastAction" != "D"
        && "$lastAction" != "$me" ]]; then
            topBot=$id
            topBotAwe=$awesomeness
            topBotTarget=$lastAction
    fi

    if [[ "$awesomeness" -lt "$worstBotAwe" ]]; then
        worstBot=$id
        worstBotAwe=$awesomeness
    fi

    if [[ "$lastAction" -eq "$me" ]]; then
        ((meAsTarget++))
        if [[ "$awesomeness" -lt "$mmwaAwe" ]]; then
            myMostWeakAttacker=$id
            mmwaAwe=$awesomeness
        fi
    fi
done

backupStrategy() {
    if [[ "$myMostWeakAttacker" != "-1" && "$mmwaAwe" -lt "$myAwe" ]]; then
        debug "attacking my most weak attacker ($myMostWeakAttacker) who is weaker then me"
        myAction=$myMostWeakAttacker
    elif [[ "$worstBot" != "-1" && "$worstBot" != "$me" ]]; then
        debug "attacking the worst bot $worstBot"
        myAction=$worstBot
    elif [[ "$myMostWeakAttacker" != "-1" ]]; then
        debug "attacking my most weak attacker $myMostWeakAttacker"
        myAction=$myMostWeakAttacker
    else
        debug "no one is attacking me anymore; attacking the last ones"
        myAction=$lastBot
    fi
}

if [[ "$meAsTarget" -gt "$((aliveBots/2))" ]]; then
    #hit-and-run
    if [[ "$myLastAction" == "D" && "$myAwe" -gt "$worstBotAwe" ]]; then
        debug "I am still under fire, but not the worst one.."
        backupStrategy
    else
        debug "I was attacked to much; defending now (attack level: $meAsTarget)"
        myAction="D"
        meAsTarget=$((meAsTarget-aliveBots/2))
    fi
elif [[ "$topBotTarget" != "" ]]; then
    myAction=$topBotTarget

    for rawBot
    do
        if [[ "$rawBot" == "" ]]; then break; fi
        bot=(${rawBot//,/ })
        if [[ "${bot[0]}" -eq "$topBotTarget" ]]; then
            if [[ "${bot[1]}" -le 0 ]]; then
                backupStrategy
            else
                debug "copying strategy from bot $topBot attacking $myAction"
            fi
            break
        fi
    done
else
    backupStrategy
fi

if ! [[ -d "./state" ]]; then mkdir -p "./state"; fi
cat <<EOF_STATE > "./state/copycat.state"
topBotTarget="$topBotTarget"
meAsTarget="$meAsTarget"
EOF_STATE

echo "$myAction"
exit 0

Her weakness: she might never get better as the ones she looks up to. :()

\$\endgroup\$
8
\$\begingroup\$

Python 3 DefensiveBot

Bot tries to find the enemy with the highest power it can kill with its current power. Otherwise, defend. Run with python DefensiveBot.py id bot1 etc

import sys

def resolve(bots, power, life):
    highPowerCanKill = -1
    highPower = 0
    for i in bots:
        if int(i[1]) < int(power):
            if(int(i[2]) > int(highPower)) and (int(i[1]) > 0):
                highPower = i[2]
                highPowerCanKill = i[0]
    if highPowerCanKill != -1:
        return highPowerCanKill
    else:
        return "D"

args = sys.argv
if len(args) == 1:
    print("ok")
    sys.exit()
fileName = str(__file__).split('\\')
fileName = fileName[len(fileName)-1]
myId = args[1]

bots = []

for i in args:
    i = i.split(',')
    if len(i) == 1:
        continue
    if i[0] == myId:
        power = i[2]
        life = i[1]
        continue
    elif i[0] == fileName:
        continue

    bots.append(i)

kill = resolve(bots, power, life)
print(kill)
\$\endgroup\$
6
  • \$\begingroup\$ This doesn't seem to run correctly with no arguments: The first time your bot is called, it will be given no arguments. Respond with ok. This is done only to make sure your bot responds. If it doesn't, it will not be added to the player list. \$\endgroup\$
    – Geobits
    Commented May 14, 2015 at 17:25
  • \$\begingroup\$ @Geobits fixed. \$\endgroup\$ Commented May 14, 2015 at 17:29
  • \$\begingroup\$ Ok, it runs, but there's extraneous printing going on. I have to comment out lines 28 and 32 for it to give valid responses. Otherwise it just dies. \$\endgroup\$
    – Geobits
    Commented May 14, 2015 at 17:33
  • \$\begingroup\$ You might also want to make sure a bot is alive before targeting them. This targets dead ones quite often, which counts as an invalid move and lowers your power. \$\endgroup\$
    – Geobits
    Commented May 14, 2015 at 17:35
  • \$\begingroup\$ sighs fixed. I have a feeling this isn't the last fix :P \$\endgroup\$ Commented May 14, 2015 at 17:38
8
\$\begingroup\$

I Know You - Java

Analyzes all enemies and uses this information to defend itself better. Unfortunately, it is prone to revenge attacks.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class IKnowYou {
    final static int LINES = 40;
    Bot me;
    final List<Bot> bots = new ArrayList<>();
    final List<Bot> livingEnemies = new ArrayList<>();
    final File file = new File("state/IKnowYou");
    final long lineCount;

    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        new IKnowYou(args).run();
    }

    public IKnowYou(String[] args) {
        for (int i = 1; i < args.length; i++) {
            Bot bot = new Bot(args[i], args[0]);
            bots.add(bot);
            if (bot.isMe) {
                me = bot;
            } else if (bot.life > 0) {
                livingEnemies.add(bot);
            }
        }
        lineCount = lineCount();
    }

    void run() {
        if (me.lastAction.equals("X")) {
            createFile();
            updateFile();
            System.out.println(livingEnemies.get(0).id);
            System.exit(0);
        }
        if (lineCount % LINES != 0) {
            updateFile();
        }
        if (underAttack()) {
            System.out.println("D");            
        } else {
            for (Bot bot : livingEnemies) {
                if (bot.lastAction.equals(me.id)){
                    System.out.println(bot.id);
                    return;
                }
            }
            int maxP = 0;
            Bot maxPowerBot = null;
            for (Bot bot : livingEnemies) {
                if (bot.power > maxP){
                    maxP = bot.power;
                    maxPowerBot = bot;
                }
            }
            System.out.println(maxPowerBot.id);
        }
    }

    void createFile() {
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {}
        }
    }

    void updateFile() {
        List<Bot> oldBots = new ArrayList<>();
        if (me.lastAction.equals("X")) {
            for (Bot bot : bots) {
                Bot copyBot = bot.copy();
                bot.life = 1000;
                bot.power = 10;
                oldBots.add(copyBot);
            }
        } else {
            String oldState = "";
            try (BufferedReader input = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = input.readLine()) != null && !line.equals("\n")) {
                    oldState = line;
                }
            } catch (Exception e) {}
            String[] parts = oldState.split(" ");
            for (int i = 0; i < parts.length; i++) {
                oldBots.add(new Bot(parts[i]));
            }
        }
        List<List<String>> ids = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            ids.add(new ArrayList<String>());
        }
        int maxL = -1, minL = 1001, maxP = 0;
        for (Bot bot : oldBots) {
            if (bot.life > maxL) {
                ids.get(0).clear();
                maxL = bot.life;
                ids.get(0).add(bot.id);
            } else if (bot.life == maxL) {
                ids.get(0).add(bot.id);
            }
            if (bot.life < minL) {
                ids.get(1).clear();
                minL = bot.life;
                ids.get(1).add(bot.id);
            } else if (bot.life == minL) {
                ids.get(1).add(bot.id);
            }
            if (bot.power > maxP) {
                ids.get(2).clear();
                maxP = bot.power;
                ids.get(2).add(bot.id);
            } else if (bot.power == maxP) {
                ids.get(2).add(bot.id);
            }
        }
        StringBuilder[] output = new StringBuilder[3];
        for (int i = 0; i < 3; i++) {
            output[i] = new StringBuilder();
        }
        output[0].append("maxL");
        output[1].append("minL");
        output[2].append("maxP");
        for (Bot bot : bots) {
            if (bot.isMe) 
                continue;
            for (int i = 0; i < 3; i++) {
                if (ids.get(i).contains(bot.lastAction)) {
                    output[i].append(' ').append(bot.id);
                }
            }
        }
        try(FileWriter wr = new FileWriter(file, true)) {
            for (int i = 0; i < 3; i++) {
                output[i].append('\n');
                wr.append(output[i].toString());
            }
            StringBuilder sb = new StringBuilder();
            for (Bot bot : bots) {
                sb.append(bot.id).append(',').append(bot.life).append(',').append(bot.power).append(' ');
            }
            wr.append(sb.toString().trim() + "\n");
        } catch (IOException e) {}
    }

    boolean underAttack() {
        Bot attacker = null;
        for (Bot bot : bots) {
            if (bot.lastAction.equals(me.id)) {
                if (attacker != null) {
                    return true;
                } else {
                    attacker = bot;
                }
            }
        }

        int maxL = 0, minL = 1001, maxP = 0;
        for (Bot bot : bots) {
            if (bot.life > maxL)
                maxL = bot.life;
            if (bot.life < minL)
                minL = bot.life;
            if (bot.power > maxP)
                maxP = bot.power;
        }
        if ((me.life < maxL && me.life > minL && me.power < maxP) || livingEnemies.size() == 1) {
            return false;
        }
        List<Map<String, Integer>> stats = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            stats.add(new HashMap<String, Integer>());
        }
        for (Bot bot : bots) {
            for (int i = 0; i < 3; i++) {
                stats.get(i).put(bot.id, 0);
            }
        }
        try (BufferedReader input = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = input.readLine()) != null) {
                if (line.startsWith("m")) {
                    int map = line.startsWith("maxL") ? 0 : line.startsWith("minL") ? 1 : 2;
                    String[] parts = line.split(" ");
                    for (int i = 1; i < parts.length; i++) {
                        int count = stats.get(map).get(parts[i]);
                        stats.get(map).put(parts[i], count+1);
                    }
                }
            }
        } catch (Exception e) {}
        for (int i = 0; i < 3; i++) {
            if ((me.life == maxL && i == 0) || (me.life == minL && i == 1) || (me.power == maxP && i == 2)) {
                for (String id : stats.get(i).keySet()) {
                    int count = stats.get(i).get(id);
                    if (count / ((float)lineCount / 4) > 0.65) {
                        for (Bot bot : bots) {
                            if (bot.id.equals(id)) {
                                if (bot.life > 0) {
                                    return true;
                                } else {
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    long lineCount() {      
        try (LineNumberReader  lnr = new LineNumberReader(new FileReader(file))) {
            lnr.skip(Long.MAX_VALUE);
            return lnr.getLineNumber();
        } catch (IOException e) {
            return 0;
        }
    }

    class Bot {
        String id, lastAction;
        int life, power;
        boolean isMe;

        public Bot() {}

        public Bot(String bot, String myId) {
            String[] parts = bot.split(",");
            id = parts[0];
            life = Integer.valueOf(parts[1]);
            power = Integer.valueOf(parts[2]);
            lastAction = parts[3];
            isMe = id.equals(myId);
        }

        public Bot(String oldBot) {
            String[] parts = oldBot.split(",");
            id = parts[0];
            life = Integer.valueOf(parts[1]);
            power = Integer.valueOf(parts[2]);
        }

        Bot copy() {
            Bot bot = new Bot();
            bot.id = id;
            bot.lastAction = lastAction;
            bot.life = life;
            bot.power = power;
            bot.isMe = isMe;
            return bot;
        }
    }
}
\$\endgroup\$
8
\$\begingroup\$

Java Tank

The Tank doesn't think, he doesn't care, he just attacks the first bot he sees! He is smart enough to not attack himself or dead ones, though.

public class Tank{
    public static void main (String[] args){
        if(args.length == 0){
            System.out.print("ok");
            System.exit(0);
        }

        String myId = args[0];
        int life = Integer.MIN_VALUE;
        String[] tokens = {};
        String opposingId = "";

        for(int i=1; i<args.length; i++){
            tokens = args[i].split(",");
            opposingId = tokens[0];
            life = Integer.parseInt(tokens[1]);
            if(life > 0 && !opposingId.equals(myId)){
                System.out.println(opposingId);
                System.exit(0);
            }
        }
        System.out.println("D");
    }
}
\$\endgroup\$
1
  • 1
    \$\begingroup\$ As noted on your other bot, this doesn't compile as it is. \$\endgroup\$
    – Geobits
    Commented May 15, 2015 at 1:45
7
\$\begingroup\$

Java - Velociraptor

The Velociraptor is a vicious killer. She will lie in wait until attacked, observing potential prey. She then goes in for the quick kill, taking down the target she can kill the fastest. After beginning her assault, the raptor knows no fear and will continue taking victims until she is the only survivor.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Velociraptor {

    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.print("ok");
            System.exit(0);
        }
        Velociraptor raptor = new Velociraptor(args);
        System.out.print(raptor.determineVictim());
    }

    private final String observationsFilePath = "state/velociraptor.txt";
    private final File observationsFile = new File(observationsFilePath);

    private int id, life, power, round;
    private List<Bot> preyList;
    private Map<Integer, Integer> preyDefendCounts;

    public Velociraptor(String[] preyStates) {
        loadObservations();
        observePrey(preyStates);
        saveObservations();
    }

    private void observePrey(String[] preyStates) {
        this.id = Integer.valueOf(preyStates[0]);
        preyList = new ArrayList<>();
        for (int i = 1; i < preyStates.length; i++) {
            String[] tokens = preyStates[i].split(",");
            int preyId = Integer.valueOf(tokens[0]);
            int preyLife = Integer.valueOf(tokens[1]);
            int preyPower = Integer.valueOf(tokens[2]);
            String lastAction = tokens[3];

            if (preyId == this.id) {
                this.life = preyLife;
                this.power = preyPower;
            } else if (preyLife > 0) {
                Bot prey = new Bot();
                prey.id = preyId;
                prey.life = preyLife;
                prey.power = preyPower;
                prey.lastAction = lastAction;
                preyList.add(prey);
                //Clever girl!
                if (prey.lastAction.equals("D")) {
                    int preyDefendCount = preyDefendCounts.getOrDefault(prey.id, 0);
                    preyDefendCount++;
                    preyDefendCounts.put(prey.id, preyDefendCount);
                }
            }
        }
    }

    public String determineVictim() {
        if (this.life == 1000) { //lay in wait until attacked
            return "D";
        }
        double fastestKill = 1000; //max game rounds
        Bot victim = null;
        for (Bot prey : preyList) {
            int preyDefendCount = preyDefendCounts.getOrDefault(prey.id, 0);
            double effectiveMultiplier = 1 - (.5 * preyDefendCount / round);
            double turnsToKill = prey.life / (this.power * effectiveMultiplier);
            //target whoever can be killed fastest
            //in case of tie, kill the prey with more power first
            if (turnsToKill < fastestKill || (victim != null && turnsToKill == fastestKill && prey.power > victim.power)) {
                fastestKill = turnsToKill;
                victim = prey;
            }
        }
        return String.valueOf(victim.id);
    }

    private void loadObservations() {
        preyDefendCounts = new HashMap<>();
        if (observationsFile.exists()) {
            try (Scanner scanner = new Scanner(observationsFile)) {
                round = Integer.valueOf(scanner.nextLine());
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    String[] tokens = line.split(",");
                    int preyId = Integer.valueOf(tokens[0]);
                    int preyDefendCount = Integer.valueOf(tokens[1]);
                    preyDefendCounts.put(preyId, preyDefendCount);
                }

            } catch (FileNotFoundException ex) {
                System.out.println(ex.getMessage());
            }
        }
        round++;
    }

    private void saveObservations() {
        if (!observationsFile.exists()) {
            try {
                observationsFile.createNewFile();
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
        }
        try (PrintWriter writer = new PrintWriter(observationsFile)) {
            writer.println(round);
            if (preyDefendCounts != null) {
                preyDefendCounts.entrySet().stream().forEach(entry -> writer.println(entry.getKey() + "," + entry.getValue()));
            }
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        }
    }

    private class Bot {

        public int id, life, power;
        public String lastAction;
    }
}
\$\endgroup\$
7
\$\begingroup\$

Python 3 - SemiRandom

Chooses between attack and defend based on randomness weighted by previous strongness-changes after attacks and defends. If attack is choosen it attacks the strongest player. Strongness is defined as life * power.

Against the 3 example bots it rarely wins. Maybe in the wild...

import sys, random

def get_goodness(r,d):
    if len(d)==0:
        return 0
    return sum(v/(r-k+5) for k,v in d.items())/sum(1/(r-k+5) for k,v in d.items())

def get_att_chance(r,ad,dd,b):
    ag=get_goodness(r,ad)+500+p/2/len(b)
    dg=get_goodness(r,dd)+500    
    return ag/(ag+dg)

args=sys.argv
if len(args)==1:
    print("ok")
    with open('state/semirandom.txt','w') as f:
        f.write('-1\n1000\n10\n{}\n{}\n"S"\n')
    sys.exit()
me=int(args[1])
b=[]
for ae in args[2:]:
    if ae[-1] in 'DX':    
        ae=ae[:-1]+'-1'
    ae=ae.split(',')
    if int(ae[0])!=me:
        b+=[[int(ae[i]) for i in range(4)]]
    else:
        l,p=int(ae[1]),int(ae[2])
with open('state/semirandom.txt','r') as f:
    data=f.read()
co,lo,po,ad,dd,h=map(eval,data.split('\n')[:-1])
r=len(ad)+len(dd)
vc=l*p-lo*po
if co==0:
    ad[r]=vc
if co==1:
    dd[r]=vc   
ll=sum([be[1] for be in b])
em=ll/p/len(b)/(1000-r)*2
target_id=max(b,key=lambda be:be[1]*be[2])[0]
if random.random()<em:
    action=0
else:
    if random.random()<get_att_chance(r,ad,dd,b):
        action=0
    else:
        action=1        
if action==0:
    act=str(target_id)
else:
    act='D'
with open('state/semirandom.txt','w') as f:
    f.write('{}\n{}\n{}\n{}\n{}\n"{}"\n'.format(action,l,p,ad,dd,h+act))        
print(act)
\$\endgroup\$
7
\$\begingroup\$

Java- The Roman Tortoise

The Roman Tortoise will attack anyone who comes near him, but will also randomly decide to attack other bots because it's not a coward. It occasionally (1 in 50) shows forgiveness.

import java.util.NoSuchElementException;
import java.util.Random;

public class RomanTortoise {

    public static void main(String[] args) {
        Random r = new Random();
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        try{
            String me = args[0];
            try{
            if(args[1].split(",")[3].equals("X"))
            {
                 System.out.print("D");
                 System.exit(0);
            }
            }
            catch(NoSuchElementException nse)
            {
                
            }
            for(int i = 1; i<args.length; i++)
            {
                try{
                    String[] tokens = args[i].split(",");
                    if(tokens.length>3)
                    {
                        String lastAction = tokens[3];
                        
                        if(lastAction.equals(me) && (Integer.parseInt(tokens[1])>0))
                        {
                            //probably attack that bot
                            if(r.nextInt()%50 != 0)
                            {
                                System.out.print(tokens[0]);
                                System.exit(0);
                            }
                        }
                    }
                }
                catch(NoSuchElementException nse)
                {
                
                }
            }
            if(r.nextInt()%2 == 0)
            {
                for(int i = 0; i<100; i++)
                {
                    try{
                        int j = (r.nextInt() % (args.length-1)) + 1;
                        String[] tokens = args[j].split(",");
                        if(tokens.length>3)
                        {
                            if(Integer.valueOf(tokens[1])>0)
                            {
                                System.out.print(tokens[0]);
                                System.exit(0);
                            }
                        }
                    }
                    catch(NoSuchElementException nse)
                    {
                        
                    }
                }
            }
        }
        catch(Exception e){}
        System.out.print("D");
        System.exit(0);
    }

}
\$\endgroup\$
2
  • \$\begingroup\$ Is there any particular reason why you attempt to catch a NoSuchElementException when one doesn't seem to be thrown in the try block? Or am I missing something? \$\endgroup\$
    – TNT
    Commented May 23, 2015 at 20:25
  • \$\begingroup\$ @TNT not any more. I was getting that exception sometimes when accessing one of the elements of an array. Corrected my bug but just left the try catch in - better safe than sorry :) \$\endgroup\$
    – euanjt
    Commented May 23, 2015 at 20:46
7
\$\begingroup\$

Java - BroBot

BroBot will attack the most powerful opponent unless an enemy with an attack greater than some progressively smaller value decides to attack BroBot, in which case he will defend that turn.

public class BroBot {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("ok");
            return;
        }

        int health = 0, id = Integer.parseInt(args[0]);
        for (int k = 1; k < args.length; k++) {
            if (Integer.parseInt(args[k].split(",")[0]) == id) {
                health = Integer.parseInt(args[k].split(",")[1]);
                break;
            }
        }

        String action = "";
        for (String s : args) {
            if (!s.contains(",")) continue;
            String[] botInfo = s.split(",");
            int botId = Integer.parseInt(botInfo[0]);
            if (botId == id) continue;
            if (!botInfo[3].equals("D")) {
                try {
                    if (Integer.parseInt(botInfo[3]) == id && Integer.parseInt(botInfo[2]) >= health / 4) {
                        action = "D";
                        break;
                    }
                } catch (NumberFormatException ex) {
                    continue;
                }
            }
        }

        if (action.isEmpty()) {
            int max = 0;
            for (String s : args) {
                if (!s.contains(",")) continue;
                String[] botInfo = s.split(",");
                if (Integer.parseInt(botInfo[0]) == id ||
                    Integer.parseInt(botInfo[1]) <= 0) continue;
                int attack = Integer.parseInt(botInfo[2]);
                if (attack > max) {
                    attack = max;
                    action = botInfo[0];
                }
            }
        }
        System.out.println(action);
    }
}

Java - SisBot

What's a brother without a sister? Many things... but that's beside the point. Being the smarter bot, SisBot saves the last actions of each bot, analyzes their current and last actions and makes her move - she'll attack the bot with the highest power without a second thought provided that her health and power are high enough and that no other bot with a power stat above a certain value decides to attack her; in that case she'll switch between attacking and defending, or just straight defending if the attacker's power is really high.

import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class SisBot {
    private static final Path directoryPath = Paths.get("state");
    private static final Path filePath = Paths.get("state" + java.io.File.separator + "SisBot.txt");
    private List<Bot> botList;
    private List<String> fileContents;
    private int id, health, power, turn;

    public SisBot(String[] args) throws IOException {
        if (args.length == 0) {
            createSaveFile();
            System.out.println("ok");
            System.exit(0);
        }
        fileContents = Files.readAllLines(filePath, Charset.defaultCharset());
        for (int k = 1; k < args.length; k++) {
            if (args[k].split(",")[3].equals("X")) {
                Files.write(filePath, "".getBytes());
                fileContents.clear();
                break;
            }
        }
        getBots(args);
        makeMove();
        writeBots();
    }

    private void createSaveFile() throws IOException {
        if (!Files.exists(filePath)) {
            if (!Files.exists(directoryPath))
                Files.createDirectory(directoryPath);
            Files.createFile(filePath);
        }
        else
            Files.write(filePath, "".getBytes());
    }

    private void getBots(String[] args) {
        id = Integer.parseInt(args[0]);
        botList = new ArrayList<Bot>();
        for (int k = 1; k < args.length; k++) {
            String[] botInfo = args[k].split(",");
            if (Integer.parseInt(botInfo[0]) != id && Integer.parseInt(botInfo[1]) > 0)
                botList.add(new Bot(args[k]));
            else if (Integer.parseInt(botInfo[0]) == id) {
                health = Integer.parseInt(botInfo[1]);
                power = Integer.parseInt(botInfo[2]);
            }
        }
    }

    private void makeMove() throws IOException {
        if (fileContents.isEmpty()) {
            System.out.println(botList.get((int)(Math.random()*botList.size())).getId());
            return;
        }
        getLastAction();
        String action = "";
        int maxHealth = 0, maxPower = 0;
        for (Bot b : botList) {
            if (power >= 40 && health >= 250) {
                if (b.getPower() > maxPower && (!b.getAction().equals("D") || botList.size() == 1)) {
                    maxPower = b.getPower();
                    action = String.valueOf(b.getId());
                }
            }
            else if (b.getAction().equals(String.valueOf(id)) && b.getLastAction() != null && b.getLastAction().equals(String.valueOf(id))) {
                System.out.println(health % 2 == 0 ? b.getId() : "D");
                return;
            }
            else if (b.getAction().equals(String.valueOf(id)) && b.getPower() > 50) {
                System.out.println("D");
                return;
            }
            else {
                if (b.getHealth() > maxHealth) {
                    maxHealth = b.getHealth();
                    action = String.valueOf(b.getId());
                }
            }
        }
        System.out.println(action);
    }

    private void getLastAction() {
        boolean endNext = false;
        for (String s : fileContents) {
            if (s.startsWith("Turn")) {
                turn = Integer.parseInt(s.split(" ")[1]);
                if (endNext)
                    break;
                else {
                    endNext = true;
                    continue;
                }
            }
            if (s.isEmpty()) break;
            String[] botInfo = s.split(",");
            for (Bot b : botList) {
                if (b.getId() == Integer.parseInt(botInfo[0]))
                    b.setLastAction(botInfo[4]);
            }
        }
    }

    private void writeBots() throws IOException {
        StringBuilder sb = new StringBuilder();
        String s = System.lineSeparator();
        sb.append("Turn " + ++turn + s);
        for (Bot b : botList) {
            b.setLastAction(b.getAction());
            sb.append(b.toString() + s);
        }
        sb.append(s);
        for (String str : fileContents)
            sb.append(str + s);
        Files.write(filePath, sb.toString().getBytes());
    }

    public static void main(String[] args) throws IOException {
        new SisBot(args);
    }

    private class Bot {
        private int id, health, power;
        private String action, lastAction;

        public Bot(String info) {
            String[] botInfo = info.split(",");
            id = Integer.parseInt(botInfo[0]);
            health = Integer.parseInt(botInfo[1]);
            power = Integer.parseInt(botInfo[2]);
            action = botInfo[3];
        }

        public int getId() {
            return id;
        }

        public int getHealth() {
            return health;
        }

        public int getPower() {
            return power;
        }

        public String getAction() {
            return action;
        }

        public void setLastAction(String lastAction) {
            this.lastAction = lastAction;
        }

        public String getLastAction() {
            return lastAction;
        }

        @Override
        public String toString() {
            return new StringBuilder()
                    .append(id).append(",")
                    .append(health).append(",")
                    .append(power).append(",")
                    .append(action).append(",")
                    .append(lastAction).toString();
        }
    }
}

I've really got to learn a different language... :P

\$\endgroup\$
2
  • \$\begingroup\$ It appears that you need a check for the selected target already being dead. \$\endgroup\$ Commented May 15, 2015 at 20:24
  • \$\begingroup\$ I thought I already had that... but then again I did create a different strategy before posting here. Thanks for catching that. \$\endgroup\$
    – TNT
    Commented May 15, 2015 at 21:46
6
\$\begingroup\$

Java - Wiisniper - reflex agent

A simple reflex agent, which identifies the most dangerous bot using a simple heuristic and then attacks it.

public class Wiisniper {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        String me = args[0], target="D";
        double bestRatio = Integer.MIN_VALUE;

        String[] tokens = args[Integer.valueOf(me)].split(",");
        double myLife = Integer.valueOf(tokens[1]);
        double myPower = Integer.valueOf(tokens[2]);

        for(int i=1;i<args.length;i++){
            tokens = args[i].split(",");
            double life = Integer.valueOf(tokens[1]);
            double power = Integer.valueOf(tokens[2]);
            double ratio = myLife/power - life/myPower;
            if(tokens[3].equals(me)) //attacks my bot
                ratio = ratio * 5;
            if(life > 0 && power > 0 && !tokens[0].equals(me) && myPower > 0 && ratio > bestRatio){
                bestRatio = ratio;
                target = tokens[0];
            }
        }
        System.out.print(target);
    }
}
\$\endgroup\$
6
\$\begingroup\$

Java - Above Average

Tries to maintain his stats at the upper quartile. Uses predicting technology to predict what the enemy will do.

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class AboveAverage {

    private static final String FILE_NAME = "state" + File.separator + "AboveAverage";

    private File file = new File(FILE_NAME);
    private List<Bot> bots = new ArrayList<>();
    private Bot me;
    private List<List<Bot>> history = new ArrayList<>();
    private String[] args;

    public AboveAverage(String[] args) {
        this.args = args;
        this.bots = readBotArray(args);
        bots.stream().filter(bot -> bot.isMe).forEach(bot -> me = bot); //Intellij told me to do this...
        if (!file.exists()){
            try {
                file.getParentFile().mkdirs();
                file.createNewFile();
            } catch (IOException ignored) {}
        }
        readHistory();
        updateFile();
    }

    private List<Bot> readBotArray(String[] args){ //First parameter is my id.
        List<Bot> bots = new ArrayList<>();
        String myId = args[0];
        for (String arg : args) {
            if (arg.equals(myId)) {    // `==` not `.equals()`
                continue;
            }
            Bot bot = new Bot(arg, myId);
            bots.add(bot);
        }
        bots.sort(Comparator.comparingDouble((Bot a) -> a.life).reversed());
        return bots;
    }

    private void updateFile() {
        PrintStream out;
        try {
            out = new PrintStream(new FileOutputStream(file, true), true);
            for (String s : args){
                if (!s.matches("\\d+|\\d+,-?\\d+,\\d+,(\\d+|D)")){
                    s.replaceAll("(\\d+,-?\\d+,\\d+,).*", "$1Invalid");
                }
                out.print(s + " ");
            }
            out.println();
        } catch (FileNotFoundException ignored) {}
    }

    private void readHistory() {
        try {
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()){
                String line = scanner.nextLine().trim();
                if (line.length() > 0) {
                    history.add(readBotArray(line.split("\\s+")));
                }
            }
        } catch (FileNotFoundException ignored) {}
    }

    public static void main(String[] args) throws FileNotFoundException {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        try {
            System.out.print(new AboveAverage(args).normalize());
        } catch (Exception e){
            Writer writer = new StringWriter();
            PrintWriter printWriter = new PrintWriter(writer);
            e.printStackTrace(printWriter);
            String s = writer.toString();
            System.out.print("error: " + s.replace("\n", " | "));
        }
    }

    String normalize() {
        if (history.size() == 0 || me.lastAction.equals("X")){
            return "D";
        }

        if (bots.stream().mapToInt(bot -> (bot.life + me.power - 1)/me.power).sum() < me.life/bots.stream().mapToInt(bot -> bot.power).sum()){
            return bots.stream().max(Comparator.comparingInt(a->a.power)).get().id;
        }

        List<Bot> bestHistory = history.stream().max((a,b) -> {
            int differenceA = 0;
            int differenceB = 0;
            for (int i = 0; i < a.size(); i++){
                if (!a.get(i).equals(bots.get(i))){
                    differenceA++;
                }
                if (!b.get(i).equals(bots.get(i))){
                    differenceB++;
                }
            }
            if (differenceA != differenceB){
                return differenceA - differenceB;
            }
            for (int i = 0; i < a.size(); i++){
                differenceA += Math.abs(bots.get(i).life - a.get(i).life) + Math.abs(bots.get(i).power - a.get(i).power) * 10;
                differenceB += Math.abs(bots.get(i).life - b.get(i).life) + Math.abs(bots.get(i).power - b.get(i).power) * 10;
            }
            return differenceA - differenceB;
        }).get();


        int i = history.indexOf(bestHistory) + 1;
        List<Bot> after = i == history.size() ? bots : history.get(i);

        Map<Bot, String> actions = new HashMap<>();
        for (Bot bot : bots){
            if (bot.equals(me)){
                continue;
            }
            after.stream().filter(future -> future.equals(bot)).forEach(future -> actions.put(bot, future.lastAction));
        }

        List<String> myActions = new ArrayList<>();
        myActions.add("D");
        myActions.add("InvalidChoice");
        myActions.addAll(bots.stream().map(bot -> bot.id).collect(Collectors.toList()));

        Map<String,List<Bot>> scenarios = new HashMap<>();
        for (String action : myActions){
            List<Bot> simulatedBots = bots.stream().map(Bot::copy).collect(Collectors.toList());  //IntelliJ told me to (kind of) golf these lines.
            actions.put(me, action);
            simulatedBots.stream().filter(bot -> actions.get(bot).equals("D")).forEach(Bot::defend);
            simulatedBots.stream().filter(bot -> !actions.get(bot).equals("D")).forEach(bot -> bot.attack(actions.get(bot), simulatedBots));
            scenarios.put(action, simulatedBots);
        }

        return scenarios.keySet().stream().min(Comparator.comparingInt((String action) -> {
            List<Bot> scenario = scenarios.get(action);
            Bot me = scenario.stream().filter(a->a.isMe).findAny().get();
            scenario.removeIf(a->a.life<1||a.equals(me));
            scenario.sort(Comparator.comparingInt(a->a.life));
            int bestLife = scenario.get(scenario.size() * 3 / 4).life;
            scenario.sort(Comparator.comparingInt(a->a.power));
            int bestPower = scenario.get(scenario.size() * 3 / 4).power;
            scenario.add(me);
            return Math.abs(me.power - bestPower)*20 + Math.abs(me.life - bestLife);
        })).get();
    }

    class Bot {
        String id, lastAction;
        int life, power;
        boolean isMe;
        boolean isDefending = false;

        public Bot() {}

        public Bot(String bot, String myId) {
            String[] parts = bot.split(",");
            id = parts[0];
            life = Integer.valueOf(parts[1]);
            power = Integer.valueOf(parts[2]);
            lastAction = parts[3];
            isMe = id.equals(myId);
        }

        Bot copy() {
            Bot bot = new Bot();
            bot.id = id;
            bot.lastAction = lastAction;
            bot.life = life;
            bot.power = power;
            bot.isMe = isMe;
            return bot;
        }

        void defend(){
            this.isDefending = true;
            this.power--;
        }

        void attack(int power){
            if (isDefending) {
                this.power += 2;
                this.life -= power / 2;
            } else {
                this.power++;
                this.life -= power;
            }
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Bot bot = (Bot) o;

            return id.equals(bot.id);

        }

        @Override
        public int hashCode() {
            return id.hashCode();
        }

        void attack(String attackId, List<Bot> bots) {
            if (life < 1){
                return;
            }
            Bot attacked = bots.stream().filter((Bot a) -> a.id.equals(attackId)).findFirst().orElse(null);
            if (attacked == null){
                power--;
                return;
            }
            if (attacked.life < 1){
                power--;
                return;
            }
            attacked.attack(power);
        }
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Supposed to use state/whatever not status. Also seems to except IndexOutOfBounds on first turn. \$\endgroup\$
    – OJFord
    Commented May 17, 2015 at 15:24
6
\$\begingroup\$

Java Equaliser

Even though defending is clearly the most effective strategy (:P), this guy thinks that bopping people over the head until they topple giants seems like fun. But screw those people who defend all the time. They don't get no power from this guy.

public class Equaliser {
    public static void main (String[] args) {
        if (args.length == 0) {
            System.out.print("ok");
            System.exit(0);
        }
    
        String myId = args[0];
        String[] tokens;
        int life, power;
        int lowestPower = Integer.MAX_VALUE;
        String lowest = "";
        int lowestLife = 1000;
        int myLife = 0;
    
        for (int i=1; i<args.length; i++) {
            tokens = args[i].split(",");
            life = Integer.parseInt(tokens[1]);
            power = Integer.parseInt(tokens[2]);
            if (!tokens[0].equals(myId)) {
                if (life > 0 && power < lowestPower && !tokens[3].equals("D")) {
                    lowest = tokens[0];
                    lowestPower = power;
                }
                lowestLife = Math.min(life, lowestLife);
            } else {
                myLife = life;
            }
        }
        
        if (myLife < lowestLife*5/4) {
            // IT'S TIME TO DEFEND!
            System.out.println("D");
        } else if (lowestPower != Integer.MAX_VALUE) {
            System.out.println(lowest);
        } else {
            // Them buffed up perma-defenders don't need no power
            System.out.println("D");
            // And if you can't beat 'em, join 'em
        }
    }
}
\$\endgroup\$
5
\$\begingroup\$

Java - Pacifier

first submission ever ! \o/ Was working on a bot for this contest that use huge data-saving and try to find pattern, and thought of this one. Basically, if he thinks his damages are too low to do anything useful, he will protect himself. Otherwise, he will attack the more threatening opponent, which is determined by the number of hit needed to kill him, and it's damage output. Couldn't give it a try, but I think he can do some nice job !

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Pacifier
{
    private static final File DATA_FILE = new File("state"+File.separator+"Pacifier.whatever");
    public static void main(String[] args)
    {

        if(args.length==0)
        {

            if(DATA_FILE.exists())
            {
                try {
                    DATA_FILE.delete();
                } catch (Exception e) {System.out.println("D");System.exit(0);}
            }
            try{
                DATA_FILE.createNewFile();
            }catch (IOException e) {}
            System.out.println("ok");
            System.exit(0);
        }

        int ownId=0,ownHp=1,ownAt=1;
        String known = null;
        BufferedReader bf = null;

        try{
            bf=new BufferedReader(new FileReader(DATA_FILE));
            known=bf.readLine();
        }catch(Exception e){System.out.println("D");System.exit(0);}

        boolean firstTurn = known==null;
        String[] mk = null,iniData=null;
        if(!firstTurn)
        {       
            mk = known.split(" ");
            iniData = mk[0].split(",");
            iniData[1] = String.valueOf(Integer.parseInt(iniData[1])+1);

        }

        String[] datas = new String[args.length-1]; 
        boolean hasReseted = true;
        for(String s : args)
        {
            if(!s.contains(","))
                ownId=Integer.parseInt(s);

            else
            {
                String[] tmp = s.split(",");
                hasReseted=(Integer.parseInt(tmp[1])==1000)?hasReseted:false;
                if(Integer.parseInt(tmp[0])==ownId)
                {
                    ownHp=Integer.parseInt(tmp[1]);
                    ownAt=Integer.parseInt(tmp[2]);
                }
                int id=Integer.parseInt(tmp[0]);
                datas[id]=s;

                if(!firstTurn)
                {
                    if(tmp[3]!="D"){
                        int to =Integer.parseInt(mk[id+1].split(",")[4]);
                        int pa = Integer.parseInt(mk[id+1].split(",")[2]);
                        datas[id]+=","+(to+pa);
                    }
                    else
                        datas[id]+=","+Integer.parseInt(mk[id+1].split(",")[4]);
                }
                else
                    datas[id]+=",0";
            }
        }

        if(firstTurn||hasReseted)
        {
            iniData = new String[2];
            iniData[0]=ownId+"";
            iniData[1]="0";
        }

        int target=(ownId==0)?1:0;
        float best=-100.f;
        if(Integer.parseInt(iniData[1])<40
                &&Integer.parseInt(iniData[1])%3==0)
            target=-1;
        else
            for(String s:datas)
            {
                if(s!=null&&s.contains(","))
                {
                    String[] tmp = s.split(",");
                    int id = Integer.parseInt(tmp[0]);
                    float hp =Float.parseFloat(tmp[1]);
                    float at = Float.parseFloat(tmp[2]);

                    float curr=((hp/(float)ownAt)*at)*(0.1f*at);
                    float dangerOverall= Float.parseFloat(tmp[4])/(100*hp);
                    target=(curr*dangerOverall>=best
                            &&id!=ownId
                            &&hp>0)?Integer.parseInt(tmp[0]):target;
                    best=(curr*dangerOverall>=best
                            &&id!=ownId
                            &&hp>0)?curr:best;
                }
            }
        store(iniData,datas);
        System.out.println((target>=0)?target:"D");
    }

    private static void store(String[] iniData,String[] datas)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(iniData[0]+","+iniData[1]);
        for(String s:datas)
        {
            if(s==null)
                break;
            sb.append(" "+s);
        }
        FileWriter fw = null;
        try{
            fw=new FileWriter(DATA_FILE);
            fw.write(sb.toString());
            fw.flush();
            fw.close();
        }catch(Exception e){e.printStackTrace();}
    }
}

He doesn't have a big brain, so he doesn't remember anything, but I think it could do some nice work. Funny point : if he's the last alive, he'll try to kick some dead bodies, zombies scares him !

Edit :

Did send ok on the first turn, just tested it against the samples, he's getting some hard time, gonna work a little bit on him before.

Edit 2:

he now memorize some datas, and do much better, never won, but actually losing each time by <50 hp... ho, and one of the run i did against samples gave me this :

14 3170 java Bully
0 0 java Pacifier
0 0 java Hero
0 0 java Coward

It's no longer happening(He won some points actually :)), but was funny :D.

Edit 3:

Using the correct Filename, and some improvement. Work pretty well, and is much better when a lot of bots are here :).

\$\endgroup\$
4
\$\begingroup\$

Java - Meta Fighter

Note: Please tell me if it doesn't work

The Meta Fighter doesn't consider every opponent as an individual enemy. He considers all of them as a whole. The Meta Fighter adds up the combined power and strength of all enemies, and considers it to be him vs. them. He then calculates which move would be most effective in lowering both of those scores. Killing a weak opponent is helpful because it lowers strength and power at the same time. However, if attacking an enemy would give it more beneficial power than it would take away strength, he decides it's not worth it and either defends or attacks himself. The Meta Fighter is only wondering why the opponent is at war with himself...

(BTW, My Second Entry Ever to Codegolf)

package folder;

public class MetaFighter {
    public static void main(String[] args) {
        if(args.length < 1){
            System.out.print("ok");
            System.exit(0);
        }
        String me = args[0], target = "D";
    int weakestAmount = 2000, weakest = 0, totalLife = 0, totalPower = 0, threat = 0, enemies = 0;
    int life = 0,power = 0;
        for(int i = 1; i < args.length; i++){
        String[] data = args[i].split(",");
        if(me.equals(data[0])){
            life = Integer.parseInt(data[1]);
            power = Integer.parseInt(data[2]);
        }else{
            if(Integer.parseInt(data[1]) > 0){
                if(Integer.parseInt(data[1]) < weakestAmount){
                    weakest = Integer.parseInt(data[0]);
                    weakestAmount = Integer.parseInt(data[1]);
            }
            totalLife += Integer.parseInt(data[1]);
            totalPower += Integer.parseInt(data[2]);
            enemies++;
            }
        }
    }
    int powerV,totalPowerV,lifeV,totalLifeV,Defend = 0,AttackSelf = 0;
     powerV = power;
     totalPowerV = totalPower;
     lifeV = life;
     totalLifeV = totalLife;
    MetaFighter m = new MetaFighter();
    
    threat = m.calculateThreat(0, 0,totalLifeV,lifeV,powerV,totalPowerV, enemies);
    if (threat < 0){
        target = Integer.toString(weakest);
    }else{
    lifeV = lifeV - powerV;
    powerV++;
    AttackSelf = m.calculateThreat(0, 1,totalLifeV,lifeV,powerV,totalPowerV, enemies);  
     powerV = power;
     totalPowerV = totalPower;
    lifeV = life;
    totalLifeV = totalLife;
    Defend = m.calculateThreat(0, 2,totalLifeV,lifeV,powerV,totalPowerV, enemies);
    if(threat > AttackSelf && threat > Defend){
        target = Integer.toString(weakest);
    }
    if(Defend > AttackSelf && Defend > threat){
        target = "D";
    }
    if(AttackSelf > threat && AttackSelf > Defend){
        target = me;
    }
    if (Defend == threat){
        target = Integer.toString(weakest);
    }
    if (enemies < 3){
        target = Integer.toString(weakest);
    }
    }
    System.out.print(target);
    System.exit(0);
}
private int calculateThreat(int i, int s,int totalLifeV,int lifeV,int powerV, int totalPowerV, int enemies){
    if(totalLifeV > 0 && lifeV > 0){
        if(s == 0){
            totalLifeV += (0-powerV);
        }
        if (s != 2){
            lifeV += (0-totalPowerV);
        }else{
            lifeV += 0.5*(0-totalPowerV);
            powerV--;
        }
        powerV += enemies;
        totalPowerV++;
        i++;
    return calculateThreat(i, 0,totalLifeV,lifeV,powerV,totalPowerV, enemies);
    }
    if(lifeV > 0){
        return -1;
    }
    return i;
}

}

Final Edit: Added Feature so it attacks if there are only 3 bots left.

Biggest Weakness: Bully.

\$\endgroup\$
2
  • \$\begingroup\$ Why is the Meta Fighter "wondering why the opponent is at war with himself" but also considers attacking himself? \$\endgroup\$
    – rudi
    Commented May 23, 2015 at 19:35
  • \$\begingroup\$ @rudi He's wondering why the opponent would fight himself in a way that isn't beneficial to the opponent. Also theoretically he will attack himself, but in all my tests it never has. \$\endgroup\$ Commented May 23, 2015 at 20:07
3
\$\begingroup\$

python 2.7 - GTA V's Trevor Phillips and Michael De Santa


Edit 2015-05-25: added first version of Michael De Santa.
Here's a little homage to GTA V. I created two Python bot representing two of three protagonists of GTA V. Please meet Trevor Phillips and Michael De Santa. Trevor has nothing too subtle about him. Michael has a good memory - and a hitlist. Once you're on it, your days are counted.

Note1 : When I have time, I'll put some more intelligence into Michael and maybe even add a Franklin (to replace the bragging Trevor).

Note 2: Michael seems to perform quite allright. I have some more idea's, but I wanted to put this out. Maybe a "better" version of him will come.

Trevor Philips

# "Computer gamers with their computer rigs. 
#  All they do is cry. 
#  They will never get the game."
#                         - Trevor Phillips.
#
import sys, random
from __builtin__ import str

# YES!!! I'm alive!!!
args=sys.argv
if len(args)==1:
    print("ok")
    sys.exit()

# Basic strategy: Hit whoever hits me or just anyone; sometimes brag a Trevor quote.
me=int(args[1])
botnrs=[]
action=''
quotes=["Now would you get me a f*cking drink! I'm not gonna ask you again!",
        "Grumble grumble grumble I've got my work grumble grumble grumble I've got my life, never the two shall meet.",
        "Well hello there beautiful. here go buy yourself something nice",
        "I'm driving, you can jerk me off if I get bored... I'm joking, you can suck me off.",
        "Do you want me to get my dick out again?!",
        "Floyd..we're having people over.  We need chips, dip, and prostitutes"]
for bot in args[2:]:
    nr,life,power,lastaction=bot.split(',')
    botnrs.append(nr)
    if lastaction==str(me):
        action=int(nr)
if action=='':
    action=int(random.choice(botnrs))
if random.random()<0.05:
    action=random.choice(quotes)
print(action)

Michael De Santa

# Surviving is winning, Franklin, everything else is bullshit. 
# Fairy tales spun by people too afraid to look life in the eye. 
# Whatever it takes, kid: survive. 
#                                            - Michael De Santa.
#
import sys, pickle, re, operator

# List of power values for a certain bot in a given round range
def getpower( history, botid, roundrange ):
    return [sum([bot[2] for bot in history[i] if bot[0]==botid]) for i in roundrange]

# If you say nothing, I say "ok".
if len(sys.argv)==1:
    print("ok")
    historyfile=open('state/MichaelDeSanta.bin','w+')
    pickle.dump([[],{},0,0],historyfile)
    historyfile.close()
    sys.exit()

# Get data from file
myid=int(sys.argv[1])
historyfile=open('state/MichaelDeSanta.bin','r')
history,hitlist,botcount,roundnr=pickle.load(historyfile)
historyfile.close()
history.append([map(int,re.sub('[DX]','-1', bot).split(',')) for bot in sys.argv[2:]])

# Update hitlist:
if roundnr==0:
    hitlist=dict.fromkeys([bot[0] for bot in history[0]],0)

maxhealth=maxpower=[0,0]
for bot in history[roundnr]:
    if bot[0] != myid:
        if bot[1]<=0:
            hitlist[bot[0]]=0
        else:
            # If you hit me, you're on the list!
            if bot[3]==myid:
                hitlist[bot[0]]+=4
            # If I can kill you with one hit... You're on my list!
            if bot[1]<getpower(history,myid,[roundnr]):
                hitlist[bot[0]]+=1
            # If you're super healthy, you deserve PUNISHMENT!
            if bot[1]>maxhealth[1]:
                maxhealth=[bot[0],bot[1]]
            # If you're powerfull... Well... I'm not afraid!
            if bot[2]>maxpower[1]:
                maxpower=[bot[0],bot[1]]
hitlist[maxhealth[0]]+=3
hitlist[maxpower[0]]+=2

action=max(hitlist.iteritems(),key=operator.itemgetter(1))[0]
hitlist[action]-=1

# Save data to file
roundnr+=1
historyfile=open('state/MichaelDeSanta.bin','w+')
pickle.dump([history,hitlist,botcount,roundnr],historyfile)
historyfile.close()

# Wrap up and print the action
print(action)
\$\endgroup\$
2
\$\begingroup\$

Java- Patroclus

Patroclus is an aggressive bot, who is determined to seek glory. He has quite a good memory (even if I do say so myself) and he believes that the best way to seek glory is attacking the most aggressive enemy. He remembers who has attacked most so far in all the games and bops them over the head with his big sword.

His biggest weakness is his Kamikaze attitude to defending- who needs it when you're wearing Achilles' armour?

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;


public class Patroclus {

    final static File file = new File("state/Patroclus.txt");   
    static List<bot> enemies;
    static String me;

    public static void main(String[] args) {
            if(args.length < 1){
                if(file.exists())
                {
                    file.delete();
                }
                System.out.print("ok");
                System.exit(0);
            }
            me = args[0];
            enemies = new LinkedList<Patroclus.bot>();
            
            if(!file.exists())
            {
                createFile();               
                for(int i = 1; i<args.length; i++)
                {
                    
                    String[] tokens = args[i].split(",");
                    bot newBot = new bot();
                    newBot.id = tokens[0];
                    newBot.life = Integer.valueOf(tokens[1]);
                    enemies.add(newBot);
                }               
            }
            else
            {
                
                openFile(args);
                
            }
            
            Collections.sort(enemies);
            Collections.reverse(enemies);
            
            String target = "D";
            for(int i = 0; (i<enemies.size()) && (i>-1); i++)
            {                               
                if(enemies.get(i).canAttack())
                {
                    target = enemies.get(i).id;
                    i = -10;
                }
            }
            saveFile();
            System.out.print(target);
            System.exit(0);
}


    private static void saveFile() {
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new FileWriter(file));
            for (bot b : enemies) {
                writer.write(b.toString());
                writer.write("#");
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {           
        }
    }

    private static void openFile(String[] args) {       
            Scanner sc;
            try {
                sc = new Scanner(file);                     
                String[] lines = sc.next().split("#");
                
                for(int i = 0; i<lines.length; i++)
                {
                
                    bot newBot = new bot(lines[i]);
                    
                    
                    int j = 1;
                    for(; j<args.length && j>0; j++)
                    {
                        String[] tokens = args[j].split(",");
                        if(tokens[0].equals(newBot.id))
                        {
                            newBot.life=Integer.valueOf(tokens[1]);
                            if(newBot.life>0 && !tokens[3].equals("D"))
                            {
                                newBot.agression++;
                            }
                            j = -10;
                        }
                    }               
                    enemies.add(newBot);
                }           
            } catch (FileNotFoundException e) {
            }       
    }
    
    private static void createFile() {
        try {
            file.createNewFile();
        } catch (IOException e) {               
        }       
    }

    private static class bot implements Comparable<bot>
    {
        int agression, life;
        String id;
        
        public bot(String toParse)
        {
            String[] tokens = toParse.split(",");
            id = tokens[0];
            agression = Integer.valueOf(tokens[1]);
        }
        
        public bot()
        {
            this.agression = 0;
            this.life = 0;
            this.id = "D";
        }
        
        @Override
        public int compareTo(bot o) {
            if(this.agression>o.agression)
                return 1;
            else if (this.agression==o.agression)
                return 0;
            else
                return -1;
        }
        
        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            sb.append(id);
            sb.append(",");
            sb.append(agression);
            
            return sb.toString();
        }
        
        public Boolean canAttack()
        {
            return life>0 && !id.equals(me);
        }
    }
}
\$\endgroup\$
2
\$\begingroup\$

Rust - Paranoid

Keeps comparing himself to the liveliest on the battlefield.

struct Bot {
    id: i32,
    life: i32,
    power: i32,
    action: String,
}

fn main() {
    let args: Vec<_> = std::env::args().collect();
    if args.len() < 2 {
        print!("ok");
    } else {
        let id: i32 = args[1].to_string().trim().parse()
            .ok()
            .expect("Please type a number!");

        let mut target_bot = Bot { id:-1, life:-1, power:-1, action:"D".to_string() };
        let mut own_bot = Bot { id:id, life:0, power:1, action:"D".to_string() };

        for arg in args {
            let split: Vec<&str> = arg.split(",").collect();
            if split.len() == 4 {
                let bot_id: i32 = split[0].to_string().trim().parse()
                    .ok()
                    .expect("Please type a number!");
                let bot_life: i32 = split[1].to_string().trim().parse()
                    .ok()
                    .expect("Please type a number!");
                let bot_power: i32 = split[2].to_string().trim().parse()
                    .ok()
                    .expect("Please type a number!");
                let bot_action: String = split[3].to_string();

                let bot = Bot { id:bot_id, life:bot_life, power:bot_power, action:bot_action };

                if bot.id != id && bot.life > target_bot.life {
                    target_bot = bot;
                } else if bot.id == id {
                    own_bot = bot;
                }
            }
        }

        /* If I am not stronger than the strongest, defend */
        let turns_to_kill = target_bot.life/own_bot.power + 1;
        let turns_to_be_killed = own_bot.life/target_bot.power;

        if target_bot.id > -1 && turns_to_kill < turns_to_be_killed {
            print!("{}", target_bot.id);
        } else {
            print!("D");
        }
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.