Advertisement
Guest User

Cloud Contest 2 - bot by dalex

a guest
Apr 3rd, 2012
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 21.05 KB | None | 0 0
  1. import org.json.JSONArray;
  2. import org.json.JSONObject;
  3.  
  4. import java.net.Socket;
  5.  
  6. import java.io.*;
  7. import java.util.*;
  8. import java.util.Map.Entry;
  9.  
  10. import static java.lang.Math.*;
  11.  
  12. public class Main {
  13.    
  14.     class Point {
  15.        
  16.         public int x, y;
  17.  
  18.         public Point(int x, int y) {
  19.             this.x = x;
  20.             this.y = y;
  21.         }
  22.  
  23.         @Override
  24.         public int hashCode() {
  25.             final int prime = 31;
  26.             int result = 1;
  27.             result = prime * result + x;
  28.             result = prime * result + y;
  29.             return result;
  30.         }
  31.  
  32.         @Override
  33.         public boolean equals(Object obj) {
  34.             if (this == obj)
  35.                 return true;
  36.             if (obj == null)
  37.                 return false;
  38.             if (getClass() != obj.getClass())
  39.                 return false;
  40.             Point other = (Point) obj;
  41.             if (x != other.x)
  42.                 return false;
  43.             if (y != other.y)
  44.                 return false;
  45.             return true;
  46.         }
  47.  
  48.         @Override
  49.         public String toString() {
  50.             return String.format("(%d %d)", x, y);
  51.         }
  52.        
  53.     }
  54.  
  55.     class Bot {
  56.         String botName;
  57.         String playerName;
  58.         int x, y;
  59.         int hp;
  60.         int respawnTime;
  61.         List<Point> canShoot;
  62.         boolean alive;
  63.        
  64.         public Bot(String botName, String playerName, int x, int y, int hp, int respawnTime, List<Point> canShoot) {
  65.             this.botName = botName;
  66.             this.playerName = playerName;
  67.             this.x = x;
  68.             this.y = y;
  69.             this.hp = hp;
  70.             this.respawnTime = respawnTime;
  71.             this.canShoot = canShoot;
  72.             this.alive = hp > 0;
  73.         }
  74.  
  75.         @Override
  76.         public String toString() {
  77.             return String.format("[%s : (%d %d), (%d)]", botName, x, y, hp);
  78.         }
  79.        
  80.         boolean canMove(int direction) {
  81.             if (direction < 0 || 4 <= direction) {
  82.                 throw new RuntimeException("wrong direction for bot");
  83.             }
  84.             int nx = x + dx[direction];
  85.             int ny = y + dy[direction];
  86.             if (good(nx, ny)) {
  87.                 if (a[nx][ny] == '0') {
  88.                     return true;
  89.                 }
  90.             }
  91.             return false;
  92.         }
  93.        
  94.     }
  95.    
  96.     public static void main(String[] args) throws Exception {
  97.         while (true) {
  98.             new Main().run();
  99.         }
  100.     }
  101.    
  102.     public void run() throws Exception {
  103.         socket = new Socket(URL, PORT);
  104.         in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  105.         out = new PrintWriter(socket.getOutputStream());
  106.         textLog = new PrintWriter("log.txt");
  107.         try {
  108.             work();
  109.         } catch (Exception e) {
  110.         } finally {
  111.             in.close();
  112.             out.close();
  113.             socket.close();
  114.         }
  115.     }
  116.    
  117.     void debug(Object... objs) {
  118.         System.out.println(Arrays.deepToString(objs));
  119.         System.out.flush();
  120.     }
  121.    
  122.     void log(Object... objs) {
  123.         System.out.println(Arrays.deepToString(objs));
  124.         System.out.flush();
  125.     }
  126.    
  127.     final String URL = "10.0.0.10";
  128.     final int PORT = 8000;
  129.     final String USER_TOKEN = "a5eed58c4350afc48efd5ffa";
  130.     //final String GAME_TOKEN = "9487765b575d49bd34816a02";
  131.     //final String GAME_TOKEN = "d838685afbff0639fdae8ae8";
  132.     //final String GAME_TOKEN = "34d9a705d95c8c444ff9331f";
  133.     //final String GAME_TOKEN = "c3b117d5f5d02d9d3ad92c23";
  134.     //final String GAME_TOKEN = "f35819a583024b85206bea31";
  135.     //final String GAME_TOKEN = "4e49ecd210fbd45d5793848d";
  136.    
  137.     //final String GAME_TOKEN = "f16d691906ed1f8800b11e7d";
  138.     //final String GAME_TOKEN = "1ede95a61a262930384e0502";
  139.     final String GAME_TOKEN = "fb4d81f113bb41130850b10a";
  140.    
  141.     final int[] dx = {0, 1, 0, -1};
  142.     final int[] dy = {1, 0, -1, 0};
  143.     final char[] dc = "rdlu".toCharArray();
  144.    
  145.     char getCommand(int direction) {
  146.         //return "drul".charAt(direction);
  147.         return dc[direction];
  148.     }
  149.    
  150.     boolean good(int x, int y) {
  151.         return x >= 0 && x < n && y >= 0 && y < m;
  152.     }
  153.    
  154.     boolean good(Point p) {
  155.         return good(p.x, p.y);
  156.     }
  157.    
  158.     Socket socket;
  159.     BufferedReader in;
  160.     PrintWriter out;
  161.     PrintWriter textLog;
  162.    
  163. //-------------------------------------------------------------------------------------------
  164.    
  165.     final int INF = 1000 * 1000;
  166.     final Random rnd = new Random();
  167.    
  168.     int n, m, moveNumber;
  169.    
  170.     List<Bot> myBots;
  171.     List<Bot> enemyBots;
  172.    
  173.     Map<String, Integer> scores;
  174.     List<String> playerNames;
  175.    
  176.     String myName;
  177.    
  178.     char[][] a;
  179.    
  180.     Map<String, Point> fireMap;
  181.     Map<String, Character> moveMap;
  182.    
  183.     void makeFire() {
  184.         //debug(myBots);
  185.         //debug(enemyBots);
  186.         boolean[][] graph = new boolean[myBots.size()][enemyBots.size()];
  187.         int[] enemyHp = new int[enemyBots.size()];
  188.         int[] dmg = new int[enemyBots.size()];
  189.         int ai = 0;
  190.         for (Bot myBot : myBots) {
  191.             int bi = 0;
  192.             for (Bot enemyBot : enemyBots) {
  193.                 enemyHp[bi] = enemyBot.hp;
  194.                 int bx = enemyBot.x;
  195.                 int by = enemyBot.y;
  196.                 Point bPoint = new Point(bx, by);
  197.                 if (myBot.canShoot.contains(bPoint)) {
  198.                     graph[ai][bi] = true;
  199.                 }
  200.                 bi++;
  201.             }
  202.             ai++;
  203.         }
  204.         int[] target = new int[myBots.size()];
  205.         Arrays.fill(target, -1);
  206.         for (int bi = 0; bi < enemyBots.size(); bi++) {
  207.             if (enemyHp[bi] - dmg[bi] == 1) {
  208.                 for (int i = 0; i < myBots.size(); i++) {
  209.                     if (target[i] == -1 && graph[i][bi]) {
  210.                         target[i] = bi;
  211.                         dmg[bi]++;
  212.                         break;
  213.                     }
  214.                 }
  215.             }
  216.         }
  217.         for (int bi = 0; bi < enemyBots.size(); bi++) {
  218.             if (enemyHp[bi] - dmg[bi] == 2) {
  219.                 for (int i = 0; i < myBots.size(); i++) {
  220.                     if (target[i] == -1 && graph[i][bi]) {
  221.                         for (int j = i+1; j < myBots.size(); j++) {
  222.                             if (target[j] == -1 && graph[j][bi]) {
  223.                                 target[i] = bi;
  224.                                 target[j] = bi;
  225.                                 dmg[bi] += 2;
  226.                                 break;
  227.                             }
  228.                         }
  229.                     }  
  230.                 }
  231.             }
  232.         }
  233.         for (int bi = 0; bi < enemyBots.size(); bi++) {
  234.             if (enemyHp[bi] - dmg[bi] == 3) {
  235.                 for (int i = 0; i < myBots.size(); i++) {
  236.                     if (target[i] == -1 && graph[i][bi]) {
  237.                         for (int j = i+1; j < myBots.size(); j++) {
  238.                             if (target[j] == -1 && graph[j][bi]) {
  239.                                 for (int k = j+1; k < myBots.size(); k++) {
  240.                                     if (target[k] == -1 && graph[k][bi]) {
  241.                                         target[i] = bi;
  242.                                         target[j] = bi;
  243.                                         target[k] = bi;
  244.                                         dmg[bi] += 3;
  245.                                         break;
  246.                                     }
  247.                                 }
  248.                             }
  249.                         }
  250.                     }  
  251.                 }
  252.             }
  253.         }
  254.         for (int i = 0; i < myBots.size(); i++) {
  255.             if (target[i] == -1) {
  256.                 for (int bi = 0; bi < enemyBots.size(); bi++) {
  257.                     if (graph[i][bi] && enemyHp[bi] - dmg[bi] > 0) {
  258.                         target[i] = bi;
  259.                         dmg[bi]++;
  260.                         break;
  261.                     }
  262.                 }
  263.             }
  264.         }
  265.         for (int i = 0; i < myBots.size(); i++) {
  266.             if (target[i] != -1) {
  267.                 Bot enemy = enemyBots.get(target[i]);
  268.                 Point point = new Point(enemy.x, enemy.y);
  269.                 fireMap.put(myBots.get(i).botName, point);
  270.             }
  271.         }
  272.         log("Fire map: " + fireMap);
  273.     }
  274.    
  275.     Point[] destPoints;
  276.     final int destPointCount = 1;
  277.    
  278.     void makeMoveRandom(Bot bot) {
  279.         char ch = 's';
  280.         for (int j = 0; j < 100; j++) {
  281.             int direction = rnd.nextInt(4);
  282.             if (bot.canMove(direction)) {
  283.                 ch = dc[direction];
  284.                 break;
  285.             }
  286.         }
  287.         moveMap.put(bot.botName, ch);
  288.     }
  289.    
  290.     void makeMove() {
  291.         Map<Point, Bot> pointMap = new HashMap<Point, Bot>();
  292.         for (int i = 0; i < myBots.size(); i++) {
  293.             Bot bot = myBots.get(i);
  294.             //makeMoveRandom(bot);
  295.             Point botPoint = new Point(bot.x, bot.y);
  296.             Point destPoint = destPoints[i % destPointCount];
  297.             int dir = whereNeedToGo(botPoint, destPoint);
  298.             Point newPoint = new Point(botPoint.x + dx[dir], botPoint.y + dy[dir]);
  299.             pointMap.put(newPoint, bot);
  300.         }
  301.         for (Entry<Point, Bot> entry : pointMap.entrySet()) {
  302.             Point destPoint = entry.getKey();
  303.             Bot bot = entry.getValue();
  304.             Point curPoint = new Point(bot.x, bot.y);
  305.             int dir = getDirection(curPoint, destPoint);
  306.             moveMap.put(bot.botName, dc[dir]);
  307.         }
  308.     }
  309.    
  310.     int getDirection(Point curPoint, Point destPoint) {
  311.         for (int i = 0; i < 4; i++) {
  312.             Point newPoint = new Point(curPoint.x + dx[i], curPoint.y + dy[i]);
  313.             if (newPoint.equals(destPoint)) {
  314.                 return i;
  315.             }
  316.         }
  317.         throw new RuntimeException("error in getDirection()");
  318.     }
  319.  
  320.     void work() throws Exception {
  321.         receiveConnectionApprove();
  322.         receiveConnectionSuccess();
  323.         receiveFieldInfo();
  324.         printArrayToLog();
  325.         myBots = new ArrayList<Bot>();
  326.         enemyBots = new ArrayList<Bot>();
  327.         scores = new TreeMap<String, Integer>();
  328.         playerNames = new ArrayList<String>();
  329.         fireMap = new TreeMap<String, Point>();
  330.         moveMap = new TreeMap<String, Character>();
  331.         destPoints = new Point[destPointCount];
  332.         for (int mv = 0; true; mv++) {
  333.             long startTime = System.currentTimeMillis();
  334.            
  335.             rnd.setSeed(System.currentTimeMillis());
  336.             myBots.clear();
  337.             enemyBots.clear();
  338.             scores.clear();
  339.             playerNames.clear();
  340.             fireMap.clear();
  341.             moveMap.clear();
  342.            
  343.             receiveBotsInfo();
  344.             removeDeadBots();
  345.             generateDestinationPoints();
  346.            
  347.             /*Collections.sort(myBots, new Comparator<Bot>() {
  348.                 @Override
  349.                 public int compare(Bot o1, Bot o2) {
  350.                     return o1.botName.compareTo(o2.botName);
  351.                 }
  352.             });*/
  353.            
  354.             for (int i = 0; i < myBots.size(); i++) {
  355.                 Bot bot = myBots.get(i);
  356.                 int x = bot.x;
  357.                 int y = bot.y;
  358.                 a[x][y] = (char)('A' + i);
  359.             }
  360.  
  361.             /*debug(myName);
  362.             debug(playerNames);
  363.             debug(scores);
  364.             debug(moveNumber);
  365.             debug(myBots);
  366.             debug(enemyBots);*/
  367.            
  368.             makeFire();
  369.             makeMove();
  370.             checkDestinationPoints();
  371.            
  372.             sendData();
  373.            
  374.             long endTime = System.currentTimeMillis();
  375.             log("Move " + moveNumber + " has been finished in " + (endTime - startTime) + "ms.");
  376.             logScores();
  377.            
  378.             System.out.println();
  379.             System.out.flush();
  380.         }
  381.     }
  382.    
  383.     void logScores() {
  384.         Set<Entry<String, Integer>> set = scores.entrySet();
  385.         String[] names = new String[set.size()];
  386.         int[] points = new int[set.size()];
  387.         int cnt = 0;
  388.         for (Entry<String, Integer> e : set) {
  389.             names[cnt] = e.getKey();
  390.             points[cnt] = e.getValue();
  391.             cnt++;
  392.         }
  393.         for (int i = 0; i < cnt-1; i++) {
  394.             for (int j = 0; j < cnt-1; j++) {
  395.                 if (points[j] < points[j+1] || points[j] == points[j+1] && names[j].compareTo(names[j+1]) > 0) {
  396.                     String tmp = names[j];
  397.                     names[j] = names[j+1];
  398.                     names[j+1] = tmp;
  399.                     int zzz = points[j];
  400.                     points[j] = points[j+1];
  401.                     points[j+1] = zzz;
  402.                 }
  403.             }
  404.         }
  405.         log("Scores");
  406.         for (int i = 0; i < cnt; i++) {
  407.             log(names[i] + ": " + points[i]);
  408.         }
  409.     }
  410.  
  411.     void checkDestinationPoints() {
  412.         for (int pi = 0; pi < destPointCount; pi++) {
  413.             Point p = destPoints[pi];
  414.             boolean needNewPoint = false;
  415.             botCycle: for (int i = pi; i < myBots.size(); i += destPointCount) {
  416.                 Bot bot = myBots.get(i);
  417.                 Point botP = new Point(bot.x, bot.y);
  418.                 /*for (Bot enemyBot : enemyBots) {
  419.                     Point enemyPoint = new Point(enemyBot.x, enemyBot.y);
  420.                     if (bot.canShoot.contains(enemyPoint)) {
  421.                         destPoints[pi] = enemyPoint;
  422.                         debug("bot" + bot.botName + " goes to point " + enemyBot);
  423.                         needNewPoint = false;
  424.                         break botCycle;
  425.                     }
  426.                 }*/
  427.                 int dist = shortestPath(p, botP);
  428.                 if (dist <= 2) {
  429.                     needNewPoint = true;
  430.                     break;
  431.                 }
  432.             }
  433.             if (needNewPoint) {
  434.                 destPoints[pi] = null;
  435.             }
  436.         }
  437.         debug(destPoints);
  438.     }
  439.  
  440.     void generateDestinationPoints() {
  441.         //log("enter into generateDestinationPoints()");
  442.         goToEnemies();
  443.         int criticalDist = (n + m) / 5 * 3;
  444.         boolean needGenerate = false;
  445.         for (int i = 0; i < destPointCount; i++) {
  446.             if (destPoints[i] == null) {
  447.                 needGenerate = true;
  448.                 break;
  449.             }
  450.         }
  451.         if (!needGenerate) {
  452.             return;
  453.         }
  454.         while (true) {
  455.             for (int i = 0; i < destPointCount; i++) {
  456.                 destPoints[i] = randomDestinationPoint(i);
  457.             }
  458.             if (destPointCount == 1) {
  459.                 break;
  460.             }
  461.             int maxDist = 0;
  462.             for (int i = 0; i < destPointCount; i++) {
  463.                 for (int j = i+1; j < destPointCount; j++) {
  464.                     int distance = shortestPath(destPoints[i], destPoints[j]);
  465.                     //log(distance);
  466.                     maxDist = max(maxDist, distance);
  467.                 }
  468.             }
  469.             if (maxDist >= criticalDist) {
  470.                 break;
  471.             }
  472.         }
  473.     }
  474.    
  475.     void goToEnemies() {
  476.         List<Point> enemyPoints = new ArrayList<Point>();
  477.         for (Bot enemyBot : enemyBots) {
  478.             enemyPoints.add(new Point(enemyBot.x, enemyBot.y));
  479.         }
  480.         for (int pi = 0; pi < destPointCount; pi++) {
  481.             int bestEnemy = -1;
  482.             int minDist = 7*INF;
  483.             for (int bi = 0; bi < enemyPoints.size(); bi++) {
  484.                 int sumDist = 0;
  485.                 for (int i = pi; i < myBots.size(); i += destPointCount) {
  486.                     Point botPoint = new Point(myBots.get(i).x, myBots.get(i).y);
  487.                     sumDist += shortestPath(botPoint, enemyPoints.get(bi));
  488.                 }
  489.                 if (bestEnemy == -1 || minDist > sumDist) {
  490.                     boolean was = false;
  491.                     for (int k = 0; k < destPointCount; k++) {
  492.                         if (destPoints[k] == null) {
  493.                             continue;
  494.                         }
  495.                         int theDist = shortestPath(destPoints[k], enemyPoints.get(bi));
  496.                         if (theDist < (n+m)/6) {
  497.                             was = true;
  498.                             break;
  499.                         }
  500.                     }
  501.                     if (!was) {
  502.                         bestEnemy = bi;
  503.                         minDist = sumDist;
  504.                     }
  505.                 }
  506.             }
  507.             if (bestEnemy != -1) {
  508.                 destPoints[pi] = enemyPoints.get(bestEnemy);
  509.             }
  510.         }
  511.     }
  512.  
  513.     int shortestPath(Point start, Point finish) {
  514.         int[][] d = new int[n][m];
  515.         for (int i = 0; i < n; i++) {
  516.             for (int j = 0; j < m; j++) {
  517.                 d[i][j] = INF;
  518.             }
  519.         }
  520.         d[start.x][start.y] = 0;
  521.         Queue<Point> q = new ArrayDeque<Point>();
  522.         q.add(start);
  523.         while (!q.isEmpty()) {
  524.             Point cur = q.poll();
  525.             if (cur.equals(finish)) {
  526.                 break;
  527.             }
  528.             int cx = cur.x;
  529.             int cy = cur.y;
  530.             for (int dir = 0; dir < 4; dir++) {
  531.                 int nx = cx + dx[dir];
  532.                 int ny = cy + dy[dir];
  533.                 if (good(nx, ny) && a[nx][ny] != '1') {
  534.                     if (d[nx][ny] > d[cx][cy] + 1) {
  535.                         d[nx][ny] = d[cx][cy] + 1;
  536.                         q.add(new Point(nx, ny));
  537.                     }
  538.                 }
  539.             }
  540.         }
  541.         return d[finish.x][finish.y];
  542.     }
  543.    
  544.     int whereNeedToGo(Point start, Point finish) {
  545.         int[][] d = new int[n][m];
  546.         int[][] p = new int[n][m];
  547.         for (int i = 0; i < n; i++) {
  548.             for (int j = 0; j < m; j++) {
  549.                 d[i][j] = INF;
  550.                 p[i][j] = -1;
  551.             }
  552.         }
  553.         d[start.x][start.y] = 0;
  554.         Queue<Point> q = new ArrayDeque<Point>();
  555.         q.add(start);
  556.         while (!q.isEmpty()) {
  557.             Point cur = q.poll();
  558.             if (cur.equals(finish)) {
  559.                 break;
  560.             }
  561.             int cx = cur.x;
  562.             int cy = cur.y;
  563.             for (int dir = 0; dir < 4; dir++) {
  564.                 int nx = cx + dx[dir];
  565.                 int ny = cy + dy[dir];
  566.                 if (good(nx, ny) && a[nx][ny] != '1') {
  567.                     if (d[nx][ny] > d[cx][cy] + 1) {
  568.                         d[nx][ny] = d[cx][cy] + 1;
  569.                         p[nx][ny] = dir;
  570.                         q.add(new Point(nx, ny));
  571.                     }
  572.                 }
  573.             }
  574.         }
  575.         if (start.equals(finish)) {
  576.             return rnd.nextInt(4);
  577.         }
  578.         int x = finish.x;
  579.         int y = finish.y;
  580.         if (p[x][y] == -1) {
  581.             return rnd.nextInt(4);
  582.         }
  583.         while (true) {
  584.             int px = x - dx[p[x][y]];
  585.             int py = y - dy[p[x][y]];
  586.             if (px == start.x && py == start.y) {
  587.                 return p[x][y];
  588.             }
  589.             x = px;
  590.             y = py;
  591.         }
  592.     }
  593.  
  594.     Point randomDestinationPoint(int pointIndex) {
  595.         Point best = null;
  596.         int oneBotNeedDist = (n + m) / 10 * 7;
  597.         for (int it = 0; it < 100; it++) {
  598.             int x = rnd.nextInt(n);
  599.             int y = rnd.nextInt(m);
  600.             if (!good(x, y)) {
  601.                 continue;
  602.             }
  603.             if (a[x][y] != '0') {
  604.                 continue;
  605.             }
  606.             Point p = new Point(x, y);
  607.             int sumDist = 0;
  608.             int botCount = 0;
  609.             for (int i = pointIndex; i < myBots.size(); i += destPointCount) {
  610.                 botCount++;
  611.                 Bot bot = myBots.get(i);
  612.                 Point botPoint = new Point(bot.x, bot.y);
  613.                 int distance = shortestPath(botPoint, p);
  614.                 sumDist += distance;
  615.             }
  616.             if (best == null) {
  617.                 best = p;
  618.             }
  619.             if (sumDist >= oneBotNeedDist * botCount) {
  620.                 break;
  621.             }
  622.         }
  623.         return best;
  624.     }
  625.  
  626.     void printArrayToLog() {
  627.         for (int i = 0; i < n; i++) {
  628.             for (int j = 0; j < m; j++) {
  629.                 textLog.print(a[i][j] + " ");
  630.             }
  631.             textLog.println();
  632.         }
  633.         textLog.println();
  634.         textLog.flush();
  635.     }
  636.  
  637.     void removeDeadBots() {
  638.         List<Bot> myAliveBots = new ArrayList<Bot>();
  639.         List<Bot> enemyAliveBots = new ArrayList<Bot>();
  640.         for (Bot myBot : myBots) {
  641.             if (myBot.alive) {
  642.                 myAliveBots.add(myBot);
  643.             }
  644.         }
  645.         for (Bot enemyBot : enemyBots) {
  646.             if (enemyBot.alive) {
  647.                 enemyAliveBots.add(enemyBot);
  648.             }
  649.         }
  650.         myBots = myAliveBots;
  651.         enemyBots = enemyAliveBots;
  652.     }
  653.  
  654.     void sendData() throws Exception {
  655.         JSONObject sent = new JSONObject();
  656.         for (Bot bot : myBots) {
  657.             if (!bot.alive) {
  658.                 continue;
  659.             }
  660.             String botName = bot.botName;
  661.             Point firePoint = fireMap.get(botName);
  662.             Character moveChar = moveMap.get(botName);
  663.             JSONObject botJSONObject = new JSONObject();
  664.             JSONArray botFireArray = new JSONArray();
  665.             if (firePoint != null) {
  666.                 addPoint(firePoint, botFireArray);
  667.             } else {
  668.                 //debug("Move number = " + moveNumber + ": bot '" + botName + "' doesn't shoot!");
  669.             }
  670.             botJSONObject.put("fire", botFireArray);
  671.             if (moveChar != null) {
  672.                 if (Character.isUpperCase(moveChar)) {
  673.                     moveChar = Character.toLowerCase(moveChar);
  674.                 }
  675.                 botJSONObject.put("move", Character.toString(moveChar));
  676.             } else {
  677.                 botJSONObject.put("move", "s");
  678.                 //debug("Move number = " + moveNumber + ": bot '" + botName + "' doesn't move!");
  679.             }
  680.             sent.put(botName, botJSONObject);
  681.         }
  682.         out.println(sent);
  683.         out.flush();
  684.     }
  685.  
  686.     void receiveBotsInfo() throws Exception {
  687.         JSONObject received = null;
  688.         try {
  689.             received = new JSONObject(in.readLine());
  690.             debug("Bots info: " + received);
  691.             moveNumber = received.getInt("turn_no");
  692.             JSONObject playersInfo = received.getJSONObject("players");
  693.             parsePlayersInfo(playersInfo);
  694.             if (received.has("bots")) {
  695.                 JSONObject botsInfo = received.getJSONObject("bots");
  696.                 parseBotsInfo(botsInfo);
  697.             }
  698.             JSONArray emptyCellsArray = received.getJSONArray("empty");
  699.             for (int i = 0; i < emptyCellsArray.length(); i++) {
  700.                 JSONArray pointArray = emptyCellsArray.getJSONArray(i);
  701.                 Point point = getPoint(pointArray);
  702.                 int x = point.x;
  703.                 int y = point.y;
  704.                 a[x][y] = '0';
  705.             }
  706.         } catch (Exception e) {
  707.             errorsCount++;
  708.             PrintWriter pw = new PrintWriter("error" + errorsCount + ".log");
  709.             pw.println("Bots info: " + (received==null?"null":received.toString()));
  710.             e.printStackTrace(pw);
  711.             pw.close();
  712.             throw e;
  713.         }
  714.     }
  715.    
  716.     static int errorsCount = 0;
  717.    
  718.     void parseBotsInfo(JSONObject botsInfo) throws Exception {
  719.         if (botsInfo == null) {
  720.             return;
  721.         }
  722.         if (botsInfo.length() == 0) {
  723.             return;
  724.         }
  725.         String[] botNames = JSONObject.getNames(botsInfo);
  726.         if (botNames == null) {
  727.             return;
  728.         }
  729.         for (String botName : botNames) {
  730.             JSONObject botInfo = botsInfo.getJSONObject(botName);
  731.             parseSingleBot(botName, botInfo);
  732.         }
  733.     }
  734.    
  735.     Point getPoint(JSONArray pointArray) throws Exception {
  736.         int x = pointArray.getInt(1);
  737.         int y = pointArray.getInt(0);
  738.         return new Point(x, y);
  739.     }
  740.    
  741.     void addPoint(Point point, JSONArray pointArray) throws Exception {
  742.         int x = point.x;
  743.         int y = point.y;
  744.         pointArray.put(0, y);
  745.         pointArray.put(1, x);
  746.     }
  747.  
  748.     void parseSingleBot(String botName, JSONObject botInfo) throws Exception {
  749.         String playerName = botInfo.getString("player");
  750.         JSONArray position = botInfo.getJSONArray("position");
  751.         Point botPoint = getPoint(position);
  752.         int x = botPoint.x;
  753.         int y = botPoint.y;
  754.         int hp = botInfo.getInt("health");
  755.         int respawnTime = botInfo.getInt("time");
  756.         JSONArray canShootArray = botInfo.getJSONArray("can_shoot");
  757.         List<Point> canShootList = new ArrayList<Point>();
  758.         for (int i = 0; i < canShootArray.length(); i++) {
  759.             JSONArray pointArray = canShootArray.getJSONArray(i);
  760.             Point canShootPoint = getPoint(pointArray);
  761.             canShootList.add(canShootPoint);
  762.         }
  763.         Bot bot = new Bot(botName, playerName, x, y, hp, respawnTime, canShootList);
  764.         if (bot.playerName.equals(myName)) {
  765.             myBots.add(bot);
  766.         } else {
  767.             enemyBots.add(bot);
  768.         }
  769.     }
  770.  
  771.     void parsePlayersInfo(JSONObject playersInfo) throws Exception {
  772.         String[] playerNamesArray = JSONObject.getNames(playersInfo);
  773.         for (String playerName : playerNamesArray) {
  774.             JSONObject playerData = playersInfo.getJSONObject(playerName);
  775.             int score = playerData.getInt("score");
  776.             scores.put(playerName, score);
  777.             playerNames.add(playerName);
  778.         }
  779.     }
  780.  
  781.     void receiveFieldInfo() throws Exception {
  782.         JSONObject received = new JSONObject(in.readLine());
  783.         myName = received.getString("user_id");
  784.         n = received.getInt("width");
  785.         m = received.getInt("height");
  786.         a = new char[n][m];
  787.         for (int i = 0; i < n; i++) {
  788.             for (int j = 0; j < m; j++) {
  789.                 a[i][j] = '0';
  790.             }
  791.         }
  792.         JSONArray bricksArray = received.getJSONArray("bricks");
  793.         for (int i = 0; i < bricksArray.length(); i++) {
  794.             JSONArray pointArray = bricksArray.getJSONArray(i);
  795.             Point point = getPoint(pointArray);
  796.             int x = point.x;
  797.             int y = point.y;
  798.             a[x][y] = '1';
  799.         }
  800.     }
  801.  
  802.     void receiveConnectionSuccess() throws Exception {
  803.         JSONObject received = new JSONObject(in.readLine());
  804.         if (!received.getString("status").equals("ok") || !received.getString("message").equals("logged in")) {
  805.             throw new RuntimeException("Status = " + received.getString("status") + ", message = " + received.getString("message"));
  806.         }
  807.         log("Connection succeeded!");
  808.     }
  809.  
  810.     void receiveConnectionApprove() throws Exception {
  811.         JSONObject received = new JSONObject(in.readLine());
  812.         if (!received.getString("status").equals("ok") || !received.getString("message").equals("ready for login")) {
  813.             throw new RuntimeException("Status = " + received.getString("status") + ", message = " + received.getString("message"));
  814.         }
  815.         log("Connection approved!");
  816.         JSONObject sent = new JSONObject();
  817.         sent.put("message_type", "login");
  818.         sent.put("game_token", GAME_TOKEN);
  819.         sent.put("user_token", USER_TOKEN);
  820.         out.println(sent);
  821.         out.flush();
  822.         log("Game data sent!");
  823.     }
  824.  
  825. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement