Guest User

LostJustice

a guest
Jun 14th, 2016
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // * This is a test script that demonstrates some abilities of the Hafen's client scripting
  2. //
  3. // It does the following actions:
  4. // - Logs in using provided login and password (replace them with the actual ones in `onLogin` function below)
  5. // - Selects a specified character (replace it with the real one in `onCharSelect` function below)
  6. // - Starts autowalking (with pathfinding)
  7. // - When a forageable curio encountered, it picks it and place it in the study interface if it is a dandelion
  8. // - When an aggresive animal or an unknown player encountered, it teleports to the hearth fire and starts autowalking again
  9. //
  10. // There are a lot more functions that you can use for the client scripting, please see the comments below
  11. //
  12. // * You should use a patched version of Amber client to make it work -- https://www.dropbox.com/s/srykok9g0uljfk6/amber-script.zip?dl=0
  13. // Source code is available here -- https://github.com/b0r3d0m/amber ("feature/script-api" branch)
  14. //
  15. // * This script should be named "script.js" (w/o double quotes) and placed in the root directory of the modified Amber client (the same directory where you have the "hafen.jar" file)
  16. //
  17. // * It is written in Javascript but you can use Java standard library via `java` object (for example, `java.lang.Thread.sleep`)
  18. //
  19. // * Please read all NOTEs and comments
  20. //
  21. // * I'm strongly recommend not to use the game's client by yourself when there's "script.js" file in the game's directory
  22. //   If you want to use the client by yourself, rename this script to something else and restart the client
  23. //
  24. // * Feel free to ask me any questions
  25. //
  26. // b0r3d0m
  27.  
  28. ///////////////////////
  29. // User-defined "global" variables
  30. ///////////////////////
  31.  
  32. /**
  33.  * Game object from the {@link onGameLoaded} function
  34.  * @type {Game}
  35.  */
  36. var g = null;
  37.  
  38.  
  39. /**
  40.  * ID of the autowalking timer
  41.  * @type {Number}
  42.  */
  43. var autoWalkingTimerId = null;
  44.  
  45. ///////////////////////
  46. // API events
  47. ///////////////////////
  48.  
  49. // NOTE that you should define all API event functions, even if you don't want to handle some of them
  50. //      Just do nothing if you don't want to process such events
  51.  
  52. /**
  53.  * It is fired when the client started
  54.  * @return {Object} options - Object that contains general options for the client
  55.  * @return {Boolean} options.renderingEnabled - Set this option to `false` if you want to disable rendering
  56.  */
  57. function onClientStarted() {
  58.   var options = {
  59.     renderingEnabled: true
  60.   };
  61.   return options;
  62. }
  63.  
  64. /**
  65.  * It is fired when the login screen appeared
  66.  * @return {Object} credentials - Object that contains information about login and password to log in with
  67.  * @return {String} credentials.login - The actual login
  68.  * @return {String} credentials.password - The actual password
  69.  */
  70. function onLogin() {
  71.   print('Logging in...');
  72.  
  73.   var credentials = {
  74.     login: user,
  75.     password: pass
  76.   };
  77.   return credentials;
  78. }
  79.  
  80. /**
  81.  * It is fired 3 seconds after the character select. screen appeared
  82.  * @return {String} characterName - Name of the character to select
  83.  */
  84. function onCharSelect() {
  85.         print('Selecting character...');
  86.  
  87.   return character;
  88. }
  89.  
  90. /** It is fired 10 seconds after the selected character entered the world
  91.  * @param {Object} game This is the main interface to the client API, so generally you should keep a reference to it somewhere in the script
  92.  */
  93. function onGameLoaded(game) {
  94.  
  95.   print('Game loaded');
  96.  
  97.   g = game;
  98.  
  99.   onRedGameLoaded();
  100.   onPorkGameLoaded();
  101.  
  102. }
  103.  
  104.  
  105.  
  106. // `game` interface:
  107. // - getPlayerCoords()
  108. //   Returns an object with the `x` and `y` properties represents the player's coordinates
  109. //
  110. // - getInvItems()
  111. //   Returns an array of items' names from the character's inventory or `null` if there was an error
  112. //
  113. // - studyCurio(curioName)
  114. //   Places a curio with the specified name from the character's inventory to the study inventory
  115. //   Returns `true` on success and `false` otherwise
  116. //   NOTE that it doesn't handle situations when you don't have enough points to study the specified curio (it returns `true` in such cases)
  117. //        Use function `getCharAttentionInfo` to check it
  118. //
  119. // - getCharAttentionInfo()
  120. //   Returns an object with `max` and `used` properties
  121. //
  122. // - goTo(x, y)
  123. //   Makes the character go to the specified coordinates (with the pathfinding enabled)
  124. //
  125. // - pickItem(id)
  126. //   Picks a foragable item with the specified id (with the pathfinding enabled)
  127. //   Takes item's id
  128. //   Returns `true` if there is an item with such id or `false` otherwise
  129. //
  130. // - travelToHearthFire()
  131. //   Makes the character travel to its hearth fire
  132. //
  133. // - getMapObjects(name)
  134. //   Returns an array of map objects with the specified name (each of them has `name`, `fullName`, `id` and `coords` properties)
  135. //
  136. // - getMapObjectsByFullName(fullName)
  137. //   The same as the `getMapObjects` function but looking for a fullName instead of name (for example, `gfx/terobjs/plants/carrot` instead of `carrot`) -- may be useful to distinguish between growing and laying objects
  138. //
  139. // - getAllMapObjects()
  140. //   Returns an array of map objects (each of them has `name`, `fullName`, `id` and `coords` properties)
  141. //
  142. // - mapObjectRightClick(id)
  143. //   Clicks an object with the specified ID via the right mouse button
  144. //   NOTE That you can't use this function for some specific objects (for example, tables -- use `openTable` function instead)
  145. //   Returns `true` on success or `false` otherwise
  146. //
  147. // - transferItem(name)
  148. //   Transfers an item with the specified name from the character's inventory to an opened container (or study interface if there are no containers opened)
  149. //   Returns `true` on success or `false` otherwise
  150. //
  151. // - transferItems(name)
  152. //   The same as the `transferItem` function but transfers all objects wit the specified name
  153. //   Returns `true` on success or `false` otherwise
  154. //
  155. // - getItemsFrom(windowName)
  156. //   Returns an array of items' names from the specified window (for example, 'Frame' in case of drying frames) or `null` if there was an error
  157. //
  158. // - transferItemFrom(windowName, itemName)
  159. //   Transfers an item with the specified name from the specified window to the character's inventory
  160. //   Returns `true` on success or `false` otherwise
  161. //
  162. // - transferItemsFrom(windowName, itemsName)
  163. //   The same as `transferItemFrom` function but transfers all objects with the specified name
  164. //   Returns `true` on success or `false` otherwise
  165. //
  166. // - getHP()
  167. //   Returns an object with `shp` and `hhp` properties represent the soft and hard hitpoints percents correspondingly (or -1 if there was an error)
  168. //
  169. // - getStamina()
  170. //   Returns stamina of the player or -1 if there was an error
  171. //
  172. // - getEnergy()
  173. //   Returns energy of the player / 100 or -1 if there was an error
  174. //
  175. // - drink()
  176. //   Makes the character drink water from any of the following containers -- bucket, kuksa, waterskin and waterflask (from both character's inventory and equipment screen)
  177. //   NOTE that this method, unlike many others, is synchronous
  178. //        This is a result of its "adaptive" behavior -- it tries to drink from one container and if it's not enough it switches to the next one
  179. //
  180. // - eat(itemName)
  181. //   Makes the character eat the specified item from its inventory
  182. //   Returns `true` on success or `false` otherwise
  183. //
  184. // - eatFrom(windowName, itemName)
  185. //   Makes the character eat the specified item from the specified window
  186. //   Returns `true` on success or `false` otherwise
  187. //
  188. // - takeItemFromStockpile()
  189. //   Takes item from an opened stockpile
  190. //   Returns `true` on success or `false` otherwise
  191. //
  192. // - getStockpileInfo()
  193. //   Returns an object that represents information about an opened stockpile (it has `resBaseName`, `used` and `total` properties) or `null` if there was an error
  194. //
  195. // - createStockpileWithItem(itemName, x, y)
  196. //   Creates a stockpile with the specified item at (x, y) coordinates
  197. //   Returns `true` on success or `false` otherwise
  198. //   NOTE However, there are a lot of situations when this function can fail but still return `true` as a result
  199. //        For example, createStockpileWithItem, unlike goTo and pickItem functions, doesn't use pathfinding (romovs didn't implement it yet)
  200. //        The rule of thumb here is to wait for some time (this function, like many others, is asynchronous) and call the `getStockpileInfo` function to check whether we actually opened a stockpile menu
  201. //
  202. // - waitForPf()
  203. //   Waits for pathfinding to finish
  204. //
  205. // - takeItem(itemName)
  206. //   Takes an item from the character's inventory (it has the same effect as left-clicking an item)
  207. //   It may be useful to call this function for map objects' interacting
  208. //   Returns `true` on success or `false` otherwise
  209. //
  210. // - getEquippedItems()
  211. //   Returns an array of items' names that equipped on the character or `null` if there was an error
  212. //
  213. // - equipItem(itemName)
  214. //   Equips the specified item
  215. //   Returns `true` on success or `false` otherwise
  216. //
  217. // - unequipItem(itemName)
  218. //   Unequips the specified item (the item will be transferred to the character's inventory)
  219. //   Returns `true` on success or `false` otherwise
  220. //
  221. // - sendAreaChatMessage(msg)
  222. //   Sends the specified message to the area chat
  223. //   Returns `true` on success or `false` otherwise
  224. //
  225. // - sendPartyChatMessage(msg)
  226. //   Sends the specified message to the party chat
  227. //   Returns `true` on success or `false` otherwise
  228. //
  229. // - sendVillageChatMessage(msg)
  230. //   Sends the specified message to the village chat
  231. //   Returns `true` on success or `false` otherwise
  232. //
  233. // - sendPrivateChatMessage(to, msg)
  234. //   Sends the specified message to the player specified in the `to` parameter
  235. //   Returns `true` on success or `false` otherwise
  236. //
  237. // - liftObject(id)
  238. //   Makes the character to lift an object with the specified ID
  239. //   Returns `true` on success or `false` otherwise
  240. //
  241. // - mapRightClick(x, y)
  242. //   Right clicks the specified location
  243. //   NOTE that this function, unlike several others, doesn't use pathfinder
  244. //
  245. // - getSpeed()
  246. //   Returns speed of the character (0 <= speed <= 3 where 0 is "crawl" and 3 is "sprint") or -1 if there was an error
  247. //
  248. // - setSpeed(speed)
  249. //   Sets speed of the character to the specified level (acceptable values -- 0 <= speed <= 3 where 0 is "crawl" and 3 is "sprint")
  250. //
  251. // - useMenuAction(hotkeys)
  252. //   Activates menu action via the specified hotkeys (for example, `g.useMenuAction(['a', 'l'];` activates Adventure -> Lift action)
  253. //   Returns `true` on success or `false` otherwise
  254. //
  255. // - craft(itemName)
  256. //   Makes the character to craft the specified item
  257. //   Returns `true` on success or `false` otherwise
  258. //   NOTE that this function doesn't check that the character actually crafted the specified item
  259. //
  260. // - craftAll(itemName)
  261. //   The same as the `craft` function but uses "Craft all" option instead of "Craft"
  262. //
  263. // - chooseFlowerMenuOption(option)
  264. //   Chooses the specified flower menu option
  265. //   Returns `true` on success or `false` otherwise
  266. //
  267. // - dropItem(itemName)
  268. //   Makes the character to drop the specified item from its inventory
  269. //   Returns `true` on success or `false` otherwise
  270. //
  271. // - dropItemFromHand()
  272. //   Makes the character to drop an item from its hand
  273. //   Returns `true` on success or `false` otherwise
  274. //
  275. // - useItemFromHandOnObject(id)
  276. //   Makes the character to use an item from its hand on an object with the specified ID
  277. //   Returns `true` on success or `false` otherwise
  278. //
  279. // - getBarrelContent(id)
  280. //   Returns a type of the barrel's content ('water', 'milk', 'honey' etc) or 'empty' if it's empty. Returns null if there was an error
  281. //
  282. // - getBarrelLiters(id)
  283. //   Returns amount of liquid inside a barrel with the specified ID or null if there was an error
  284. //   NOTE that this function right-clicks the barrel and waits 5 seconds for the "Barrel" window to appear
  285. //
  286. // - getGrowthStage(id)
  287. //   Returns growth stage of a plant with the specified ID or -1 if there was an error
  288. //
  289. // - getHighlightedMapObjects()
  290. //   Returns an array of highlighted map objects (each of them has `name`, `fullName`, `id` and `coords` properties)
  291. //
  292. // - waitForTaskToFinish()
  293. //   Waits for the current task to finish (until hourglass is gone)
  294. //
  295. // - useItemFromHandOnCoords(x, y)
  296. //   Uses an item from hand on the specified coords (you can take it to your hand via `takeItem` function)
  297. //   Returns `true` on success or `false` otherwise
  298. //
  299. // - dropItemFromHandToWindow(windowName)
  300. //   Drops an item from hand to the specified window (useful when having a butcket in your hands)
  301. //   Returns `true` on success or `false` otherwise
  302. //
  303. // - takeItemFromWindow(windowName, itemName)
  304. //   The same as the `takeItem` function but takes an item from the specified window
  305. //   Returns `true` on success or `false` otherwise
  306. //
  307. // - feastEat(itemName)
  308. //   Clicks a "Feast" button and then eats the specified item (NOTE that you should open a table before using this function via the `openTable` function, see below)
  309. //   Returns `true` on success or `false` otherwise
  310. //
  311. // - openTable(id)
  312. //   Opens a table with the specified ID
  313. //   Returns `true` on success or `false` otherwise
  314. //
  315. // - getCharInvSize()
  316. //   Returns an object with the `width` and `height` properties set to the appropriate cells count or null if there was an error
  317. //
  318. // - getCharInvCellsUsageMatrix()
  319. //   Returns a 2D array with 0 and 1 values representing free and used cells correspondingly or null if there was an error
  320. //   You can access specific cell via the Cartesian coordinate system syntax where (0, 0) is the top-left cell
  321. //
  322. // - getFreeCharInvCellsCount()
  323. //   Returns a count of free cells in the character's inventory or -1 if there was an error
  324. //
  325. // - getFuelLevel(id, windowName)
  326. //   Returns fuel level of an object with the specified ID or null if there was an error
  327. //   NOTE that this function right-clicks the object and waits several seconds for the corresponding window to appear
  328. //
  329. // - getWaterLevel(id, windowName)
  330. //   Returns water level of an object with the specified ID or null if there was an error
  331. //   NOTE that this function right-clicks the object and waits several seconds for the corresponding window to appear
  332. //
  333. // - logout()
  334. //   Logs out from the current account
  335. //
  336. // - quit()
  337. //   Closes game's window
  338. //   NOTE that in most situations it's better to call the `logout` function instead of this one
  339. //        because the `logout` sends a direct message about your willings to the game's server while the `quit` function
  340. //        just simply calls `System.exit(0)` that can lead to the more "delayed" logout
  341.  
  342. // NOTE that any events except `onLogin` and `onCharSelect` can be fired **before** `onGameLoaded`
  343. // NOTE that the majority of API functions are asynchronous -- including but not limited to `goTo`, `pickItem`, `travelToHearthFire` and `logout`
  344. //      Synrhonous ones include `getInvItems` and `quit`
  345. // NOTE that you should NOT use the === operator when the API objects take place in comparisons, use == operator instead
  346. // NOTE that any functions that work with items' names expect an item's base resource name
  347. //      So instead of 'Dried Fox Hide' you should pass 'foxhide', instead of 'Raw Fox Hide' you should pass 'foxhide-blood' etc
  348.  
  349. /** It is fired when a foragable curio was found (once for each of them)
  350.  * @param {Number} id ID of the curio
  351.  * @param {String} name Name of the curio
  352.  * @param {Object} coords Coordinates of the curio
  353.  * @param {Number} coords.x x coordinate of the curio
  354.  * @param {Number} coords.y y coordinate of the curio
  355.  */
  356. function onCurioFound(id, name, coords) {
  357.     onRedCurioFound(id, name, coords);
  358.     onPorkCurioFound(id, name, coords);
  359. }
  360.  
  361. /** It is fired when a creature was encountered (once for each of them)
  362.  * @param {Number} id ID of the creature
  363.  * @param {String} name Name of the creature
  364.  * @param {Object} coords Coordinates of the creature
  365.  * @param {Number} coords.x x coordinate of the creature
  366.  * @param {Number} coords.y y coordinate of the creature
  367.  */
  368. function onCreatureFound(id, name, coords) {
  369.     onRedCreatureFound(id, name, coords);
  370.     onPorkCreatureFound(id, name, coords);
  371.   if (g == null) {
  372.     return;
  373.   }
  374.  
  375.   if (isAggr(name)) {
  376.     print('Creature "' + name + '" encountered, trying to travel to the hearth fire...');
  377.  
  378.     stopAutoWalking();
  379.     g.travelToHearthFire();
  380.  
  381.     setTimeout(function() {
  382.       print('Resuming autowalking...');
  383.       startAutoWalking();
  384.     }, second*10);
  385.   }
  386. }
  387.  
  388. /** It is fired when another player was encountered (once for each of them)
  389.  * @param {Number} id ID of the player
  390.  * @param {Boolean} isKin Indicates whether the player is in the kin list or not
  391.  * @param {Object} coords Coordinates of the player
  392.  * @param {Number} coords.x x coordinate of the creature
  393.  * @param {Number} coords.y y coordinate of the creature
  394.  */
  395. function onPlayerFound(id, isKin, coords) {
  396.     onRedPlayerFound(id, isKin, coords);
  397.     onPorkPlayerFound(id, isKin, coords);
  398.   if (g == null) {
  399.     return;
  400.   }
  401.  
  402.   if (!isKin) {
  403.     print('Non-kin player encountered, trying to travel to the hearth fire...');
  404.  
  405.     stopAutoWalking();
  406.     g.travelToHearthFire();
  407.  
  408.     setTimeout(function() {
  409.       print('Resuming autowalking...');
  410.       startAutoWalking();
  411.     }, second*10);
  412.   }
  413. }
  414.  
  415. /** It is fired when the flower menu appears (the one that opens after right clicking an object)
  416.  * @param {Array} options Available flower menu options
  417.  */
  418. function onFlowerMenuOpen(options) {
  419.     onRedFlowerMenuOpen(options);
  420.     onPorkFlowerMenuOpen(options);
  421.   // ignored
  422. }
  423.  
  424. /** It is fired when the user enters a command in the console window
  425.  * @param {String} input User command
  426.  */
  427. function onUserInput(input) {
  428.     onRedUserInput(input);
  429.     onPorkUserInput(input);
  430.   // ignored
  431. }
  432.  
  433. /** It is fired when a chat message received from another player
  434.  * @param {String} chat Chat name
  435.  * @param {String} from Sender's name (or '???' if it's unknown)
  436.  * @param {String} msg Message
  437.  */
  438. function onChatMessage(chat, from, msg) {
  439.     onRedChatMessage(chat, from, msg);
  440.     onPorkChatMessage(chat, from, msg);
  441.   // ignored
  442. }
  443.  
  444. /** It is fired when a new object highlighted via ALT + LMB
  445.  * @param {Object} obj Highlighted map object
  446.  * @param {String} obj.name Basename of the map object's resource
  447.  * @param {String} obj.fullName Full name of the map object's resource
  448.  * @param {Number} obj.id Map object's ID
  449.  * @param {Object} obj.coords Coordinates of the map object
  450.  * @param {Number} obj.coords.x x coordinate of the map object
  451.  * @param {Number} obj.coords.y y coordinate of the map object
  452.  */
  453. function onMapObjectHighlight(obj) {
  454.     onRedMapObjectHighlight(obj);
  455.     onPorkMapObjectHighlight(obj);
  456.   // ignored
  457. }
  458.  
  459. ///////////////////////
  460. // User-defined functions
  461. ///////////////////////
  462.  
  463. /** Starts autowalking timer that will move character x+50, y+50 every second */
  464. function startAutoWalking() {
  465.     startRedAutoWalking();
  466.     startPorkAutoWalking();
  467. }
  468.  
  469. /** Stops autowalking timer */
  470. function stopAutoWalking() {
  471.   stopRedAutoWalking();
  472.   stopPorkAutoWalking();
  473. }
  474.  
  475. /** Determines whether the specified animal is aggresive (NOTE that this function is incomplete)
  476.  * @param {String} animal Name of the animal to check
  477.  * @return {Boolean} true if the specified animal is aggressive or false otherwise
  478.  */
  479. function isAggr(animal) {
  480.     if(agroToggle)
  481.         return animal == "badger" || animal == "lynx" || animal == "bat" || animal == "bear" || animal == "boar" || isRedAggr(animal) || isPorkAggr(animal); // etc
  482.     else
  483.         return false;
  484. }
  485.  
  486. /** Returns a mental weight of the specified curio (NOTE that this function is incomplete)
  487.  * @param {String} curioName Name of the curio
  488.  * @return {Number} Mental weight of the specified curio
  489.  */
  490. function getMentalWeight(curioName) {
  491.     getRedMentalWeight(curioName);
  492.     getPorkMentalWeight(curioName);
  493.   var mws = {
  494.     'dandelion': 1
  495.     // etc
  496.   };
  497.   return mws[curioName];
  498. }
  499.  
  500. /** Prints the specified message to stdout
  501.  * @param {String} msg Message to print
  502.  */
  503. function print(msg) {
  504.   java.lang.System.out.println(msg);
  505. }
  506.  
  507. /**
  508.  * Sleeps for the specified amount of milliseconds <br>
  509.  * NOTE that this function should be used carefully <br>
  510.  *      It prevents the event loop from triggering new actions until you finally return from the API event function <br>
  511.  *      If possible, use `setTimeout` and `setInterval` functions instead <br>
  512.  * @param {Number} millisecs Amount of milliseconds to sleep for
  513.  */
  514. function sleep(millisecs) {
  515.   java.lang.Thread.sleep(millisecs);
  516. }
  517.  
  518. ///////////////////////
  519. // Helper functions to work with timeouts and intervals
  520. ///////////////////////
  521.  
  522. var setTimeout,
  523.     clearTimeout,
  524.     setInterval,
  525.     clearInterval;
  526.  
  527. (function () {
  528.     var timer = new java.util.Timer();
  529.     var counter = 1;
  530.     var ids = {};
  531.  
  532.     setTimeout = function(fn, delay) {
  533.         var id = counter++;
  534.         ids[id] = new JavaAdapter(java.util.TimerTask, {run: fn});
  535.         timer.schedule(ids[id], delay);
  536.         return id;
  537.     };
  538.  
  539.     clearTimeout = function(id) {
  540.         timer.purge();
  541.         delete ids[id];
  542.     };
  543.  
  544.     setInterval = function(fn, delay) {
  545.         var id = counter++;
  546.         ids[id] = new JavaAdapter(java.util.TimerTask, {run: fn});
  547.         timer.schedule(ids[id], delay, delay);
  548.         return id;
  549.     };
  550.  
  551.     clearInterval = clearTimeout;
  552.  
  553. })();
  554.  
  555.  
  556.  
  557. function onRedGameLoaded() {
  558.    
  559.   gameStart();
  560.  
  561. }
  562.  
  563. /** It is fired when a foragable curio was found (once for each of them)
  564.  * @param {Number} id ID of the curio
  565.  * @param {String} name Name of the curio
  566.  * @param {Object} coords Coordinates of the curio
  567.  * @param {Number} coords.x x coordinate of the curio
  568.  * @param {Number} coords.y y coordinate of the curio
  569.  */
  570. function onRedCurioFound(id, name, coords) {
  571.   //Nothing atm.
  572. }
  573.  
  574. /** It is fired when a creature was encountered (once for each of them)
  575.  * @param {Number} id ID of the creature
  576.  * @param {String} name Name of the creature
  577.  * @param {Object} coords Coordinates of the creature
  578.  * @param {Number} coords.x x coordinate of the creature
  579.  * @param {Number} coords.y y coordinate of the creature
  580.  */
  581. function onRedCreatureFound(id, name, coords) {
  582.   //Nothing atm.
  583. }
  584.  
  585. /** It is fired when another player was encountered (once for each of them)
  586.  * @param {Number} id ID of the player
  587.  * @param {Boolean} isKin Indicates whether the player is in the kin list or not
  588.  * @param {Object} coords Coordinates of the player
  589.  * @param {Number} coords.x x coordinate of the creature
  590.  * @param {Number} coords.y y coordinate of the creature
  591.  */
  592. function onRedPlayerFound(id, isKin, coords) {
  593.   //Nothing atm.
  594. }
  595.  
  596. /** It is fired when the flower menu appears (the one that opens after right clicking an object)
  597.  * @param {Array} options Available flower menu options
  598.  */
  599. function onRedFlowerMenuOpen(options) {
  600.    
  601.   // ignored
  602. }
  603.  
  604. /** It is fired when the user enters a command in the console window
  605.  * @param {String} input User command
  606.  */
  607. function onRedUserInput(input) {
  608.   //Checks for red's command
  609.   if(input == 'red walk')
  610.   {
  611.       walkDefaultToggle();
  612.   }
  613.   else if(input == 'red target walk')
  614.   {
  615.       walkToToggle();
  616.   }
  617.   else if(input == 'red auto walk')
  618.   {
  619.       walkAutoToggle();
  620.   }
  621.   else if(input == 'print objects')
  622.   {
  623.       printObjectNamesOnScreen();
  624.   }
  625.   else if(input == 'agro toggle')
  626.   {
  627.       agroToggleSwitch();
  628.   }
  629.   else if(input == 'qchopper')
  630.   {
  631.       qChopperToggle();
  632.   }
  633.   else if(input == 'qblocker')
  634.   {
  635.       qBlockChopperToggle();
  636.   }
  637.   else if(input == 'qboarder')
  638.   {
  639.       qBoardCutterToggle();
  640.   }
  641.   else if(input == 'qstumper')
  642.   {
  643.       qStumperToggle();
  644.   }
  645.   else if(input == 'qlandforager')
  646.   {
  647.       qLandForagerToggle();
  648.   }
  649.   else if(input == 'beast hostile')
  650.   {
  651.       allowHostileToggle();
  652.   }
  653.   else if(input == 'beast player')
  654.   {
  655.       allowPlayerToggle();
  656.   }
  657.   else if(input == 'beast friendly')
  658.   {
  659.       allowFriendlyToggle();
  660.   }
  661.   else if(input == 'print commands')
  662.   {
  663.     print('red walk, red target walk, red auto walk, print objects, print commands, agro toggle, findcurious, qchopper, qstumper, pickbranches, pickboughs, beast hostile, beast friendly, beast player');  
  664.   }
  665.   else
  666.   {
  667.      
  668.   }
  669. }
  670.  
  671. /** It is fired when a chat message received from another player
  672.  * @param {String} chat Chat name
  673.  * @param {String} from Sender's name (or '???' if it's unknown)
  674.  * @param {String} msg Message
  675.  */
  676. function onRedChatMessage(chat, from, msg) {
  677.   // ignored
  678. }
  679.  
  680. /** It is fired when a new object highlighted via ALT + LMB
  681.  * @param {Object} obj Highlighted map object
  682.  * @param {String} obj.name Basename of the map object's resource
  683.  * @param {String} obj.fullName Full name of the map object's resource
  684.  * @param {Number} obj.id Map object's ID
  685.  * @param {Object} obj.coords Coordinates of the map object
  686.  * @param {Number} obj.coords.x x coordinate of the map object
  687.  * @param {Number} obj.coords.y y coordinate of the map object
  688.  */
  689. function onRedMapObjectHighlight(obj) {
  690.   // ignored
  691. }
  692.  
  693. ///////////////////////
  694. // User-defined functions
  695. ///////////////////////
  696.  
  697. /** Starts autowalking timer that will move character x+50, y+50 every second */
  698. function startRedAutoWalking() {
  699.     if(RedAutoWalkingSwitch)
  700.     {
  701.         if(debug)
  702.         print('Start the auto walk steps...');
  703.         autoWalkingTimerId = setInterval(function()
  704.           {
  705.             if(RedAutoWalkingSwitch)
  706.             walk();
  707.           }, second*5);
  708.     }
  709. }
  710.  
  711. /** Stops autowalking timer */
  712. function stopRedAutoWalking() {
  713.   clearInterval(autoWalkingTimerId);
  714.   // NOTE that clearInterval (nor clearTimeout) does NOT wait for the currently executing task to finish
  715.   //      so let's sleep for some time manually
  716.   sleep(second*20);
  717. }
  718.  
  719. /** Determines whether the specified animal is aggresive (NOTE that this function is incomplete)
  720.  * @param {String} animal Name of the animal to check
  721.  * @return {Boolean} true if the specified animal is aggressive or false otherwise
  722.  */
  723. function isRedAggr(animal) {
  724.     return false;
  725. }
  726.  
  727. /** Returns a mental weight of the specified curio (NOTE that this function is incomplete)
  728.  * @param {String} curioName Name of the curio
  729.  * @return {Number} Mental weight of the specified curio
  730.  */
  731. function getRedMentalWeight(curioName) {
  732.   //Nothing.
  733. }
  734.  
  735.  
  736.  
  737. /**
  738.  *
  739.  */
  740.  
  741. /**
  742.  * Function called on to enable walking from path finder in priority order.
  743.  * Order of Importance: Random, Target, None.
  744.  */
  745. function walk() {
  746.     if (RedWalkDefault) {
  747.         defaultWalk();
  748.     }
  749.     else if (WalkToSwitch) {
  750.         walkTo();
  751.     }
  752.     else {
  753.  
  754.     }
  755. }
  756.  
  757. /**
  758.  * Walks to a specific point. If it gets stuck, it tries to remove itself by walking randomly. Once near set target
  759.  * coordinates, the function turns off.
  760.  */
  761. function walkTo() {
  762.     g.goTo(toX, toY);
  763.     var playerCoords = g.getPlayerCoords();
  764.     if (isStuck()) {
  765.         print('Is stuck! Fixing itself.');
  766.         RedWalkDefault = true;
  767.         sleep(second * 5);
  768.         RedWalkDefault = false;
  769.         print('Try walking again.');
  770.     }
  771.     if (getDistance() < toP) {
  772.         WalkToSwitch = false;
  773.     }
  774. }
  775.  
  776. /**
  777.  * Method for default random walking.
  778.  */
  779. function defaultWalk() {
  780.     direction();
  781.     var playerCoords = g.getPlayerCoords();
  782.     g.goTo(playerCoords.x + xDirection * getRandomInt(0, 200), yDirection * playerCoords.y + getRandomInt(0, 200));
  783.     if (debug)
  784.         print('Decrease the step count...');
  785.     directionCount = directionCount - 1;
  786.     if (debug)
  787.         print('Sleep on walk...');
  788. }
  789.  
  790. /**
  791.  * Turns wandering on.
  792.  */
  793. function wanderOn() {
  794.     RedWalkDefault = true;
  795. }
  796.  
  797. /**
  798.  * Turns wandering off.
  799.  */
  800. function wanderOff() {
  801.     RedWalkDefault = false;
  802. }
  803.  
  804. /**
  805.  * Allows the player to wander randomly a bit.
  806.  */
  807. function wander() {
  808.     wanderOn();
  809.     defaultWalk();
  810.     sleep(getRandomInt(1, 10) * second);
  811.     wanderOff();
  812. }
  813.  
  814. /**
  815.  * Determines when a new direction is needed and sets a new direction and amount of steps
  816.  * for that direction.
  817.  */
  818. function direction() {
  819.     if (debug)
  820.         print('Check if there is a direction step count or if the player is stuck...');
  821.     if (directionCount <= 0 || isStuck()) {
  822.         if (debug)
  823.             print('There was not a count, pick a new one...');
  824.         directionCount = getDirectionCount(20);
  825.         if (debug)
  826.             print('The direction count is now ' + directionCount + '.');
  827.  
  828.         xDirection = getDirection();
  829.         if (debug)
  830.             print('The x direction is now ' + xDirection + '.');
  831.         yDirection = getDirection();
  832.         if (debug)
  833.             print('The y direction is now ' + yDirection + '.');
  834.     }
  835. }
  836.  
  837. /**
  838.  * Determines if the bot is stuck or not.
  839.  * @returns {Boolean} returns true if the bot is stuck, false if it is not.
  840.  */
  841. function isStuck() {
  842.     var playerCoords = g.getPlayerCoords();
  843.     if (oldPlayerX == playerCoords.x && oldPlayerY == playerCoords.y) {
  844.         if (isStuckCooldown <= 0 && !ignoreStuckCount) {
  845.             if (debug)
  846.                 print('Player is stuck!');
  847.             oldPlayerX = 0;
  848.             oldPlayerY = 0;
  849.             isStuckCooldown = 5;
  850.             return true;
  851.         }
  852.         else {
  853.             isStuckCooldown--;
  854.             return false;
  855.         }
  856.  
  857.     }
  858.     else {
  859.         oldPlayerX = playerCoords.x;
  860.         oldPlayerY = playerCoords.y;
  861.         return false;
  862.     }
  863. }
  864. /**
  865.  * Checks the distance of the object to the player against the target object.
  866.  * If the checked object is closer than target object, then the target is changed to the checked object.
  867.  */
  868. function currentCloserDistanceToObject(Object) {
  869.     var dx = playerCoords.x - Object.coords.x;
  870.     var dy = playerCoords.y - Object.coords.y;
  871.     var distanceToObject = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  872.     if (debug) {
  873.         print("dx, dy: " + dx + "," + dy);
  874.         print('Testing distance to log: ' + distanceToObject.name + ', ' + distanceToObject.id + ', ' + distanceToObject.coords.x + ', ' + distanceToObject.coords.y);
  875.         print('Distance to the log is: ' + distanceToLog);
  876.     }
  877.     if (nearestObject == null || distanceToObject < nearestObjectDistance || nearestObjectDistance == null) {
  878.         nearestObject = distanceToObject;
  879.         nearestObjectDistance = distanceToObject;
  880.         if (debug) {
  881.             print('Distance to the closest log is: ' + nearestLogDistance);
  882.         }
  883.     }
  884.     return distanceToObject;
  885. }
  886.  
  887. /**
  888.  * Walks to the given object and returns true if it is near the object and flase if it isn't.
  889.  */
  890. function walkToObject(Object) {
  891.     walkToSet(Object.coords.x + getRandomInt(-20, 20), Object.coords.y + getRandomInt(-20, 20), 10);
  892.     if (getDistance() < toP) {
  893.         if (debug)
  894.             print('Is near Object.')
  895.         return true;
  896.     }
  897.     else {
  898.         if (debug)
  899.             print('Is not near the Object, walking closer.')
  900.         walkTo();
  901.         if (isStuck()) {
  902.             wander();
  903.         }
  904.         return false;
  905.     }
  906. }
  907. /**
  908.  *
  909.  */
  910.  
  911. function printObjectNamesOnScreen()
  912. {
  913.     var mapObjects = g.getAllMapObjects();
  914.     for (var i = 0; i < mapObjects.length; ++i) {
  915.         var mapObject = mapObjects[i];
  916.         print('Name: ' + mapObject.name + ' - FullName: ' + mapObject.fullName + ' - ID: ' + mapObject.id);
  917.         }
  918. }
  919. /**
  920.  *
  921.  */
  922.  
  923. /**
  924.  * Sets the target coordinates to walk to and begins walking to the target coordinates.
  925.  */
  926. function walkToStart(x, y, precision) {
  927.     walkToSet(x, y, precision);
  928.     walkTo();
  929. }
  930.  
  931. /**
  932.  * Sets the walk to target without invoking walkTo();
  933.  */
  934. function walkToSet(x, y, precision) {
  935.     toX = x;
  936.     toY = y;
  937.     toP = precision;
  938.     WalkToSwitch = true;
  939. }
  940.  
  941. /**
  942.  * Gets an integer between min and max values.
  943.  * @param min - the minimum value the integer could be.
  944.  * @param max - the maximum value the integer could be.
  945.  * @returns The randomly chosen integer.
  946.  */
  947. function getRandomInt(min, max) {
  948.     return Math.random() * (max - min) + min;
  949. }
  950.  
  951. /**
  952.  * Gets an integer that is either 1 or -1 but not 0.
  953.  * @returns {Number} returned is 1 or -1 which is a direction.
  954.  */
  955. function getDirection() {
  956.     var c = Math.random() * (1 - -1) + -1;
  957.     c = c.toFixed(0);
  958.     if (c == 0) {
  959.         return getDirection();
  960.     }
  961.  
  962.     return c;
  963. }
  964.  
  965. /** Gets a random direction step count between 0 an max.
  966.  * @param max The maximum amount of steps the bot is able to take in a direction.
  967.  * @returns Returns a number between 0 and max.
  968.  */
  969. function getDirectionCount(max) {
  970.     return getRandomInt(0, Math.abs(max)).toFixed(0);
  971. }
  972.  
  973. /**
  974.  * Gets the distance between object1.coords and object2.coords.
  975.  * @param objectOne Is the first object1.coords, usually the player.
  976.  * @param ObjectTwo Is the second object2.coords.
  977.  * @returns Returns the distance between two objects in tile length.
  978.  */
  979. function getDistance(objectOne, ObjectTwo) {
  980.     var dx = objectOne.x - ObjectTwo.x;
  981.     var dy = objectOne.y - ObjectTwo.y;
  982.     return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  983. }
  984.  
  985. /**
  986.  * Gets the distance of an object to the target coordinates.
  987.  * @param objectOne The object1.coords to find distance from target coordinates.
  988.  * @returns Returns the distance of the object from the target coordinates in tiles length.
  989.  */
  990. function getDistance(objectOne) {
  991.     var dx = objectOne.x - toX;
  992.     var dy = objectOne.y - toY;
  993.     return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  994. }
  995.  
  996. /**
  997.  * Gets the distance of the player from the target coordinates.
  998.  * @returns Returns the distance of the player from the target coordinates in tiles in tiles length.
  999.  */
  1000. function getDistance() {
  1001.     var playerCoords = g.getPlayerCoords();
  1002.     var dx = playerCoords.x - toX;
  1003.     var dy = playerCoords.y - toY;
  1004.     return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  1005. }
  1006.  
  1007. /**
  1008.  * Hearths the player back home.
  1009.  */
  1010. function hearthHome() {
  1011.     sleep(second * 2);
  1012.     g.travelToHearthFire();
  1013.     sleep(second * 1);
  1014.     g.waitForTaskToFinish();
  1015. }
  1016.  
  1017. function regenStamina() {
  1018.     WalkToSwitch = false;
  1019.     RedWalkDefault = false;
  1020.     waitForStamina(95);
  1021. }
  1022.  
  1023. function waitForStamina(target) {
  1024.     stamina = g.getStamina()
  1025.     if (stamina < target) {
  1026.         var secondsToWait = Math.ceil((target - stamina) * 6.666);
  1027.         print('Stamina not enough, it is: ' + stamina);
  1028.         print('Waiting ' + secondsToWait + ' seconds...')
  1029.         sleep(second * secondsToWait);
  1030.         print('Checking stamina again...')
  1031.         waitForStamina(target);
  1032.     }
  1033. }
  1034.  
  1035. function pickOption(option, options) {
  1036.     if (options.length != null || options.length == 0) {
  1037.         print('Options length is: ' + options.length)
  1038.         for (var i = 0; i < options.length; i++) {
  1039.             print(option[i]);
  1040.             if (options[i] == option) {
  1041.  
  1042.                 g.chooseFlowerMenuOption(option);
  1043.                 return true;
  1044.  
  1045.             }
  1046.         }
  1047.     }
  1048.     return false;
  1049.  
  1050. }
  1051.  
  1052. function arrayContains(array, value)
  1053. {
  1054.     for(var i = 0; i < array.length; i++)
  1055.         {
  1056.             if(array[i] == value)
  1057.                 return true;
  1058.         }
  1059.     return false;
  1060.     }
  1061. /**
  1062.  *
  1063.  */
  1064. function BeastWatcher() {
  1065.     //Variables
  1066.     var HostileBeastsList = new Array();
  1067.     var PlayerBeastsList = new Array();
  1068.     var FriendlyBeastsList = new Array();
  1069.  
  1070.     var HostileBeastToleranceDistance = 200;
  1071.     var UnknownPlayerBeastToleranceDistance = 200;
  1072.     var FriendBeastToerlanceDistance = 200;
  1073.  
  1074.     /**
  1075.      * The run function for this bot.
  1076.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  1077.      */
  1078.     this.runBeastWatcher = function() {
  1079.         if (BeastWatcherRun) {
  1080.             updateBeastsList();
  1081.             checkBeastDistances();
  1082.         }
  1083.     }
  1084.  
  1085.     var listContains = function(list, object) {
  1086.         if (list != null) {
  1087.             for (var x = 0; x < list.length; x++) {
  1088.                 if (list[x] == object) {
  1089.                     return true;
  1090.                 }
  1091.             }
  1092.         }
  1093.         return false;
  1094.     }
  1095.  
  1096.     var updateBeastsList = function() {
  1097.         var mapObjects = g.getAllMapObjects();
  1098.  
  1099.         for (var i = 0; i < mapObjects.length; ++i) {
  1100.             if (mapObjects[i].name == 'body') {
  1101.                 continue;
  1102.             }
  1103.             else if (isHostileBeast(mapObjects[i].name)) {
  1104.                 if (!listContains(HostileBeastsList, mapObjects[i])) {
  1105.                     HostileBeastsList.push(mapObjects[i]);
  1106.                 }
  1107.             }
  1108.             else if (isUnknownPlayer(mapObjects[i].name)) {
  1109.                 if (!listContains(PlayerBeastsList, mapObjects[i])) {
  1110.                     PlayerBeastsList.push(mapObjects[i]);
  1111.                 }
  1112.             }
  1113.             else if (isFriendlyBeast(mapObjects[i].name)) {
  1114.                 if (!listContains(FriendlyBeastsList, mapObjects[i])) {
  1115.                     FriendlyBeastsList.push(mapObjects[i]);
  1116.                 }
  1117.             }
  1118.         }
  1119.     }
  1120.  
  1121.     var checkBeastDistances = function() {
  1122.         if (AllowHostile) {
  1123.             for (var i = 0; i < HostileBeastsList.length; i++) {
  1124.                 if (getDistance(HostileBeastsList[i].coords) < HostileBeastToleranceDistance) {
  1125.                     goHome();
  1126.                 }
  1127.             }
  1128.         }
  1129.         if (AllowPlayer) {
  1130.             for (var i = 0; i < PlayerBeastsList.length; i++) {
  1131.                 if (getDistance(PlayerBeastsList[i].coords) < UnknownPlayerBeastToleranceDistance) {
  1132.                     goHome();
  1133.                 }
  1134.             }
  1135.         }
  1136.         if (AllowFriendly) {
  1137.             for (var i = 0; i < FriendlyBeastsList.length; i++) {
  1138.                 if (getDistance(FriendlyBeastsList[i].coords) < FriendlyBeastToleranceDistance) {
  1139.                     goHome();
  1140.                 }
  1141.             }
  1142.         }
  1143.     }
  1144.  
  1145.     var goHome = function() {
  1146.         hearthHome();
  1147.     }
  1148.  
  1149.  
  1150. }
  1151. /**
  1152.  *
  1153.  */
  1154. function qBlockChopper() {
  1155.     var block;
  1156.     var atBlock;
  1157.     var choppedBlocks = new Array();
  1158.     var blockCutCount = 0;
  1159.     var finishedChopping = false;
  1160.  
  1161.     /**
  1162.      * The run function for this bot.
  1163.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  1164.      */
  1165.     this.runBlockChopper = function() {
  1166.         if (qBlockChopperRun) {
  1167.             stamina();
  1168.             if (block == null)
  1169.                 findBlock();
  1170.             if (goToBlock()) {
  1171.                 chopBlock();
  1172.             }
  1173.             if (blockCutCount != 0)
  1174.                 if (finishedChopping)
  1175.                     goHome();
  1176.         }
  1177.     }
  1178.  
  1179.     /**
  1180.      * Finds the next available target block to chop.
  1181.      */
  1182.     var findBlock = function() {
  1183.  
  1184.         var playerCoords = g.getPlayerCoords();
  1185.  
  1186.         var nearestBlockDistance = null;
  1187.         var distanceToBlock = null;
  1188.  
  1189.         var mapObjects = g.getAllMapObjects();
  1190.  
  1191.         for (var i = 0; i < mapObjects.length; ++i) {
  1192.             if (mapObjects[i].name == 'body') {
  1193.                 continue;
  1194.             }
  1195.             else if (isLog(mapObjects[i].name)) {
  1196.                 var alreadyChopped = false;
  1197.                 if (choppedBlocks != null) {
  1198.                     for (var b = 0; b < choppedBlocks.length; ++b) {
  1199.                         if (choppedBlocks[i] == mapObjects[i].id)
  1200.                             alreadyChopped = true;
  1201.                     }
  1202.                 }
  1203.                 if (!alreadyChopped) {
  1204.  
  1205.  
  1206.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  1207.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  1208.                     distanceToBlock = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  1209.                     if (debug) {
  1210.                         print("dx, dy: " + dx + "," + dy);
  1211.                         print('Testing distance to block: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  1212.                         print('Distance to the block is: ' + distanceToBlock);
  1213.                     }
  1214.                     if (block == null || distanceToBlock < nearestBlockDistance || nearestBlockDistance == null) {
  1215.                         block = mapObjects[i];
  1216.                         nearestBlockDistance = distanceToBlock;
  1217.                         if (debug) {
  1218.                             print('Distance to the closest block is: ' + nearestBlockDistance);
  1219.                         }
  1220.                     }
  1221.                 }
  1222.             }
  1223.             else {
  1224.  
  1225.             }
  1226.         }
  1227.         if (block == null) {
  1228.             wander();
  1229.         }
  1230.     }
  1231.  
  1232.     /**
  1233.      * Goes to the target block and returns true if near the log, otherwise returns false.
  1234.      */
  1235.     var goToBlock = function() {
  1236.         walkToSet(block.coords.x + getRandomInt(-20, 20), block.coords.y + getRandomInt(-20, 20), 10);
  1237.         if (getDistance() < toP) {
  1238.             if (debug)
  1239.                 print('Is near block.')
  1240.             return true;
  1241.         }
  1242.         else {
  1243.             if (debug)
  1244.                 print('Is not near the block, walking closer.')
  1245.             walkTo();
  1246.             if (isStuck()) {
  1247.                 wander();
  1248.             }
  1249.             return false;
  1250.         }
  1251.  
  1252.     }
  1253.  
  1254.     /**
  1255.      * Chops the target block.
  1256.      */
  1257.     var chopBlock = function() {
  1258.  
  1259.         g.mapObjectRightClick(block.id);
  1260.         sleep(second * 1);
  1261.         finishedChopping = false;
  1262.  
  1263.         g.chooseFlowerMenuOption('Chop into blocks');
  1264.         sleep(second * 20);
  1265.         if (debug)
  1266.             print('Chopping and waiting for task to finish.');
  1267.         g.waitForTaskToFinish();
  1268.         if (debug)
  1269.             print('Task finished, checking if the block is still there.');
  1270.         if (blockCutCount <= 10) {
  1271.             blockCutCount++;
  1272.             if (debug)
  1273.                 print('Target block probably still there, count is: ' + blockCutCount);
  1274.  
  1275.         }
  1276.         else {
  1277.             if (debug)
  1278.                 print('Target block probably not still there...');
  1279.  
  1280.             finishedChopping = true;
  1281.             blockCutCount = 0;
  1282.             choppedBlocks.push(block.id);
  1283.             block = null;
  1284.  
  1285.         }
  1286.     }
  1287.  
  1288.     /**
  1289.      * A method to stop walking and start regenerating stamina.
  1290.      */
  1291.     var stamina = function() {
  1292.  
  1293.         WalkToSwitch = false;
  1294.         RedWalkDefault = false;
  1295.         waitForStamina(95);
  1296.  
  1297.     }
  1298.  
  1299.     /**
  1300.      * A method to go home if needed.
  1301.      */
  1302.     var goHome = function() {
  1303.         hearthHome();
  1304.     }
  1305.  
  1306.  
  1307.  
  1308. }
  1309. /**
  1310.  *
  1311.  */
  1312. function qBoardCutter() {
  1313.     var board;
  1314.     var atBoard;
  1315.     var sawedBoards = new Array();
  1316.     var boardCutCount = 0;
  1317.     var finishedChopping = false;
  1318.  
  1319.     /**
  1320.      * The run function for this bot.
  1321.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  1322.      */
  1323.     this.runBoardCutter = function() {
  1324.         if (qBoardCutterRun) {
  1325.             stamina();
  1326.             if (board == null)
  1327.                 findBoard();
  1328.             if (goToBoard()) {
  1329.                 sawBoard();
  1330.             }
  1331.             if (boardCutCount != 0)
  1332.                 if (finishedChopping)
  1333.                     goHome();
  1334.         }
  1335.     }
  1336.  
  1337.     /**
  1338.      * Finds the next available target board to saw.
  1339.      */
  1340.     var findBoard = function() {
  1341.  
  1342.         var playerCoords = g.getPlayerCoords();
  1343.  
  1344.         var nearestBoardDistance = null;
  1345.         var distanceToBoard = null;
  1346.  
  1347.         var mapObjects = g.getAllMapObjects();
  1348.  
  1349.         for (var i = 0; i < mapObjects.length; ++i) {
  1350.             if (mapObjects[i].name == 'body') {
  1351.                 continue;
  1352.             }
  1353.             else if (isLog(mapObjects[i].name)) {
  1354.                 var alreadyChopped = false;
  1355.                 if (sawedBoards != null) {
  1356.                     for (var b = 0; b < sawedBoards.length; ++b) {
  1357.                         if (sawedBoards[i] == mapObjects[i].id)
  1358.                             alreadyChopped = true;
  1359.                     }
  1360.                 }
  1361.                 if (!alreadyChopped) {
  1362.  
  1363.  
  1364.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  1365.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  1366.                     distanceToBoard = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  1367.                     if (debug) {
  1368.                         print("dx, dy: " + dx + "," + dy);
  1369.                         print('Testing distance to board: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  1370.                         print('Distance to the board is: ' + distanceToBoard);
  1371.                     }
  1372.                     if (board == null || distanceToBoard < nearestBoardDistance || nearestBoardDistance == null) {
  1373.                         board = mapObjects[i];
  1374.                         nearestBoardDistance = distanceToBoard;
  1375.                         if (debug) {
  1376.                             print('Distance to the closest board is: ' + nearestBoardDistance);
  1377.                         }
  1378.                     }
  1379.                 }
  1380.             }
  1381.             else {
  1382.  
  1383.             }
  1384.         }
  1385.         if (board == null) {
  1386.             wander();
  1387.         }
  1388.     }
  1389.  
  1390.     /**
  1391.      * Goes to the target board and returns true if near the log, otherwise returns false.
  1392.      */
  1393.     var goToBoard = function() {
  1394.         walkToSet(board.coords.x + getRandomInt(-20, 20), board.coords.y + getRandomInt(-20, 20), 10);
  1395.         if (getDistance() < toP) {
  1396.             if (debug)
  1397.                 print('Is near board.')
  1398.             return true;
  1399.         }
  1400.         else {
  1401.             if (debug)
  1402.                 print('Is not near the board, walking closer.')
  1403.             walkTo();
  1404.             if (isStuck()) {
  1405.                 wander();
  1406.             }
  1407.             return false;
  1408.         }
  1409.  
  1410.     }
  1411.  
  1412.     /**
  1413.      * Chops the target board.
  1414.      */
  1415.     var sawBoard = function() {
  1416.  
  1417.         g.mapObjectRightClick(board.id);
  1418.         sleep(second * 1);
  1419.         finishedChopping = false;
  1420.  
  1421.         g.chooseFlowerMenuOption('Make boards');
  1422.         sleep(second * 20);
  1423.         if (debug)
  1424.             print('Chopping and waiting for task to finish.');
  1425.         g.waitForTaskToFinish();
  1426.         if (debug)
  1427.             print('Task finished, checking if the board is still there.');
  1428.         if (boardCutCount <= 10) {
  1429.             boardCutCount++;
  1430.             if (debug)
  1431.                 print('Target board probably still there, count is: ' + boardCutCount);
  1432.  
  1433.         }
  1434.         else {
  1435.             if (debug)
  1436.                 print('Target board probably not still there...');
  1437.  
  1438.             finishedChopping = true;
  1439.             boardCutCount = 0;
  1440.             sawedBoards.push(board.id);
  1441.             board = null;
  1442.  
  1443.         }
  1444.     }
  1445.  
  1446.     /**
  1447.      * A method to stop walking and start regenerating stamina.
  1448.      */
  1449.     var stamina = function() {
  1450.  
  1451.         WalkToSwitch = false;
  1452.         RedWalkDefault = false;
  1453.         waitForStamina(95);
  1454.  
  1455.     }
  1456.  
  1457.     /**
  1458.      * A method to go home if needed.
  1459.      */
  1460.     var goHome = function() {
  1461.         hearthHome();
  1462.     }
  1463.  
  1464.  
  1465.  
  1466. }
  1467. /**
  1468.  *
  1469.  */
  1470.  
  1471. function qBoughPicker() {
  1472.     var tree;
  1473.     var atTree;
  1474.     var pickedTrees = new Array();
  1475.     var treePickCount = 0;
  1476.     var finishedPicking = false;
  1477.  
  1478.     var invFull = false;
  1479.  
  1480.     var goingBackToPile = false;
  1481.     var fullStockpiles = new Array();
  1482.     var stockpile;
  1483.     var atStockpile;
  1484.  
  1485.     /**
  1486.      * The run function for this bot.
  1487.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  1488.      */
  1489.     this.runBoughPicker = function() {
  1490.         if (qBoughPickerRun) {
  1491.             stamina();
  1492.             checkInventorySpace();
  1493.             if (invFull) {
  1494.                 goBackToPile();
  1495.                 findClosestEmptyStockpile();
  1496.                 goToStockpile();
  1497.                 storeStockpile();
  1498.                 goGoBackPicking();
  1499.             }
  1500.             else {
  1501.                 if (tree == null)
  1502.                     findTree();
  1503.                 if (goToTree()) {
  1504.                     pickTree();
  1505.                 }
  1506.                 if (treePickCount != 0)
  1507.                     if (finishedPicking)
  1508.                         goHome();
  1509.             }
  1510.         }
  1511.     }
  1512.  
  1513.     /**
  1514.      * Finds a tree to cut down and sets it as the target tree.
  1515.      */
  1516.     var findTree = function() {
  1517.  
  1518.         var playerCoords = g.getPlayerCoords();
  1519.  
  1520.         var nearestTreeDistance = null;
  1521.         var distanceToTree = null;
  1522.  
  1523.         var mapObjects = g.getAllMapObjects();
  1524.  
  1525.         for (var i = 0; i < mapObjects.length; ++i) {
  1526.             if (mapObjects[i].name == 'body') {
  1527.                 continue;
  1528.             }
  1529.             else if (isTree(mapObjects[i].name)) {
  1530.                 var alreadyChopped = false;
  1531.                 if (pickedTrees != null) {
  1532.                     for (var b = 0; b < pickedTrees.length; ++b) {
  1533.                         if (pickedTrees[i] == mapObjects[i].id)
  1534.                             alreadyChopped = true;
  1535.                     }
  1536.                 }
  1537.                 if (!alreadyChopped) {
  1538.  
  1539.  
  1540.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  1541.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  1542.                     distanceToTree = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  1543.                     if (debug) {
  1544.                         print("dx, dy: " + dx + "," + dy);
  1545.                         print('Testing distance to tree: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  1546.                         print('Distance to the tree is: ' + distanceToTree);
  1547.                     }
  1548.                     if (tree == null || distanceToTree < nearestTreeDistance || nearestTreeDistance == null) {
  1549.                         tree = mapObjects[i];
  1550.                         nearestTreeDistance = distanceToTree;
  1551.                         if (debug) {
  1552.                             print('Distance to the closest tree is: ' + nearestTreeDistance);
  1553.                         }
  1554.                     }
  1555.                 }
  1556.             }
  1557.             else {
  1558.  
  1559.             }
  1560.         }
  1561.         if (tree == null) {
  1562.             wander();
  1563.         }
  1564.     }
  1565.  
  1566.     /**
  1567.      * Goes to the target tree and returns true if at the target, otherwise returns false.
  1568.      */
  1569.     var goToTree = function() {
  1570.         walkToSet(tree.coords.x + getRandomInt(-20, 20), tree.coords.y + getRandomInt(-20, 20), 10);
  1571.         if (getDistance() < toP) {
  1572.             if (debug)
  1573.                 print('Is near tree.')
  1574.             return true;
  1575.         }
  1576.         else {
  1577.             if (debug)
  1578.                 print('Is not near the tree, walking closer.')
  1579.             walkTo();
  1580.             if (isStuck()) {
  1581.                 wander();
  1582.             }
  1583.             return false;
  1584.         }
  1585.  
  1586.     }
  1587.  
  1588.     /**
  1589.      * Chops the target tree down.
  1590.      */
  1591.     var pickTree = function() {
  1592.  
  1593.         g.mapObjectRightClick(tree.id);
  1594.         sleep(second * 1);
  1595.         finishedPicking = false;
  1596.  
  1597.         g.chooseFlowerMenuOption('Take bough');
  1598.         sleep(second * 20);
  1599.         if (debug)
  1600.             print('picking and waiting for task to finish.');
  1601.         g.waitForTaskToFinish();
  1602.         if (debug)
  1603.             print('Task finished, checking if the tree is still there.');
  1604.         if (treePickCount <= 10) {
  1605.             treePickCount++;
  1606.             if (debug)
  1607.                 print('Target tree probably still there, count is: ' + treePickCount);
  1608.  
  1609.         }
  1610.         else {
  1611.             if (debug)
  1612.                 print('Target tree probably not still there...');
  1613.  
  1614.             finishedPicking = true;
  1615.             treePickCount = 0;
  1616.             pickedTrees.push(tree.id);
  1617.             tree = null;
  1618.  
  1619.         }
  1620.     }
  1621.  
  1622.     /**
  1623.      * A method to stop walking and start regenerating stamina.
  1624.      */
  1625.     var stamina = function() {
  1626.  
  1627.         WalkToSwitch = false;
  1628.         RedWalkDefault = false;
  1629.         waitForStamina(95);
  1630.  
  1631.     }
  1632.  
  1633.     /**
  1634.      * A method to go home if needed.
  1635.      */
  1636.     var goHome = function() {
  1637.         hearthHome();
  1638.     }
  1639.  
  1640.     var checkInventorySpace = function() {
  1641.         if (!goingBackToPile) {
  1642.             var boughInvWidth = g.getCharInvSize().width;
  1643.             var boughInvHeight = g.getCharInvSize().height;
  1644.             var xCoordInv = new Array();
  1645.             var yCoordInv = new Array();
  1646.             var freeSpace = 0;
  1647.             var invMatrix = g.getCharInvCellsUsageMatrix();
  1648.             for(var i = 0; i < boughInvWidth; i++)
  1649.                 {
  1650.                     for(var j = 0; j < boughInvHeight-1; j++)
  1651.                         {
  1652.                             if(invMatrix(i,j) == 0)
  1653.                                 {
  1654.                                     if(invMatrix(i,j+1) == 0)
  1655.                                         {
  1656.                                             if(!arrayContains(xCoordInv,i) || (!arrayContains(yCoordInv, j) && !arrayContains(yCoordInv, j+1)))
  1657.                                                 {
  1658.                                                     XCoordInv.push(i);
  1659.                                                     yCoordInv.push(j);
  1660.                                                     yCoordInv.push(j+1);
  1661.                                                     freeSpace++;
  1662.                                                 }
  1663.                                         }
  1664.                                 }
  1665.                         }
  1666.                 }
  1667.             if(freeSpace < 5)
  1668.                 invFull = true;
  1669.             else
  1670.                 infFull = false;
  1671.         }
  1672.     }
  1673.  
  1674.     var goBackToPile = function() {
  1675.         if (goingBackToPile) {
  1676.  
  1677.         }
  1678.         else {
  1679.             goHome();
  1680.             goingBackToPile = true;
  1681.         }
  1682.  
  1683.  
  1684.     }
  1685.  
  1686.     var findClosestEmptyStockPile = function() {
  1687.         var playerCoords = g.getPlayerCoords();
  1688.  
  1689.         var nearestStockpile = null;
  1690.         var distanceToStockpile = null;
  1691.  
  1692.         var mapObjects = g.getAllMapObjects();
  1693.  
  1694.         for (var i = 0; i < mapObjects.length; ++i) {
  1695.             if (mapObjects[i].name == 'body') {
  1696.                 continue;
  1697.             }
  1698.             else if (isBoughStockpile(mapObjects[i].name)) {
  1699.                 var alreadyStored = false;
  1700.                 if (fullStockpiles != null) {
  1701.                     for (var b = 0; b < fullStockpiles.length; ++b) {
  1702.                         if (fullStockpiles[i] == mapObjects[i].id)
  1703.                             alreadyStored = true;
  1704.                     }
  1705.                 }
  1706.                 if (!alreadyStored) {
  1707.  
  1708.  
  1709.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  1710.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  1711.                     distanceToStockpile = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  1712.                     if (debug) {
  1713.                         print("dx, dy: " + dx + "," + dy);
  1714.                         print('Testing distance to stockpile: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  1715.                         print('Distance to the stockpile is: ' + distanceToStockpile);
  1716.                     }
  1717.                     if (tree == null || distanceToStockpile < nearestStockpile || nearestStockpile == null) {
  1718.                         tree = mapObjects[i];
  1719.                         nearestStockpile = distanceToStockpile;
  1720.                         if (debug) {
  1721.                             print('Distance to the closest stockpile is: ' + nearestStockpile);
  1722.                         }
  1723.                     }
  1724.                 }
  1725.             }
  1726.             else {
  1727.  
  1728.             }
  1729.         }
  1730.         if (stockpile == null) {
  1731.             wander();
  1732.         }
  1733.     }
  1734.  
  1735.     var goToStockpile = function() {
  1736.         walkToSet(stockpile.coords.x + getRandomInt(-20, 20), stockpile.coords.y + getRandomInt(-20, 20), 10);
  1737.         if (getDistance() < toP) {
  1738.             if (debug)
  1739.                 print('Is near stockpile.')
  1740.             return true;
  1741.         }
  1742.         else {
  1743.             if (debug)
  1744.                 print('Is not near the stockpile, walking closer.')
  1745.             walkTo();
  1746.             if (isStuck()) {
  1747.                 wander();
  1748.             }
  1749.             return false;
  1750.         }
  1751.  
  1752.     }
  1753.  
  1754.     var storeStockpile = function() {
  1755.         g.mapObjectRightClick(stockpile.id);
  1756.  
  1757.         sleep(second);
  1758.         if (g.getStockpileInfo() != null) {
  1759.  
  1760.             stockpileInfo = g.getStockpileInfo();
  1761.  
  1762.             print('Putting boughes into stockpile...');
  1763.  
  1764.             var items = g.getInvItems();
  1765.  
  1766.             var space = stockpileInfo.total;
  1767.  
  1768.             var taken = stockpileInfo.used;
  1769.  
  1770.             for (var i = 0; i < items.length; i++) {
  1771.                 if (items[i] == 'bough') {
  1772.                     if (taken < space) {
  1773.  
  1774.                         sleep(second);
  1775.  
  1776.                         g.takeItem(items[i]);
  1777.  
  1778.                         sleep(second);
  1779.  
  1780.                         g.useItemFromHandOnObject(stockpile.id);
  1781.  
  1782.                         sleep(second * 0.5);
  1783.  
  1784.                         taken++;
  1785.  
  1786.                     }
  1787.                     else {
  1788.  
  1789.                         fullStockpiles.push(stockpile);
  1790.                         stockpile = null;
  1791.                     }
  1792.  
  1793.                     break;
  1794.  
  1795.                 }
  1796.  
  1797.             }
  1798.         }
  1799.     }
  1800.    
  1801.     var checkInventoryForBoughes = function()
  1802.     {
  1803.         var items = g.getInvItems();
  1804.         for (var i = 0; i < items.length; i++) {
  1805.             if (items[i] == 'bough') {
  1806.                 return true;
  1807.             }
  1808.         }
  1809.         return false;
  1810.     }
  1811.    
  1812.     var goGoBackPicking = function()
  1813.     {
  1814.         if(checkInventoryForBoughes)
  1815.             {
  1816.                
  1817.             }
  1818.         else
  1819.             {
  1820.                 goingBackToPile = false;
  1821.                 invFull = false;
  1822.                 tree = null;
  1823.                 atTree = false;
  1824.                 atStockpile = false;
  1825.                 stockpile = null;
  1826.                 treePickCount = 0;
  1827.             }
  1828.     }
  1829.  
  1830. }
  1831. /**
  1832.  *
  1833.  */
  1834.  
  1835. function qBranchPicker() {
  1836.     var tree;
  1837.     var atTree;
  1838.     var pickedTrees = new Array();
  1839.     var treePickCount = 0;
  1840.     var finishedPicking = false;
  1841.  
  1842.     var invFull = false;
  1843.  
  1844.     var goingBackToPile = false;
  1845.     var fullStockpiles = new Array();
  1846.     var stockpile;
  1847.     var atStockpile;
  1848.  
  1849.     /**
  1850.      * The run function for this bot.
  1851.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  1852.      */
  1853.     this.runBranchPicker = function() {
  1854.         if (qBranchPickerRun) {
  1855.             stamina();
  1856.             checkInventorySpace();
  1857.             if (invFull) {
  1858.                 goBackToPile();
  1859.                 findClosestEmptyStockpile();
  1860.                 goToStockpile();
  1861.                 storeStockpile();
  1862.                 goGoBackPicking();
  1863.             }
  1864.             else {
  1865.                 if (tree == null)
  1866.                     findTree();
  1867.                 if (goToTree()) {
  1868.                     pickTree();
  1869.                 }
  1870.                 if (treePickCount != 0)
  1871.                     if (finishedPicking)
  1872.                         goHome();
  1873.             }
  1874.         }
  1875.     }
  1876.  
  1877.     /**
  1878.      * Finds a tree to cut down and sets it as the target tree.
  1879.      */
  1880.     var findTree = function() {
  1881.  
  1882.         var playerCoords = g.getPlayerCoords();
  1883.  
  1884.         var nearestTreeDistance = null;
  1885.         var distanceToTree = null;
  1886.  
  1887.         var mapObjects = g.getAllMapObjects();
  1888.  
  1889.         for (var i = 0; i < mapObjects.length; ++i) {
  1890.             if (mapObjects[i].name == 'body') {
  1891.                 continue;
  1892.             }
  1893.             else if (isTree(mapObjects[i].name)) {
  1894.                 var alreadyChopped = false;
  1895.                 if (pickedTrees != null) {
  1896.                     for (var b = 0; b < pickedTrees.length; ++b) {
  1897.                         if (pickedTrees[i] == mapObjects[i].id)
  1898.                             alreadyChopped = true;
  1899.                     }
  1900.                 }
  1901.                 if (!alreadyChopped) {
  1902.  
  1903.  
  1904.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  1905.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  1906.                     distanceToTree = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  1907.                     if (debug) {
  1908.                         print("dx, dy: " + dx + "," + dy);
  1909.                         print('Testing distance to tree: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  1910.                         print('Distance to the tree is: ' + distanceToTree);
  1911.                     }
  1912.                     if (tree == null || distanceToTree < nearestTreeDistance || nearestTreeDistance == null) {
  1913.                         tree = mapObjects[i];
  1914.                         nearestTreeDistance = distanceToTree;
  1915.                         if (debug) {
  1916.                             print('Distance to the closest tree is: ' + nearestTreeDistance);
  1917.                         }
  1918.                     }
  1919.                 }
  1920.             }
  1921.             else {
  1922.  
  1923.             }
  1924.         }
  1925.         if (tree == null) {
  1926.             wander();
  1927.         }
  1928.     }
  1929.  
  1930.     /**
  1931.      * Goes to the target tree and returns true if at the target, otherwise returns false.
  1932.      */
  1933.     var goToTree = function() {
  1934.         walkToSet(tree.coords.x + getRandomInt(-20, 20), tree.coords.y + getRandomInt(-20, 20), 10);
  1935.         if (getDistance() < toP) {
  1936.             if (debug)
  1937.                 print('Is near tree.')
  1938.             return true;
  1939.         }
  1940.         else {
  1941.             if (debug)
  1942.                 print('Is not near the tree, walking closer.')
  1943.             walkTo();
  1944.             if (isStuck()) {
  1945.                 wander();
  1946.             }
  1947.             return false;
  1948.         }
  1949.  
  1950.     }
  1951.  
  1952.     /**
  1953.      * Chops the target tree down.
  1954.      */
  1955.     var pickTree = function() {
  1956.  
  1957.         g.mapObjectRightClick(tree.id);
  1958.         sleep(second * 1);
  1959.         finishedPicking = false;
  1960.  
  1961.         g.chooseFlowerMenuOption('Take branch');
  1962.         sleep(second * 20);
  1963.         if (debug)
  1964.             print('picking and waiting for task to finish.');
  1965.         g.waitForTaskToFinish();
  1966.         if (debug)
  1967.             print('Task finished, checking if the tree is still there.');
  1968.         if (treePickCount <= 10) {
  1969.             treePickCount++;
  1970.             if (debug)
  1971.                 print('Target tree probably still there, count is: ' + treePickCount);
  1972.  
  1973.         }
  1974.         else {
  1975.             if (debug)
  1976.                 print('Target tree probably not still there...');
  1977.  
  1978.             finishedPicking = true;
  1979.             treePickCount = 0;
  1980.             pickedTrees.push(tree.id);
  1981.             tree = null;
  1982.  
  1983.         }
  1984.     }
  1985.  
  1986.     /**
  1987.      * A method to stop walking and start regenerating stamina.
  1988.      */
  1989.     var stamina = function() {
  1990.  
  1991.         WalkToSwitch = false;
  1992.         RedWalkDefault = false;
  1993.         waitForStamina(95);
  1994.  
  1995.     }
  1996.  
  1997.     /**
  1998.      * A method to go home if needed.
  1999.      */
  2000.     var goHome = function() {
  2001.         hearthHome();
  2002.     }
  2003.  
  2004.     var checkInventorySpace = function() {
  2005.         if (!goingBackToPile) {
  2006.             if (g.getFreeCharInvCellsCount() < 5)
  2007.                 invFull = true;
  2008.             else
  2009.                 invFull = false;
  2010.         }
  2011.     }
  2012.  
  2013.     var goBackToPile = function() {
  2014.         if (goingBackToPile) {
  2015.  
  2016.         }
  2017.         else {
  2018.             goHome();
  2019.             goingBackToPile = true;
  2020.         }
  2021.  
  2022.  
  2023.     }
  2024.  
  2025.     var findClosestEmptyStockPile = function() {
  2026.         var playerCoords = g.getPlayerCoords();
  2027.  
  2028.         var nearestStockpile = null;
  2029.         var distanceToStockpile = null;
  2030.  
  2031.         var mapObjects = g.getAllMapObjects();
  2032.  
  2033.         for (var i = 0; i < mapObjects.length; ++i) {
  2034.             if (mapObjects[i].name == 'body') {
  2035.                 continue;
  2036.             }
  2037.             else if (isBranchStockpile(mapObjects[i].name)) {
  2038.                 var alreadyStored = false;
  2039.                 if (fullStockpiles != null) {
  2040.                     for (var b = 0; b < fullStockpiles.length; ++b) {
  2041.                         if (fullStockpiles[i] == mapObjects[i].id)
  2042.                             alreadyStored = true;
  2043.                     }
  2044.                 }
  2045.                 if (!alreadyStored) {
  2046.  
  2047.  
  2048.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  2049.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  2050.                     distanceToStockpile = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  2051.                     if (debug) {
  2052.                         print("dx, dy: " + dx + "," + dy);
  2053.                         print('Testing distance to stockpile: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  2054.                         print('Distance to the stockpile is: ' + distanceToStockpile);
  2055.                     }
  2056.                     if (tree == null || distanceToStockpile < nearestStockpile || nearestStockpile == null) {
  2057.                         tree = mapObjects[i];
  2058.                         nearestStockpile = distanceToStockpile;
  2059.                         if (debug) {
  2060.                             print('Distance to the closest stockpile is: ' + nearestStockpile);
  2061.                         }
  2062.                     }
  2063.                 }
  2064.             }
  2065.             else {
  2066.  
  2067.             }
  2068.         }
  2069.         if (stockpile == null) {
  2070.             wander();
  2071.         }
  2072.     }
  2073.  
  2074.     var goToStockpile = function() {
  2075.         walkToSet(stockpile.coords.x + getRandomInt(-20, 20), stockpile.coords.y + getRandomInt(-20, 20), 10);
  2076.         if (getDistance() < toP) {
  2077.             if (debug)
  2078.                 print('Is near stockpile.')
  2079.             return true;
  2080.         }
  2081.         else {
  2082.             if (debug)
  2083.                 print('Is not near the stockpile, walking closer.')
  2084.             walkTo();
  2085.             if (isStuck()) {
  2086.                 wander();
  2087.             }
  2088.             return false;
  2089.         }
  2090.  
  2091.     }
  2092.  
  2093.     var storeStockpile = function() {
  2094.         g.mapObjectRightClick(stockpile.id);
  2095.  
  2096.         sleep(second);
  2097.         if (g.getStockpileInfo() != null) {
  2098.  
  2099.             stockpileInfo = g.getStockpileInfo();
  2100.  
  2101.             print('Putting branches into stockpile...');
  2102.  
  2103.             var items = g.getInvItems();
  2104.  
  2105.             var space = stockpileInfo.total;
  2106.  
  2107.             var taken = stockpileInfo.used;
  2108.  
  2109.             for (var i = 0; i < items.length; i++) {
  2110.                 if (items[i] == 'branch') {
  2111.                     if (taken < space) {
  2112.  
  2113.                         sleep(second);
  2114.  
  2115.                         g.takeItem(items[i]);
  2116.  
  2117.                         sleep(second);
  2118.  
  2119.                         g.useItemFromHandOnObject(stockpile.id);
  2120.  
  2121.                         sleep(second * 0.5);
  2122.  
  2123.                         taken++;
  2124.  
  2125.                     }
  2126.                     else {
  2127.  
  2128.                         fullStockpiles.push(stockpile);
  2129.                         stockpile = null;
  2130.                     }
  2131.  
  2132.                     break;
  2133.  
  2134.                 }
  2135.  
  2136.             }
  2137.         }
  2138.     }
  2139.    
  2140.     var checkInventoryForBranches = function()
  2141.     {
  2142.         var items = g.getInvItems();
  2143.         for (var i = 0; i < items.length; i++) {
  2144.             if (items[i] == 'branch') {
  2145.                 return true;
  2146.             }
  2147.         }
  2148.         return false;
  2149.     }
  2150.    
  2151.     var goGoBackPicking = function()
  2152.     {
  2153.         if(checkInventoryForBranches)
  2154.             {
  2155.                
  2156.             }
  2157.         else
  2158.             {
  2159.                 goingBackToPile = false;
  2160.                 invFull = false;
  2161.                 tree = null;
  2162.                 atTree = false;
  2163.                 atStockpile = false;
  2164.                 stockpile = null;
  2165.                 treePickCount = 0;
  2166.             }
  2167.     }
  2168.  
  2169. }
  2170. /**
  2171.  *
  2172.  */
  2173.  
  2174. function qChopper() {
  2175.     var tree;
  2176.     var atTree;
  2177.     var choppedTrees = new Array();
  2178.     var treeCutCount = 0;
  2179.     var finishedChopping = false;
  2180.  
  2181.     /**
  2182.      * The run function for this bot.
  2183.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  2184.      */
  2185.     this.runChopper = function() {
  2186.         if (qChopperRun) {
  2187.             stamina();
  2188.             if (tree == null)
  2189.                 findTree();
  2190.             if (goToTree()) {
  2191.                 chopTree();
  2192.             }
  2193.             if (treeCutCount != 0)
  2194.                 if (finishedChopping)
  2195.                     goHome();
  2196.         }
  2197.     }
  2198.  
  2199.     /**
  2200.      * Finds a tree to cut down and sets it as the target tree.
  2201.      */
  2202.     var findTree = function() {
  2203.  
  2204.         var playerCoords = g.getPlayerCoords();
  2205.  
  2206.         var nearestTreeDistance = null;
  2207.         var distanceToTree = null;
  2208.  
  2209.         var mapObjects = g.getAllMapObjects();
  2210.  
  2211.         for (var i = 0; i < mapObjects.length; ++i) {
  2212.             if (mapObjects[i].name == 'body') {
  2213.                 continue;
  2214.             }
  2215.             else if (isTree(mapObjects[i].name)) {
  2216.                 var alreadyChopped = false;
  2217.                 if (choppedTrees != null) {
  2218.                     for (var b = 0; b < choppedTrees.length; ++b) {
  2219.                         if (choppedTrees[i] == mapObjects[i].id)
  2220.                             alreadyChopped = true;
  2221.                     }
  2222.                 }
  2223.                 if (!alreadyChopped) {
  2224.  
  2225.  
  2226.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  2227.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  2228.                     distanceToTree = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  2229.                     if (debug) {
  2230.                         print("dx, dy: " + dx + "," + dy);
  2231.                         print('Testing distance to tree: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  2232.                         print('Distance to the tree is: ' + distanceToTree);
  2233.                     }
  2234.                     if (tree == null || distanceToTree < nearestTreeDistance || nearestTreeDistance == null) {
  2235.                         tree = mapObjects[i];
  2236.                         nearestTreeDistance = distanceToTree;
  2237.                         if (debug) {
  2238.                             print('Distance to the closest tree is: ' + nearestTreeDistance);
  2239.                         }
  2240.                     }
  2241.                 }
  2242.             }
  2243.             else {
  2244.  
  2245.             }
  2246.         }
  2247.         if (tree == null) {
  2248.             wander();
  2249.         }
  2250.     }
  2251.  
  2252.     /**
  2253.      * Goes to the target tree and returns true if at the target, otherwise returns false.
  2254.      */
  2255.     var goToTree = function() {
  2256.         walkToSet(tree.coords.x + getRandomInt(-20, 20), tree.coords.y + getRandomInt(-20, 20), 10);
  2257.         if (getDistance() < toP) {
  2258.             if (debug)
  2259.                 print('Is near tree.')
  2260.             return true;
  2261.         }
  2262.         else {
  2263.             if (debug)
  2264.                 print('Is not near the tree, walking closer.')
  2265.             walkTo();
  2266.             if (isStuck()) {
  2267.                 wander();
  2268.             }
  2269.             return false;
  2270.         }
  2271.  
  2272.     }
  2273.  
  2274.     /**
  2275.      * Chops the target tree down.
  2276.      */
  2277.     var chopTree = function() {
  2278.  
  2279.         g.mapObjectRightClick(tree.id);
  2280.         sleep(second * 1);
  2281.         finishedChopping = false;
  2282.  
  2283.         g.chooseFlowerMenuOption('Chop');
  2284.         sleep(second * 20);
  2285.         if (debug)
  2286.             print('Chopping and waiting for task to finish.');
  2287.         g.waitForTaskToFinish();
  2288.         if (debug)
  2289.             print('Task finished, checking if the tree is still there.');
  2290.         if (treeCutCount <= 10) {
  2291.             treeCutCount++;
  2292.             if (debug)
  2293.                 print('Target tree probably still there, count is: ' + treeCutCount);
  2294.  
  2295.         }
  2296.         else {
  2297.             if (debug)
  2298.                 print('Target tree probably not still there...');
  2299.  
  2300.             finishedChopping = true;
  2301.             treeCutCount = 0;
  2302.             choppedTrees.push(tree.id);
  2303.             tree = null;
  2304.  
  2305.         }
  2306.     }
  2307.  
  2308.     /**
  2309.      * A method to stop walking and start regenerating stamina.
  2310.      */
  2311.     var stamina = function() {
  2312.  
  2313.         WalkToSwitch = false;
  2314.         RedWalkDefault = false;
  2315.         waitForStamina(95);
  2316.  
  2317.     }
  2318.  
  2319.     /**
  2320.      * A method to go home if needed.
  2321.      */
  2322.     var goHome = function() {
  2323.         hearthHome();
  2324.     }
  2325.  
  2326.  
  2327.  
  2328. }
  2329. /**
  2330.  *
  2331.  */
  2332.  
  2333. /**
  2334.  *
  2335.  */
  2336.  
  2337. function qLandForager() {
  2338.     var forage;
  2339.     var atForager;
  2340.     var choppedForagers = new Array();
  2341.     var forageAttemptCount = 0;
  2342.     var finishedCollecting = false;
  2343.  
  2344.     /**
  2345.      * The run function for this bot.
  2346.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  2347.      */
  2348.     this.runLandForager = function() {
  2349.         if (qLandForagerRun) {
  2350.             stamina();
  2351.             if (forage == null)
  2352.                 findForage();
  2353.             if(forage != null)
  2354.                 if (goToForage()) {
  2355.                     collectForage();
  2356.             }
  2357.         }
  2358.     }
  2359.  
  2360.     /**
  2361.      * Finds a forage to collect and sets it as the target forage.
  2362.      */
  2363.     var findForage = function() {
  2364.  
  2365.         var playerCoords = g.getPlayerCoords();
  2366.  
  2367.         var nearestForagerDistance = null;
  2368.         var distanceToForager = null;
  2369.  
  2370.         var mapObjects = g.getAllMapObjects();
  2371.  
  2372.         for (var i = 0; i < mapObjects.length; ++i) {
  2373.             if (mapObjects[i].name == 'body') {
  2374.                 continue;
  2375.             }
  2376.             else if (isForage(mapObjects[i].fullName)) {
  2377.                 var alreadyForaged = false;
  2378.                 if (choppedForagers != null) {
  2379.                     for (var b = 0; b < choppedForagers.length; ++b) {
  2380.                         if (choppedForagers[i] == mapObjects[i].id)
  2381.                             alreadyForaged = true;
  2382.                     }
  2383.                 }
  2384.                 if (!alreadyForaged) {
  2385.  
  2386.  
  2387.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  2388.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  2389.                     distanceToForager = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  2390.                     if (debug) {
  2391.                         print("dx, dy: " + dx + "," + dy);
  2392.                         print('Testing distance to forage: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  2393.                         print('Distance to the forage is: ' + distanceToForager);
  2394.                     }
  2395.                     if (forage == null || distanceToForager < nearestForagerDistance || nearestForagerDistance == null) {
  2396.                         forage = mapObjects[i];
  2397.                         nearestForagerDistance = distanceToForager;
  2398.                         if (debug) {
  2399.                             print('Distance to the closest forage is: ' + nearestForagerDistance);
  2400.                         }
  2401.                     }
  2402.                 }
  2403.             }
  2404.             else {
  2405.  
  2406.             }
  2407.         }
  2408.         if (forage == null) {
  2409.             print('Wandering to find foragables...');
  2410.             wander();
  2411.         }
  2412.     }
  2413.  
  2414.     /**
  2415.      * Goes to the target forage and returns true if at the target, otherwise returns false.
  2416.      */
  2417.     var goToForage = function() {
  2418.         walkToSet(forage.coords.x + getRandomInt(-20, 20), forage.coords.y + getRandomInt(-20, 20), 10);
  2419.         if (getDistance() < toP) {
  2420.             if (debug)
  2421.                 print('Is near forage.')
  2422.             return true;
  2423.         }
  2424.         else {
  2425.             if (debug)
  2426.                 print('Is not near the forage, walking closer.')
  2427.             walkTo();
  2428.             if (isStuck()) {
  2429.                 wander();
  2430.             }
  2431.             return false;
  2432.         }
  2433.  
  2434.     }
  2435.  
  2436.     /**
  2437.      * Chops the target forage down.
  2438.      */
  2439.     var collectForage = function() {
  2440.  
  2441.         g.mapObjectRightClick(forage.id);
  2442.         sleep(second * 1);
  2443.         finishedCollecting = false;
  2444.  
  2445.         g.chooseFlowerMenuOption('Pick');
  2446.         sleep(second * 20);
  2447.         if (debug)
  2448.             print('Picking and waiting for task to finish.');
  2449.         g.waitForTaskToFinish();
  2450.         if (debug)
  2451.             print('Task finished, checking if the forage is still there.');
  2452.         if (forageAttemptCount <= 1) {
  2453.             forageAttemptCount++;
  2454.             if (debug)
  2455.                 print('Target forage probably still there, count is: ' + forageAttemptCount);
  2456.  
  2457.         }
  2458.         else {
  2459.             if (debug)
  2460.                 print('Target forage probably not still there...');
  2461.  
  2462.             finishedCollecting = true;
  2463.             forageAttemptCount = 0;
  2464.             choppedForagers.push(forage.id);
  2465.             forage = null;
  2466.  
  2467.         }
  2468.     }
  2469.  
  2470.     /**
  2471.      * A method to stop walking and start regenerating stamina.
  2472.      */
  2473.     var stamina = function() {
  2474.  
  2475.         WalkToSwitch = false;
  2476.         RedWalkDefault = false;
  2477.         waitForStamina(50);
  2478.  
  2479.     }
  2480.  
  2481.     /**
  2482.      * A method to go home if needed.
  2483.      */
  2484.     var goHome = function() {
  2485.         hearthHome();
  2486.     }
  2487.  
  2488.  
  2489.  
  2490. }
  2491. /**
  2492.  *
  2493.  */
  2494.  
  2495. function qLogCollector() {
  2496.     var log;
  2497.     var atLog;
  2498.     var collectedLogs = new Array();
  2499.     var logCollectCount = 0;
  2500.     var finishedCollecting = false;
  2501.     var goingToStockPile = false;
  2502.  
  2503.     var hearthLogX = null;
  2504.     var hearthLogY = null;
  2505.  
  2506.     var coords = new Array();
  2507.     /**
  2508.      * The run function for this bot.
  2509.      * Runs the AI in order that the bot performs it in the asynchronous thread.
  2510.      */
  2511.     this.runLoger = function() {
  2512.         if (hearthLogX == null || herthLogY == null) {
  2513.             var playerCoords = g.getPlayerCoords();
  2514.             hearthLogX = playerCoords.coords.x;
  2515.             hearthLogY = playerCoords.coords.y;
  2516.         }
  2517.         if (qLogerRun) {
  2518.             stamina();
  2519.             if (!finishedCollecting) {
  2520.                 findLog();
  2521.                 if (goToLog()) {
  2522.                     pickUpLog();
  2523.                     goHome();
  2524.                 }
  2525.             }
  2526.             if (finishedCollecting) {
  2527.                 if (!goingToStockPile) {
  2528.  
  2529.                     coords = getStockPosition();
  2530.                     goToStockpile(coords[0], coords[1]);
  2531.                 }
  2532.                 else if (logCollectCount < 10) {
  2533.                     goToStockpile(coords[0], coords[1]);
  2534.                     logCollectCount++;
  2535.                 }
  2536.                 else {
  2537.                     logCollectCount = 0;
  2538.                     goHome();
  2539.                     collectedLogs.push(log);
  2540.                     log = null;
  2541.                     finishedCollect = false;
  2542.                     atLog = false;
  2543.                 }
  2544.             }
  2545.         }
  2546.     }
  2547.  
  2548.     var findLog = function() {
  2549.  
  2550.         var playerCoords = g.getPlayerCoords();
  2551.  
  2552.         var nearestLogDistance = null;
  2553.         var distanceToLog = null;
  2554.  
  2555.         var mapObjects = g.getAllMapObjects();
  2556.  
  2557.         for (var i = 0; i < mapObjects.length; ++i) {
  2558.             if (mapObjects[i].name == 'body') {
  2559.                 continue;
  2560.             }
  2561.             else if (isLog(mapObjects[i].name)) {
  2562.                 var alreadyRemoved = false;
  2563.                 if (collectedLogs != null) {
  2564.                     for (var b = 0; b < collectedLogs.length; ++b) {
  2565.                         if (collectedLogs[i] == mapObjects[i].id)
  2566.                             alreadyRemoved = true;
  2567.                     }
  2568.                 }
  2569.                 if (!alreadyRemoved) {
  2570.  
  2571.  
  2572.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  2573.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  2574.                     distanceToLog = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  2575.                     if (debug) {
  2576.                         print("dx, dy: " + dx + "," + dy);
  2577.                         print('Testing distance to log: ' + mapObjects[i].name + ', ' + mapObjects[i].id + ', ' + mapObjects[i].coords.x + ', ' + mapObjects[i].coords.y);
  2578.                         print('Distance to the log is: ' + distanceToLog);
  2579.                     }
  2580.                     if (log == null || distanceToLog < nearestLogDistance || nearestLogDistance == null) {
  2581.                         log = mapObjects[i];
  2582.                         nearestLogDistance = distanceToLog;
  2583.                         if (debug) {
  2584.                             print('Distance to the closest log is: ' + nearestLogDistance);
  2585.                         }
  2586.                     }
  2587.                 }
  2588.             }
  2589.             else {
  2590.  
  2591.             }
  2592.         }
  2593.         if (log == null) {
  2594.             wander();
  2595.         }
  2596.     }
  2597.  
  2598.     var goToLog = function() {
  2599.  
  2600.         return walkToObject(log);
  2601.  
  2602.     }
  2603.  
  2604.     var pickUpLog = function() {
  2605.         if (!finishedCollecting) {
  2606.             if (g.liftObject(log.id)) {
  2607.                 if (debug)
  2608.                     print('Lifting log.')
  2609.                 finishedCollecting = true;
  2610.  
  2611.             }
  2612.         }
  2613.     }
  2614.  
  2615.     /**
  2616.      * A method to stop walking and start regenerating stamina.
  2617.      */
  2618.     var stamina = function() {
  2619.  
  2620.         WalkToSwitch = false;
  2621.         RedWalkDefault = false;
  2622.         waitForStamina(95);
  2623.  
  2624.     }
  2625.  
  2626.     /**
  2627.      * A method to go home if needed.
  2628.      */
  2629.     var goHome = function() {
  2630.         hearthHome();
  2631.     }
  2632.  
  2633.     var getStockPosition = function() {
  2634.         var mapObjects = g.getAllMapObjects();
  2635.         //Offset along x axis (<==)
  2636.         var c = 50;
  2637.         //Offset along y axis (V==)
  2638.         var b = -200;
  2639.         //Offset coordinates from the hearth fire for bottom left corner of the stockpile.
  2640.         var xI = hearthLogX + c;
  2641.         var yI = hearthLogY + b;
  2642.         //How much to increment the coordinates check on each axis from initial.
  2643.         var increment = 1;
  2644.         //How much space has to be between each log.
  2645.         var space = 5;
  2646.  
  2647.         //The array to store the found coordinates in.
  2648.         var placeCoords = new Array();
  2649.         //Make sure there is something on the screen, otherwise this is pointless.
  2650.         if (mapObjects != null) {
  2651.             //For each block yi, check per yi+1 (going up towards hearth fire)
  2652.             //as long as yi is less than the hearth fire location minus ten degrees.
  2653.             for (var yi = yI; yi < hearthLogY-10; yi + increment) {
  2654.                 //For each block xi, check per xi-1 (going right)
  2655.                 //as long as xi is greater than the far right x final position.
  2656.                 for (var xi = xI; xi > xI - 2 * c; xi - increment) {
  2657.                     //Place the coordinates in the map to verify if these coordinates are true
  2658.                     //and to return later if they are true.
  2659.                     placeCoords.push(xi);
  2660.                     placeCoords.push(yi);
  2661.                     //For each object, check the coordinate isn't in a radius of another object
  2662.                     //at that location.
  2663.                     for (var i = 0; i < mapObjects.size(); i++) {
  2664.                         //Find the max possible x position an object has to be outside of.
  2665.                         var mX = xi + space;
  2666.                         //Find the max possible y position an object has to be outside of.
  2667.                         var mY = yi + space;
  2668.                         //Find the minimum possible x position an object has to be outside of.
  2669.                         var nX = xi - space;
  2670.                         //Find the minimum possible y position an object has to be outside of.
  2671.                         var nY = yi - space;
  2672.                         //Get the x coordinates of the object.
  2673.                         var oX = mapObjects[i].coords.x;
  2674.                         //get the y coordinates of the object.
  2675.                         var oY = mapObjects[i].coords.y;
  2676.                         //If the object is in between both min and max bounds then it is within the radius coordinates.
  2677.                         if (nX < oX < mX && nY < oY < mY) {
  2678.                             //These coordinates are too close to another object so pop them off the list and remove them.
  2679.                             placeCoords.pop();
  2680.                             placeCoords.pop();
  2681.                         }
  2682.                     }
  2683.                     //If there were any coordinates that were not popped off, then set the for loops final conditions
  2684.                     //to stop any further coordinates being added. No longer is it needed to loop for more coordinates
  2685.                     //because we have at least one set.
  2686.                     if (placeCoords.length() > 1) {
  2687.                         yi = hearthLogY;
  2688.                         xi = xI - 2 * c;
  2689.                     }
  2690.                 }
  2691.             }
  2692.         }
  2693.         //Set going to stock pile as true to prevent any other further actions.
  2694.         goingToStockPile = true;
  2695.         //Return the array with the x and y coordinates.
  2696.         return placeCoords;
  2697.     }
  2698.  
  2699.     var goToStockpile = function(sX, sY) {
  2700.         RedWalkDefault = false;
  2701.         WalkToSwitch = false;
  2702.         if (goingToStockPile) {
  2703.             g.mapRightClick(sX, sY);
  2704.         }
  2705.         else {
  2706.             g.mapRightClick(toX, toY);
  2707.         }
  2708.     }
  2709.  
  2710.     /**
  2711.      * In case this code is needed again. To be removed in the next release.
  2712.     var pasteSave = function()
  2713.     {
  2714.        
  2715.         g.useMenuAction(['a', 'y']);
  2716.         sleep(second*1);
  2717.         finishedCollecting = false;
  2718.        
  2719.         g.mapRightClick(log.coords.x, log.coords.y)
  2720.         sleep(second*20);
  2721.         print('Removing and waiting for task to finish.');
  2722.         g.waitForTaskToFinish();
  2723.         print('Task finished, checking if the log is still there.');
  2724.         if(logCollectCount <= 10)
  2725.         {
  2726.             logCollectCount++;
  2727.            
  2728.             if(debug)
  2729.             print('Target log probably still there, count is: ' + logCollectCount);
  2730.            
  2731.         }
  2732.         else
  2733.         {
  2734.             if(debug)
  2735.             print('Target log probably not still there...');
  2736.            
  2737.             finishedCollecting = true;
  2738.             logCollectCount = 0;
  2739.             collectedLogs.push(log.id);
  2740.             log = null;
  2741.            
  2742.         }
  2743.     }
  2744.     */
  2745.  
  2746.  
  2747. }
  2748. /**
  2749.  *
  2750.  */
  2751.  
  2752. function isTree(tree) {
  2753.     return tree == "alder" || tree == "appletree" || tree == "ash" || tree == "aspen" || tree == "baywillow" || tree == "beech" || tree == "birch" ||
  2754.         tree == "birdcherrytree" || tree == "buckthorn" || tree == "cedar" || tree == "cherry" || tree == "chestnuttree" || tree == "conkertree" ||
  2755.         tree == "corkoak" || tree == "crabappletree" || tree == "cypress" || tree == "elm" || tree == "fir" || tree == "goldenchain" || tree == "hazel" ||
  2756.         tree == "hornbeam" || tree == "juniper" || tree == "kingsoak" || tree == "larch" || tree == "laurel" || tree == "linden" || tree == "maple" ||
  2757.         tree == "mulberry" || tree == "oak" || tree == "olivetree" || tree == "peatree" || tree == "pine" || tree == "planetree" || tree == "plumtree" ||
  2758.         tree == "poplar" || tree == " rowan" || tree == "sallow" || tree == "spruce" || tree == "sweetgum" || tree == "walnuttree" || tree == "whitebeam" ||
  2759.         tree == "willow" || tree == "yew"; // etc
  2760. }
  2761.  
  2762. function isLog(log) {
  2763.     return log.name.endsWith('log');
  2764. }
  2765.  
  2766. function isForage(forage) {
  2767.     var str = forage;
  2768.     var substr = "herbs";
  2769.     var result = str.indexOf(substr) > -1;
  2770.     return result;
  2771. }
  2772.  
  2773. function isStump(stump) {
  2774.     return stump.endsWith('stump');
  2775. }
  2776.  
  2777. function isHostileBeast(beast) {
  2778.     return beast == "badger" || beast == "bat" || beast == "bear" || beast == "boar" || beast == "lynx" || beast == "troll";
  2779.    
  2780. }
  2781.  
  2782. function isFriendlyBeast(beast) {
  2783.     return beast == "ant" || beast == "auroch" || beast == "mouflon" || beast == "deer" || beast == "moose" || beast == "bunny" || beast == "squirrel" || beast == "horse";
  2784. }
  2785.  
  2786. function isUnknownPlayer(beast) {
  2787.     return beast == "player";
  2788. }
  2789.  
  2790. function isBranchStockpile(stockpile)
  2791. {
  2792.     return stockpile.name == "stockpileBranch";
  2793. }
  2794. /**
  2795.  *
  2796.  */
  2797.  
  2798. /**
  2799.  * Toggles walking to target coordinates on and off.
  2800.  */
  2801. function walkToToggle() {
  2802.     if (WalkToSwitch) {
  2803.         print('Walking to target has stopped...');
  2804.         WalkToSwitch = false;
  2805.     }
  2806.     else {
  2807.         print('Walking to target has resumed...');
  2808.         WalkToSwitch = true;
  2809.     }
  2810. }
  2811.  
  2812. /**
  2813.  * Toggles walking randomly in a direction on and off.
  2814.  */
  2815. function walkDefaultToggle() {
  2816.     if (RedWalkDefault) {
  2817.         print('Red Walking has stopped...');
  2818.         RedWalkDefault = false;
  2819.     }
  2820.     else {
  2821.         print('Red Walking has resumed...');
  2822.         RedWalkDefault = true;
  2823.     }
  2824. }
  2825.  
  2826. /**
  2827.  * Toggles if the red bot can walk control walking or not.
  2828.  */
  2829. function walkAutoToggle() {
  2830.     if (RedAutoWalkingSwitch) {
  2831.         print('Red Auto Walking has stopped...');
  2832.         RedAutoWalkingSwitch = false;
  2833.     }
  2834.     else {
  2835.         print('Red Auto Walking has resumed...');
  2836.         RedAutoWalkingSwitch = true;
  2837.     }
  2838. }
  2839.  
  2840. /**
  2841.  * Toggles if the bot can user the chopper to chop down trees or not.
  2842.  */
  2843. /*
  2844. function chopperToggle()
  2845. {
  2846.     if(choppingTrees)
  2847.         {
  2848.         print('Chopping has stopped...');
  2849.         choppingTrees = false;
  2850.         }
  2851.     else
  2852.         {
  2853.         print('Chopping has resumed...');
  2854.         choppingTrees = true;
  2855.         chopWood();
  2856.         }
  2857. }
  2858. */
  2859.  
  2860. /**
  2861.  * Toggles on and off the qChopper bot.
  2862.  */
  2863. function qChopperToggle() {
  2864.     if (qChopperRun) {
  2865.         print('qChopper Bot has stopped...');
  2866.         qChopperRun = false;
  2867.         RedWalkDefault = false;
  2868.         WalkToSwitch = false;
  2869.     }
  2870.     else {
  2871.         print('qChopper Bot has resumed...');
  2872.         qChopperRun = true;
  2873.     }
  2874. }
  2875.  
  2876. /**
  2877.  * Toggles on and off the qStumper bot.
  2878.  */
  2879. function qStumperToggle() {
  2880.     if (qStumperRun) {
  2881.         print('qStumper Bot has stopped...');
  2882.         qStumperRun = false;
  2883.         RedWalkDefault = false;
  2884.         WalkToSwitch = false;
  2885.     }
  2886.     else {
  2887.         print('qStumper Bot has resumed...');
  2888.         qStumperRun = true;
  2889.     }
  2890. }
  2891.  
  2892. /**
  2893.  * Toggles on and off the qBoardCutter bot.
  2894.  */
  2895. function qBoardCutterToggle() {
  2896.     if (qBoardCutterRun) {
  2897.         print('qBoardCutter Bot has stopped...');
  2898.         qBoardCutterRun = false;
  2899.         RedWalkDefault = false;
  2900.         WalkToSwitch = false;
  2901.     }
  2902.     else {
  2903.         print('qBoardCutter Bot has resumed...');
  2904.         qBoardCutterRun = true;
  2905.     }
  2906. }
  2907.  
  2908. /**
  2909.  * Toggles on and off the qBlockChopper bot.
  2910.  */
  2911. function qBlockChopperToggle() {
  2912.     if (qBlockChopperRun) {
  2913.         print('qBlockChopper Bot has stopped...');
  2914.         qBlockChopperRun = false;
  2915.         RedWalkDefault = false;
  2916.         WalkToSwitch = false;
  2917.     }
  2918.     else {
  2919.         print('qBlockChopper Bot has resumed...');
  2920.         qBlockChopperRun = true;
  2921.     }
  2922. }
  2923.  
  2924. /**
  2925.  * Toggles on and off the qLandForager bot.
  2926.  */
  2927. function qLandForagerToggle() {
  2928.     if (qLandForagerRun) {
  2929.         print('qLandForager Bot has stopped...');
  2930.         qLandForagerRun = false;
  2931.         RedWalkDefault = false;
  2932.         WalkToSwitch = false;
  2933.     }
  2934.     else {
  2935.         print('qLandForager Bot has resumed...');
  2936.         qLandForagerRun = true;
  2937.     }
  2938. }
  2939.  
  2940. /**
  2941.  * Toggles if bot can hearth home if in danger or not.
  2942.  */
  2943. function agroToggleSwitch() {
  2944.     if (agroToggle) {
  2945.         print('Agro Homing has stopped...');
  2946.         agroToggle = false;
  2947.     }
  2948.     else {
  2949.         print('Agro Homing has resumed...');
  2950.         agroToggle = true;
  2951.     }
  2952. }
  2953.  
  2954. /**
  2955.  * Toggles hearthing home and checking for hostile beasts.
  2956.  */
  2957. function allowHostileToggle() {
  2958.     if(AllowHostile)
  2959.         {
  2960.             print('Hostile Beast Monitoring has stopped...');
  2961.             AllowHostile = false;
  2962.         }
  2963.     else
  2964.         {
  2965.             print('Hostile Beast Monitoring has resumed...');
  2966.             AllowHostile = true;
  2967.         }
  2968. }
  2969.  
  2970. /**
  2971.  * Toggles hearthing home and checking for player beasts.
  2972.  */
  2973. function allowPlayerToggle() {
  2974.     if(AllowPlayer)
  2975.         {
  2976.             print('Player Beast Monitoring has stopped...');
  2977.             AllowPlayer = false;
  2978.         }
  2979.     else
  2980.         {
  2981.             print('Player Beast Monitoring has resumed...');
  2982.             AllowPlayer = true;
  2983.         }
  2984. }
  2985.  
  2986. /**
  2987.  * Toggles hearthing home and checking for friendly beasts.
  2988.  */
  2989. function allowFriendlyToggle() {
  2990.     if(AllowFriendly)
  2991.         {
  2992.             print('Friendly Beast Monitoring has resumed...');
  2993.             AllowFriendly = false;
  2994.         }
  2995.     else
  2996.         {
  2997.             print('Friendly Beast Monitoring has resumed...');
  2998.             AllowFriendly = true;
  2999.         }
  3000. }
  3001.  
  3002.  
  3003. /**
  3004.  *
  3005.  */
  3006. //Main Global Variables
  3007. /**
  3008.  * A game second.
  3009.  */
  3010. var second = 1000;
  3011. /**
  3012.  * To allow debugging.
  3013.  */
  3014. var debug = true;
  3015. /**
  3016.  * Multiply by this variable to convert to tiles.
  3017.  */
  3018. var tileUnit = 1/10;
  3019.  
  3020. //Toggles
  3021. var agroToggle = false;
  3022.  
  3023. var RedAutoWalkingSwitch = true;
  3024.  
  3025. var RedWalkDefault = false;
  3026.  
  3027. var WalkToSwitch = false;
  3028.  
  3029. var ignoreStuckCount = false;
  3030.  
  3031. var updateTasks = true;
  3032.  
  3033. var isStuckCooldown = 0;
  3034.  
  3035. var directionCount = 0;
  3036.  
  3037. var xDirection = 0;
  3038. var yDirection = 0;
  3039.  
  3040. var oldPlayerX = 0;
  3041. var oldPlayerY = 0;
  3042.  
  3043. var toX = 0;
  3044. var toY = 0;
  3045. var toP = 0;
  3046.  
  3047. var nearestObjectDistance = null;
  3048.  
  3049. //For monitoring animals
  3050.  
  3051. var beastWatchList = new Array();
  3052.  
  3053. var AllowHostile = true;
  3054.  
  3055. var AllowPlayer = false;
  3056.  
  3057. var AllowFriendly = false;
  3058.  
  3059. //Automation run booleans.
  3060.  
  3061. var qChopperRun = false;
  3062.  
  3063. var qBlockChopperRun = false;
  3064.  
  3065. var qBoardCutterRun = false;
  3066.  
  3067. var qLandForagerRun = false;
  3068.  
  3069. var qBoughPickerRun = false;
  3070.  
  3071. var qBranchPickerRun = false;
  3072.  
  3073. var qStumperRun = false;
  3074.  
  3075. var qLogerRun = false;
  3076.  
  3077. var BeastWatcherRun = false;
  3078.  
  3079.  
  3080.  
  3081. /**
  3082.  *
  3083.  */
  3084. function ExampleClass()
  3085. {
  3086.     //Private Variable
  3087.     var privateVariable;
  3088.    
  3089.     //Public Variable
  3090.     this.publicVariable;
  3091.    
  3092.     //Private Method
  3093.     var somePrivateFunction = function()
  3094.     {
  3095.        
  3096.     }
  3097.    
  3098.     //Public Method
  3099.     this.somePublicFunction = function()
  3100.     {
  3101.         somePrivateFunction();
  3102.     }
  3103.    
  3104. }
  3105.  
  3106. function exampleClassRun()
  3107. {
  3108.     example = new ExampleClass();
  3109.    
  3110.     example.publicVariable;
  3111.    
  3112.     example.somePublicFunction();
  3113. }
  3114.  
  3115. /**
  3116.  *
  3117.  */
  3118.  
  3119. function asyncThread() {
  3120.     //Bots
  3121.     var chopperBot;
  3122.     var beastWatcherBot;
  3123.     var boarderBot;
  3124.     var blockerBot;
  3125.     var landForagerBot;
  3126.  
  3127.     this.updateTasks = true;
  3128.     /**
  3129.      * Controls the bot tasks queue.
  3130.      */
  3131.     this.asyncTask = function() {
  3132.         if (updateTasks) {
  3133.             async = setInterval(function() {
  3134.                 beastWatcherBot.runBeastWatcher();
  3135.                 chopperBot.runChopper();
  3136.                 boarderBot.runBoardCutter();
  3137.                 blockerBot.runBlockChopper();
  3138.                 landForagerBot.runLandForager();
  3139.             }, second);
  3140.         }
  3141.     }
  3142.  
  3143.     /**
  3144.      * Creates the initial needed instances of each bot.
  3145.      */
  3146.     this.createInstances = function() {
  3147.         beastWatcherBot = new BeastWatcher();
  3148.         chopperBot = new qChopper();
  3149.         boarderBot = new qBoardCutter();
  3150.         blockerBot = new qBlockChopper();
  3151.         landForagerBot = new qLandForager();
  3152.     }
  3153.  
  3154. }
  3155. /**
  3156.  *
  3157.  */
  3158. function Command(command, Actions)
  3159. {
  3160.     //Private Variable
  3161.     var actions = new Array();
  3162.     actions = Actions;
  3163.     var str = command;
  3164.    
  3165.     //Public Variable
  3166.     this.publicVariable;
  3167.    
  3168.     //Private Method
  3169.     var somePrivateFunction = function()
  3170.     {
  3171.        
  3172.     }
  3173.    
  3174.     //Public Method
  3175.     this.somePublicFunction = function()
  3176.     {
  3177.         somePrivateFunction();
  3178.     }
  3179.    
  3180. }
  3181. /**
  3182.  *
  3183.  */
  3184. function CommandHandler()
  3185. {
  3186.     //Private Variable
  3187.     var privateVariable;
  3188.    
  3189.     //Public Variable
  3190.     this.publicVariable;
  3191.    
  3192.     //Private Method
  3193.     var somePrivateFunction = function()
  3194.     {
  3195.        
  3196.     }
  3197.    
  3198.     //Public Method
  3199.     this.somePublicFunction = function()
  3200.     {
  3201.         somePrivateFunction();
  3202.     }
  3203.    
  3204. }
  3205. /**
  3206.  *
  3207.  */
  3208.  
  3209. /**
  3210.  * Determines what happens on login.
  3211.  */
  3212. function gameStart() {
  3213.     if (debug) {
  3214.         print('Travel to hearth fire...');
  3215.         g.travelToHearthFire();
  3216.         if (debug)
  3217.             print('Sleep 10 seconds...');
  3218.         sleep(second * 10);
  3219.     }
  3220.     print('Starting autowalking...');
  3221.     startAutoWalking();
  3222.     print('Starting new asynchronous process...');
  3223.     var async = new asyncThread();
  3224.     print('Creating needed instances...');
  3225.     async.createInstances();
  3226.     print('Start the asynchronous task queue.');
  3227.     async.asyncTask();
  3228.     print('Asynchronous processes are established!');
  3229. }
  3230. /**
  3231.  *
  3232.  */
  3233.  
  3234.  
  3235. /*
  3236. function chopWood()
  3237. {
  3238.     while(choppingTrees)
  3239.     {
  3240.         print('Regenerating stamina...');
  3241.         regenStamina();
  3242.         print('Finding closest tree...');
  3243.         findClosestTree();
  3244.         print('Found closest tree! Now walking to it.');
  3245.         print('The target is: ' + targetTree.name);
  3246.         print('Chopping tree.')
  3247.         walkToStart(targetTree.coords.x+getRandomInt(-20,20), targetTree.coords.y+getRandomInt(-20,20), 10);
  3248.         if(getDistance()<toP)
  3249.         {
  3250.             print('Is near tree, now chopping the tree.')
  3251.             chopTree();
  3252.             sleep(second*5);
  3253.         }
  3254.         else
  3255.         {
  3256.             print('Is not near the tree, walking closer.')
  3257.             walkTo();
  3258.             if(isStuck())
  3259.             {
  3260.                 var playerCoords = g.getPlayerCoords();
  3261.                 getDirection();
  3262.                 g.mapRightClick(playerCoords.x + xDirection*getRandomInt(20,40), playerCoords.y + yDirection*getRandomInt(20,40));
  3263.             }
  3264.         }
  3265.     }
  3266. }
  3267.  
  3268.  
  3269. function chopTree()
  3270. {
  3271.     print('Right clicking tree with ID: ' + targetTree.id);
  3272.     g.mapObjectRightClick(targetTree.id);
  3273.     sleep(second*1);
  3274.     finishedCutting = false;
  3275.     cutTree();
  3276.    
  3277. }
  3278.  
  3279. function cutTree()
  3280. {
  3281.     g.chooseFlowerMenuOption('Chop');
  3282.     sleep(second*20);
  3283.     print('Chopping and waiting for task to finish.');
  3284.     g.waitForTaskToFinish();
  3285.     print('Task finished, checking if the tree is still there.');
  3286.     if(targetTreeCount <= 10)
  3287.     {
  3288.         targetTreeCount++;
  3289.         print('Target tree probably still there, count is: ' + targetTreeCount);
  3290.         regenStamina();
  3291.         walkToStart(targetTree.coords.x+getRandomInt(-20,20), targetTree.coords.y+getRandomInt(-20,20), 5);
  3292.         chopTree();
  3293.        
  3294.     }
  3295.     else
  3296.     {
  3297.         print('Target tree probably not still there...');
  3298.         sleep(second*2);
  3299.         g.travelToHearthFire();
  3300.         sleep(second*1);
  3301.         g.waitForTaskToFinish();
  3302.         finishedCutting = true;
  3303.         targetTreeCount = 0;
  3304.         treeChoppedList.push(targetTree.id);
  3305.         targetTree = null;
  3306.         chopWood();
  3307.        
  3308.     }
  3309. }
  3310.  
  3311.  
  3312. function findClosestTree()
  3313. {
  3314.  
  3315.       var playerCoords = g.getPlayerCoords();
  3316.      
  3317.       var nearestTreeDistance = null;
  3318.       var distanceToTree = null;
  3319.      
  3320.       var mapObjects = g.getAllMapObjects();
  3321.      
  3322.       for (var i = 0; i < mapObjects.length; ++i)
  3323.       {
  3324.  
  3325.         if (mapObjects[i].name == 'body') {
  3326.           continue;
  3327.         }
  3328.         else if(isTree(mapObjects[i].name))
  3329.         {
  3330.             var alreadyChopped = false;
  3331.             if(treeChoppedList != null)
  3332.                 {
  3333.                     for (var b = 0; b < treeChoppedList.length; ++b) {
  3334.                
  3335.                         if(treeChoppedList[i] == mapObjects[i].id)
  3336.                             alreadyChopped = true;
  3337.                     }
  3338.                 }
  3339.             if(!alreadyChopped)
  3340.             {
  3341.                
  3342.                
  3343.                     var dx = playerCoords.x - mapObjects[i].coords.x;
  3344.                     var dy = playerCoords.y - mapObjects[i].coords.y;
  3345.                     distanceToTree = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
  3346.                     print("dx, dy: " + dx +","+dy);
  3347.                     print('Testing distance to tree: ' + mapObjects[i].name +', '+mapObjects[i].id+', '+mapObjects[i].coords.x+', '+mapObjects[i].coords.y);
  3348.                     print('Distance to the tree is: ' + distanceToTree);
  3349.                    
  3350.                 if (targetTree == null || distanceToTree < nearestTreeDistance || nearestTreeDistance == null) {
  3351.                     targetTree = mapObjects[i];
  3352.                     nearestTreeDistance = distanceToTree;
  3353.                     print('Distance to the closest tree is: ' + nearestTreeDistance);
  3354.                 }
  3355.             }
  3356.         }
  3357.         else
  3358.         {
  3359.            
  3360.         }
  3361.        
  3362.       }
  3363.  
  3364. }
  3365. */
  3366. /**
  3367.  *
  3368.  */
  3369. /*
  3370. function collectingLogs()
  3371. {
  3372.     sleep(second*2);
  3373.     g.travelToHearthFire();
  3374.     sleep(second*1);
  3375.     g.waitForTaskToFinish();
  3376.    
  3377.     var playerCoords = g.getPlayerCoords();
  3378.    
  3379.     hearthX = playerCoords.x;
  3380.     hearthY = playerCoords.y;
  3381.    
  3382.     logStockpileX = playerCoords.x;
  3383.     logStockpileY = playerCoords.y+50;
  3384.  
  3385.    
  3386.    
  3387.     getAllLogsOnMap();
  3388.    
  3389.     while(areThereLogs())
  3390.         {
  3391.             targetLog = listOfLogs.pop();
  3392.             listOfLogs.push(targetLog);
  3393.             if(!holdingLog)
  3394.             print('Target log cords are: '+targetLog.coords.x + ', ' + targetLog.coords.y);
  3395.             if(holdingLog)
  3396.             print('Target Stockpile cords are: '+logStockpileX + ', ' + logStockpileY);
  3397.             sleep(second*5);
  3398.             if(getDistance()<toP)
  3399.             {
  3400.                 print('Distance to target is: ' + getDistance())
  3401.                 print('Has reached final destination!');
  3402.                 if(holdingLog == false)
  3403.                     {
  3404.                         if(g.liftObject(targetLog.id))
  3405.                         {
  3406.                             print('Lifting log.')
  3407.                             holdingLog = true;
  3408.                             sleep(second*2);
  3409.                             g.travelToHearthFire();
  3410.                             sleep(second*1);
  3411.                             g.waitForTaskToFinish();
  3412.                             sleep(second*10);
  3413.                             print('Now walking to stockpile!');
  3414.                             hearthX = playerCoords.x;
  3415.                             hearthY = playerCoords.y;
  3416.                             walkToStart(logStockpileX + getRandomInt(-10,10), logStockpileY + getRandomInt(-10,10), 5);
  3417.                             g.mapRightClick(toX, toY);
  3418.  
  3419.                         }
  3420.                     }
  3421.                 else if(holdingLog)
  3422.                     {
  3423.                         print('Distance to target is: ' + getDistance())
  3424.                         print('Is at stockpile!');
  3425.                         walkToStart(logStockpileX + getRandomInt(-10,10), logStockpileY + getRandomInt(-10,10), 5);
  3426.                         getDirection();
  3427.                         g.mapRightClick(playerCoords.x + xDirection*1, playerCoords.y + yDirection*1);
  3428.                         sleep(second*5);
  3429.                         listOfLogs.pop();
  3430.                         targetLog = null;
  3431.                         sleep(second*2);
  3432.                         g.travelToHearthFire();
  3433.                         sleep(second*1);
  3434.                         g.waitForTaskToFinish();
  3435.                         hearthX = playerCoords.x;
  3436.                         hearthY = playerCoords.y;
  3437.                         holdingLog = false;
  3438.                     }
  3439.             }
  3440.             if(holdingLog == false && targetLog != null)
  3441.                 {
  3442.                     print('Walking to a log...');
  3443.                     walkToStart(targetLog.coords.x + getRandomInt(-15,15), targetLog.coords.y + getRandomInt(-15,15), 5);
  3444.                 }
  3445.             if(holdingLog && targetLog != null)
  3446.                 {
  3447.                     print('Walking to a stockpile...');
  3448.                     walkToStart(logStockpileX + getRandomInt(-10,10), logStockpileY + getRandomInt(-10,10), 5);
  3449.                     g.mapRightClick(logStockpileX, logStockpileY);
  3450.                     if(isStuck())
  3451.                         {
  3452.                             getDirection();
  3453.                             g.mapRightClick(playerCoords.x + xDirection*getRandomInt(20,40), playerCoords.y + yDirection*getRandomInt(20,40));
  3454.                         }
  3455.                 }
  3456.             print('Distance to target is: ' + getDistance())
  3457.  
  3458.            
  3459.         }
  3460. }
  3461.  
  3462. function areThereLogs()
  3463. {
  3464.     if(listOfLogs.length == 0)
  3465.     {
  3466.         return false;
  3467.     }
  3468.     else
  3469.     {
  3470.         return true;
  3471.     }
  3472. }
  3473.  
  3474. function getAllLogsOnMap()
  3475. {
  3476.     var mapObjects = g.getAllMapObjects();
  3477.    
  3478.     for (var i = 0; i < mapObjects.length; ++i)
  3479.     {
  3480.         var logObject = mapObjects[i];
  3481.         if(isLog(logObject))
  3482.         {
  3483.             listOfLogs.push(logObject);
  3484.         }  
  3485.     }
  3486.    
  3487. }
  3488.  
  3489. function findMoreLogs()
  3490. {
  3491.    
  3492. }
  3493. */
  3494.  
  3495. var lookForCurious = false;
  3496. var worldCheckerId = null;
  3497. var checkedBoughTrees = [];
  3498. var checkedBranchTrees = [];
  3499. var fullStockpiles = [];
  3500. var finishedTask = false;
  3501. var boughWorking = false;
  3502. var branchWorking = false;
  3503. var pickBoughs = false;
  3504. var pickBranches = false;
  3505. var previousLocation = null;
  3506. var storedPlayerX = 0;
  3507. var storedPlayerY = 0;
  3508.  
  3509. function onPorkGameLoaded() {
  3510.    
  3511.   checkMap();
  3512.  
  3513. }
  3514.  
  3515. /** It is fired when a foragable curio was found (once for each of them)
  3516.  * @param {Number} id ID of the curio
  3517.  * @param {String} name Name of the curio
  3518.  * @param {Object} coords Coordinates of the curio
  3519.  * @param {Number} coords.x x coordinate of the curio
  3520.  * @param {Number} coords.y y coordinate of the curio
  3521.  */
  3522. function onPorkCurioFound(id, name, coords) {
  3523.    
  3524.     if(lookForCurious) {
  3525.           if (g == null) {
  3526.             return;
  3527.           }
  3528.          
  3529.           print('Curio "' + name + '" found, trying to pick it...');
  3530.          
  3531.           while(g.getPlayerCoords().x != coords.x && g.getPlayerCoords.y != coords.y){
  3532.              
  3533.                if(lookForCurious) {
  3534.                    g.goTo(coords.x, coords.y);
  3535.                    sleep(1000);
  3536.          
  3537.                 }
  3538.                 else
  3539.                  {
  3540.                  break;
  3541.                  }
  3542.           }
  3543.           g.pickItem(id);
  3544.           sleep(5000);
  3545.          
  3546.           print('Picked ' + name + ".");
  3547.          
  3548.     }    
  3549.    
  3550. }
  3551.  
  3552. /** It is fired when a creature was encountered (once for each of them)
  3553.  * @param {Number} id ID of the creature
  3554.  * @param {String} name Name of the creature
  3555.  * @param {Object} coords Coordinates of the creature
  3556.  * @param {Number} coords.x x coordinate of the creature
  3557.  * @param {Number} coords.y y coordinate of the creature
  3558.  */
  3559. function onPorkCreatureFound(id, name, coords) {
  3560.   //Nothing atm.
  3561. }
  3562.  
  3563. /** It is fired when another player was encountered (once for each of them)
  3564.  * @param {Number} id ID of the player
  3565.  * @param {Boolean} isKin Indicates whether the player is in the kin list or not
  3566.  * @param {Object} coords Coordinates of the player
  3567.  * @param {Number} coords.x x coordinate of the creature
  3568.  * @param {Number} coords.y y coordinate of the creature
  3569.  */
  3570. function onPorkPlayerFound(id, isKin, coords) {
  3571.   //Nothing atm.
  3572. }
  3573.  
  3574. /** It is fired when the flower menu appears (the one that opens after right clicking an object)
  3575.  * @param {Array} options Available flower menu options
  3576.  */
  3577. function onPorkFlowerMenuOpen(options) {
  3578.    
  3579.     if(pickBoughs){
  3580.    
  3581.     var foundBough = false;
  3582.    
  3583.     for(var i = 0; i < options.length; i++) {
  3584.        
  3585.         if(options[i] == 'Take bough') {
  3586.            
  3587.             g.chooseFlowerMenuOption('Take bough');
  3588.            
  3589.             sleep(second*10);
  3590.            
  3591.             foundBough = true;
  3592.            
  3593.             finishedTask = true;
  3594.            
  3595.         }
  3596.        
  3597.     }
  3598.    
  3599.     if(!foundBough) {
  3600.        
  3601.         g.mapRightClick(g.getPlayerCoords().x, g.getPlayerCoords().y);
  3602.        
  3603.         g.chooseFlowerMenuOption(options[0]);
  3604.        
  3605.         g.goTo(g.getPlayerCoords().x + 1, g.getPlayerCoords().y + 1);
  3606.        
  3607.         finishedTask = true;
  3608.        
  3609.     }
  3610.    
  3611.     }
  3612.     else if(pickBranches){
  3613.        
  3614.         var foundBranch = false;
  3615.        
  3616.         for(var i = 0; i < options.length; i++) {
  3617.            
  3618.             if(options[i] == 'Take branch') {
  3619.                
  3620.                 g.chooseFlowerMenuOption('Take branch');
  3621.                
  3622.                 sleep(second*10);
  3623.                
  3624.                 foundBranch = true;
  3625.                
  3626.                 finishedTask = true;
  3627.                
  3628.             }
  3629.            
  3630.         }
  3631.        
  3632.         if(!foundBranch) {
  3633.            
  3634.             g.mapRightClick(g.getPlayerCoords().x, g.getPlayerCoords().y);
  3635.            
  3636.             g.chooseFlowerMenuOption(options[0]);
  3637.            
  3638.             g.goTo(g.getPlayerCoords().x + 1, g.getPlayerCoords().y + 1);
  3639.            
  3640.             finishedTask = true;
  3641.            
  3642.         }
  3643.        
  3644.         }
  3645.    
  3646. }
  3647.  
  3648. /** It is fired when the user enters a command in the console window
  3649.  * @param {String} input User command
  3650.  */
  3651. function onPorkUserInput(input) {
  3652.     if(input == 'findcurious') {
  3653.         if(lookForCurious) {
  3654.             lookForCurious = false;
  3655.             print('Curious Searched: Disabled');
  3656.         }
  3657.         else
  3658.         {
  3659.             lookForCurious = true;
  3660.             print('Curious Searched: Enabled');
  3661.         }
  3662.     }
  3663.     else if(input == 'pickboughs') {
  3664.         if(pickBoughs) {
  3665.             pickBoughs = false;
  3666.             print('Bough Picking: Disabled');
  3667.         }
  3668.         else
  3669.         {
  3670.             pickBoughs = true;
  3671.             print('Bough Picking: Enabled');
  3672.         }
  3673.     }
  3674.     else if(input == 'pickbranches') {
  3675.         if(pickBranches) {
  3676.             pickBranches = false;
  3677.             print('Branch Picking: Disabled');
  3678.         }
  3679.         else
  3680.         {
  3681.             pickBranches = true;
  3682.             print('Branch Picking: Enabled');
  3683.         }
  3684.     }
  3685.     else if(input == 'print inventory') {
  3686.        
  3687.         var inv = g.getInvItems();
  3688.        
  3689.         for(var index = 0; index < inv.length; index++) {
  3690.            
  3691.             print(inv[index]);
  3692.            
  3693.         }
  3694.        
  3695.     }
  3696. }
  3697.  
  3698. /** It is fired when a chat message received from another player
  3699.  * @param {String} chat Chat name
  3700.  * @param {String} from Sender's name (or '???' if it's unknown)
  3701.  * @param {String} msg Message
  3702.  */
  3703. function onPorkChatMessage(chat, from, msg) {
  3704.   // ignored
  3705. }
  3706.  
  3707. /** It is fired when a new object highlighted via ALT + LMB
  3708.  * @param {Object} obj Highlighted map object
  3709.  * @param {String} obj.name Basename of the map object's resource
  3710.  * @param {String} obj.fullName Full name of the map object's resource
  3711.  * @param {Number} obj.id Map object's ID
  3712.  * @param {Object} obj.coords Coordinates of the map object
  3713.  * @param {Number} obj.coords.x x coordinate of the map object
  3714.  * @param {Number} obj.coords.y y coordinate of the map object
  3715.  */
  3716. function onPorkMapObjectHighlight(obj) {
  3717.   // ignored
  3718. }
  3719.  
  3720. ///////////////////////
  3721. // User-defined functions
  3722. ///////////////////////
  3723.  
  3724. /** Starts autowalking timer that will move character x+50, y+50 every second */
  3725. function startPorkAutoWalking() {
  3726.     //Nothing
  3727. }
  3728.  
  3729. /** Stops autowalking timer */
  3730. function stopPorkAutoWalking() {
  3731.   //Nothing
  3732. }
  3733.  
  3734. /** Determines whether the specified animal is aggresive (NOTE that this function is incomplete)
  3735.  * @param {String} animal Name of the animal to check
  3736.  * @return {Boolean} true if the specified animal is aggressive or false otherwise
  3737.  */
  3738. function isPorkAggr(animal) {
  3739.     return false;
  3740. }
  3741.  
  3742. /** Returns a mental weight of the specified curio (NOTE that this function is incomplete)
  3743.  * @param {String} curioName Name of the curio
  3744.  * @return {Number} Mental weight of the specified curio
  3745.  */
  3746. function getPorkMentalWeight(curioName) {
  3747.   //Nothing.
  3748. }
  3749.  
  3750. function checkMap() {
  3751.  
  3752.     worldCheckId = setInterval(function() {
  3753.         if(g != null && !boughWorking) {
  3754.             pickBoughScript();
  3755.         }
  3756.         if(g != null && !branchWorking) {
  3757.             pickBranchScript();
  3758.         }
  3759.     }, second * 10);
  3760.    
  3761. }
  3762.  
  3763. function pickBoughScript() {
  3764.    
  3765.     if(pickBoughs) {
  3766.    
  3767.     boughWorking = true;
  3768.    
  3769.     var checked = ["alder",
  3770.                    "elm", "fir",
  3771.                    "spruce" ,"yew"];
  3772.    
  3773.     for(var i = 0; i < checked.length; i++) {
  3774.    
  3775.     var mapObjects = g.getMapObjects(checked[i]);
  3776.    
  3777.     print('Checking for ' + checked[i]);
  3778.    
  3779.     for(var index = 0; index < mapObjects.length ; index++) {
  3780.        
  3781.         if(pickBoughs) {
  3782.        
  3783.         var map = mapObjects[index];
  3784.        
  3785.         // - getMapObjects(name)
  3786.         //   Returns an array of map objects with the specified name (each of them has `name`, `fullName`, `id` and `coords` properties)
  3787.        
  3788.         var found = true;
  3789.        
  3790.         var invNotFull = true;
  3791.        
  3792.         if(g.getFreeCharInvCellsCount() >= 14) {
  3793.            
  3794.         }
  3795.         else
  3796.         {
  3797.             invNotFull = false;
  3798.         }
  3799.        
  3800.         if(invNotFull) {
  3801.        
  3802.         for(var x = 0; checkedBoughTrees.length < x; x++) {
  3803.                        
  3804.             if(checkedBoughTrees[x] == map.id) {
  3805.                
  3806.                 found = false;
  3807.                
  3808.             }
  3809.            
  3810.         }
  3811.        
  3812.         if(found) {
  3813.            
  3814.             //print('Found appropriate match.');
  3815.            
  3816.             // - mapObjectRightClick(id)
  3817.             //   Clicks an object with the specified ID via the right mouse button
  3818.             //   NOTE That you can't use this function for some specific objects (for example, tables -- use `openTable` function instead)
  3819.             //   Returns `true` on success or `false` otherwise
  3820.            
  3821.             var xBackup = map.coords.x;
  3822.            
  3823.             var yBackup = map.coords.y;
  3824.            
  3825.             var randomChangeX = getRandomInt(-10,10);
  3826.            
  3827.             var randomChangeY = getRandomInt(-10,10);
  3828.            
  3829.             var timesStuck = 0;
  3830.            
  3831.             var totalTimesStuck = 0;
  3832.            
  3833.             while(g.getPlayerCoords().x != xBackup + randomChangeX && g.getPlayerCoords().y != yBackup + randomChangeY) {
  3834.                
  3835.                 if((g.getPlayerCoords().x - (xBackup + randomChangeX)) < 5 && (g.getPlayerCoords().x - (xBackup + randomChangeX)) > -5 && (g.getPlayerCoords().y - (yBackup + randomChangeY)) < 5 && (g.getPlayerCoords().y - (yBackup + randomChangeY)) > -5) {
  3836.                    
  3837.                     break;
  3838.                    
  3839.                 }
  3840.                
  3841.                 if(!isPorkStuck()) {
  3842.                    
  3843.                 timesStuck = 0;
  3844.                
  3845.                 g.goTo(xBackup + randomChangeX, yBackup + randomChangeY);
  3846.                
  3847.                 //print('Going');
  3848.                
  3849.                 }
  3850.                 else
  3851.                 {
  3852.                
  3853.                 timesStuck++;
  3854.                
  3855.                 totalTimesStuck++;
  3856.                
  3857.                 if(totalTimesStuck > 20) {
  3858.                    
  3859.                     print('Stuck too many times... Skipping.');
  3860.                    
  3861.                     print(map.name + ' with id of ' + map.id + ' was skipped, as it could not be pathed to.');
  3862.                    
  3863.                     finishedTask = true;
  3864.                    
  3865.                     break;
  3866.                    
  3867.                 }
  3868.                
  3869.                 print('Stuck');
  3870.                
  3871.                 if(timesStuck < 4) {
  3872.                    
  3873.                     randomChangeX = getRandomInt(-15,15);
  3874.                    
  3875.                     randomChangeY = getRandomInt(-15,15);
  3876.                    
  3877.                     g.goTo(xBackup + randomChangeX, yBackup + randomChangeY);
  3878.                    
  3879.                     if(g.getPlayerCoords().x == xBackup + randomChangeX && g.getPlayerCoords().y == yBackup + randomChangeY) {
  3880.                        
  3881.                         break;
  3882.                        
  3883.                     }
  3884.                    
  3885.                 }
  3886.                 else
  3887.                 {
  3888.                    
  3889.                     randomChangeX = getRandomInt(-25,25);
  3890.                    
  3891.                     randomChangeY = getRandomInt(-25,25);
  3892.                    
  3893.                     g.goTo(g.getPlayerCoords().x + randomChangeX, g.getPlayerCoords().y + randomChangeY);
  3894.                    
  3895.                     randomChangeX = getRandomInt(-15,15);
  3896.                    
  3897.                     randomChangeY = getRandomInt(-15,15);
  3898.                    
  3899.                 }
  3900.                
  3901.                 }
  3902.            
  3903.                 sleep(second * 1);
  3904.                
  3905.             }
  3906.            
  3907.             g.mapRightClick(g.getPlayerCoords().x, g.getPlayerCoords().y);
  3908.            
  3909.             //print('Found tree');
  3910.            
  3911.             sleep(second);
  3912.            
  3913.             g.mapObjectRightClick(map.id);
  3914.            
  3915.             var timesWaited = 0;
  3916.            
  3917.             while(!finishedTask) {
  3918.                
  3919.                 print('Waiting');
  3920.                
  3921.                 timesWaited++;
  3922.                
  3923.                 if(timesWaited > 20) {
  3924.                    
  3925.                     break;
  3926.                    
  3927.                 }
  3928.                 else
  3929.                 {
  3930.                
  3931.                 sleep(second);
  3932.                
  3933.                 }
  3934.                
  3935.             }
  3936.            
  3937.             finishedTask = false;
  3938.            
  3939.             //print('Finished');
  3940.            
  3941.             g.goTo(g.getPlayerCoords().x,g.getPlayerCoords().y);
  3942.            
  3943.             checkedBoughTrees[checkedBoughTrees.length] = map.id;
  3944.            
  3945.         }
  3946.        
  3947.         }
  3948.         else
  3949.         {
  3950.            
  3951.             print('Inventory needs emptying');
  3952.            
  3953.             previousCoords = g.getPlayerCoords();
  3954.             hearthHome();
  3955.             g.travelToHearthFire();
  3956.            
  3957.             sleep(second*7);
  3958.            
  3959.             index--;
  3960.            
  3961.             index = Math.max(0, index);
  3962.            
  3963.             g.goTo(g.getPlayerCoords().x,g.getPlayerCoords().y);
  3964.            
  3965.             sleep(1000);
  3966.            
  3967.             var stockpiles = g.getMapObjects('stockpile-bough');
  3968.            
  3969.             print('Checking for stockpile-bough');
  3970.            
  3971.             for(var ind = 0; ind < stockpiles.length ; ind++) {
  3972.                
  3973.                 var stockpile = stockpiles[ind];
  3974.                
  3975.                 var stockFound = true;
  3976.                
  3977.                 for(var full = 0; full < fullStockpiles.length; full++) {
  3978.                    
  3979.                     if(fullStockpiles[i] == stockpile.id) {
  3980.                        
  3981.                         stockFound = false;
  3982.                        
  3983.                     }
  3984.                    
  3985.                 }
  3986.                
  3987.                 if(stockFound) {
  3988.                    
  3989.                     var xBackups = stockpile.coords.x;
  3990.                    
  3991.                     var yBackups = stockpile.coords.y;
  3992.                    
  3993.                     var randomChangeXs = getRandomInt(-20,20);
  3994.                    
  3995.                     var randomChangeYs = getRandomInt(-20,20);
  3996.                    
  3997.                     var timesStucks = 0;
  3998.                    
  3999.                     var totalTimesStucks = 0;
  4000.                    
  4001.                     while(g.getPlayerCoords().x != xBackups + randomChangeXs && g.getPlayerCoords().y != yBackups + randomChangeYs) {
  4002.                        
  4003.                         if((g.getPlayerCoords().x - (xBackups + randomChangeXs)) < 5 && (g.getPlayerCoords().x - (xBackups + randomChangeXs)) > -5 && (g.getPlayerCoords().y - (yBackups + randomChangeYs)) < 5 && (g.getPlayerCoords().y - (yBackups + randomChangeYs)) > -5) {
  4004.                            
  4005.                             break;
  4006.                            
  4007.                         }
  4008.                        
  4009.                         if(!isPorkStuck()) {
  4010.                            
  4011.                         timesStucks = 0;
  4012.                        
  4013.                         g.goTo(xBackups + randomChangeXs, yBackups + randomChangeYs);
  4014.                        
  4015.                         //print('Going to stockpile');
  4016.                        
  4017.                         }
  4018.                         else
  4019.                         {
  4020.                        
  4021.                         timesStucks++;
  4022.                        
  4023.                         totalTimesStucks++;
  4024.                        
  4025.                         if(totalTimesStucks > 30) {
  4026.                            
  4027.                             print('Stuck too many times... Skipping.');
  4028.                            
  4029.                             break;
  4030.                            
  4031.                         }
  4032.                        
  4033.                         //print('Stuck');
  4034.                        
  4035.                         if(timesStucks < 4) {
  4036.                            
  4037.                             randomChangeXs = getRandomInt(-20,20);
  4038.                            
  4039.                             randomChangeYs = getRandomInt(-20,20);
  4040.                            
  4041.                             g.goTo(xBackups + randomChangeXs, yBackups + randomChangeYs);
  4042.                            
  4043.                             if(g.getPlayerCoords().x == xBackups + randomChangeXs && g.getPlayerCoords().y == yBackups + randomChangeYs) {
  4044.                                
  4045.                                 break;
  4046.                                
  4047.                             }
  4048.                            
  4049.                         }
  4050.                         else
  4051.                         {
  4052.                            
  4053.                             randomChangeXs = getRandomInt(-25,25);
  4054.                            
  4055.                             randomChangeYs = getRandomInt(-25,25);
  4056.                            
  4057.                             g.goTo(g.getPlayerCoords().x + randomChangeXs, g.getPlayerCoords().y + randomChangeYs);
  4058.                            
  4059.                             randomChangeXs = getRandomInt(-20,20);
  4060.                            
  4061.                             randomChangeYs = getRandomInt(-20,20);
  4062.                            
  4063.                         }
  4064.                        
  4065.                         }
  4066.                    
  4067.                         sleep(second * 1);
  4068.                        
  4069.                     }
  4070.                    
  4071.                     g.mapRightClick(g.getPlayerCoords().x, g.getPlayerCoords().y);
  4072.                    
  4073.                     print('Found stockpile.');
  4074.                    
  4075.                     sleep(second);
  4076.                    
  4077.                     g.mapObjectRightClick(stockpile.id);
  4078.                    
  4079.                     sleep(second*5);
  4080.                    
  4081.                     var stockpileInfo = g.getStockpileInfo();
  4082.                    
  4083.                     if(stockpileInfo != null) {
  4084.                        
  4085.                         print('Unloading inventory');
  4086.                        
  4087.                         var items = g.getInvItems();
  4088.                        
  4089.                         var total = stockpileInfo.total;
  4090.                        
  4091.                         var used = stockpileInfo.used;
  4092.                        
  4093.                         for(var z = 0; z < items.length; z++) {
  4094.                            
  4095.                             for(var boughCheck = 0; boughCheck < checked.length; boughCheck++) {
  4096.                                
  4097.                                 if(items[z] == ('bough-' + checked[boughCheck])) {
  4098.                                    
  4099.                                     if(used < total) {
  4100.                                        
  4101.                                         sleep(second);
  4102.                                        
  4103.                                         g.takeItem(items[z]);
  4104.                                        
  4105.                                         sleep(second);
  4106.                                        
  4107.                                         g.useItemFromHandOnObject(stockpile.id);
  4108.                                        
  4109.                                         sleep(second * 0.5);
  4110.                                        
  4111.                                         used++;
  4112.                                        
  4113.                                     }
  4114.                                     else
  4115.                                     {
  4116.                                        
  4117.                                         fullStockpiles[fullStockpiles.length] = stockpile.id;
  4118.                                        
  4119.                                     }
  4120.                                    
  4121.                                     break;
  4122.                                    
  4123.                                 }
  4124.                                
  4125.                             }
  4126.                            
  4127.                         }
  4128.                        
  4129.                     }
  4130.                     else
  4131.                     {
  4132.                        
  4133.                         var timesTried = 0;
  4134.                        
  4135.                         var success = false;
  4136.                        
  4137.                         while(timesTried < 10) {
  4138.                            
  4139.                             timesTried++;
  4140.                            
  4141.                             g.mapObjectRightClick(stockpile.id);
  4142.                            
  4143.                             sleep(second);
  4144.                            
  4145.                             if(g.getStockpileInfo() != null) {
  4146.                                
  4147.                                 success = true;
  4148.                                
  4149.                             }
  4150.                            
  4151.                         }
  4152.                        
  4153.                         if(success) {
  4154.                            
  4155.                             stockpileInfo = g.getStockpileInfo();
  4156.                            
  4157.                             //print('Unloading inventory');
  4158.                            
  4159.                             var items = g.getInvItems();
  4160.                            
  4161.                             var total = stockpileInfo.total;
  4162.                            
  4163.                             var used = stockpileInfo.used;
  4164.                            
  4165.                             for(var z = 0; z < items.length; z++) {
  4166.                                
  4167.                                 for(var boughCheck = 0; boughCheck < checked.length; boughCheck++) {
  4168.                                    
  4169.                                     if(items[z] == ('bough-' + checked[boughCheck])) {
  4170.                                        
  4171.                                         if(used < total) {
  4172.                                            
  4173.                                             sleep(second);
  4174.                                            
  4175.                                             g.takeItem(items[z]);
  4176.                                            
  4177.                                             sleep(second);
  4178.                                            
  4179.                                             g.useItemFromHandOnObject(stockpile.id);
  4180.                                            
  4181.                                             sleep(second * 0.5);
  4182.                                            
  4183.                                             used++;
  4184.                                            
  4185.                                         }
  4186.                                         else
  4187.                                         {
  4188.                                            
  4189.                                             fullStockpiles[fullStockpiles.length] = stockpile.id;
  4190.                                            
  4191.                                         }
  4192.                                        
  4193.                                         break;
  4194.                                        
  4195.                                     }
  4196.                                    
  4197.                                 }
  4198.                                
  4199.                             }
  4200.                            
  4201.                         }
  4202.                        
  4203.                     }
  4204.                    
  4205.                     print('Finished with stockpile');
  4206.                    
  4207.                 }
  4208.                
  4209.             }
  4210.            
  4211.             if(g.getFreeCharInvCellsCount() >= 16) {
  4212.                
  4213.                 boughWorking = false;
  4214.  
  4215.             }
  4216.             else
  4217.             {
  4218.                 invNotFull = false;
  4219.                
  4220.                 boughWorking = false;
  4221.                
  4222.                 pickBoughs = false;
  4223.  
  4224.             }
  4225.            
  4226.             while(g.getPlayerCoords().x != previousCoords.x && g.getPlayerCoords().y != previousCoords.y) {
  4227.                
  4228.                 var randomChangeXss = getRandomInt(-10,10);
  4229.                
  4230.                 var randomChangeYss = getRandomInt(-10,10);
  4231.                
  4232.                 var timesStuckz = 0;
  4233.                
  4234.                 var totalTimesStuckz = 0;
  4235.                
  4236.                 if(!isPorkStuck()) {
  4237.                    
  4238.                     timesStuckz = 0;
  4239.                    
  4240.                     g.goTo(previousCoords.x + randomChangeXss, previousCoords.y  + randomChangeYss);
  4241.                    
  4242.                     print('Going to previous location');
  4243.                    
  4244.                     }
  4245.                     else
  4246.                     {
  4247.                    
  4248.                     timesStuckz++;
  4249.                    
  4250.                     totalTimesStuckz++;
  4251.                    
  4252.                     if(totalTimesStuckz > 50) {
  4253.                        
  4254.                         print('Stuck too many times... Skipping.');
  4255.                        
  4256.                         break;
  4257.                        
  4258.                     }
  4259.                    
  4260.                     //print('Stuck');
  4261.                    
  4262.                     if(timesStuckz < 4) {
  4263.                        
  4264.                         randomChangeXss = getRandomInt(-20,20);
  4265.                        
  4266.                         randomChangeYss = getRandomInt(-20,20);
  4267.                        
  4268.                         g.goTo(previousCoords.x + randomChangeXss, previousCoords.y + randomChangeYss);
  4269.                        
  4270.                         if(g.getPlayerCoords().x == previousCoords.x + randomChangeXss && g.getPlayerCoords().y == previousCoords.y + randomChangeYss) {
  4271.                            
  4272.                             break;
  4273.                            
  4274.                         }
  4275.                        
  4276.                     }
  4277.                     else
  4278.                     {
  4279.                        
  4280.                         randomChangeXs = getRandomInt(-25,25);
  4281.                        
  4282.                         randomChangeYs = getRandomInt(-25,25);
  4283.                        
  4284.                         g.goTo(g.getPlayerCoords().x + randomChangeXs, g.getPlayerCoords().y + randomChangeYs);
  4285.                        
  4286.                         randomChangeXs = getRandomInt(-20,20);
  4287.                        
  4288.                         randomChangeYs = getRandomInt(-20,20);
  4289.                        
  4290.                     }
  4291.                    
  4292.                     }
  4293.                
  4294.                     sleep(second * 1);
  4295.                
  4296.             }
  4297.                            
  4298.         }
  4299.        
  4300.         }
  4301.         else
  4302.         {
  4303.            
  4304.             boughWorking = false;
  4305.            
  4306.         }
  4307.        
  4308.     }
  4309.    
  4310.     }
  4311.    
  4312.     boughWorking = false;
  4313.    
  4314.     pickBoughs = false;
  4315.    
  4316.     }
  4317.     else
  4318.     {
  4319.         boughWorking = false;
  4320.        
  4321.         pickBoughs = false;
  4322.        
  4323.     }
  4324.    
  4325. }
  4326.  
  4327. function pickBranchScript() {
  4328.    
  4329.     if(pickBranches) {
  4330.    
  4331.     branchWorking = true;
  4332.    
  4333.     var checked = ["alder", "appletree", "ash", "aspen", "baywillow", "beech",
  4334.                    "birch", "birdcherrytree" ,"buckthorn" ,"cedar" ,"cherry" ,"chestnuttree",
  4335.                    "conkertree", "corkoak", "crabappletree", "cypress", "elm", "fir", "goldenchain", "hazel",
  4336.                    "hornbeam" ,"juniper" ,"kingsoak" ,"larch" ,"laurel" ,"linden" ,"maple",
  4337.                    "mulberry" ,"oak" ,"olivetree" ,"peatree" ,"pine" ,"planetree" ,"plumtree",
  4338.                    "poplar" ," rowan" ,"sallow" ,"spruce" ,"sweetgum" ,"walnuttree" ,"whitebeam",
  4339.                    "willow" ,"yew"];
  4340.    
  4341.     for(var i = 0; i < checked.length; i++) {
  4342.    
  4343.     var mapObjects = g.getMapObjects(checked[i]);
  4344.    
  4345.     //print('Checking for ' + checked[i]);
  4346.    
  4347.     for(var index = 0; index < mapObjects.length ; index++) {
  4348.        
  4349.         if(pickBranches) {
  4350.        
  4351.         var map = mapObjects[index];
  4352.        
  4353.         // - getMapObjects(name)
  4354.         //   Returns an array of map objects with the specified name (each of them has `name`, `fullName`, `id` and `coords` properties)
  4355.        
  4356.         var found = true;
  4357.        
  4358.         var invNotFull = true;
  4359.        
  4360.         if(g.getFreeCharInvCellsCount() >= 16) {
  4361.            
  4362.         }
  4363.         else
  4364.         {
  4365.             invNotFull = false;
  4366.         }
  4367.        
  4368.         if(invNotFull) {
  4369.        
  4370.         for(var x = 0; checkedBranchTrees.length < x; x++) {
  4371.                        
  4372.             if(checkedBranchTrees[x] == map.id) {
  4373.                
  4374.                 found = false;
  4375.                
  4376.             }
  4377.            
  4378.         }
  4379.        
  4380.         if(found) {
  4381.            
  4382.             print('Found appropriate match.');
  4383.            
  4384.             // - mapObjectRightClick(id)
  4385.             //   Clicks an object with the specified ID via the right mouse button
  4386.             //   NOTE That you can't use this function for some specific objects (for example, tables -- use `openTable` function instead)
  4387.             //   Returns `true` on success or `false` otherwise
  4388.            
  4389.             var xBackup = map.coords.x;
  4390.            
  4391.             var yBackup = map.coords.y;
  4392.            
  4393.             var randomChangeX = getRandomInt(-10,10);
  4394.            
  4395.             var randomChangeY = getRandomInt(-10,10);
  4396.            
  4397.             var timesStuck = 0;
  4398.            
  4399.             var totalTimesStuck = 0;
  4400.            
  4401.             while(g.getPlayerCoords().x != xBackup + randomChangeX && g.getPlayerCoords().y != yBackup + randomChangeY) {
  4402.                
  4403.                 if((g.getPlayerCoords().x - (xBackup + randomChangeX)) < 5 && (g.getPlayerCoords().x - (xBackup + randomChangeX)) > -5 && (g.getPlayerCoords().y - (yBackup + randomChangeY)) < 5 && (g.getPlayerCoords().y - (yBackup + randomChangeY)) > -5) {
  4404.                    
  4405.                     break;
  4406.                    
  4407.                 }
  4408.                
  4409.                 if(!isPorkStuck()) {
  4410.                    
  4411.                 timesStuck = 0;
  4412.                
  4413.                 g.goTo(xBackup + randomChangeX, yBackup + randomChangeY);
  4414.                
  4415.                 //print('Going');
  4416.                
  4417.                 }
  4418.                 else
  4419.                 {
  4420.                
  4421.                 timesStuck++;
  4422.                
  4423.                 totalTimesStuck++;
  4424.                
  4425.                 if(totalTimesStuck > 20) {
  4426.                    
  4427.                     print('Stuck too many times... Skipping.');
  4428.                    
  4429.                     print(map.name + ' with id of ' + map.id + ' was skipped, as it could not be pathed to.');
  4430.                    
  4431.                     finishedTask = true;
  4432.                    
  4433.                     break;
  4434.                    
  4435.                 }
  4436.                
  4437.                 //print('Stuck');
  4438.                
  4439.                 if(timesStuck < 4) {
  4440.                    
  4441.                     randomChangeX = getRandomInt(-15,15);
  4442.                    
  4443.                     randomChangeY = getRandomInt(-15,15);
  4444.                    
  4445.                     g.goTo(xBackup + randomChangeX, yBackup + randomChangeY);
  4446.                    
  4447.                     if(g.getPlayerCoords().x == xBackup + randomChangeX && g.getPlayerCoords().y == yBackup + randomChangeY) {
  4448.                        
  4449.                         break;
  4450.                        
  4451.                     }
  4452.                    
  4453.                 }
  4454.                 else
  4455.                 {
  4456.                    
  4457.                     randomChangeX = getRandomInt(-25,25);
  4458.                    
  4459.                     randomChangeY = getRandomInt(-25,25);
  4460.                    
  4461.                     g.goTo(g.getPlayerCoords().x + randomChangeX, g.getPlayerCoords().y + randomChangeY);
  4462.                    
  4463.                     randomChangeX = getRandomInt(-15,15);
  4464.                    
  4465.                     randomChangeY = getRandomInt(-15,15);
  4466.                    
  4467.                 }
  4468.                
  4469.                 }
  4470.            
  4471.                 sleep(second * 1);
  4472.                
  4473.             }
  4474.            
  4475.             g.mapRightClick(g.getPlayerCoords().x, g.getPlayerCoords().y);
  4476.            
  4477.             print('Found tree');
  4478.            
  4479.             sleep(second);
  4480.            
  4481.             g.mapObjectRightClick(map.id);
  4482.            
  4483.             var timesWaited = 0;
  4484.            
  4485.             while(!finishedTask) {
  4486.                
  4487.                 //print('Waiting');
  4488.                
  4489.                 timesWaited++;
  4490.                
  4491.                 if(timesWaited > 20) {
  4492.                    
  4493.                     break;
  4494.                    
  4495.                 }
  4496.                 else
  4497.                 {
  4498.                
  4499.                 sleep(second);
  4500.                
  4501.                 }
  4502.                
  4503.             }
  4504.            
  4505.             finishedTask = false;
  4506.            
  4507.             print('Finished');
  4508.            
  4509.             g.goTo(g.getPlayerCoords().x,g.getPlayerCoords().y);
  4510.            
  4511.             checkedBranchTrees[checkedBranchTrees.length] = map.id;
  4512.            
  4513.         }
  4514.        
  4515.         }
  4516.         else
  4517.         {
  4518.            
  4519.             print('Inventory needs emptying');
  4520.            
  4521.             previousCoords = g.getPlayerCoords();
  4522.             hearthHome();
  4523.             g.travelToHearthFire();
  4524.            
  4525.             sleep(second*7);
  4526.            
  4527.             index--;
  4528.            
  4529.             index = Math.max(0, index);
  4530.            
  4531.             g.goTo(g.getPlayerCoords().x,g.getPlayerCoords().y);
  4532.            
  4533.             sleep(1000);
  4534.            
  4535.             var stockpiles = g.getMapObjects('stockpile-branch');
  4536.            
  4537.             print('Checking for stockpile-branch');
  4538.            
  4539.             for(var ind = 0; ind < stockpiles.length ; ind++) {
  4540.                
  4541.                 var stockpile = stockpiles[ind];
  4542.                
  4543.                 var stockFound = true;
  4544.                
  4545.                 for(var full = 0; full < fullStockpiles.length; full++) {
  4546.                    
  4547.                     if(fullStockpiles[i] == stockpile.id) {
  4548.                        
  4549.                         stockFound = false;
  4550.                        
  4551.                     }
  4552.                    
  4553.                 }
  4554.                
  4555.                 if(stockFound) {
  4556.                    
  4557.                     var xBackups = stockpile.coords.x;
  4558.                    
  4559.                     var yBackups = stockpile.coords.y;
  4560.                    
  4561.                     var randomChangeXs = getRandomInt(-20,20);
  4562.                    
  4563.                     var randomChangeYs = getRandomInt(-20,20);
  4564.                    
  4565.                     var timesStucks = 0;
  4566.                    
  4567.                     var totalTimesStucks = 0;
  4568.                    
  4569.                     while(g.getPlayerCoords().x != xBackups + randomChangeXs && g.getPlayerCoords().y != yBackups + randomChangeYs) {
  4570.                        
  4571.                         if((g.getPlayerCoords().x - (xBackups + randomChangeXs)) < 5 && (g.getPlayerCoords().x - (xBackups + randomChangeXs)) > -5 && (g.getPlayerCoords().y - (yBackups + randomChangeYs)) < 5 && (g.getPlayerCoords().y - (yBackups + randomChangeYs)) > -5) {
  4572.                            
  4573.                             break;
  4574.                            
  4575.                         }
  4576.                        
  4577.                         if(!isPorkStuck()) {
  4578.                            
  4579.                         timesStucks = 0;
  4580.                        
  4581.                         g.goTo(xBackups + randomChangeXs, yBackups + randomChangeYs);
  4582.                        
  4583.                         //print('Going to stockpile');
  4584.                        
  4585.                         }
  4586.                         else
  4587.                         {
  4588.                        
  4589.                         timesStucks++;
  4590.                        
  4591.                         totalTimesStucks++;
  4592.                        
  4593.                         if(totalTimesStucks > 30) {
  4594.                            
  4595.                             print('Stuck too many times... Skipping.');
  4596.                            
  4597.                             break;
  4598.                            
  4599.                         }
  4600.                        
  4601.                         //print('Stuck');
  4602.                        
  4603.                         if(timesStucks < 4) {
  4604.                            
  4605.                             randomChangeXs = getRandomInt(-20,20);
  4606.                            
  4607.                             randomChangeYs = getRandomInt(-20,20);
  4608.                            
  4609.                             g.goTo(xBackups + randomChangeXs, yBackups + randomChangeYs);
  4610.                            
  4611.                             if(g.getPlayerCoords().x == xBackups + randomChangeXs && g.getPlayerCoords().y == yBackups + randomChangeYs) {
  4612.                                
  4613.                                 break;
  4614.                                
  4615.                             }
  4616.                            
  4617.                         }
  4618.                         else
  4619.                         {
  4620.                            
  4621.                             randomChangeXs = getRandomInt(-25,25);
  4622.                            
  4623.                             randomChangeYs = getRandomInt(-25,25);
  4624.                            
  4625.                             g.goTo(g.getPlayerCoords().x + randomChangeXs, g.getPlayerCoords().y + randomChangeYs);
  4626.                            
  4627.                             randomChangeXs = getRandomInt(-20,20);
  4628.                            
  4629.                             randomChangeYs = getRandomInt(-20,20);
  4630.                            
  4631.                         }
  4632.                        
  4633.                         }
  4634.                    
  4635.                         sleep(second * 1);
  4636.                        
  4637.                     }
  4638.                    
  4639.                     g.mapRightClick(g.getPlayerCoords().x, g.getPlayerCoords().y);
  4640.                    
  4641.                     print('Found stockpile.');
  4642.                    
  4643.                     sleep(second);
  4644.                    
  4645.                     g.mapObjectRightClick(stockpile.id);
  4646.                    
  4647.                     sleep(second*5);
  4648.                    
  4649.                     var stockpileInfo = g.getStockpileInfo();
  4650.                    
  4651.                     if(stockpileInfo != null) {
  4652.                        
  4653.                         print('Unloading inventory');
  4654.                        
  4655.                         var items = g.getInvItems();
  4656.                        
  4657.                         var total = stockpileInfo.total;
  4658.                        
  4659.                         var used = stockpileInfo.used;
  4660.                        
  4661.                         for(var z = 0; z < items.length; z++) {
  4662.                            
  4663.                             for(var boughCheck = 0; boughCheck < checked.length; boughCheck++) {
  4664.                                
  4665.                                 if(items[z] == 'branch') {
  4666.                                    
  4667.                                     if(used < total) {
  4668.                                        
  4669.                                         sleep(second);
  4670.                                        
  4671.                                         g.takeItem(items[z]);
  4672.                                        
  4673.                                         sleep(second);
  4674.                                        
  4675.                                         g.useItemFromHandOnObject(stockpile.id);
  4676.                                        
  4677.                                         sleep(second * 0.5);
  4678.                                        
  4679.                                         used++;
  4680.                                        
  4681.                                     }
  4682.                                     else
  4683.                                     {
  4684.                                        
  4685.                                         fullStockpiles[fullStockpiles.length] = stockpile.id;
  4686.                                        
  4687.                                     }
  4688.                                    
  4689.                                     break;
  4690.                                    
  4691.                                 }
  4692.                                
  4693.                             }
  4694.                            
  4695.                         }
  4696.                        
  4697.                     }
  4698.                     else
  4699.                     {
  4700.                        
  4701.                         var timesTried = 0;
  4702.                        
  4703.                         var success = false;
  4704.                        
  4705.                         while(timesTried < 10) {
  4706.                            
  4707.                             timesTried++;
  4708.                            
  4709.                             g.mapObjectRightClick(stockpile.id);
  4710.                            
  4711.                             sleep(second);
  4712.                            
  4713.                             if(g.getStockpileInfo() != null) {
  4714.                                
  4715.                                 success = true;
  4716.                                
  4717.                             }
  4718.                            
  4719.                         }
  4720.                        
  4721.                         if(success) {
  4722.                            
  4723.                             stockpileInfo = g.getStockpileInfo();
  4724.                            
  4725.                             print('Unloading inventory');
  4726.                            
  4727.                             var items = g.getInvItems();
  4728.                            
  4729.                             var total = stockpileInfo.total;
  4730.                            
  4731.                             var used = stockpileInfo.used;
  4732.                            
  4733.                             for(var z = 0; z < items.length; z++) {
  4734.                                
  4735.                                 for(var boughCheck = 0; boughCheck < checked.length; boughCheck++) {
  4736.                                    
  4737.                                     if(items[z] == 'branch') {
  4738.                                        
  4739.                                         if(used < total) {
  4740.                                            
  4741.                                             sleep(second);
  4742.                                            
  4743.                                             g.takeItem(items[z]);
  4744.                                            
  4745.                                             sleep(second);
  4746.                                            
  4747.                                             g.useItemFromHandOnObject(stockpile.id);
  4748.                                            
  4749.                                             sleep(second * 0.5);
  4750.                                            
  4751.                                             used++;
  4752.                                            
  4753.                                         }
  4754.                                         else
  4755.                                         {
  4756.                                            
  4757.                                             fullStockpiles[fullStockpiles.length] = stockpile.id;
  4758.                                            
  4759.                                         }
  4760.                                        
  4761.                                         break;
  4762.                                        
  4763.                                     }
  4764.                                    
  4765.                                 }
  4766.                                
  4767.                             }
  4768.                            
  4769.                         }
  4770.                        
  4771.                     }
  4772.                    
  4773.                     print('Finished with stockpile');
  4774.                    
  4775.                 }
  4776.                
  4777.             }
  4778.            
  4779.             if(g.getFreeCharInvCellsCount() >= 16) {
  4780.                
  4781.                 branchWorking = false;
  4782.  
  4783.             }
  4784.             else
  4785.             {
  4786.                 invNotFull = false;
  4787.                
  4788.                 branchWorking = false;
  4789.                
  4790.                 pickBranches = false;
  4791.  
  4792.             }
  4793.            
  4794.             while(g.getPlayerCoords().x != previousCoords.x && g.getPlayerCoords().y != previousCoords.y) {
  4795.                
  4796.                 var randomChangeXss = getRandomInt(-10,10);
  4797.                
  4798.                 var randomChangeYss = getRandomInt(-10,10);
  4799.                
  4800.                 var timesStuckz = 0;
  4801.                
  4802.                 var totalTimesStuckz = 0;
  4803.                
  4804.                 if(!isPorkStuck()) {
  4805.                    
  4806.                     timesStuckz = 0;
  4807.                    
  4808.                     g.goTo(previousCoords.x + randomChangeXss, previousCoords.y  + randomChangeYss);
  4809.                    
  4810.                     print('Going to previous location');
  4811.                    
  4812.                     }
  4813.                     else
  4814.                     {
  4815.                    
  4816.                     timesStuckz++;
  4817.                    
  4818.                     totalTimesStuckz++;
  4819.                    
  4820.                     if(totalTimesStuckz > 50) {
  4821.                        
  4822.                         print('Stuck too many times... Skipping.');
  4823.                        
  4824.                         break;
  4825.                        
  4826.                     }
  4827.                    
  4828.                     //print('Stuck');
  4829.                    
  4830.                     if(timesStuckz < 4) {
  4831.                        
  4832.                         randomChangeXss = getRandomInt(-20,20);
  4833.                        
  4834.                         randomChangeYss = getRandomInt(-20,20);
  4835.                        
  4836.                         g.goTo(previousCoords.x + randomChangeXss, previousCoords.y + randomChangeYss);
  4837.                        
  4838.                         if(g.getPlayerCoords().x == previousCoords.x + randomChangeXss && g.getPlayerCoords().y == previousCoords.y + randomChangeYss) {
  4839.                            
  4840.                             break;
  4841.                            
  4842.                         }
  4843.                        
  4844.                     }
  4845.                     else
  4846.                     {
  4847.                        
  4848.                         randomChangeXs = getRandomInt(-25,25);
  4849.                        
  4850.                         randomChangeYs = getRandomInt(-25,25);
  4851.                        
  4852.                         g.goTo(g.getPlayerCoords().x + randomChangeXs, g.getPlayerCoords().y + randomChangeYs);
  4853.                        
  4854.                         randomChangeXs = getRandomInt(-20,20);
  4855.                        
  4856.                         randomChangeYs = getRandomInt(-20,20);
  4857.                        
  4858.                     }
  4859.                    
  4860.                     }
  4861.                
  4862.                     sleep(second * 1);
  4863.                
  4864.             }
  4865.                            
  4866.         }
  4867.        
  4868.         }
  4869.         else
  4870.         {
  4871.            
  4872.             branchWorking = false;
  4873.            
  4874.         }
  4875.        
  4876.     }
  4877.    
  4878.     }
  4879.    
  4880.     branchWorking = false;
  4881.    
  4882.     pickBranches = false;
  4883.    
  4884.     }
  4885.     else
  4886.     {
  4887.         branchWorking = false;
  4888.        
  4889.         pickBranches = false;
  4890.        
  4891.     }
  4892.    
  4893. }
  4894.  
  4895. function isPorkStuck() {
  4896.    
  4897.     var playerCoords = g.getPlayerCoords();
  4898.    
  4899.     if (storedPlayerX == playerCoords.x && storedPlayerY == playerCoords.y) {
  4900.        
  4901.         storedPlayerX = playerCoords.x;
  4902.         storedPlayerY = playerCoords.y;
  4903.        
  4904.         return true;
  4905.        
  4906.     } else {
  4907.        
  4908.         storedPlayerX = playerCoords.x;
  4909.         storedPlayerY = playerCoords.y;
  4910.        
  4911.         return false;
  4912.        
  4913.     }
  4914.  
  4915. }
Advertisement
Add Comment
Please, Sign In to add comment