diff --git a/twitch/chatguessr.js b/twitch/chatguessr.js index fec3bb2..5273db6 100644 --- a/twitch/chatguessr.js +++ b/twitch/chatguessr.js @@ -1,25 +1,42 @@ +const GameHelper = require('./helpers/cg-gh.js') + (function() { - var isOpen = false, - guesses = {}; + var isOpen = $.getSetIniDbBoolean('cgstatus', 'isOpen', false), + seed = {}, + guesses = { + '1':[ + {user:'Alpha',location:'0,0',distance:5,score:2,streak:0}, + {user:'Beta',location:'5,0',distance:100,score:3,streak:0}, + {user:'Charlie',location:'6,6',distance:1000,score:0,streak:0}, + {user:'Delta',location:'42,6',distance:1,score:5,streak:1} + ], + '2':[ + + ], + }; + + function dbSetSeed(id) { + $.inidb.SetBoolean("chatguessr", "isOpen", "", open); + isOpen = open; + } - function DBsetOpen(open) { + function dbSetOpen(open) { $.inidb.SetBoolean("chatguessr", "isOpen", "", open); isOpen = open; sendData('status',open); } - - function DBClearG() { + function dbClearGuesses() { guesses = {}; $.inidb.SetString("chatguessr", "guesses", JSON.stringify(guesses)); sendData('guesses',guesses); } - function DBAddG(user,position) { + function dbAddGuess(user,position) { if(guesses[user] && guesses[user].length > 0){ }else if(isCoordinates(position)){ guesses[user] = position; $.inidb.SetString("chatguessr", "guesses", JSON.stringify(guesses)); - sendData('guesses',guesses); + sendData('guesses',JSON.stringify(guesses)); } } @@ -46,29 +63,37 @@ if (command.equalsIgnoreCase('g')) { if(isOpen) DBAddG(sender,args); }else if (command.equalsIgnoreCase('cg')) { - if (!action) { - $.say($.whisperPrefix(sender) + $.lang.get('chatguessr.help', ' Use "!cg [open | close | ...]" to open/close the feature.')); - } else if (action.equalsIgnoreCase('open')) { - if(!isOpen) DBsetOpen(true); - } else if (action.equalsIgnoreCase('close')) { - if(isOpen) DBsetOpen(false); - } else if (action.equalsIgnoreCase('clear')) { - DBClearG(); - } else if (action.equalsIgnoreCase('timer')) { - sendData(action, new Date(Date.now().getTime()+value*1000*60)); - } else { - $.say($.whisperPrefix(sender) + $.lang.get('chatguessr.help')); + //send url + //$.say($.whisperPrefix(sender) + $.lang.get('chatguessr.help', ' Use "!cg [open | close | ...]" to open/close the feature.')); + }else if(command.equalsIgnoreCase('cga')){ + if(action.equalsIgnoreCase('open')){ + isOpen = true; + $.getSetIniDbBoolean('cgstatus', 'isOpen', true); + }else if(action.equalsIgnoreCase('close')){ + isOpen = false; + $.getSetIniDbBoolean('cgstatus', 'isOpen', false) + }else if(action.equalsIgnoreCase('start')){ + seed = GameHelper.fetchSeed(args[1]); + }else if(action.equalsIgnoreCase('end')){ + isOpen = false; + $.getSetIniDbBoolean('cgstatus', 'isOpen', false) + }else if(action.equalsIgnoreCase('refresh')){ + let newseed = GameHelper.fetchSeed(args[1]); + }else if(action.equalsIgnoreCase('gg')){ + sendData('guesses',JSON.stringify(guesses)); } } }); $.bind('initReady', function() { - $.registerChatCommand('./custom/custom/chatguessr.js', 'cg'); + $.registerChatCommand('./custom/custom/chatguessr.js', 'cg',7); $.registerChatCommand('./custom/custom/chatguessr.js', 'g',7); - - $.registerChatSubcommand('cg', 'open', 2); - $.registerChatSubcommand('cg', 'close', 2); - $.registerChatSubcommand('cg', 'clear', 2); + $.registerChatCommand('./custom/custom/chatguessr.js', 'cga'); + $.registerChatSubcommand('cga', 'open', 2); + $.registerChatSubcommand('cga', 'close', 2); + $.registerChatSubcommand('cga', 'start', 2); + $.registerChatSubcommand('cga', 'end', 2); + $.registerChatSubcommand('cga', 'refresh', 2); }); -})(); \ No newline at end of file +})(); diff --git a/twitch/helpers/cg-gh.js b/twitch/helpers/cg-gh.js new file mode 100644 index 0000000..5497856 --- /dev/null +++ b/twitch/helpers/cg-gh.js @@ -0,0 +1,129 @@ +/* axios v0.25.0 | (c) 2022 by Matt Zabriskie */ +/* axios v0.24.0 | (c) 2022 by Matt Zabriskie */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.axios=t():e.axios=t()}(this,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=11)}([function(e,t,n){"use strict";var r=n(3),o=Object.prototype.toString;function i(e){return"[object Array]"===o.call(e)}function s(e){return void 0===e}function a(e){return null!==e&&"object"==typeof e}function u(e){if("[object Object]"!==o.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}function c(e){return"[object Function]"===o.call(e)}function f(e,t){if(null!=e)if("object"!=typeof e&&(e=[e]),i(e))for(var n=0,r=e.length;n=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*"}}};r.forEach(["delete","get","head"],(function(e){c.headers[e]={}})),r.forEach(["post","put","patch"],(function(e){c.headers[e]=r.merge(s)})),e.exports=c},function(e,t,n){"use strict";function r(e){this.message=e}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,e.exports=r},function(e,t,n){"use strict";e.exports=function(e,t){return function(){for(var n=new Array(arguments.length),r=0;r=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([n]):s[t]?s[t]+", "+n:n}})),s):s}},function(e,t,n){"use strict";var r=n(0);e.exports=r.isStandardBrowserEnv()?function(){var e,t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");function o(e){var r=e;return t&&(n.setAttribute("href",r),r=n.href),n.setAttribute("href",r),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}return e=o(window.location.href),function(t){var n=r.isString(t)?o(t):t;return n.protocol===e.protocol&&n.host===e.host}}():function(){return!0}},function(e,t,n){"use strict";var r=n(10).version,o={};["object","boolean","number","function","string","symbol"].forEach((function(e,t){o[e]=function(n){return typeof n===e||"a"+(t<1?"n ":" ")+e}}));var i={};o.transitional=function(e,t,n){function o(e,t){return"[Axios v"+r+"] Transitional option '"+e+"'"+t+(n?". "+n:"")}return function(n,r,s){if(!1===e)throw new Error(o(r," has been removed"+(t?" in "+t:"")));return t&&!i[r]&&(i[r]=!0,console.warn(o(r," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(n,r,s)}},e.exports={assertOptions:function(e,t,n){if("object"!=typeof e)throw new TypeError("options must be an object");for(var r=Object.keys(e),o=r.length;o-- >0;){var i=r[o],s=t[i];if(s){var a=e[i],u=void 0===a||s(a,i,e);if(!0!==u)throw new TypeError("option "+i+" must be "+u)}else if(!0!==n)throw Error("Unknown option "+i)}},validators:o}},function(e,t,n){"use strict";var r=n(2);function o(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");var t;this.promise=new Promise((function(e){t=e}));var n=this;this.promise.then((function(e){if(n._listeners){var t,r=n._listeners.length;for(t=0;t res.data) + .catch((error) => console.log(error)); + }; + + static async getCountryBDC(location) { + return axios + .get(`https://api.bigdatacloud.net/data/reverse-geocode?latitude=${location.lat}&longitude=${location.lng}&key=${BDC_KEY}`) + .then((res) => countryCodes[res.data.countryCode]) + .catch((error) => error); + }; + + /** + * Returns an array of 9 coodinates as objects. + * Each coordinate is 100 meters aways from the given + * coordinate y angles from 0 to 315 + * The first coordinate is the original passed + * @param {Object} location {lat, lng} + * @return {Array} Coordinates [{lat, lng}, {lat, lng}] x 8 + */ + static getSurroundings (location) { + const meters = 100; + const R_EARTH = 6378.137; + const M = 1 / (((2 * Math.PI) / 360) * R_EARTH) / 1000; + + function moveFrom(coords, angle, distance) { + let radianAngle = (angle * Math.PI) / 180; + let x = 0 + distance * Math.cos(radianAngle); + let y = 0 + distance * Math.sin(radianAngle); + let newLat = coords.lat + y * M; + let newLng = coords.lng + (x * M) / Math.cos(coords.lat * (Math.PI / 180)); + return { lat: newLat, lng: newLng }; + } + let coordinates = [location]; + for (let angle = 0; angle < 360; angle += 45) { + coordinates.push(moveFrom({ lat: location.lat, lng: location.lng }, angle, meters)); + } + return coordinates; + }; + + /** + * Check if the param is coordinates + * @param {string} coordinates + * @return {boolean} + */ + static isCoordinates (coordinates) { + const regex = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/g; + return regex.test(coordinates); + }; + + /** + * Returns map scale + * @param {Object} bounds map bounds + * @return {number} map scale + */ + static calculateScale(bounds){ + return GameHelper.haversineDistance({ lat: bounds.min.lat, lng: bounds.min.lng }, { lat: bounds.max.lat, lng: bounds.max.lng }) / 7.458421; + } + + /** + * Returns distance in km between two coordinates + * @param {Object} mk1 {lat, lng} + * @param {Object} mk2 {lat, lng} + * @return {number} km + */ + static haversineDistance(mk1, mk2){ + const R = 6371.071; + const rlat1 = mk1.lat * (Math.PI / 180); + const rlat2 = mk2.lat * (Math.PI / 180); + const difflat = rlat2 - rlat1; + const difflon = (mk2.lng - mk1.lng) * (Math.PI / 180); + const km = + 2 * + R * + Math.asin(Math.sqrt(Math.sin(difflat / 2) * Math.sin(difflat / 2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.sin(difflon / 2) * Math.sin(difflon / 2))); + return km; + }; + + /** + * Returns score based on distance and scale + * @param {number} distance + * @param {number} scale + * @return {number} score + */ + static calculateScore(distance, scale){ + return Math.round(5000 * Math.pow(0.99866017, (distance * 1000) / scale)); + } + + /** Replace special chars + * @param {String} val + */ + static normalize(val){ + return val.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); + } + + /** Matches words above 3 letters + * @param {String} input + * @param {String} key + */ + static isMatch(input, key){ + return input.length >= 3 && key.includes(input) && input.length <= key.length; + } + + /** Find country by code or name + * @param {String} input + * @return {Object} countryCodesNames + */ + static findCountry(input){ + const normalized = GameHelper.normalize(input); + return countryCodesNames.find((country) => country.code === normalized || GameHelper.isMatch(normalized, country.names.toLowerCase())); + }; +} + +module.exports = GameHelper; \ No newline at end of file diff --git a/web/chatguessr/SRC_ORIG.js b/web/chatguessr/SRC_ORIG.js new file mode 100644 index 0000000..ea2872a Binary files /dev/null and b/web/chatguessr/SRC_ORIG.js differ