什么不会杀死我...


106

总览

这是一场机器人大战,看谁能生存最长。但是,这些漫游器会通过受到攻击来增强其功能,因此在拍摄前您需要仔细考虑。

每回合,您都可以选择要攻击或防御的机器人。攻击会缩短其生命并增加力量。最后一个机器人站获胜。

机器人

每个机器人以1000生命和10力量开始。

受到攻击时:

  • 从你的生命中减去攻击者的力量
  • 你的力量提高1。

因此,如果在第一回合中受到两个机器人的攻击,则您将拥有980点生命和12点力量。

如果您选择捍卫:

  • 你的力量会降低1
  • 此回合对您的所有攻击将减少一半
  • 如果您受到攻击,则每个攻击者将获得2点力量,而不是1点

因此,如果您在第一回合防御并受到两个机器人的攻击,您将拥有990点生命和13点力量。如果您防御并且没有受到攻击,那么您将拥有1000点生命,但是只有9点力量。

如果转弯结束时您的力量小于1,则将其设置为1。如果您的生命低于1,您将死亡。

输入输出

机器人每回合叫一次。每转一圈有一个时间限制。

初始

第一次调用您的漫游器时,将不会给出任何参数。回应ok。这样做只是为了确保您的机器人能够响应。如果没有,它将不会被添加到播放器列表中。

每转

每回合,您的机器人都将获得有关游戏中所有机器人的信息作为命令行参数。这些参数的一个示例是:

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

第一个参数是您的漫游器的唯一ID。然后,出现一个用空格分隔的漫游器列表。每个漫游器的格式为:

id,life,power,lastAction

lastAction可以是一个整数,表示他们攻击了哪个机器人,D是否防御了,以及X这是否是第一回合。其他都是整数。

因此,在上面的示例中,您1在最后一轮被机器人保护。Bot 0攻击了您,并且仍然处于启动状态。

每转的输出非常简单。只需将您要攻击的机器人输出为整数(例如03)或D进行防御即可。不要攻击已死亡或不存在的机器人,因为这将视为无效命令。任何无效的命令都将导致您失去1次电源。

比赛结构

每个游戏都包含以1000生命值和10力量开始的所有机器人。所有漫游器均同时采取措施。游戏的最大回合数为1000。

如果在回合结束时仍有一个机器人存活(生命> 0),则该机器人将获得1分并开始另一场比赛。如果达到转弯限制,并且有多个机器人处于活动状态,那么没人会得到积分。如果所有剩余的漫游器都死于同一回合,则没有人获得分数。

锦标赛包括15场比赛。最后谁得分最高者获胜!每种获胜游戏中剩余的生命总和打破关系。

漫游器只能在名为state(“ Hero”可以写入state/hero.whatever)的直接子文件夹中读取或写入以自身命名的单个文件。该文件的大小不得超过1024 2个字节。注意遵守时间限制。您的程序必须在一秒内终止才能计数,而不仅仅是给出响应。

这些文件将在每次锦标赛前擦除,但会在每个游戏中持续存在。id游戏之间的所有漫游器标识符()也将保持不变。

控制者

以下是比赛控制器(Stronger.java)。默认情况下,它仅输出最终结果(排序的玩家列表,优胜者排在首位),这可能需要一段时间。它没有冻结,只是保持沉默。如果您想要更详细的转弯输出,请-log在运行时添加参数。

要添加机器人,您有两种选择:

  • 将命令添加为参数(java Stronger -log "python bot.py"

  • 将命令添加到defaultPlayers[]源代码("python bot.py")中

机器人HeroBullyCoward可以在此答案中找到,并将用于评分目的。

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;
        }
    }
}

规则

  • 您最多可以输入两个机器人。如果您想从游戏中删除一个来输入第三个,请删除其帖子。

  • 您不能通过荟萃分析来定位或以其他方式选出机器人。仅使用您的漫游器所提供的信息。这包括您自己的机器人,因此您不能输入两个相互勾结的机器人。

  • 请勿尝试以任何方式干扰控制器或其他机器人的运行。

  • 您的机器人可能无法实例化或以其他方式运行控制器或其他机器人。

结果

(截至2015年5月22日00:00:00Z提交的漫游器数量)

这轮比赛进行得更好,只有两场比赛在1000转时停顿。拉尔夫·马歇尔(Ralph Marshall)的桑塔亚娜(Santyana)赢得了第一名,是唯一获得三场胜利的机器人。那还不够,所以他在Tactician上获得了第三名。Stormcrow的Phantom Menace排名第二,在这里排名第一。总而言之,新成员的表现非常不错,排名前六位的职位少于五个职位。恭喜,欢迎光临本站!

赢得零分的机器人没有列出,以节省空间。上面时间戳之前发布的所有漫游器均已运行,因此,如果您看不到自己的漫游器,则它不会赢得任何收益。

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粗略并行控制器(由他人提供):

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;
        }
    }
}

2
@Tim机器人列表以空格分隔。每个漫游器的统计信息以逗号分隔。
Geobits,2015年

3
@Mark当前的机器人大约一半防御方向,一半攻击。防御性机器人都没有一个赢家。我同意它鼓励某种防御,但是侵略的好处在于,纯粹的防御根本无法赢得任何分。只有您是唯一的幸存者,您才能赢得积分。
Geobits

8
如果有人想知道现在有更多提交者,僵尸程序如何堆积起来,那么这就是我的“非正式”测试运行的结果:3-809-英雄;2-593-Velociraptor; 1-471-SurpriseBot; 1-433-ward夫; 1-371-Santayana; 1-364-威斯尼珀; 1-262-分析师;1-230-Bully;1-132-均衡器;1-71-IKnowYou; 0-0-precog,Berserker,BroBot,SemiRandom,MonteBot,Tactician,SnappingTurtle,Psycho,Revenger,机会,PhantomMenace,坦克,Boxer,Guardian,AverageAverage,DefensiveBot。来自Opportunity,AboveAvg,BroBot,Boxer和SemiRandom的许多无效命令。
OJFord

3
我有一个并行版本的控制器,它比原始控制器运行游戏的速度更快,如果有人有兴趣的话,我可以发布它...
其他

3
@Manu只要没有同时执行每个机器人,就没有关系。我认为并行版本仍然让所有漫游器先转一圈然后再转到下一个。就像我说的,如果要发布,我将在使用前进行验证。
Geobits,2015年

Answers:


25

C ++-MonteBot

模拟大量随机游戏,并选择导致未死的最大机会的举动。

当您可以让计算机为您创建策略时,为什么要考虑一种策略?

注意:使用-O3标志进行编译以获得最佳性能。

#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

此外,可以利用多线程使该机器人运行得更快。但是,由于我不抢先地知道该机器人在超时之前(在评审平台上)可以评估多少次迭代,因此我不会在竞争中使用该机器人(带有以下代码)。

下面的代码仅出于好奇的缘故。

注意:使用-O3和-fopenmp标志进行编译以获得最佳性能。

#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;
}

2
有趣的策略。与20ish对手进行模拟大约需要多长时间?
拉尔夫·马歇尔

2
@RalphMarshall它可以为几个对手相当快地(从0.03秒到0.2秒)进行6万次模拟,但是很快对20个对手(平均10秒)变得非常慢。希望过早终止该算法仍会产生可行的解决方案。
Potatomato

我正在考虑为此机器人添加多线程支持,以使程序运行更快,但是我不知道判断计算机在该机器人超时之前将能够评估多少次迭代。为了进行概要分析,我可能会牺牲第一款游戏,以便该机器人能够运行最佳迭代次数。
Potatomato

23

Java心理

没有人知道这种疯狂的心理会做什么-可能会攻击任何人:死去的机器人,甚至是他自己。

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);
    }
}


19

Scala-Bandwagoner

随行者不在乎荣誉或原则。随行者处于低位,避免成为最弱者或最强者。Bandwagoner与人群同行,以共识目标为目标,以避免引起关注。

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"
    }
}

您是否知道为什么我会在第一行收到愚蠢的错误“尝试不是scala.util的成员”?谷歌搜索使我茫然。我有一个标准的scala安装,直接从存储库安装2.9.2。
Geobits,2015年

@Geobits多数民众赞成在比我的更旧的scala版本,我正在运行2.11。如果无法升级,请告诉我,我将修复我的代码。
2015年

2
知道了 我在文档中将“ Since 2.10”读为“ Since 2.1.0”,无法弄清楚为什么它不在2.9.2中:(
Geobits,2015年

18

Java复仇者

复仇者对争吵不感兴趣。但是,如果遭到攻击,寻求报仇!

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);
    }
}

4
仅供参考:即使目标死亡,也不会停止攻击。
Geobits,2015年

26
@Geobits哦,但是报仇是一道最好的菜..已经死了?:p不是故意的;更新。
OJFord

17

Java-英雄,恶霸和胆小鬼

包括这三个机器人作为示例,但它们在得分比赛中使用。它们都有简单的行为。

英雄

英雄只会攻击每一回合中生命最多的人

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);
    }
}

欺负

同时,恶霸每回合都会攻击生命最短的人。

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);
    }
}

懦夫

直到他的生命达到500岁或以下,科沃德什么也不会做。然后,他每回合攻击功率最小的人

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);
    }
}

请享用!


7
有趣的是,英雄证明是一种非常有效的技术;甚至针对更“复杂”的机器人(例如MonteBot,Analyst)。这只是一个简单的例子,还是您基于一些见识?
OJFord

1
不,我只是以示例为例介绍了前三件事。老实说,我认为这不会做得很好。
Geobits,2015年

16

Perl-战术师

最初是作为我的Let'em Fight机器人的编辑,但由于进行了足够的更改,因此我决定将其作为新条目进行输入。新逻辑如下

  • 如果没有人在前一回合中进攻,则以最高生命值进攻对手。至少在我还活着的时候,这应该可以防止没有人攻击别人的结局。
  • 如果有人在最​​后一轮攻击了我,请选择最强大的此类攻击者并进行反击。
  • 如果我们只剩下两个机器人,或者我的力量低于平均水平,请以最高生命攻击对手。
  • 如果我自己的额定功率低于平均水平,请发起攻击以将我的功率提高到更合理的水平
  • 不然我花时间

我已经在本地对其他Java机器人进行了测试,这些Java机器人已经获得了一些成功,但是对我而言仍然不是一个惊人的入门。

#!/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

那些不记得历史的人注定要早逝,或诸如此类。该机器人试图通过保留每个机器人在所有回合中的总实力的历史记录并始终攻击最强的机器人来利用比赛的多轮性质。从理论上讲,这应该可以使任何机器人都无法胜任,但是我当然只是在我还活着的时候收集统计信息,因此,如果该机器人的寿命很短,那么统计数据就不会太好了。

#!/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";
}

请注意,我很确定我删除了我的其他条目(标记为Let'em Fight),所以我应该只有两个机器人,但如果没有,请忽略该机器人,而仅使用这两个机器人。谢谢。
拉尔夫·马歇尔

6
恭喜您在最新的记分牌中同时获得第一和第三名:)
Geobits,2015年

最优秀!这是一个巨大的挑战。
拉尔夫·马歇尔

14

Java守护者

守护者保护弱者。他会攻击最后一轮捡起现在最弱小的活着的机器人的人(可能还包括他自己)。不过,他足够聪明,不会进攻:

1)自己(除非他恶霸,否则他认为自己应得的。)

2)攻击自己的机器人

3)僵尸机器人

4)生命还不到十的机器人(希望他们已经吸取了教训!)

监护人将在需要时重复选择同一名玩家。“最弱的球员”和“被他选中的人”的关系都排在列表的第一个(也就是说,是随机的)。

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");
    }
}

1
请修复此机器人其他机器人中的许多错字和错误。我不能按原样编译它们。
Geobits 2015年

我认为,在情况下,它一直是欺负它应该想想它的完成,即d efend。
user3819867 2015年

错误已修复。@ user3819867,我想补充一下,但是监护人会不惜一切代价保护弱者,即使自己付出了代价。
Xynariz

13

Java-分析师

通过将攻击者的力量乘以5(如果攻击者将其乘以25)来确定每个对手的威胁。如果出现平局,它会以最少的生命攻击玩家。

许多代码是从Geobits的答案中借用的。

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);
    }
}

12

Python 2,鳄龟

隐藏在它的壳,出现咬的第一人来攻击它最后一轮(除非他们死了),然后返回到它的外壳再次
与运行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,狂战士

狂战士粉碎!击中自己直到拥有足够的力量,然后开始攻击最近的生物。如果由于某种原因无法确定应该击中谁,也将击中自身。

编辑:将狂战士的怒气阈值从50更改为25,因为否则它在执行任何操作之前都会自动退出...

与运行 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:])

12

R-机会

该bot需要使用来调用Rscript Opportunity.R。它会记住谁做了什么,并且攻击对手防御自己的可能性较小(即过去使用D最少的机器人),除非他意识到其中一个机器人连续两次攻击他,在这种情况下它将开始防御本身或攻击攻击的机器人,如果它可以比攻击者更快地杀死它。

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")
    }

真好 我已经在R中开始了一个解决方案,但这要好得多。
Alex A.

好吧,如果您能想到一个好的策略,请毫不犹豫地输入一个新的R机器人(欢迎您即使需要也可以重用我的一些代码)!我很想看到一个朱莉娅机器人(因为您偶尔会在朱莉亚打高尔夫球)。
plannapus 2015年

也许我会用朱莉娅来试一试。感谢您的鼓励。:)
Alex A.

10

Python 2-拳击手

Boxer机器人将主要保持警惕,躲避和编织。时不时地,它会向防守不佳的强大对手发出快速刺戳或横传,希望随着时间的流逝而逐渐消失。

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'

更新:修复了导致一些无效输出的错误。


4
354个字符?高尔夫,这是什么?;)
Casey Kuball 2015年

1
@Darthfett:仅仅是因为这里有许多Java提交,并不意味着每个人都需要用类似数量的样板纸来乱扔他们的代码……
不再与2015年

11
拳击手很瘦-他很容易满足自己的体重。他的饮食和理解很健康。您不会发现他在吃静态打字的汉堡,也不用嚼大括号炸薯条。
逻辑骑士

4
为简洁起见,@ CarpetPython Terseness与冗长同样糟糕。
Kroltan

9

C-SurpriseBot

假设第一回合将陷入困境并防守。之后,攻击上一回合没有防守的人-他们将永远不会看到它来临!

这个答案有点愚蠢,但是我想写一个相当通用的平台来用C语言构建一个答案,所以就到这里了。

//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;
}

9

Python 2-Precog

Precog尝试根据过去的动作频率来预测其他人的动作,然后尝试一些模拟并选择一个最大化其得分的模拟。它不是特别可靠,但是……ESP不是真实的。: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

2
该机器人似乎偶尔会攻击其他已经死亡的机器人。否则,它是一个相当强大的机器人(因为它使我的机器人从一直在对抗测试机器人的比赛中赢得的所有时间减少到只有我的测试中包含了您的机器人的50%的时间)。
Potatomato

9

bash-CopyCat

CopyCat钦佩强大,健康且​​具有侵略性的产品,并且像他们一样攻击。如果她有“印象”,表明大多数机器人在这里进攻,那么她将开始自卫或进攻弱者,除非她变得更强壮或其他大多数机器人在这里停止进攻。

只需执行 /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

她的弱点:她可能无法像她所期待的那样变得更好。:()


8

Python 3 DefensiveBot

Bot试图找到可以用当前力量杀死的最高力量的敌人。否则,保卫。与运行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)

没有参数似乎无法正确运行:第一次调用您的漫游器时,将没有任何参数。回应 ok这样做只是为了确保您的机器人能够响应。如果没有,它将不会被添加到播放器列表中。
Geobits,2015年

@Geobits已修复。
伊莱亚斯·本尼维德斯

好的,它可以运行,但是有多余的打印正在进行。我必须注释掉第28和32行,以便给出有效的响应。否则它会死掉。
Geobits,2015年

您可能还需要确保在确定目标之前,该机器人还活着。这经常瞄准死者,这算是无效的举动,并降低了您的力量。
Geobits,2015年

叹息固定。我觉得这不是最后解决方法:P
Elias Benevedes

8

爪哇坦克

坦克不在乎,他不在乎,他只是攻击看到的第一个机器人!不过,他足够聪明,不会攻击自己或死者。

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");
    }
}

1
如您在其他bot上所指出的那样,它不会按原样编译。
Geobits

8

Java-幻影威胁

嗨!这是我在Code Golf的第一篇文章。我是C#家伙,所以请原谅我的法语。我已经使用了《英雄》和《胆小鬼》示例代码的一部分。

我的机器人是一个简单的人,具有相当的政治态度。大多数时候,他只是躲在大厅里喝咖啡,准备自己的计划。但是,当机会出现并且获利前景足够强大时,他便从舒适的大堂扶手椅上跳了起来,扔掉了报纸,然后开始赚钱。

在对他造成任何伤害之后,他才为自己辩护。否则他的行为就像一个真正的英雄(这是一个政治决定,因为它很安全)。当他只有三个竞争对手时,他将获得胜利。

他遵循一些基本原则。每一位严肃的政治家都应该有一些牢不可破的原则和明确定义的形象。

除了自己,不要帮助别人!(自我主义者)

荣耀意味着死亡!(怀疑论者)

死后什么都没有!(无神论者)

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);
        }

    }
}

1
非常好,目前排名第二。欢迎来到网站:)
Geobits,2015年

噢,谢谢,尽管这是一个令人惊喜的惊喜,但我不得不承认我从未停止相信我的机器人:P。
风暴鸦

7

我认识你-Java

分析所有敌人并使用此信息更好地防御自己。不幸的是,它很容易报仇攻击。

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;
        }
    }
}

7

Java-迅猛龙

迅猛龙是恶性杀手。她将躺在等待被攻击之前,观察潜在的猎物。然后,她开始快速杀死敌人,并击落了可以杀死最快的目标。在开始袭击后,猛禽无所畏惧,并将继续劫持受害者,直到她是唯一的幸存者。

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;
    }
}

7

Python 3-SemiRandom

根据攻击和防御后先前强度变化加权的随机性在攻击和防御之间进行选择。如果选择攻击,它将攻击最强的玩家。强度定义为life * power

在3个示例机器人中,它很少获胜。也许在野外...

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)

7

Java-罗马龟

罗马龟会攻击附近的任何人,但也会随机决定攻击其他机器人,因为这不是胆小鬼。偶尔(50分之一)表示宽恕。

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);
    }

}

有什么特别的原因为什么您试图抓住NoSuchElementException似乎没有被扔进障碍物的东西try?还是我错过了什么?
TNT 2015年

@TNT不再。当访问数组的元素之一时,有时会遇到异常。更正了我的错误,但只保留了尝试-安全胜过遗憾:)
euanjt 2015年

7

Java-BroBot

BroBot会攻击最强大的对手,除非攻击力大于某个逐渐减小的值的敌人决定攻击BroBot,在这种情况下,他将保卫该回合。

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

什么是没有姐姐的兄弟?许多事情……但这不重要。作为更智能的机器人,SisBot会保存每个机器人的最新动作,分析它们的当前动作和最后动作,并做出自己的举动-只要健康和力量足够强大,并且她会毫不犹豫地以最大的力量攻击该机器人。功率统计值超过特定值的其他机器人都不会决定攻击她;在这种情况下,她将在攻击和防御之间切换,或者如果攻击者的能力确实很高,则可以直接防御。

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();
        }
    }
}

我真的必须学习另一种语言...:P


似乎需要检查所选目标是否已经失效。
拉尔夫·马歇尔

我以为我已经拥有了……但是在发布之前,我确实创建了一个不同的策略。感谢您抓住这一点。
TNT

6

Java均衡器

尽管防守显然是最有效的策略(:P),但他认为,将人们甩到头顶,直到他们推倒巨人似乎很有趣。但是要拧紧那些一直在捍卫的人。他们没有从这个家伙那里得到任何力量。

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
        }
    }
}

6

Java-Wiisniper-反射代理

一个简单的反射代理,它使用简单的启发式方法识别最危险的机器人,然后对其进行攻击。

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);
    }
}

6

Java-高于平均水平

尝试将自己的统计数据保持在前四分位。使用预测技术来预测敌人的行动。

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);
        }
    }
}

应该state/whatever不用status。似乎除了IndexOutOfBounds第一回合。
OJFord

5

Java-安抚奶嘴

有史以来第一次提交!\ o /正在为此比赛开发一种机器人,该机器人使用大量数据节省功能并尝试查找模式,并想到了这一模式。基本上,如果他认为自己的损失太低而无法做任何有用的事情,他将保护自己。否则,他将攻击更具威胁性的对手,这取决于杀死他所需的命中次数及其伤害输出。无法尝试,但我认为他可以做得很好!

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();}
    }
}

他没有大脑,所以他什么都不记得,但是我认为它可以做得很好。有趣的一点:如果他还活着,他会尝试踢一些尸体,僵尸会吓死他!

编辑:

确实在第一回合上发送了ok,只是对样本进行了测试,他遇到了一些困难,之前需要对他进行一些工作。

编辑2:

他现在记住了一些数据,并且做得更好,从来没有赢过,但是每次每次损失<50 hp ... ho,我对样品进行的一次测试给了我这个:

14 3170 Java恶霸
0 0 Java安慰者
0 0 Java英雄
0 0 Java Coward

它不再发生了(他实际上赢得了一些积分:)),但是很有趣:D。

编辑3:

使用正确的文件名,并有所改进。工作得很好,当许多机器人在这里时,效果会更好:)。


3

Java-元斗士

注意:请告诉我它是否无效

Meta Fighter不会将每个对手都视为一个单独的敌人。他把所有这些都考虑在内。元战斗机加总了所有敌人的力量和力量,并认为这是他与他们的对抗。然后,他计算出哪种举动最有效地降低了这两个分数。杀死一个虚弱的对手很有帮助,因为它同时降低了力量和力量。但是,如果攻击敌人会给它带来比夺走力量更多的有益力量,那么他认为这是不值得的,可以防御或攻击自己。Meta Fighter只是想知道对手为什么要与自己交战...

(顺便说一句,我第二次进入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;
}

}

最终编辑:添加了功能,因此如果仅剩3个漫游器就可以进行攻击。

最大的弱点:恶霸。


为什么Meta Fighter“想知道对手为什么要与自己交战”,却又考虑攻击自己?
鲁迪

@rudi他想知道为什么对手会以对对手无益的方式来对抗自己。从理论上讲,他也会攻击自己,但在我所有的测试中,他从来没有。
colorado777

3

python 2.7-GTA V的Trevor Phillips和Michael De Santa


编辑2015-05-25:添加了Michael De Santa的第一个版本。
这是对GTA V的致敬。我创建了两个Python机器人,代表GTA V的三个主角中的两个。请见Trevor Phillips和Michael De Santa。特雷弗对他没什么微妙的。迈克尔的记忆力很好-而且很受欢迎。一旦开始,您的日子就会被计算在内。

注意1:有时间的时候,我会给迈克尔更多的情报,甚至可能加一个富兰克林(以取代吹牛的特雷弗)。

注2:迈克尔的表现似乎还不错。我还有更多想法,但是我想把这个说出来。也许他的“更好”版本会来。

特雷弗·飞利浦

# "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)

迈克尔·德·桑塔

# 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)

2

爪哇-Patroclus

Patroclus是一个富有进取心的机器人,他决心寻求荣耀。他有很好的记忆力(即使我自己也这么说),并且他认为寻求荣耀的最佳方法是攻击最具攻击性的敌人。他记得到目前为止,谁在所有比赛中攻击最多,然后用大剑将他们击中头部。

他最大的弱点是他的神风队(Kamikaze)对防守的态度-当您穿着阿喀琉斯的盔甲时,谁需要它?

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);
        }
    }
}

2

-偏执狂

不断将自己与战场上最活跃的人进行比较。

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");
        }
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.