PsyOps

battlebot.java

May 24th, 2014
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.63 KB | None | 0 0
  1. package twcore.bots.battlebot;
  2.  
  3. import twcore.bots.battlebot.PlayerOps.BZPlayer;
  4. import twcore.bots.battlebot.PlayerOps.PlayerOps;
  5. import twcore.bots.battlebot.PlayerOps.Status;
  6. import twcore.bots.battlebot.PublicOps.PublicOps;
  7. import twcore.core.BotAction;
  8. import twcore.core.BotSettings;
  9. import twcore.core.EventRequester;
  10. import twcore.core.SubspaceBot;
  11. import twcore.core.events.ArenaJoined;
  12. import twcore.core.events.FlagClaimed;
  13. import twcore.core.events.FlagDropped;
  14. import twcore.core.events.FrequencyChange;
  15. import twcore.core.events.FrequencyShipChange;
  16. import twcore.core.events.LoggedOn;
  17. import twcore.core.events.Message;
  18. import twcore.core.events.PlayerDeath;
  19. import twcore.core.events.PlayerEntered;
  20. import twcore.core.events.PlayerLeft;
  21. import twcore.core.events.PlayerPosition;
  22. import twcore.core.events.Prize;
  23. import twcore.core.events.WatchDamage;
  24. import twcore.core.game.Player;
  25.  
  26. import java.util.*;
  27. /*----------------------------------------------------------------------------------\
  28.  *                            Battle Zone Bot:
  29.  *                            
  30.  * BattleBot will be in control of our public arena for BattleZone
  31.  * The three main statuses for the public arena are:
  32.  * Spectating  - In 8025 and speccing
  33.  * Public      - Inside Main area and playing normal pub type play/gaming
  34.  * Battle      - In one of the outside boxes setup for VS battle or Event games (usually set in subarenas)
  35.  * My main objective for this bot is to organize public play and subarena play all in one area
  36.  * Too much population ends up getting spread out over too many subarenas
  37.  *----------------------------------------------------------------------------------*/
  38. public class battlebot extends SubspaceBot {
  39.  
  40.     private BotSettings m_botSettings;          // Stores settings for your bot as found in the .cfg file.
  41.                                                 // In this case, it would be settings from battlebot.cfg
  42.  
  43.     // sending over bot functions to public module
  44.     PublicOps pub;
  45.     // Chat class to limit biller msgs/commands
  46.     ChatBuffer bzChat = new ChatBuffer();
  47.     // bob the door man - plz tip
  48.     DoorMan bob;
  49.     // Shortcut to ba
  50.     BotAction b;
  51.     // Help command handler
  52.     HelpBrowser bzHelp;
  53.    
  54.     /**
  55.      * Creates a new instance of your bot.
  56.      */
  57.     public battlebot(BotAction botAction) {
  58.         super(botAction);
  59.         requestEvents();
  60.         // m_botSettings contains the data specified in file <botname>.cfg
  61.         m_botSettings = m_botAction.getBotSettings();
  62.         // my shortcut to ba
  63.         b = this.ba;
  64.         // sending needed classes to our own
  65.         bob = new DoorMan(b,bzChat);
  66.         pub = new PublicOps(this,bzChat,bob);
  67.         bzHelp = new HelpBrowser(this);
  68.     }
  69.    
  70.     /**
  71.      * This method requests event information from any events your bot wishes
  72.      * to "know" about; if left commented your bot will simply ignore them.
  73.      */
  74.     /*-------------------------------------------------------------------------------\
  75.      *
  76.      *                             EVENT REGISTRY
  77.      *                            
  78.      *-------------------------------------------------------------------------------*/
  79.     public void requestEvents() {
  80.         EventRequester req = m_botAction.getEventRequester();
  81.         req.request(EventRequester.MESSAGE);
  82.         req.request(EventRequester.ARENA_JOINED);
  83.         req.request(EventRequester.PLAYER_ENTERED);
  84.         req.request(EventRequester.PLAYER_POSITION);
  85.         req.request(EventRequester.FREQUENCY_SHIP_CHANGE);
  86.         req.request(EventRequester.LOGGED_ON);
  87.         req.request(EventRequester.PLAYER_LEFT);
  88.         req.request(EventRequester.PRIZE);
  89.         req.request(EventRequester.FREQUENCY_CHANGE);
  90.         req.request(EventRequester.PLAYER_DEATH);
  91.         req.request(EventRequester.FLAG_CLAIMED);
  92.         req.request(EventRequester.FLAG_DROPPED);
  93.         // req.request(EventRequester.WEAPON_FIRED);
  94.         // req.request(EventRequester.ARENA_LIST);
  95.         req.request(EventRequester.WATCH_DAMAGE);
  96.         // req.request(EventRequester.FLAG_POSITION);
  97.     }
  98.  
  99.     /*-------------------------------------------------------------------------------\
  100.      *
  101.      *                             NEEDED VARS
  102.      *                            
  103.      *-------------------------------------------------------------------------------*/
  104.     // Random numbers duh
  105.     Random ran = new Random();
  106.     // Used for Game timer
  107.     Timer timer = new Timer();
  108.     // Bot Game status
  109.     boolean GameOn = false;
  110.     // Controls my custom Player List
  111.     PlayerOps Players = new PlayerOps();
  112.     // Command to join needed chats
  113.     String ChatCommand = "?chat=battledev,battle";
  114.    
  115.     // Regions
  116.     // - Start Box
  117.     private short[] m_StartBox = new short[]{ 520 * 16, 510 * 16, 524 * 16, 514 * 16 };
  118.     private short[] m_PublicArea = new short[]{ 0, 328 * 16, 1023 * 16, 768 * 16 };
  119.     private short[] m_MapRoom1 = new short[]{ 225 * 16, 778 * 16, 499 * 16, 846 * 16};
  120.     private short[] m_MapRoom2 = new short[]{ 499 * 16, 792 * 16, 785 * 16, 846 * 16};
  121.    
  122.     // Timestamps for updating bot position
  123.     long TS_BotPosUpdate = System.currentTimeMillis() ;
  124.     long Delay_BotPosUpdate = 75;
  125.     boolean BotPosToggle = false;
  126.    
  127.     String NextWDToggle = "~none~";
  128.     long NextWDTimestamp = System.currentTimeMillis();
  129.     /*-------------------------------------------------------------------------------\
  130.      *
  131.      *                             SUBSPACE EVENTS
  132.      *                            
  133.      *-------------------------------------------------------------------------------*/
  134.     // - MESSAGE EVENT
  135.     public void handleEvent(Message event)
  136.     {
  137.         bzCommandHandler(event);   
  138.     }
  139.     // - DAMAGE EVENT
  140.     public void handleEvent(WatchDamage w)
  141.     {
  142.         if(!GameOn) return;
  143.        
  144.         if (pub.damageEventHandled(w)) return;
  145.     }
  146.     // - LOGGEN ON
  147.     public void handleEvent(LoggedOn event)
  148.     {
  149.         m_botAction.joinArena(m_botSettings.getString("arena"));
  150.     }
  151.     // - PLAYER POSITION
  152.     public void handleEvent(PlayerPosition p)
  153.     {
  154.         if(!GameOn) return;
  155.         RegionControl(p);  
  156.     }
  157.     // - PLAYER ENTERED
  158.     public void handleEvent(PlayerEntered pe)
  159.     {  
  160.         if(!GameOn) return;
  161.        
  162.         Players.PlayerEntered(m_botAction.getPlayerName(pe.getPlayerID()));
  163.         watchDamageOn(m_botAction.getPlayerName(pe.getPlayerID()));
  164.     }
  165.     // - ARENA JOINED
  166.     public void handleEvent(ArenaJoined event)
  167.     {  
  168.         InitializeBot();   
  169.     }
  170.     // - FREQUENCY CHANGE
  171.     public void handleEvent(FrequencyChange sc)
  172.     {
  173.         if(!GameOn) return;
  174.     }
  175.     // - GET GREEN EVENT
  176.     public void handleEvent(Prize pr)
  177.     {  
  178.         if(!GameOn) return;
  179.         pub.prizeEvent(pr);
  180.     }
  181.     // - FLAG CLAIMED
  182.     public void handleEvent(FlagClaimed fc)
  183.     {  
  184.         if(!GameOn) return;
  185.         pub.flagClaimed(fc);   
  186.     }
  187.     // - FLAG DROPPED
  188.     public void handleEvent(FlagDropped fd)
  189.     {  
  190.         if(!GameOn) return;
  191.         pub.flagDropped(fd);   
  192.     }
  193.     // - PLAYER DEATH
  194.     public void handleEvent(PlayerDeath pd)
  195.     {
  196.         if(!GameOn) return;
  197.         if (pub.playerDeath(pd)) return;   
  198.     }
  199.     // - PLAYER LEFT
  200.     public void handleEvent(PlayerLeft pl)
  201.     {  
  202.  
  203.         if(!GameOn) return;
  204.        
  205.         String name = b.getPlayerName(pl.getPlayerID());
  206.         if(name == null) b.sendChatMessage("Player ID Returned null - bug found yay.");
  207.         pub.playerLeftEvent(pl);
  208.         Players.removePlayer(name);
  209.     }
  210.     // - SHIP CHANGE
  211.     public void handleEvent(FrequencyShipChange sc)
  212.     {
  213.         if(!GameOn) return;
  214.        
  215.         // Grab player info from our custom Player Class
  216.         BZPlayer bp = Players.getPlayer(m_botAction.getPlayerName( sc.getPlayerID()));
  217.        
  218.         // we shouldnt be getting null here
  219.         if (bp == null) return;
  220.  
  221.         // Update Main Player status
  222.         if (sc.getShipType() == 0 && bp.PlayerStatus() != Status.Spectating)
  223.         {   bp.setStatus(Status.Spectating);    }
  224.        
  225.         if (pub.shipChangeEvent(sc)) return;
  226.     }
  227.    
  228.     /*-------------------------------------------------------------------------------\
  229.      *
  230.      *                             MAIN ZONE TIMER
  231.      *                            
  232.      *-------------------------------------------------------------------------------*/
  233.     class GameTimer extends TimerTask {
  234.         @Override
  235.         public void run() {
  236.             if(!playerListUpdated) updatePlayerList();
  237.             // check to see if its time to toggle bot position
  238.             BotPosUpdate();
  239.             // Update chat buffer module
  240.             bzChat.updateChatBuffer(b);
  241.             // Checks the status of doors and updates if needed
  242.             bob.UpdateDoors();
  243.             // Run pub timer
  244.             pub.pubGameTimer();
  245.             // Check for watchdamage commands
  246.             if (GameOn)updateWatchDamageList();
  247.         }
  248.     }
  249.     /*-------------------------------------------------------------------------------\
  250.      *
  251.      *                             CHAT COMMANDS
  252.      *                            
  253.      *-------------------------------------------------------------------------------*/
  254.     // --  HELP
  255.     // Checks our home directory for help files and sends back to player
  256.     public void doHelp(String name, String args) {
  257.         String[] helpMessage;
  258.  
  259.         if (args == null || args.trim().length() == 0) helpMessage = bzHelp.getHelp("overview");
  260.         else if (args.charAt(0) == '!') helpMessage = bzHelp.getHelp(args.substring(1));
  261.         else helpMessage = bzHelp.getHelp(args);
  262.  
  263.         for (int i = 0; i < helpMessage.length; i++)
  264.             m_botAction.sendUnfilteredPrivateMessage(name, helpMessage[i]);
  265.     }
  266.     // -- ALL OTHER COMMANDS
  267.     public void bzCommandHandler(Message event) {
  268.         // Retreive name. If the message is remote, then event.getMessager() returns null, and event.getPlayerID returns a value.
  269.         // If the message is from the same arena, event.getMessager() returns a string, and event.getPlayerID will return 0.
  270.         String name = event.getMessager() != null ? event.getMessager() : m_botAction.getPlayerName(event.getPlayerID());
  271.         if (name == null) name = "-anonymous-";
  272.  
  273.         // Help commands
  274.         if ((event.getMessageType() == Message.PRIVATE_MESSAGE || event.getMessageType() == Message.PUBLIC_MESSAGE)
  275.                 && event.getMessage().startsWith("!help"))
  276.         {
  277.             doHelp(b.getPlayerName(event.getPlayerID()),
  278.                     event.getMessage().trim() == "!help" ? "":event.getMessage().substring(5, event.getMessage().length()).trim());
  279.             return;
  280.         }
  281.        
  282.      // Toggle debug mode
  283.         if (event.getMessage().trim().contains("Damage logging ON") || event.getMessage().trim().contains("Damage logging OFF"))
  284.         {
  285.             String response = event.getMessage().trim().split(" ",-1)[2].toLowerCase();
  286.  
  287.             if (b.getPlayer(watchDamageList.get(0)) == null)
  288.             {
  289.                 bzChat.debugMessage("Damage logging: Player [ "+watchDamageList.get(0)+" ] left before command could be sent.");
  290.                 watchDamageList.remove(0);
  291.                 return;
  292.             }
  293.            
  294.             if (response.equals("on"))
  295.             {
  296.                 bzChat.debugMessage("Damage logging toggled on for: [ "+watchDamageList.get(0)+" ]");
  297.                 watchDamageList.remove(0);
  298.             }
  299.             else
  300.                 b.sendUnfilteredPrivateMessage(watchDamageList.get(0), "*watchdamage");
  301.         }
  302.        
  303.         // Toggle debug mode
  304.         if (event.getMessage().trim().equalsIgnoreCase("!test"))
  305.         {
  306.             b.sendArenaMessage("Flag Coords [ "+b.getFlag(0).getXLocation()+"  | "+b.getFlag(0).getYLocation()+" ] ");
  307.             short x = b.getPlayer((b.getFlag(0).getPlayerID())).getXLocation();
  308.             short y = b.getPlayer((b.getFlag(0).getPlayerID())).getYLocation();
  309.             b.sendArenaMessage("Player Flag Coords [ "+x+"  | "+y+" ] ");
  310.         }
  311.        
  312.         // Toggle debug mode
  313.         if (event.getMessage().trim().equalsIgnoreCase("!debug"))
  314.         {
  315.             bzChat.setDebug(!bzChat.debugMode);
  316.             return;
  317.         }
  318.        
  319.         // Checking if public command
  320.         if (pub.isPublicCommand(event)) return;
  321.        
  322.         // Default implemented command: !die
  323.         if (event.getMessageType() == Message.PRIVATE_MESSAGE && event.getMessage().equalsIgnoreCase("!die")) {
  324.             //m_botAction.sendPublicMessage(name + " commanded me to die. Disconnecting...");
  325.             try { Thread.sleep(50); } catch (Exception e) {};
  326.             m_botAction.die();
  327.         }
  328.         // Returns Status List
  329.         else if (event.getMessage().trim().equalsIgnoreCase("!plist"))
  330.         {   for (String s: Players.getList())   m_botAction.sendPrivateMessage(event.getPlayerID(), s); }
  331.     }
  332.     /*-------------------------------------------------------------------------------\
  333.      *
  334.      *                          ZONE INITIALIZATION TASKS
  335.      *                            
  336.      *-------------------------------------------------------------------------------*/
  337.     // Initialization tasks to get bot started
  338.     public void InitializeBot()
  339.     {
  340.         // Have bot get reliable kills
  341.         m_botAction.setReliableKills(1);
  342.         // Setting debug messaging to true
  343.         bzChat.setDebug(true);
  344.         // Have bot join chats
  345.         bzChat.sendChatMsg(0, ChatCommand);
  346.        
  347.         // Start Main GameTimer
  348.         timer.scheduleAtFixedRate(new GameTimer(),5000 ,10); //delay in milliseconds
  349.         // Initialize pub class
  350.         pub.initializePub();
  351.     }
  352.     private boolean playerListUpdated = false;
  353.     private long playerListUpdateTS = System.currentTimeMillis();
  354.     public void updatePlayerList()
  355.     {
  356.         if(System.currentTimeMillis() - playerListUpdateTS < 10000) return;
  357.        
  358.         playerListUpdated = true;
  359.         // Get all Players
  360.         Iterator<Player> i = b.getPlayerIterator();
  361.          // Get all players on same freq and toggle lvz.
  362.          while( i.hasNext() )
  363.          {
  364.             Player p = i.next();
  365.             Players.PlayerEntered(m_botAction.getPlayerName(p.getPlayerID()));
  366.             watchDamageOn(p.getPlayerName());
  367.            
  368.             if (p.isPlaying())
  369.             {
  370.                 if(InRegion(p.getXLocation(),p.getYLocation(),m_PublicArea))
  371.                 {  
  372.                     pub.playerJoinedPublic(p.getPlayerName());
  373.                 }
  374.                 else if (InRegion(p.getXLocation(),p.getYLocation(),m_MapRoom1)
  375.                         || InRegion(p.getXLocation(),p.getYLocation(),m_MapRoom2))
  376.                 {
  377.                     b.sendArenaMessage("Warped player out of map room on BotInitialization. [ "+p.getPlayerName()+" ]");
  378.                     b.warpTo(p.getPlayerID(), 512, 512);
  379.                     pub.playerJoinedPublic(p.getPlayerName());
  380.                 }
  381.                 else
  382.                 {
  383.                     b.sendArenaMessage("Warped player out of Battle Box area on BotInitialization. [ "+p.getPlayerName()+" ]");
  384.                     b.warpTo(p.getPlayerID(), 512, 512);
  385.                     pub.playerJoinedPublic(p.getPlayerName());
  386.                 }
  387.             }
  388.          }
  389.         // Start Bot/Game
  390.         GameOn = true;
  391.         watchDamageTS = System.currentTimeMillis();
  392.         // Send initialization message
  393.         bzChat.sendChatMsg(1, m_botAction.getBotName() + " is now initialized.");
  394.     }
  395.     /*-------------------------------------------------------------------------------\
  396.      *
  397.      *                             MISC FUNCTIONS
  398.      *                            
  399.      *-------------------------------------------------------------------------------*/
  400.     List<String> watchDamageList = new ArrayList<String>();
  401.     long watchDamageTS = System.currentTimeMillis();
  402.     public void updateWatchDamageList()
  403.     {
  404.         if (!watchDamageList.isEmpty() && System.currentTimeMillis() - watchDamageTS > 1000)
  405.         {
  406.             watchDamageTS = System.currentTimeMillis();
  407.             b.sendUnfilteredPrivateMessage(watchDamageList.get(0), "*watchdamage");
  408.         }
  409.     }
  410.     public void watchDamageOn(String PlayerName)
  411.     {
  412.         watchDamageList.add(PlayerName);
  413.     }
  414.     /*----------------------------------------------\
  415.      * BOT POSITION TOGGLE - helps us get as much player position info as possible
  416.      *---------------------------------------------*/
  417.     // Toggles between 2 diff spots so we can get as many playerposition packets as possible
  418.     public void BotPosUpdate()
  419.     {
  420.         if (System.currentTimeMillis() - TS_BotPosUpdate > Delay_BotPosUpdate)
  421.         {
  422.             // Update timestamp
  423.             TS_BotPosUpdate = System.currentTimeMillis();
  424.             // Toggle position
  425.             BotPosToggle = !BotPosToggle;
  426.             // Stop speccing a player
  427.             b.stopSpectatingPlayer();
  428.             // Send bot to new position
  429.             b.getShip().move((BotPosToggle ? 256:768) * 16, 587 * 16);
  430.         }
  431.     }
  432.     /*----------------------------------------------\
  433.      *      MANAGE OUR REGIONS AND HOTSPOTS
  434.      *---------------------------------------------*/
  435.     // Check to see if a player is over a region or hotspot
  436.     public void RegionControl(PlayerPosition p)
  437.     {      
  438.         // Grab player info from our cutom Player Class
  439.         BZPlayer bp = Players.getPlayer(m_botAction.getPlayerName( p.getPlayerID()));
  440.         // we shouldnt be getting null here
  441.         if (bp == null) return;
  442.        
  443.         // Checking if position is for pub - if so ignore the rest
  444.         if(pub.playerPositionHandled(p)) return;
  445.        
  446.         // ------------ START BOX
  447.         if (InRegion(p,m_StartBox) && bp.PlayerStatus() == Status.Spectating)
  448.         {
  449.             bp.setStatus(Status.Public);
  450.             pub.playerJoinedPublic(bp.PlayerName());
  451.         }
  452.     }
  453.     // Simple collision check - seeing if player is in a given region
  454.     private boolean InRegion( PlayerPosition p, short[] Region)
  455.     {   return InRegion(p.getXLocation(),p.getYLocation(),Region);  }
  456.     // Simple collision check - seeing if player is in a given region
  457.     private boolean InRegion( short x, short y, short[] Region)
  458.     {
  459.         return (x > Region[0] && x < Region[2] &&
  460.                 y > Region[1] && y < Region[3]) ? true:false;
  461.     }
  462. }
Advertisement
Add Comment
Please, Sign In to add comment