User:King Dragonhoff/wikia.js

/*

<<<<<< This script is under construction. >>>>>>

Clash Royale Deck Builder tool By King Dragonhoff Special thanks to Blaster Niceshot Dependencies - The tables on card articles must be given the appropriate ID's.   - id="unit-statistics-table" should be applied to the table with the level-dependent statistics. - id="unit-attributes-table" should be applied to the table with the statistics that are the same for all levels of the card. - Remember that an ID must never be used more than once per page. - Cells in the unit-statistics-table must contain a number. If the exact statistic is unknown, enter an estimate along with. - The tables on card articles must not contain cells that use the colspan or rowspan attributes. - The header cells in the card tables must remain consistant across the site. Maintainance Since this tool retrieves the card statistics from the wiki articles, this script will typically only need to be modified when new cards are added to the game.

// *********************** Variables and functions ************************* var lookupResult = {}; var dataTimeout; var elixirTotal, elixirAverage, elixirBar, elixirBarDiff, c; var hitpointsTotal, hitpointsAverage, hitpointsBar, hitpointsBarDiff, d, dCount, dCountNoX; // Define input elements function ccalcInputs(type,number) { if (type === "Common") { return 'Common Rare Epic Legendary Archers Arrows Barbarians Bomber Cannon Fire Spirits Goblins Knight Minion Horde Minions <option value="Mortar">Mortar <option value="Royal Giant">Royal Giant <option value="Skeletons">Skeletons <option value="Spear Goblins">Spear Goblins <option value="Tesla">Tesla <option value="Zap">Zap  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  9  10  11  12  13  '; } else if (type === "Rare") { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common">Common <option value="Rare" selected>Rare <option value="Epic">Epic <option value="Legendary">Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Barbarian Hut" selected>Barbarian Hut <option value="Bomb Tower">Bomb Tower <option value="Elixir Collector">Elixir Collector <option value="Fireball">Fireball <option value="Furnace">Furnace <option value="Giant">Giant <option value="Goblin Hut">Goblin Hut <option value="Hog Rider">Hog Rider <option value="Inferno Tower">Inferno Tower <option value="Mini P.E.K.K.A.">Mini P.E.K.K.A. <option value="Musketeer">Musketeer <option value="Rocket">Rocket <option value="Three Musketeers">Three Musketeers <option value="Tombstone">Tombstone <option value="Valkyrie">Valkyrie <option value="Wizard">Wizard  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  9  10  11  '; } else if (type === "Epic") { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common">Common <option value="Rare">Rare <option value="Epic" selected>Epic <option value="Legendary">Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Baby Dragon" selected>Baby Dragon <option value="Balloon">Balloon <option value="Dark Prince">Dark Prince <option value="Freeze">Freeze <option value="Giant Skeleton">Giant Skeleton <option value="Goblin Barrel">Goblin Barrel <option value="Golem">Golem <option value="Guards">Guards <option value="Lightning">Lightning <option value="Mirror">Mirror <option value="P.E.K.K.A.">P.E.K.K.A. <option value="Poison">Poison <option value="Prince">Prince <option value="Rage">Rage <option value="Skeleton Army">Skeleton Army <option value="Witch">Witch <option value="X-Bow">X-Bow  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  '; } else if (type === "Legendary") { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common">Common <option value="Rare">Rare <option value="Epic">Epic <option value="Legendary" selected>Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Ice Wizard" selected>Ice Wizard <option value="Lava Hound">Lava Hound <option value="Miner">Miner <option value="Princess">Princess <option value="Sparky">Sparky  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  '; } else { return '<select id="ccalc-rarity' + number + '" name="ccalc-rarity' + number + '"class="ccalc-rarity-input"><option value="Common" selected>Common <option value="Rare">Rare <option value="Epic">Epic <option value="Legendary">Legendary <select id="ccalc-card' + number + '" name="ccalc-card' + number + '" class="ccalc-card-input"><option value="Archers" selected>Archers <option value="Arrows">Arrows <option value="Barbarians">Barbarians <option value="Bomber">Bomber <option value="Cannon">Cannon <option value="Fire Spirits">Fire Spirits <option value="Goblins">Goblins <option value="Knight">Knight <option value="Minion Horde">Minion Horde <option value="Minions">Minions <option value="Mortar">Mortar <option value="Royal Giant">Royal Giant <option value="Skeletons">Skeletons <option value="Spear Goblins">Spear Goblins <option value="Tesla">Tesla <option value="Zap">Zap  <select id="ccalc-level' + number + '" name="ccalc-level' + number + '" class="ccalc-level-input"> 1  2  3  4  5  6  7  8  9  10  11  12  13  '; } } // Data Retrieval Function function getPageData(page) { var property = ''; var attribute = ''; // Code that will execute while AJAX request is running clearTimeout(dataTimeout); dataTimeout = setTimeout(function {       alert("It is taking a long time to retrieve the card's statistics. If the form is not re-enabled soon, check your Internet connection and refresh the page. If this does not seem to be the problem, check the card's wiki page to ensure that it has not been vandalized. If you are unable to fix the problem, contact a member of the wiki's staff.");    }, 10000); $('#ccalc-submit').html(' ').prop("disabled", true); $(".ccalc-rarity-input, .ccalc-card-input").prop("disabled", true); // Test if data for this page has already been retrieved if (lookupResult[page]) { // data already exists clearTimeout(dataTimeout); $('#ccalc-submit').html('Submit').prop("disabled", false); $(".ccalc-rarity-input, .ccalc-card-input").prop("disabled", false); } else { // data does not exist // AJAX Request $.get('http://clashroyale.wikia.com/index.php?title=' + page) .done(function(statData) {           lookupResult[page] = {};            $('#unit-attributes-table tbody tr:eq(0) th',statData).each(function(b) { attribute = $(this).clone.children.remove.end.text.trim.toLowerCase; lookupResult[page][attribute] = $('td:eq(' + b + ')',$("#unit-attributes-table tbody tr:eq(1)",statData)).text.trim; });           $('#unit-statistics-table tbody tr:eq(0) th',statData).each(function(i) { property = $(this).clone.children.remove.end.text.trim.toLowerCase; if (i > 0) { lookupResult[page][property] = [0]; $('#unit-statistics-table tbody tr',statData).each(function(a) {                       if (a > 0) {                            lookupResult[page][property].push($('td:eq(' + i + ')',$(this)).text.trim.replace(/\D/g, ""));                            if (a === $('#unit-statistics-table tbody tr',statData).length - 1 && i === $('#unit-statistics-table tbody tr:eq(0) th',statData).length - 1) {                                // Code that will execute                                // after AJAX request has finished and                                // data has been added to lookupResult object                                clearTimeout(dataTimeout);                                $('#ccalc-submit').html('Submit').prop("disabled", false);                                $(".ccalc-rarity-input, .ccalc-card-input").prop("disabled", false);                            }                        } });               }            });        });    } } // Deck image updating function function refreshDeck(card,index) {    $.getJSON('/api.php?action=parse&text=&format=json', function(n) { var addCardTemplate = n.parse.text['*']; $('td.ccalc-card[data-card-index="' + index + '"]').html(addCardTemplate); }); } // Card name by number function function cardName(number) {   return $("#ccalc-card" + number).val; } // Card level by number function function cardLevel(number) {    return $("#ccalc-level" + number).val; } // ****************************** Get Started ****************************** $(document).ready(function { // Build Form // Place inputs $('#ccalc-harness1').html(ccalcInputs("Common","1")); $('#ccalc-harness2').html(ccalcInputs("Common","2")); $('#ccalc-harness3').html(ccalcInputs("Common","3")); $('#ccalc-harness4').html(ccalcInputs("Common","4")); $('#ccalc-harness5').html(ccalcInputs("Common","5")); $('#ccalc-harness6').html(ccalcInputs("Common","6")); $('#ccalc-harness7').html(ccalcInputs("Common","7")); $('#ccalc-harness8').html(ccalcInputs("Common","8")); // Set default card inputs and initial fallback values $('#ccalc-card1').val("Archers").attr({"data-fallback-val": "Archers", "data-fallback-rarity": "Common"}); $('#ccalc-card2').val("Arrows").attr({"data-fallback-val": "Arrows", "data-fallback-rarity": "Common"}); $('#ccalc-card3').val("Barbarians").attr({"data-fallback-val": "Barbarians", "data-fallback-rarity": "Common"}); $('#ccalc-card4').val("Bomber").attr({"data-fallback-val": "Bomber", "data-fallback-rarity": "Common"}); $('#ccalc-card5').val("Cannon").attr({"data-fallback-val": "Cannon", "data-fallback-rarity": "Common"}); $('#ccalc-card6').val("Fire Spirits").attr({"data-fallback-val": "Fire Spirits", "data-fallback-rarity": "Common"}); $('#ccalc-card7').val("Goblins").attr({"data-fallback-val": "Goblins", "data-fallback-rarity": "Common"}); $('#ccalc-card8').val("Knight").attr({"data-fallback-val": "Knight", "data-fallback-rarity": "Common"}); // Place Submit button $('#ccalc-submit-harness').html('<button type="submit" id="ccalc-submit">Submit '); // ******************* On rarity change, replace inputs ***************** $('#cardCalculator').on('change', '.ccalc-rarity-input', function {       var newRarity = this.value;        var cardIndex = $(this).parent.attr("data-card-index");        var oldCard = $("#ccalc-card" + cardIndex).attr("data-fallback-val");        var oldCardRarity = $("#ccalc-card" + cardIndex).attr("data-fallback-rarity");        $(this).parent.html(ccalcInputs(newRarity,cardIndex));        // Perform card change functions as if the card selection was changed        var changedInput = $("#ccalc-card" + cardIndex);        var newCard = $(changedInput).val;        var newCardIndex = cardIndex;        // If user selects an already-selected card, swap them.        var dupCardIndex = $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.attr("data-card-index");        if (dupCardIndex) {            refreshDeck(oldCard,dupCardIndex);        }        $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.html(ccalcInputs(oldCardRarity,dupCardIndex)).children(".ccalc-card-input").val(oldCard).attr({"data-fallback-val": oldCard, "data-fallback-rarity": oldCardRarity}); // Replace fallback value, get data, replace card image $(changedInput).attr({"data-fallback-val": newCard, "data-fallback-rarity": $("#ccalc-rarity" + newCardIndex).val}); getPageData(newCard); refreshDeck(newCard,newCardIndex); });   // ******** On card change, get card statistics and change deck image ********    $('#cardCalculator').on('change', '.ccalc-card-input', function { var changedInput = this; var newCard = this.value; var oldCard = $(this).attr("data-fallback-val"); var oldCardRarity = $(this).attr("data-fallback-rarity"); var newCardIndex = $(this).parent.attr('data-card-index'); // If user selects an already-selected card, swap them. var dupCardIndex = $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.attr("data-card-index"); if (dupCardIndex) { refreshDeck(oldCard,dupCardIndex); }       $(".ccalc-card-input[data-fallback-val='" + newCard + "']").parent.html(ccalcInputs(oldCardRarity,dupCardIndex)).children(".ccalc-card-input").val(oldCard).attr({"data-fallback-val": oldCard, "data-fallback-rarity": oldCardRarity}); // Replace fallback value, get data, replace card image $(this).attr({"data-fallback-val": newCard, "data-fallback-rarity": $("#ccalc-rarity" + newCardIndex).val}); getPageData(newCard); refreshDeck(newCard,newCardIndex); });   $('.ccalc-card-input').change;    // ************************* Submit and show results ************************    $("#ccalc-submit").click(function { if ($.isEmptyObject(lookupResult[$("#ccalc-card1").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card2").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card3").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card4").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card5").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card6").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card7").val]) === false && $.isEmptyObject(lookupResult[$("#ccalc-card8").val]) === false) { // Successful Output $("#cardCalculator-result").fadeIn("slow"); // ****************** Average Elixir Cost *************************** elixirTotal = 0; for (c = 1; c < 9; c++) { if (isNaN(lookupResult[cardName(c)].cost) === true) { lookupResult[cardName(c)].cost = 2; }               elixirTotal += Number(lookupResult[cardName(c)].cost); }           elixirAverage = elixirTotal / 8; elixirBar = (elixirAverage * 100) / 8; // 8 is the max capcity of the bar elixirBarDiff = 100 - elixirBar; $("#ccalc-averageElixir .bar1").css("width", elixirBar + "%").children(".bar-value").text(roundNum(2,elixirAverage)); $("#ccalc-averageElixir .bar2").css("width", elixirBarDiff + "%"); // *********************** Average Hitpoints ************************* hitpointsTotal = 0; // Sum card hitpoint values for (d = 1; d < 9; d++) { // Check for count value dCount = String(lookupResult[cardName(d)].count); dCountNoX = dCount.replace(/x/g, ""); if (isNaN(dCountNoX) === true) { lookupResult[cardName(d)].count = 1; } else { lookupResult[cardName(d)].count = Number(dCountNoX); }               // Make sure the card can have hitpoints if (lookupResult[cardName(d)].type == "Troop" || lookupResult[cardName(d)].type == "Building") { // Check for a card that spawns units on death then check for missing value if (cardName(d) == "Golem") { if (isNaN(lookupResult[cardName(d)]["golem hitpoints"][cardLevel(d)]) === false && isNaN(lookupResult[cardName(d)]["golemite hitpoints"][cardLevel(d)]) === false) { hitpointsTotal += Number(lookupResult[cardName(d)]["golem hitpoints"][cardLevel(d)]) + (2 * Number(lookupResult[cardName(d)]["golemite hitpoints"][cardLevel(d)])); }                   } else if (cardName(d) == "Lava Hound") { if (isNaN(lookupResult[cardName(d)]['lava hound hitpoints'][cardLevel(d)]) === false && isNaN(lookupResult[cardName(d)]['lava pup hitpoints'][cardLevel(d)]) === false) { hitpointsTotal += Number(lookupResult[cardName(d)]['lava hound hitpoints'][cardLevel(d)]) + (6 * Number(lookupResult[cardName(d)]['lava pup hitpoints'][cardLevel(d)])); }                   } else { if (isNaN(lookupResult[cardName(d)].hitpoints[cardLevel(d)]) === false) { hitpointsTotal += Number(lookupResult[cardName(d)].hitpoints[cardLevel(d)]) * Number(lookupResult[cardName(d)].count); }                   }                }            }            hitpointsAverage = hitpointsTotal / 8; hitpointsBar = (hitpointsAverage * 100) / 4000; // 4000 is the max capacity of the bar hitpointsBarDiff = 100 - hitpointsBar; $("#ccalc-averageHitpoints .bar1").css("width", hitpointsBar + "%").children(".bar-value").text(roundNum(2,hitpointsAverage)); $("#ccalc-averageHitpoints .bar2").css("width", hitpointsBarDiff + "%"); } else { alert("The calculator was unable to retrieve one or more of the cards' statistics. Please check your Internet connection and refresh the page. If this does not seem to be the problem, check the card's wiki page to ensure that it has not been vandalized. If you are unable to fix the problem, contact a member of the wiki's staff."); }   }); });