MediaWiki:Script/Calculator.js : Différence entre versions

 
(22 révisions intermédiaires par le même utilisateur non affichées)
Ligne 8 : Ligne 8 :
  
 
function removeAccent(str) {
 
function removeAccent(str) {
   return str
+
   return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    .normalize("NFD")
+
}
    .replace(/[\u0300-\u036f]/g, "")
+
 
 +
function toNormalForm(str) {
 +
  return removeAccent(str)
 +
    .replace("-", " ")
 +
    .replace(/[^a-zA-Z0-9 ]/g, "")
 
     .toLowerCase();
 
     .toLowerCase();
 
}
 
}
  
function toNormalForm(str) {
+
function pseudoFormat(str) {
   return removeAccent(str).replace(/[^a-zA-Z0-9 ]/g, "");
+
   return removeAccent(str).replace(/[^A-Za-z0-9 \(\)\+_-]+/g, "");
 
}
 
}
  
Ligne 28 : Ligne 32 :
 
   }
 
   }
 
   return copy;
 
   return copy;
 +
}
 +
 +
function compareNumbers(a, b) {
 +
  return b - a;
 +
}
 +
 +
function isChecked(attribute) {
 +
  return attribute === "on";
 
}
 
}
  
Ligne 34 : Ligne 46 :
 
}
 
}
  
function numberFormat(number, precision) {
+
function truncateNumber(number, precision) {
   return Math.round(number * 10 ** precision) / 10 ** precision;
+
   return Math.floor(number * 10 ** precision) / 10 ** precision;
 
}
 
}
  
Ligne 46 : Ligne 58 :
 
}
 
}
  
function addRowToTableResult(tableResult, value) {
+
function editTableResultRow(row, valuesToDisplay, numberFormat) {
   var newRow = tableResult.insertRow(-1);
+
   row.innerHTML = "";
  var firstCell = newRow.insertCell(0);
+
  for (var index = 0; index < valuesToDisplay.length; index++) {
 +
    var cell = row.insertCell();
 +
    var textContent;
  
  firstCell.textContent = value;
+
    if (index >= 3) {
  firstCell.colSpan = 2;
+
      textContent = numberFormat.format(valuesToDisplay[index]);
 +
    } else {
 +
      textContent = valuesToDisplay[index];
 +
    }
 +
 
 +
    cell.textContent = textContent;
 +
  }
 +
 
 +
  return row;
 +
}
  
   newRow.style.fontWeight = "bold";
+
function addRowToTableResultHistory(
 +
   tableResultHistory,
 +
  valuesToDisplay,
 +
  deleteFightTemplate,
 +
  numberFormat
 +
) {
 +
  var row = tableResultHistory.insertRow();
 +
  editTableResultRow(row, valuesToDisplay, numberFormat);
 +
  var cell = row.insertCell();
 +
  cell.appendChild(deleteFightTemplate.cloneNode(true));
 
}
 
}
  
function addToTableResult(tableResult, damagesWeighted, minMaxDamages) {
+
function calcMeanDamages(damagesWeightedByType, totalCardinal) {
   var firstIteration = true;
+
   var sumDamages = 0;
  
   for (var damages in damagesWeighted) {
+
   for (var damagesTypeName in damagesWeightedByType) {
     if (firstIteration && minMaxDamages) {
+
     if (damagesTypeName === "miss") {
      damages = parseInt(damages);
+
       continue;
      if (damages < minMaxDamages.min) {
 
        minMaxDamages.min = damages;
 
      }
 
       firstIteration = false;
 
 
     }
 
     }
  
     var newRow = tableResult.insertRow(-1);
+
     var damagesWeighted = damagesWeightedByType[damagesTypeName];
    var firstCell = newRow.insertCell(0);
 
  
     firstCell.textContent = damages;
+
     for (var damages in damagesWeighted) {
 
+
      sumDamages += damages * damagesWeighted[damages];
    var secondCell = newRow.insertCell(1);
+
    }
    secondCell.textContent =
 
      numberFormat(damagesWeighted[damages] * 100, 3)
 
        .toString()
 
        .replace(".", ",") + " %";
 
 
   }
 
   }
  
   damages = parseInt(damages);
+
   return sumDamages / totalCardinal;
  if (minMaxDamages && damages > minMaxDamages.max) {
 
    minMaxDamages.max = damages;
 
  }
 
 
}
 
}
  
function clearTableResult(tableResult) {
+
function prepareDamagesData(
   var tableHeaderRowCount = 1;
+
  damagesWeightedByType,
   var rowCount = tableResult.rows.length;
+
  possibleDamagesCountTemp,
 +
  totalCardinal
 +
) {
 +
   var minDamages = Infinity;
 +
  var maxDamages = 0;
 +
  var scatterDataByType = {};
 +
  var sumDamages = 0;
 +
  var possibleDamagesCount = 0;
 +
   var uniqueDamagesCount = 0;
 +
 
 +
  for (var damagesTypeName in damagesWeightedByType) {
 +
    if (damagesTypeName === "miss") {
 +
      scatterDataByType.miss = damagesWeightedByType.miss;
 +
      possibleDamagesCount++;
 +
      uniqueDamagesCount++;
 +
      continue;
 +
    }
  
  for (var rowIndex = tableHeaderRowCount; rowIndex < rowCount; rowIndex++) {
+
    var firstIteration = true;
     tableResult.deleteRow(tableHeaderRowCount);
+
    var damagesWeighted = damagesWeightedByType[damagesTypeName];
  }
+
     var scatterData = [];
}
+
    scatterDataByType[damagesTypeName] = scatterData;
  
function filterClass(selectedRace, classChoice, selectValueIsChanged = false) {
+
    for (var damages in damagesWeighted) {
  showElement(classChoice.parentElement);
+
      damages = +damages;
  
  for (var option of classChoice.options) {
+
      if (firstIteration) {
    if (option.getAttribute("data-race") === selectedRace) {
+
        if (damages < minDamages) {
      if (!selectValueIsChanged) {
+
          minDamages = damages;
        classChoice.value = option.value;
+
         }
         selectValueIsChanged = true;
+
        firstIteration = false;
 
       }
 
       }
       showElement(option);
+
 
     } else {
+
       var weight = damagesWeighted[damages];
       hideElement(option);
+
      var probability = weight / totalCardinal;
 +
 
 +
      sumDamages += damages * weight;
 +
      damagesWeighted[damages] = probability;
 +
      scatterData.push({ x: damages, y: probability });
 +
     }
 +
 
 +
    var scatterDataLength = scatterData.length;
 +
 
 +
    possibleDamagesCount += possibleDamagesCountTemp;
 +
    uniqueDamagesCount += scatterDataLength;
 +
 
 +
    if (damages > maxDamages) {
 +
       maxDamages = damages;
 
     }
 
     }
 
   }
 
   }
   if (selectedRace == "lycan") {
+
 
     hideElement(classChoice.parentElement);
+
   if (minDamages === Infinity) {
 +
     minDamages = 0;
 
   }
 
   }
 +
 +
  return [
 +
    sumDamages / totalCardinal,
 +
    minDamages,
 +
    maxDamages,
 +
    scatterDataByType,
 +
    possibleDamagesCount,
 +
    uniqueDamagesCount,
 +
  ];
 
}
 
}
  
function filterWeapon(
+
function aggregateDamages(scatterData, maxPoints) {
  selectedRace,
+
   var dataLength = scatterData.length;
  weapon,
+
   var remainingData = dataLength;
  weaponCategory,
+
   var aggregateScatterData = [];
  selectValueIsChanged = false
 
) {
 
   var allowedWeaponsPerRace = {
 
    warrior: [0, 3, 8],
 
    ninja: [0, 1, 2, 8],
 
    sura: [0, 7, 8],
 
    shaman: [4, 6, 8],
 
    lycan: [5, 8],
 
   };
 
   var allowedWeapons = allowedWeaponsPerRace[selectedRace];
 
  
   if (!selectValueIsChanged) {
+
   for (var groupIndex = 0; groupIndex < maxPoints; groupIndex++) {
     var weaponType = weaponData[weapon.value][1];
+
     var groupLength = Math.floor(remainingData / (maxPoints - groupIndex));
 +
    var startIndex = dataLength - remainingData;
 +
    var aggregateDamages = 0;
 +
    var aggregateProbability = 0;
  
     if (!isValueInArray(weaponType, allowedWeapons)) {
+
     for (var index = startIndex; index < startIndex + groupLength; index++) {
       weapon.value = 0;
+
       var { x: damages, y: probability } = scatterData[index];
 +
      aggregateDamages += damages * probability;
 +
      aggregateProbability += probability;
 
     }
 
     }
 +
 +
    aggregateScatterData.push({
 +
      x: aggregateDamages / aggregateProbability,
 +
      y: aggregateProbability,
 +
    });
 +
 +
    remainingData -= groupLength;
 
   }
 
   }
  
   var children = weaponCategory.children;
+
   return aggregateScatterData;
 +
}
  
   for (var index = 0; index < children.length; index++) {
+
function addToDamagesChart(
     var child = children[index];
+
  scatterDataByType,
 +
  damagesChart,
 +
  isReducePointsChecked
 +
) {
 +
  var { chart, datasetsStyle, maxPoints, reduceChartPointsContainer } =
 +
    damagesChart;
 +
  var isFirstDataset = true;
 +
  var datasets = chart.data.datasets;
 +
 
 +
  datasets.length = 0;
 +
 
 +
   for (var index = 0; index < datasetsStyle.length; index++) {
 +
     var dataset = copyObject(datasetsStyle[index]);
 +
 
 +
    if (!scatterDataByType.hasOwnProperty(dataset.name)) {
 +
      continue;
 +
    }
 +
 
 +
    var scatterData = scatterDataByType[dataset.name];
 +
    var canBeReduced = scatterData.length > 2 * maxPoints;
 +
 
 +
    dataset.hidden = !isFirstDataset;
 +
    dataset.canBeReduced = canBeReduced;
  
     if (isValueInArray(index, allowedWeapons)) {
+
     if (canBeReduced && isReducePointsChecked) {
       showElement(child);
+
       dataset.data = aggregateDamages(scatterData, maxPoints);
 
     } else {
 
     } else {
       hideElement(child);
+
       dataset.data = scatterData;
 +
    }
 +
 
 +
    if (isFirstDataset) {
 +
      isFirstDataset = false;
 +
 
 +
      if (canBeReduced) {
 +
        showElement(reduceChartPointsContainer);
 +
 
 +
        if (!isReducePointsChecked) {
 +
          handleChartAnimations(chart, false);
 +
        }
 +
      } else {
 +
        hideElement(reduceChartPointsContainer);
 +
        handleChartAnimations(chart, true);
 +
      }
 
     }
 
     }
 +
 +
    datasets.push(dataset);
 
   }
 
   }
 +
 +
  chart.data.missPercentage = scatterDataByType.miss;
 +
  chart.update();
 
}
 
}
  
function getSelectedWeapon(weaponCategory) {
+
function addToBonusVariationChart(
   return weaponCategory.querySelector("input[type='radio']:checked");
+
  damagesByBonus,
 +
  augmentationByBonus,
 +
  xLabel,
 +
  chart
 +
) {
 +
   chart.data.datasets[0].data = damagesByBonus;
 +
  chart.data.datasets[1].data = augmentationByBonus;
 +
  chart.options.scales.x.title.text = xLabel;
 +
  chart.update();
 
}
 
}
  
function handleWeaponDisplay(weaponDisplay, newWeapon, weaponValue) {
+
function handleChartAnimations(chart, addAnimations) {
   var newImage = newWeapon.nextElementSibling.cloneNode();
+
   chart.options.animation = addAnimations;
   var newText = document.createElement("span");
+
   chart.options.animations.colors = addAnimations;
   var oldImage = weaponDisplay.firstChild;
+
   chart.options.animations.x = addAnimations;
  var oldText = oldImage.nextElementSibling;
+
   chart.options.transitions.active.animation.duration = addAnimations * 1000;
 
 
  newText.textContent = " " + weaponData[weaponValue][0] + " ";
 
 
 
   weaponDisplay.replaceChild(newImage, oldImage);
 
  weaponDisplay.replaceChild(newText, oldText);
 
 
}
 
}
  
function filterUpgrade(
+
function updateDamagesChartDescription(
   selectedRace,
+
   uniqueDamagesCounters,
   weaponUpgrade,
+
   uniqueDamagesCount,
   weaponValue,
+
   formatNumber
  randomAttackValue,
+
) {
  randomMagicAttackValue,
+
   uniqueDamagesCounters.forEach(function (element) {
  currentUpgrade
+
     if (uniqueDamagesCount <= 1) {
) {
+
      hideElement(element.parentElement);
   var weapon = weaponData[weaponValue];
 
 
 
  if (isValueInArray("serpent", weapon[0].toLowerCase())) {
 
    showElement(randomAttackValue);
 
 
 
    if (selectedRace === "sura" || selectedRace === "shaman") {
 
      showElement(randomMagicAttackValue);
 
    }
 
  } else {
 
     hideElement(randomAttackValue);
 
    hideElement(randomMagicAttackValue);
 
  }
 
 
 
  var upgradeNumber = weapon[3].length;
 
 
 
  if (upgradeNumber <= 1) {
 
    hideElement(weaponUpgrade.parentElement);
 
  } else {
 
    showElement(weaponUpgrade.parentElement);
 
 
 
    weaponUpgrade.innerHTML = "";
 
 
 
    for (var upgrade = 0; upgrade < upgradeNumber; upgrade++) {
 
      var option = document.createElement("option");
 
      option.value = upgrade;
 
      option.textContent = "+" + upgrade;
 
      weaponUpgrade.appendChild(option);
 
    }
 
    if (currentUpgrade === undefined) {
 
      option.selected = true;
 
 
     } else {
 
     } else {
       weaponUpgrade.value = currentUpgrade;
+
       showElement(element.parentElement);
       currentUpgrade = undefined;
+
       element.textContent = formatNumber.format(uniqueDamagesCount);
 
     }
 
     }
   }
+
   });
 
}
 
}
  
function filterState(stateChoice, polymorphMonster) {
+
function getMonsterName(monsterVnum) {
   if (stateChoice.value === "polymorph") {
+
   var monsterAttributes = monsterData[monsterVnum];
    showElement(polymorphMonster.parentElement);
+
   return monsterAttributes[monsterAttributes.length - 1];
   } else {
 
    hideElement(polymorphMonster.parentElement);
 
  }
 
 
}
 
}
  
function filterPlayerRank(lowRankCheckbox, playerRankChoice) {
+
function filterClass(selectedRace, classChoice, selectValueIsChanged = false) {
   if (lowRankCheckbox.checked) {
+
   showElement(classChoice.parentElement);
    showElement(playerRankChoice.parentElement);
 
  } else {
 
    hideElement(playerRankChoice.parentElement);
 
  }
 
}
 
  
function filterSkills(selectedClass, skillElementsToFilter) {
+
   for (var option of classChoice.options) {
   for (var element of skillElementsToFilter) {
+
     if (option.getAttribute("data-race") === selectedRace) {
     if (isValueInArray(selectedClass, element.dataset.class)) {
+
      if (!selectValueIsChanged) {
       showElement(element);
+
        classChoice.value = option.value;
 +
        selectValueIsChanged = true;
 +
      }
 +
       showElement(option);
 
     } else {
 
     } else {
       hideElement(element);
+
       hideElement(option);
 
     }
 
     }
 +
  }
 +
  if (selectedRace == "lycan") {
 +
    hideElement(classChoice.parentElement);
 
   }
 
   }
 
}
 
}
  
function filterAttackTypeSelection(attacker, attackTypeSelection) {
+
function filterWeapon(
   var attackerClass = attacker.class;
+
  selectedRace,
   var selectedOption =
+
  weaponElement,
    attackTypeSelection.options[attackTypeSelection.selectedIndex];
+
  weaponCategory,
 +
  allowedWeaponsPerRace,
 +
   selectValueIsChanged = false
 +
) {
 +
   var allowedWeapons = allowedWeaponsPerRace[selectedRace];
  
   for (var option of attackTypeSelection.options) {
+
   if (!selectValueIsChanged) {
     optionClass = option.dataset.class;
+
     var weaponType = weaponData[weaponElement.value][1];
  
     if (optionClass) {
+
     if (!isValueInArray(weaponType, allowedWeapons)) {
       if (
+
       weaponElement.value = 0;
        optionClass === attackerClass &&
+
    }
        attacker[option.value] &&
+
  }
        attacker.state !== "polymorph"
+
 
      ) {
+
  var children = weaponCategory.children;
        showElement(option);
+
 
      } else {
+
  for (var index = 0; index < children.length; index++) {
        hideElement(option);
+
    var child = children[index];
  
        if (selectedOption === option) {
+
    if (isValueInArray(index, allowedWeapons)) {
          attackTypeSelection.selectedIndex = 0;
+
      showElement(child);
        }
+
    } else {
       }
+
       hideElement(child);
 
     }
 
     }
 
   }
 
   }
 
}
 
}
  
function filterForm(characters, battle) {
+
function getSelectedWeapon(weaponCategory) {
   characters.characterCreation.addEventListener("change", function (event) {
+
   return weaponCategory.querySelector("input[type='radio']:checked");
    var target = event.target;
+
}
    var targetName = target.name;
 
  
    switch (targetName) {
+
function handleWeaponDisplay(weaponDisplay, newWeapon, weaponVnum) {
      case "race":
+
  var newImage = newWeapon.nextElementSibling.cloneNode();
        var selectedRace = target.value;
+
  var newText = document.createElement("span");
        filterClass(selectedRace, characters.classChoice);
+
  var oldImage = weaponDisplay.firstChild;
        filterWeapon(
+
  var oldText = oldImage.nextElementSibling;
          selectedRace,
+
  var weaponName = createWeapon(weaponVnum).name;
          characters.weapon,
 
          characters.weaponCategory
 
        );
 
  
        var newWeapon = getSelectedWeapon(characters.weaponCategory);
+
  if (weaponVnum == 0) {
        handleWeaponDisplay(
+
    newText.textContent = " " + weaponName + " ";
          characters.weaponDisplay,
+
  } else {
          newWeapon,
+
    var weaponLink = document.createElement("a");
          characters.weapon.value
+
    weaponLink.href = mw.util.getUrl(weaponName);
        );
+
    weaponLink.title = weaponName;
        filterUpgrade(
+
    weaponLink.textContent = weaponName;
          selectedRace,
+
 
          characters.weaponUpgrade,
+
    newText.appendChild(document.createTextNode(" "));
          characters.weapon.value,
+
    newText.appendChild(weaponLink);
          characters.randomAttackValue,
+
    newText.appendChild(document.createTextNode(" "));
          characters.randomMagicAttackValue
+
  }
        );
 
        filterSkills(
 
          characters.classChoice.value,
 
          characters.skillElementsToFilter
 
        );
 
  
        if (
+
  weaponDisplay.replaceChild(newImage, oldImage);
          characters.characterCreation.name.value ===
+
  weaponDisplay.replaceChild(newText, oldText);
          battle.attackerSelection.value
+
}
        ) {
 
          battle.resetAttackType = true;
 
        }
 
        break;
 
      case "class":
 
        filterSkills(target.value, characters.skillElementsToFilter);
 
  
        if (
+
function filterUpgrade(
          characters.characterCreation.name.value ===
+
  selectedRace,
          battle.attackerSelection.value
+
  weaponUpgrade,
        ) {
+
  weaponVnum,
          battle.resetAttackType = true;
+
  randomAttackValue,
        }
+
  randomMagicAttackValue,
        break;
+
  currentUpgrade
      case "weapon":
+
) {
        handleWeaponDisplay(
+
  var weapon = createWeapon(weaponVnum);
          characters.weaponDisplay,
+
 
          target,
+
  if (weapon.isSerpent) {
          characters.weapon.value
+
    showElement(randomAttackValue);
        );
 
        filterUpgrade(
 
          characters.race.value,
 
          characters.weaponUpgrade,
 
          target.value,
 
          characters.randomAttackValue,
 
          characters.randomMagicAttackValue
 
        );
 
        break;
 
      case "state":
 
        filterState(target, characters.polymorphMonster);
 
        if (
 
          characters.characterCreation.name.value ===
 
          battle.attackerSelection.value
 
        ) {
 
          battle.resetAttackType = true;
 
        }
 
        break;
 
      case "lowRank":
 
        filterPlayerRank(target, characters.playerRankChoice);
 
        break;
 
    }
 
  
     if (targetName.startsWith("attackSkill")) {
+
     if (selectedRace === "sura" || selectedRace === "shaman") {
       battle.resetAttackType = true;
+
       showElement(randomMagicAttackValue);
 
     }
 
     }
   });
+
   } else {
}
+
    hideElement(randomAttackValue);
 +
    hideElement(randomMagicAttackValue);
 +
  }
  
function getSavedCharacters() {
+
   var upgradeNumber = weapon.upgrades.length;
   var savedCharacters = localStorage.getItem("savedCharactersCalculator");
 
  
   if (savedCharacters) {
+
   if (upgradeNumber <= 1) {
     return JSON.parse(savedCharacters);
+
     hideElement(weaponUpgrade.parentElement);
 +
  } else {
 +
    showElement(weaponUpgrade.parentElement);
 
   }
 
   }
  return {};
 
}
 
  
function getSavedMonsters() {
+
   weaponUpgrade.innerHTML = "";
   var savedMonsters = localStorage.getItem("savedMonstersCalculator");
 
  
   if (savedMonsters) {
+
   for (var upgrade = 0; upgrade < upgradeNumber; upgrade++) {
     return JSON.parse(savedMonsters);
+
     var option = document.createElement("option");
 +
    option.value = upgrade;
 +
    option.textContent = "+" + upgrade;
 +
    weaponUpgrade.appendChild(option);
 +
  }
 +
  if (currentUpgrade === undefined) {
 +
    option.selected = true;
 +
  } else {
 +
    weaponUpgrade.value = currentUpgrade;
 +
    currentUpgrade = undefined;
 
   }
 
   }
  return [];
 
 
}
 
}
  
function addUniquePseudo(characterDataObject, savedCharactersPseudo) {
+
function filterState(selectedState, polymorphMonster) {
   var characterPseudo = characterDataObject.name;
+
   if (selectedState === "polymorph") {
  var originalPseudo = characterPseudo;
+
    showElement(polymorphMonster.parentElement);
  var count = 0;
+
   } else {
 
+
    hideElement(polymorphMonster.parentElement);
  var regex = /(.*)(\d)$/;
 
   var match = characterPseudo.match(regex);
 
 
 
  if (match) {
 
    originalPseudo = match[1];
 
    count = match[2];
 
 
   }
 
   }
 +
}
  
  while (isValueInArray(characterPseudo, savedCharactersPseudo)) {
+
function filterCheckbox(checkbox, element) {
     characterPseudo = originalPseudo + count;
+
  if (checkbox.checked) {
     count++;
+
     showElement(element);
 +
  } else {
 +
     hideElement(element);
 
   }
 
   }
 
  characterDataObject.name = characterPseudo;
 
  return [characterDataObject, characterPseudo];
 
 
}
 
}
  
function convertToNumber(value) {
+
function filterSkills(selectedClass, skillElementsToFilter) {
   var valueNumber = Number(value);
+
   for (var element of skillElementsToFilter) {
  return isNaN(valueNumber) ? value : valueNumber;
+
    if (isValueInArray(selectedClass, element.dataset.class)) {
 +
      showElement(element);
 +
    } else {
 +
      hideElement(element);
 +
    }
 +
  }
 
}
 
}
  
function updateSavedCharacters(savedCharacters) {
+
function filterAttackTypeSelection(attacker, attackTypeSelection) {
   localStorage.setItem(
+
   var attackerClass = attacker.class;
     "savedCharactersCalculator",
+
  var selectedOption =
     JSON.stringify(savedCharacters)
+
    attackTypeSelection.options[attackTypeSelection.selectedIndex];
  );
+
  var attackerIsNotPolymorph = !isPolymorph(attacker);
 +
 
 +
  for (var index = 2; index < attackTypeSelection.options.length; index++) {
 +
    var option = attackTypeSelection.options[index];
 +
    var optionClass = option.dataset.class;
 +
    var optionValue = option.value;
 +
 
 +
     if (
 +
      attackerIsNotPolymorph &&
 +
      attacker[optionValue] &&
 +
      (attackerClass === optionClass ||
 +
        (optionValue.startsWith("horseSkill") &&
 +
          isRiding(attacker) &&
 +
          (!optionClass || isValueInArray(attackerClass, optionClass))))
 +
    ) {
 +
      showElement(option);
 +
     } else {
 +
      hideElement(option);
 +
 
 +
      if (selectedOption === option) {
 +
        attackTypeSelection.selectedIndex = 0;
 +
      }
 +
    }
 +
  }
 
}
 
}
  
function updateSavedMonsters(savedMonsters) {
+
function filterAttackTypeSelectionMonster(attackTypeSelection) {
   localStorage.setItem(
+
   for (var index = 2; index < attackTypeSelection.options.length; index++) {
     "savedMonstersCalculator",
+
     hideElement(attackTypeSelection.options[index]);
    JSON.stringify(savedMonsters)
+
   }
   );
+
 
 +
  if (attackTypeSelection.selectedIndex !== 1) {
 +
    attackTypeSelection.selectedIndex = 0;
 +
  }
 
}
 
}
  
function saveCharacter(
+
function filterForm(characters, battle) {
  savedCharacters,
+
   var characterCreation = characters.characterCreation;
   characterCreation,
+
   var allowedWeaponsPerRace = battle.constants.allowedWeaponsPerRace;
   battle,
+
 
   newCharacter,
+
   characterCreation.addEventListener("change", function (event) {
  characterDataObject
+
     var target = event.target;
) {
+
     var targetName = target.name;
  if (!characterDataObject) {
 
     var characterData = new FormData(characterCreation);
 
     var characterDataObject = {};
 
  
     characterData.forEach(function (value, key) {
+
     switch (targetName) {
       characterDataObject[key] = convertToNumber(value);
+
       case "race":
    });
+
        var selectedRace = target.value;
  }
+
        var classChoice = characterCreation.class;
 +
        var weaponElement = characterCreation.weapon;
  
  savedCharacters[characterDataObject.name] = characterDataObject;
+
        filterClass(selectedRace, classChoice);
  updateSavedCharacters(savedCharacters);
+
        filterWeapon(
 +
          selectedRace,
 +
          weaponElement,
 +
          characters.weaponCategory,
 +
          allowedWeaponsPerRace
 +
        );
  
  if (newCharacter) {
+
        var newWeapon = getSelectedWeapon(characters.weaponCategory);
    addBattleChoice(battle, characterDataObject.name);
+
        handleWeaponDisplay(
  }
+
          characters.weaponDisplay,
 
+
          newWeapon,
  if (battle.resetAttackType) {
+
          weaponElement.value
    filterAttackTypeSelection(characterDataObject, battle.attackTypeSelection);
+
        );
    battle.resetAttackType = false;
+
        filterUpgrade(
  }
+
          selectedRace,
}
+
          characterCreation.weaponUpgrade,
 +
          weaponElement.value,
 +
          characters.randomAttackValue,
 +
          characters.randomMagicAttackValue
 +
        );
 +
        filterSkills(classChoice.value, characters.skillElementsToFilter);
  
function saveButtonGreen(characters, animation) {
+
        if (characterCreation.name.value === battle.attackerSelection.value) {
  if (animation) {
+
          battle.resetAttackType = true;
    characters.saveButton.classList.add("save-animation");
+
        }
  } else {
+
        break;
    characters.saveButton.classList.remove("save-animation");
+
      case "class":
  }
+
        filterSkills(target.value, characters.skillElementsToFilter);
  characters.saveButton.classList.remove("unsaved-button");
 
}
 
  
function saveButtonOrange(characters) {
+
        if (characterCreation.name.value === battle.attackerSelection.value) {
  characters.saveButton.classList.remove("save-animation");
+
          battle.resetAttackType = true;
  characters.saveButton.classList.add("unsaved-button");
+
        }
}
+
        break;
 
+
      case "weapon":
function characterCreationListener(characters, battle) {
+
        handleWeaponDisplay(
  characters.characterCreation.addEventListener("submit", function (event) {
+
          characters.weaponDisplay,
    event.preventDefault();
+
          target,
 
+
          characterCreation.weapon.value
    if (characters.unsavedChanges) {
+
        );
       saveCharacter(
+
        filterUpgrade(
         characters.savedCharacters,
+
          characterCreation.race.value,
         characters.characterCreation,
+
          characterCreation.weaponUpgrade,
         battle
+
          target.value,
       );
+
          characters.randomAttackValue,
       saveButtonGreen(characters, true);
+
          characters.randomMagicAttackValue
       characters.unsavedChanges = false;
+
        );
 +
        break;
 +
      case "state":
 +
        filterState(target.value, characterCreation.polymorphMonster);
 +
        if (characterCreation.name.value === battle.attackerSelection.value) {
 +
          battle.resetAttackType = true;
 +
        }
 +
        break;
 +
      case "lowRank":
 +
        filterCheckbox(target, characterCreation.playerRank.parentElement);
 +
        break;
 +
      case "isBlessed":
 +
        filterCheckbox(target, characters.blessingCreation);
 +
        break;
 +
       case "onYohara":
 +
         filterCheckbox(target, characters.yoharaCreation);
 +
        break;
 +
      case "isMarried":
 +
         filterCheckbox(target, characters.marriageCreation);
 +
         break;
 +
    }
 +
 
 +
    if (
 +
       targetName.startsWith("attackSkill") ||
 +
       targetName.startsWith("horseSkill")
 +
    ) {
 +
       battle.resetAttackType = true;
 
     }
 
     }
 
   });
 
   });
 
}
 
}
  
function downloadCharacter(character) {
+
function addUniquePseudo(characterDataObject, savedCharactersPseudo) {
   var content = JSON.stringify(character);
+
   var characterPseudo = String(characterDataObject.name);
  var link = document.createElement("a");
+
   var originalPseudo = characterPseudo;
   var blob = new Blob([content], { type: "text/plain" });
+
   var count = 0;
   var blobURL = URL.createObjectURL(blob);
 
  
   link.href = blobURL;
+
   var regex = /(.*)(\d)$/;
  link.download = character.name + ".txt";
+
   var match = characterPseudo.match(regex);
  link.click();
 
   URL.revokeObjectURL(blobURL);
 
}
 
  
function uploadCharacter(
+
  if (match) {
  characters,
+
    originalPseudo = match[1];
  characterTemplate,
+
    count = match[2];
  charactersContainer,
+
  }
  battle
 
) {
 
  var fileInput = document.createElement("input");
 
  
   fileInput.type = "file";
+
   while (isValueInArray(characterPseudo, savedCharactersPseudo)) {
  fileInput.accept = ".txt";
+
    characterPseudo = originalPseudo + count;
  fileInput.multiple = true;
+
    count++;
   fileInput.click();
+
   }
  
   fileInput.addEventListener("change", function (event) {
+
   characterDataObject.name = characterPseudo;
    var selectedFiles = event.target.files;
+
  return [characterDataObject, characterPseudo];
    var selectFilesLength = selectedFiles.length;
+
}
  
    hideElement(characters.characterCreation);
+
function convertToNumber(value) {
 +
  var valueNumber = Number(value);
 +
  return isNaN(valueNumber) ? value : valueNumber;
 +
}
  
    for (var fileIndex = 0; fileIndex < selectFilesLength; fileIndex++) {
+
function getLocalStorageValue(key, defaultValue) {
      var selectedFile = selectedFiles[fileIndex];
+
  var storedValue = localStorage.getItem(key);
  
      if (selectedFile.type === "text/plain") {
+
  if (storedValue) {
        var reader = new FileReader();
+
    return JSON.parse(storedValue);
        reader.onload = function (e) {
+
  }
          var fileContent = e.target.result;
 
          try {
 
            var characterDataObject = JSON.parse(fileContent);
 
            var characterPseudo = characterDataObject.name;
 
  
            if (characterPseudo) {
+
  return defaultValue;
              characterPseudo = validPseudo(characterPseudo);
+
}
              [characterDataObject, characterPseudo] = addUniquePseudo(
 
                characterDataObject,
 
                Object.keys(characters.savedCharacters)
 
              );
 
              var selectedCharacter = handleNewCharacter(
 
                characters,
 
                characterTemplate,
 
                charactersContainer,
 
                battle,
 
                characterPseudo
 
              )[0];
 
  
              if (selectFilesLength === 1) {
+
function getSavedCharacters() {
                updateForm(
+
  return getLocalStorageValue("savedCharactersCalculator", {});
                  characterDataObject,
+
}
                  characters.characterCreation,
 
                  characters,
 
                  selectedCharacter
 
                );
 
              }
 
  
              saveCharacter(
+
function getSavedMonsters() {
                characters.savedCharacters,
+
  return getLocalStorageValue("savedMonstersCalculator", []).filter(function (
                characters.characterCreation,
+
    num
                battle,
+
  ) {
                true,
+
    return !isNaN(Number(num));
                characterDataObject
 
              );
 
            }
 
          } catch (error) {
 
            if (error.name === "TypeError") {
 
              // delete the character
 
            }
 
          }
 
        };
 
        reader.readAsText(selectedFile);
 
      }
 
    }
 
 
   });
 
   });
 
}
 
}
  
function deleteCharacter(characters, pseudo, element, battle) {
+
function getSavedFights() {
   battle.battleForm.reset();
+
   return getLocalStorageValue("savedFightsCalculator", []);
  delete characters.savedCharacters[pseudo];
+
}
  element.remove();
 
  
  updateSavedCharacters(characters.savedCharacters);
+
function saveToLocalStorage(key, value) {
   removeBattleChoice(battle, pseudo);
+
   localStorage.setItem(key, JSON.stringify(value));
 +
}
  
  if (
+
function updateSavedCharacters(savedCharacters) {
    !Object.keys(characters.savedCharacters).length ||
+
   saveToLocalStorage("savedCharactersCalculator", savedCharacters);
    characters.characterCreation.name.value === pseudo
 
   ) {
 
    saveButtonGreen(characters);
 
    characters.unsavedChanges = false;
 
    hideElement(characters.characterCreation);
 
  }
 
 
}
 
}
  
function deleteMonster(characters, monsterName, element, battle) {
+
function updateSavedMonsters(savedMonsters) {
   battle.battleForm.reset();
+
   saveToLocalStorage("savedMonstersCalculator", savedMonsters);
  characters.savedMonsters.splice(
+
}
    characters.savedMonsters.indexOf(monsterName),
 
    1
 
  );
 
  element.remove();
 
  
  updateSavedMonsters(characters.savedMonsters);
+
function updateSavedFights(savedFights) {
   removeBattleChoice(battle, monsterName);
+
   saveToLocalStorage("savedFightsCalculator", savedFights);
 
}
 
}
  
function handleStyle(characters, selectedElement) {
+
function saveCharacter(
   var currentCharacter = characters.currentCharacter;
+
  savedCharacters,
 +
  characterCreation,
 +
  battle,
 +
  newCharacter,
 +
  characterDataObject
 +
) {
 +
   if (!characterDataObject) {
 +
    var characterData = new FormData(characterCreation);
 +
    var characterDataObject = {};
 +
 
 +
    characterData.forEach(function (value, key) {
 +
      characterDataObject[key] = convertToNumber(value);
 +
    });
 +
  }
 +
 
 +
  savedCharacters[characterDataObject.name] = characterDataObject;
 +
  updateSavedCharacters(savedCharacters);
  
   if (currentCharacter) {
+
   if (newCharacter) {
     currentCharacter.classList.remove("selected-character");
+
     addBattleChoice(battle, characterDataObject.name);
 
   }
 
   }
  
   selectedElement.classList.add("selected-character");
+
   if (battle.resetAttackType) {
  characters.currentCharacter = selectedElement;
+
    filterAttackTypeSelection(characterDataObject, battle.attackTypeSelection);
 +
    battle.resetAttackType = false;
 +
  }
 
}
 
}
  
function updateForm(formData, characterCreation, characters, selectedElement) {
+
function saveButtonGreen(saveButton) {
   saveButtonGreen(characters);
+
   saveButton.classList.remove("unsaved-character");
  showElement(characterCreation);
+
}
  handleStyle(characters, selectedElement);
 
  
   characterCreation.reset();
+
function saveButtonOrange(saveButton) {
 +
   saveButton.classList.add("unsaved-character");
 +
}
  
   for (var [name, value] of Object.entries(formData)) {
+
function characterCreationListener(characters, battle) {
     var formElement = characterCreation[name];
+
   var { characterCreation, saveButton, weaponCategory } = characters;
 +
 
 +
  characterCreation.addEventListener("submit", function (event) {
 +
     event.preventDefault();
  
     if (!formElement) {
+
     if (characters.unsavedChanges) {
       continue;
+
       saveCharacter(characters.savedCharacters, characterCreation, battle);
 +
      saveButtonGreen(saveButton);
 +
      characters.unsavedChanges = false;
 
     }
 
     }
 +
  });
  
    if (formElement.type === "checkbox") {
+
  document.addEventListener("keydown", function (event) {
      if (value === "on") {
+
    if (event.ctrlKey && event.key === "s") {
        formElement.checked = true;
+
      event.preventDefault();
       }
+
       saveButton.click();
    } else {
 
      formElement.value = value;
 
 
     }
 
     }
   }
+
   });
   var selectedRace = characterCreation.race.value;
+
 
  var selectedClass = characterCreation.class.value;
+
   weaponCategory.addEventListener("mouseover", function (event) {
 +
    label = event.target.closest("label");
  
  filterClass(selectedRace, characters.classChoice, true);
+
    if (label) {
  filterWeapon(
+
      var tooltip = label.lastChild;
    selectedRace,
 
    characters.weapon,
 
    characters.weaponCategory,
 
    true
 
  );
 
  
  var newWeapon = getSelectedWeapon(characters.weaponCategory);
+
      if (tooltip.classList.contains("popContenu")) {
  handleWeaponDisplay(
+
        var tooltipRect = tooltip.getBoundingClientRect();
    characters.weaponDisplay,
+
        var modalRect = weaponCategory.getBoundingClientRect();
    newWeapon,
 
    characters.weapon.value
 
  );
 
  filterUpgrade(
 
    selectedRace,
 
    characters.weaponUpgrade,
 
    characters.weapon.value,
 
    characters.randomAttackValue,
 
    characters.randomMagicAttackValue,
 
    formData.upgrade
 
  );
 
  filterState(characters.stateChoice, characters.polymorphMonster);
 
  filterPlayerRank(characters.lowRankCheckbox, characters.playerRankChoice);
 
  filterSkills(selectedClass, characters.skillElementsToFilter);
 
}
 
  
function handleClickOnCharacter(
+
        if (tooltipRect.right > modalRect.right) {
   spanInput,
+
          tooltip.style.left = "-100%";
   target,
+
        } else if (tooltipRect.left < modalRect.left) {
 +
          tooltip.style.left = "200%";
 +
        }
 +
      }
 +
    }
 +
  });
 +
}
 +
 
 +
function downloadData(content, type, filename) {
 +
  var link = document.createElement("a");
 +
   var blob = new Blob([content], { type: type });
 +
  var blobURL = URL.createObjectURL(blob);
 +
 
 +
  link.href = blobURL;
 +
  link.download = filename;
 +
  document.body.appendChild(link);
 +
 
 +
  link.click();
 +
  document.body.removeChild(link);
 +
  URL.revokeObjectURL(blobURL);
 +
}
 +
 
 +
function uploadCharacter(
 +
   selectedFiles,
 
   characters,
 
   characters,
   characterElement,
+
   characterTemplate,
   battle,
+
   charactersContainer,
   edition
+
   battle
 
) {
 
) {
   var displayedPseudo = characters.characterCreation.name.value;
+
   var selectFilesLength = selectedFiles.length;
  var pseudo = spanInput.dataset.name;
+
 
 +
  for (var fileIndex = 0; fileIndex < selectFilesLength; fileIndex++) {
 +
    var selectedFile = selectedFiles[fileIndex];
 +
 
 +
    if (selectedFile.type === "text/plain") {
 +
      var reader = new FileReader();
 +
      reader.onload = function (e) {
 +
        var fileContent = e.target.result;
 +
        try {
 +
          var characterDataObject = JSON.parse(fileContent);
 +
 
 +
          if (characterDataObject.hasOwnProperty("name")) {
 +
            var characterPseudo = String(characterDataObject.name);
  
  if (edition) {
+
            hideElement(characters.characterCreation);
    if (!characters.unsavedChanges) {
+
            characterPseudo = validPseudo(characterPseudo);
      updateForm(
 
        characters.savedCharacters[pseudo],
 
        characters.characterCreation,
 
        characters,
 
        characterElement
 
      );
 
    } else if (displayedPseudo === pseudo) {
 
      // pass
 
    } else {
 
      var result = confirm(
 
        "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
 
      );
 
  
      if (result) {
+
            [characterDataObject, characterPseudo] = addUniquePseudo(
        updateForm(
+
              characterDataObject,
          characters.savedCharacters[pseudo],
+
              Object.keys(characters.savedCharacters)
          characters.characterCreation,
+
            );
          characters,
+
            var selectedCharacter = handleNewCharacter(
          characterElement
+
              characters,
        );
+
              characterTemplate,
        characters.unsavedChanges = false;
+
              charactersContainer,
      }
+
              battle,
    }
+
              characterPseudo
  } else {
+
            )[0];
    if (target.tagName === "path") {
 
      target = target.parentElement;
 
    }
 
  
    switch (target.dataset.icon) {
+
            if (selectFilesLength === 1) {
      case "duplicate":
+
              updateForm(
        if (!characters.unsavedChanges) {
+
                characterDataObject,
          addNewCharacter(
+
                characters.characterCreation,
            characters,
+
                characters,
            characters.newCharacterTemplate,
+
                selectedCharacter,
            characters.charactersContainer,
+
                battle
            battle,
+
              );
            pseudo
+
            }
          );
 
        } else {
 
          var result = confirm(
 
            "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
 
          );
 
  
          if (result) {
+
             saveCharacter(
             addNewCharacter(
+
               characters.savedCharacters,
              characters,
+
               characters.characterCreation,
               characters.newCharacterTemplate,
 
               characters.charactersContainer,
 
 
               battle,
 
               battle,
               pseudo
+
               true,
 +
              characterDataObject
 
             );
 
             );
            saveButtonGreen(characters);
+
          }
            characters.unsavedChanges = false;
+
        } catch (error) {
 +
          console.log(error);
 +
          if (error.name === "TypeError") {
 +
            // delete the character
 
           }
 
           }
 
         }
 
         }
        break;
+
      };
 +
      reader.readAsText(selectedFile);
 +
    }
 +
  }
 +
}
 +
 
 +
function handleUploadCharacter(
 +
  characters,
 +
  characterTemplate,
 +
  charactersContainer,
 +
  battle
 +
) {
 +
  var characterInput = characters.characterInput;
 +
  var dropZone = characters.dropZone;
  
      case "download":
+
  characterInput.accept = ".txt";
        downloadCharacter(characters.savedCharacters[pseudo]);
+
  characterInput.multiple = true;
        break;
+
  dropZone.setAttribute("tabindex", "0");
  
      case "delete":
+
  dropZone.addEventListener("click", function () {
        var result = confirm(
+
    characterInput.click();
          "Voulez-vous vraiment supprimer définitivement le personnage " +
+
  });
            pseudo +
 
            " ?"
 
        );
 
        if (result) {
 
          deleteCharacter(characters, pseudo, characterElement, battle);
 
        }
 
        break;
 
    }
 
  }
 
}
 
  
function handleNewCharacter(
+
  dropZone.addEventListener("dragover", function (event) {
  characters,
+
    event.preventDefault();
  characterTemplate,
+
    dropZone.classList.add("drop-zone--dragover");
  charactersContainer,
+
  });
  battle,
 
  pseudo
 
) {
 
  var newCharacterTemplate = characterTemplate.cloneNode(true);
 
  var spanInput = newCharacterTemplate.querySelector("span.input");
 
  
   newCharacterTemplate.setAttribute("tabindex", "0");
+
   ["dragleave", "dragend"].forEach(function (type) {
   charactersContainer.appendChild(newCharacterTemplate);
+
    dropZone.addEventListener(type, function () {
 +
      dropZone.classList.remove("drop-zone--dragover");
 +
    });
 +
   });
  
   if (pseudo) {
+
   dropZone.addEventListener("drop", function (event) {
     spanInput.textContent = pseudo;
+
     event.preventDefault();
     spanInput.setAttribute("data-name", pseudo);
+
     uploadCharacter(
   }
+
      event.dataTransfer.files,
 +
      characters,
 +
      characterTemplate,
 +
      charactersContainer,
 +
      battle
 +
    );
 +
    dropZone.classList.remove("drop-zone--dragover");
 +
   });
  
   newCharacterTemplate.addEventListener("click", function (event) {
+
   characterInput.addEventListener("change", function (event) {
     var target = event.target;
+
     uploadCharacter(
 
+
      event.target.files,
    if (target.tagName === "path" || target.tagName === "svg") {
+
       characters,
       handleClickOnCharacter(
+
      characterTemplate,
        spanInput,
+
       charactersContainer,
        target,
+
       battle
        characters,
+
    );
        newCharacterTemplate,
 
        battle
 
       );
 
    } else {
 
       handleClickOnCharacter(
 
        spanInput,
 
        null,
 
        characters,
 
        newCharacterTemplate,
 
        battle,
 
        true
 
      );
 
    }
 
 
   });
 
   });
 +
}
  
  newCharacterTemplate.addEventListener("keydown", function (event) {
+
function deleteCharacter(characters, pseudo, element, battle) {
    if (event.keyCode === 13) {
+
  battle.battleForm.reset();
      event.target.click();
+
  delete characters.savedCharacters[pseudo];
    }
+
  element.remove();
   });
+
 
 +
   updateSavedCharacters(characters.savedCharacters);
 +
  removeBattleChoice(battle, pseudo);
  
   return [newCharacterTemplate, spanInput];
+
   if (
 +
    !Object.keys(characters.savedCharacters).length ||
 +
    characters.characterCreation.name.value === pseudo
 +
  ) {
 +
    saveButtonGreen(characters.saveButton);
 +
    characters.unsavedChanges = false;
 +
    hideElement(characters.characterCreation);
 +
    showElement(characters.characterCreation.previousElementSibling);
 +
  }
 
}
 
}
  
function validPseudo(pseudo) {
+
function deleteMonster(characters, monsterVnum, element, battle) {
   var newPseudo = pseudo.replace(/[^A-Za-z0-9]+/g, "");
+
   battle.battleForm.reset();
 +
  characters.savedMonsters.splice(
 +
    characters.savedMonsters.indexOf(monsterVnum),
 +
    1
 +
  );
  
   if (!newPseudo) {
+
   if (element) {
     return "Pseudo";
+
     element.remove();
 
   }
 
   }
  
   return newPseudo;
+
   updateSavedMonsters(characters.savedMonsters);
 +
  removeBattleChoice(battle, monsterVnum);
 
}
 
}
  
function addNewCharacter(
+
function handleStyle(characters, selectedElement) {
   characters,
+
  var currentCharacter = characters.currentCharacter;
   characterTemplate,
+
 
   charactersContainer,
+
  if (currentCharacter) {
   battle,
+
    currentCharacter.classList.remove("selected-character");
   pseudoToDuplicate
+
  }
 +
 
 +
  selectedElement.classList.add("selected-character");
 +
   characters.currentCharacter = selectedElement;
 +
}
 +
 
 +
function updateForm(
 +
  formData,
 +
   characterCreation,
 +
   characters,
 +
   selectedElement,
 +
   battle
 
) {
 
) {
   function editAndSetCharacterPseudoInput(selectedCharacter, spanInput) {
+
   saveButtonGreen(characters.saveButton);
    var maxPseudoLength = 15;
+
  hideElement(characterCreation.previousElementSibling);
 +
  showElement(characterCreation);
 +
  handleStyle(characters, selectedElement);
 +
 
 +
  characterCreation.reset();
  
    var selection = window.getSelection();
+
  for (var [name, value] of Object.entries(formData)) {
     var range = document.createRange();
+
     var formElement = characterCreation[name];
  
     if (pseudoToDuplicate) {
+
     if (!formElement) {
       spanInput.textContent = pseudoToDuplicate;
+
       continue;
 
     }
 
     }
  
     spanInput.contentEditable = true;
+
     if (formElement.type === "checkbox") {
     spanInput.focus();
+
      if (isChecked(value)) {
     range.selectNodeContents(spanInput);
+
        formElement.checked = true;
    selection.removeAllRanges();
+
      }
    selection.addRange(range);
+
     } else {
 +
      formElement.value = value;
 +
     }
 +
  }
 +
  var selectedRace = characterCreation.race.value;
 +
  var classChoice = characterCreation.class;
 +
  var weaponElement = characterCreation.weapon;
  
    function pseudoValidation() {
+
  filterClass(selectedRace, classChoice, true);
      var characterPseudo = validPseudo(spanInput.textContent);
+
  filterWeapon(
      var characterDataObject = { name: characterPseudo };
+
    selectedRace,
 +
    weaponElement,
 +
    characters.weaponCategory,
 +
    battle.constants.allowedWeaponsPerRace,
 +
    true
 +
  );
  
      if (pseudoToDuplicate) {
+
  var newWeapon = getSelectedWeapon(characters.weaponCategory);
        characterDataObject = copyObject(
 
          characters.savedCharacters[pseudoToDuplicate]
 
        );
 
        characterDataObject.name = characterPseudo;
 
      }
 
  
      [characterDataObject, characterPseudo] = addUniquePseudo(
+
  handleWeaponDisplay(characters.weaponDisplay, newWeapon, weaponElement.value);
        characterDataObject,
+
  filterUpgrade(
        Object.keys(characters.savedCharacters)
+
    selectedRace,
      );
+
    characterCreation.weaponUpgrade,
 
+
    weaponElement.value,
      selection.removeAllRanges();
+
    characters.randomAttackValue,
      spanInput.contentEditable = false;
+
    characters.randomMagicAttackValue,
      spanInput.textContent = characterPseudo;
+
    formData.weaponUpgrade
      spanInput.setAttribute("data-name", characterPseudo);
+
  );
 +
  filterState(
 +
    characterCreation.state.value,
 +
    characterCreation.polymorphMonster
 +
  );
 +
  filterCheckbox(
 +
    characterCreation.lowRank,
 +
    characterCreation.playerRank.parentElement
 +
  );
 +
  filterCheckbox(characterCreation.onYohara, characters.yoharaCreation);
 +
  filterCheckbox(characterCreation.isBlessed, characters.blessingCreation);
 +
  filterCheckbox(characterCreation.isMarried, characters.marriageCreation);
 +
  filterSkills(classChoice.value, characters.skillElementsToFilter);
 +
  handleBonusVariationUpdate(characterCreation, characters.bonusVariation);
 +
}
 +
 
 +
function handleClickOnCharacter(
 +
  spanInput,
 +
  target,
 +
  characters,
 +
  characterElement,
 +
  battle,
 +
  edition
 +
) {
 +
  var displayedPseudo = characters.characterCreation.name.value;
 +
  var pseudo = spanInput.dataset.name;
  
 +
  if (edition) {
 +
    if (!characters.unsavedChanges) {
 
       updateForm(
 
       updateForm(
         characterDataObject,
+
         characters.savedCharacters[pseudo],
 
         characters.characterCreation,
 
         characters.characterCreation,
 
         characters,
 
         characters,
         selectedCharacter
+
         characterElement,
 +
        battle
 
       );
 
       );
      saveCharacter(
+
    } else if (displayedPseudo === pseudo) {
        characters.savedCharacters,
+
      // pass
        characters.characterCreation,
+
    } else {
        battle,
+
      var result = confirm(
         true
+
         "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
 
       );
 
       );
    }
 
  
    function handleMaxLength(event) {
+
       if (result) {
       if (spanInput.textContent.length > maxPseudoLength) {
+
         updateForm(
         spanInput.textContent = spanInput.textContent.slice(0, maxPseudoLength);
+
          characters.savedCharacters[pseudo],
        range.setStart(spanInput.childNodes[0], maxPseudoLength);
+
          characters.characterCreation,
         selection.removeAllRanges();
+
          characters,
         selection.addRange(range);
+
          characterElement,
 +
          battle
 +
         );
 +
         characters.unsavedChanges = false;
 
       }
 
       }
 
     }
 
     }
 
+
  } else {
     function handleBlur() {
+
     if (target.tagName === "path") {
      spanInput.removeEventListener("blur", handleBlur);
+
       target = target.parentElement;
       spanInput.removeEventListener("input", handleMaxLength);
 
      pseudoValidation();
 
 
     }
 
     }
  
     function handleKeyDown(event) {
+
     switch (target.dataset.icon) {
       if (event.key === "Enter") {
+
       case "duplicate":
        event.preventDefault();
+
        if (!characters.unsavedChanges) {
 
+
          addNewCharacter(
        spanInput.removeEventListener("keydown", handleKeyDown);
+
            characters,
        spanInput.removeEventListener("blur", handleBlur);
+
            characters.newCharacterTemplate,
         spanInput.removeEventListener("input", handleMaxLength);
+
            characters.charactersContainer,
 +
            battle,
 +
            pseudo
 +
          );
 +
         } else {
 +
          var result = confirm(
 +
            "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
 +
          );
  
        pseudoValidation();
+
          if (result) {
      }
+
            addNewCharacter(
    }
+
              characters,
 +
              characters.newCharacterTemplate,
 +
              characters.charactersContainer,
 +
              battle,
 +
              pseudo
 +
            );
 +
            saveButtonGreen(characters.saveButton);
 +
            characters.unsavedChanges = false;
 +
          }
 +
        }
 +
        break;
  
    spanInput.addEventListener("input", handleMaxLength);
+
      case "download":
    spanInput.addEventListener("keydown", handleKeyDown);
+
        var character = characters.savedCharacters[pseudo];
    spanInput.addEventListener("blur", handleBlur);
+
        downloadData(
  }
+
          JSON.stringify(character),
 +
          "text/plain",
 +
          character.name + ".txt"
 +
        );
 +
        break;
  
  hideElement(characters.characterCreation);
+
      case "delete":
  var [selectedCharacter, spanInput] = handleNewCharacter(
+
        var result = confirm(
    characters,
+
          "Voulez-vous vraiment supprimer définitivement le personnage " +
    characterTemplate,
+
            pseudo +
    charactersContainer,
+
            " ?"
    battle
+
        );
  );
+
        if (result) {
 
+
          deleteCharacter(characters, pseudo, characterElement, battle);
   editAndSetCharacterPseudoInput(selectedCharacter, spanInput);
+
        }
 +
        break;
 +
    }
 +
   }
 
}
 
}
  
function handleFocus() {
+
function handleNewCharacter(
   var tooltipLinks = document.querySelectorAll("div.tooltip a");
+
  characters,
   tooltipLinks.forEach(function (link) {
+
  characterTemplate,
    link.setAttribute("tabindex", -1);
+
  charactersContainer,
  });
+
  battle,
}
+
  pseudo
 +
) {
 +
   var newCharacterTemplate = characterTemplate.cloneNode(true);
 +
   var spanInput = newCharacterTemplate.querySelector("span.input");
  
function characterManagement(characters, battle) {
+
  newCharacterTemplate.setAttribute("tabindex", "0");
   var characterTemplate = characters.newCharacterTemplate;
+
   charactersContainer.appendChild(newCharacterTemplate);
   var charactersContainer = characters.charactersContainer;
+
 
 +
   if (pseudo) {
 +
    spanInput.textContent = pseudo;
 +
    spanInput.setAttribute("data-name", pseudo);
 +
  }
  
   Object.keys(characters.savedCharacters).forEach(function (pseudo) {
+
   newCharacterTemplate.addEventListener("click", function (event) {
     handleNewCharacter(
+
     var target = event.target;
      characters,
 
      characterTemplate,
 
      charactersContainer,
 
      battle,
 
      pseudo
 
    );
 
  });
 
  
  characters.addNewCharacterButton.addEventListener("click", function (event) {
+
    if (target.tagName === "path" || target.tagName === "svg") {
    if (!characters.unsavedChanges) {
+
      handleClickOnCharacter(
      addNewCharacter(
+
        spanInput,
 +
        target,
 
         characters,
 
         characters,
         characterTemplate,
+
         newCharacterTemplate,
        charactersContainer,
 
 
         battle
 
         battle
 
       );
 
       );
 
     } else {
 
     } else {
       var result = confirm(
+
       handleClickOnCharacter(
         "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
+
         spanInput,
 +
        null,
 +
        characters,
 +
        newCharacterTemplate,
 +
        battle,
 +
        true
 
       );
 
       );
 
      if (result) {
 
        addNewCharacter(
 
          characters,
 
          characterTemplate,
 
          charactersContainer,
 
          battle
 
        );
 
        saveButtonGreen(characters);
 
        characters.unsavedChanges = false;
 
      }
 
 
     }
 
     }
 
   });
 
   });
  
   characters.uploadCharacter.addEventListener("click", function (event) {
+
   newCharacterTemplate.addEventListener("keydown", function (event) {
     uploadCharacter(characters, characterTemplate, charactersContainer, battle);
+
     if (event.keyCode === 13) {
 +
      event.target.click();
 +
    }
 
   });
 
   });
  
   characters.characterCreation.addEventListener("change", function () {
+
   return [newCharacterTemplate, spanInput];
    saveButtonOrange(characters);
+
}
    characters.unsavedChanges = true;
 
  });
 
  
  filterForm(characters, battle);
+
function validPseudo(pseudo) {
  characterCreationListener(characters, battle);
+
   var newPseudo = pseudoFormat(pseudo);
   handleFocus();
 
  
   window.addEventListener("beforeunload", function (event) {
+
   if (!newPseudo) {
     if (characters.unsavedChanges) {
+
     return "Pseudo";
      event.preventDefault();
+
  }
      event.returnValue = "";
+
 
      return "";
+
   return newPseudo;
    }
 
   });
 
 
}
 
}
  
function handleNewMonster(
+
function addNewCharacter(
 
   characters,
 
   characters,
   monsterTemplate,
+
   characterTemplate,
   monstersContainer,
+
   charactersContainer,
 
   battle,
 
   battle,
   monsterName,
+
   pseudoToDuplicate
  monsterList
 
 
) {
 
) {
   var newMonsterTemplate = monsterTemplate.cloneNode(true);
+
   function editAndSetCharacterPseudoInput(selectedCharacter, spanInput) {
  var spanInput = newMonsterTemplate.querySelector("span.input");
+
    var maxPseudoLength = 20;
  var deleteSvg = newMonsterTemplate.querySelector("svg");
 
  
  spanInput.textContent = monsterName;
+
    var selection = window.getSelection();
  monstersContainer.appendChild(newMonsterTemplate);
+
    var range = document.createRange();
  
  newMonsterTemplate.setAttribute("tabindex", "0");
+
    if (pseudoToDuplicate) {
  newMonsterTemplate.setAttribute("data-name", monsterName);
+
      spanInput.textContent = pseudoToDuplicate;
  monstersContainer.appendChild(newMonsterTemplate);
+
    }
  
  deleteSvg.addEventListener("click", function (event) {
+
    spanInput.contentEditable = true;
     deleteMonster(characters, monsterName, newMonsterTemplate, battle);
+
    spanInput.focus();
     var inputMonster = monsterList.querySelector(
+
     range.selectNodeContents(spanInput);
      "input[name='" + monsterName + "']"
+
     selection.removeAllRanges();
    );
+
     selection.addRange(range);
     inputMonster.checked = false;
 
  });
 
}
 
  
function monsterManagement(characters, battle) {
+
     function pseudoValidation() {
  function handleDropdown(searchMonster, monsterList) {
+
       var characterPseudo = validPseudo(spanInput.textContent);
     searchMonster.addEventListener("focus", function (event) {
+
      var characterDataObject = { name: characterPseudo };
       showElement(monsterList);
 
    });
 
  
    document.addEventListener("mousedown", function (event) {
+
      if (pseudoToDuplicate) {
      var target = event.target;
+
        characterDataObject = copyObject(
      if (!monsterList.contains(target) && !searchMonster.contains(target)) {
+
          characters.savedCharacters[pseudoToDuplicate]
         hideElement(monsterList);
+
        );
 +
         characterDataObject.name = characterPseudo;
 
       }
 
       }
    });
 
  }
 
  
  function addMonsterNames(monsterList) {
+
      [characterDataObject, characterPseudo] = addUniquePseudo(
    var monsterIndex = 0;
+
        characterDataObject,
 +
        Object.keys(characters.savedCharacters)
 +
      );
  
    for (var monsterName in monsterData) {
+
       selection.removeAllRanges();
       var li = document.createElement("li");
+
       spanInput.contentEditable = false;
       var label = document.createElement("label");
+
       spanInput.textContent = characterPseudo;
       var input = document.createElement("input");
+
       spanInput.setAttribute("data-name", characterPseudo);
       var textNode = document.createTextNode(monsterName);
 
  
       label.htmlFor = "monster" + monsterIndex;
+
       updateForm(
       input.id = "monster" + monsterIndex;
+
        characterDataObject,
       input.type = "checkbox";
+
        characters.characterCreation,
 +
        characters,
 +
        selectedCharacter,
 +
        battle
 +
      );
 +
       saveCharacter(
 +
        characters.savedCharacters,
 +
        characters.characterCreation,
 +
        battle,
 +
        true
 +
       );
 +
    }
  
       input.name = monsterName;
+
    function handleMaxLength(event) {
 
+
       if (spanInput.textContent.length > maxPseudoLength) {
      label.appendChild(input);
+
        spanInput.textContent = spanInput.textContent.slice(0, maxPseudoLength);
      label.appendChild(textNode);
+
        range.setStart(spanInput.childNodes[0], maxPseudoLength);
      li.appendChild(label);
+
        selection.removeAllRanges();
      monsterList.appendChild(li);
+
        selection.addRange(range);
 
+
       }
       monsterIndex++;
 
 
     }
 
     }
  }
 
  
  function filterNames(searchMonster, monsterList) {
+
    function handleBlur() {
     var debounceTimer;
+
      spanInput.removeEventListener("blur", handleBlur);
 +
      spanInput.removeEventListener("input", handleMaxLength);
 +
      pseudoValidation();
 +
     }
  
     searchMonster.addEventListener("input", function (event) {
+
     function handleKeyDown(event) {
       clearTimeout(debounceTimer);
+
       if (event.key === "Enter") {
      debounceTimer = setTimeout(function () {
+
         event.preventDefault();
         var value = toNormalForm(event.target.value);
 
        for (var element of monsterList.children) {
 
          if (!isValueInArray(value, toNormalForm(element.textContent))) {
 
            hideElement(element);
 
          } else {
 
            showElement(element);
 
          }
 
        }
 
      }, 500);
 
    });
 
  }
 
  
  var monsterTemplate = characters.newMonsterTemplate;
+
        spanInput.removeEventListener("keydown", handleKeyDown);
  var monstersContainer = characters.monstersContainer;
+
        spanInput.removeEventListener("blur", handleBlur);
  var monsterList = characters.monsterList;
+
        spanInput.removeEventListener("input", handleMaxLength);
  var searchMonster = characters.searchMonster;
 
  var monsterListForm = characters.monsterListForm;
 
  
  handleDropdown(searchMonster, monsterList);
+
        pseudoValidation();
  addMonsterNames(monsterList, characters.monsterListTemplate);
+
      }
  filterNames(searchMonster, monsterList);
+
    }
 +
 
 +
    spanInput.addEventListener("input", handleMaxLength);
 +
    spanInput.addEventListener("keydown", handleKeyDown);
 +
    spanInput.addEventListener("blur", handleBlur);
 +
  }
  
   characters.savedMonsters.forEach(function (monsterName) {
+
   hideElement(characters.characterCreation);
    handleNewMonster(
+
  var [selectedCharacter, spanInput] = handleNewCharacter(
      characters,
+
    characters,
      monsterTemplate,
+
    characterTemplate,
      monstersContainer,
+
    charactersContainer,
      battle,
+
    battle
      monsterName,
+
  );
      monsterList
 
    );
 
    var inputMonster = monsterList.querySelector(
 
      "input[name='" + monsterName + "']"
 
    );
 
  
    if (inputMonster) {
+
  editAndSetCharacterPseudoInput(selectedCharacter, spanInput);
      inputMonster.checked = true;
+
}
    } else {
 
      deleteMonster(characters, monsterName, newMonsterTemplate, battle);
 
    }
 
  });
 
  
   monsterListForm.addEventListener("submit", function (event) {
+
function handleFocus() {
     event.preventDefault();
+
   var tooltipLinks = document.querySelectorAll("div.tooltip a");
 +
  tooltipLinks.forEach(function (link) {
 +
     link.setAttribute("tabindex", -1);
 
   });
 
   });
 +
}
  
   monsterListForm.addEventListener("change", function (event) {
+
function handleBonusVariationUpdate(characterCreation, bonusVariation) {
     var target = event.target;
+
   var selectedBonus = characterCreation.bonusVariation.value;
     var monsterName = target.name;
+
 
 +
  if (characterCreation.hasOwnProperty(selectedBonus)) {
 +
     handleBonusVariation(characterCreation[selectedBonus], bonusVariation);
 +
  } else {
 +
     var { minValue, maxValue } = bonusVariation;
  
     if (monsterName === "search-monster") {
+
     minValue.removeAttribute("min");
      return;
+
     minValue.removeAttribute("max");
     }
 
  
     if (target.checked) {
+
     maxValue.removeAttribute("min");
      handleNewMonster(
+
    maxValue.removeAttribute("max");
        characters,
 
        monsterTemplate,
 
        monstersContainer,
 
        battle,
 
        monsterName,
 
        monsterList
 
      );
 
  
      characters.savedMonsters.push(monsterName);
+
    hideElement(bonusVariation.container);
      updateSavedMonsters(characters.savedMonsters);
+
   }
      addBattleChoice(battle, monsterName, true);
 
    } else {
 
      var currentMonsterTemplate = monstersContainer.querySelector(
 
        "[data-name='" + monsterName + "']"
 
      );
 
      deleteMonster(characters, monsterName, currentMonsterTemplate, battle);
 
    }
 
   });
 
 
}
 
}
  
function removeBattleChoice(battle, name) {
+
function getTargetContent(targetParent, targetName, isSkill) {
   var battleSelects = [battle.attackerSelection, battle.victimSelection];
+
   var targetContent = "";
 +
 
 +
  if (targetParent.children.length <= 1) {
 +
    targetContent = targetParent.textContent;
 +
  } else if (targetName === "weaponUpgrade") {
 +
    targetContent = targetParent.children[1].textContent;
 +
  } else if (isSkill) {
 +
    var container = targetParent.children[1];
 +
 
 +
    for (var index = 1; index < container.children.length; index++) {
 +
      var element = container.children[index];
 +
 
 +
      if (element.checkVisibility()) {
 +
        targetContent += element.textContent;
 +
      }
 +
    }
 +
  } else {
 +
    for (var index = 1; index < targetParent.children.length; index++) {
 +
      var element = targetParent.children[index];
  
  battleSelects.forEach(function (battleSelect) {
+
       if (element.checkVisibility()) {
    for (
+
         targetContent += element.textContent;
      var optionIndex = 0;
 
      optionIndex < battleSelect.options.length;
 
      optionIndex++
 
    ) {
 
       if (battleSelect.options[optionIndex].value === name) {
 
         battleSelect.remove(optionIndex);
 
        break;
 
 
       }
 
       }
 
     }
 
     }
   });
+
   }
 +
 
 +
  return targetContent;
 
}
 
}
  
function addBattleChoice(battle, name, isMonster = false) {
+
function handleBonusVariation(target, bonusVariation, isSelectedByUser) {
   function createOption(text) {
+
   var { activation, inputDisplay, minValue, maxValue, container } =
     var option = document.createElement("option");
+
     bonusVariation;
    option.textContent = text;
+
 
    option.value = text;
+
  var {
 +
    min: targetMin,
 +
    max: targetMax,
 +
    name: targetName,
 +
    value: targetValue,
 +
    parentElement: targetParent,
 +
    tagName,
 +
  } = target;
 +
 
 +
  targetMin = Number(targetMin);
 +
  targetMax = Number(targetMax);
 +
  targetValue = Number(targetValue);
 +
 
 +
  var isSkill = tagName === "SELECT";
  
     if (!isMonster) {
+
  if (container.contains(target) || targetName == 0) {
       option.classList.add("notranslate");
+
     if (!isSelectedByUser) {
 +
       hideElement(container);
 
     }
 
     }
 +
    return;
 +
  }
  
     return option;
+
  if (isSkill) {
 +
     var options = target.options;
 +
 
 +
    targetMin = options[0].value;
 +
    targetMax = options[options.length - 1].value;
 
   }
 
   }
  
   if (isMonster && monsterData[name][1]) {
+
  minValue.min = targetMin;
     // pass
+
  minValue.max = targetMax;
 +
 
 +
  maxValue.min = targetMin;
 +
  maxValue.max = targetMax;
 +
 
 +
   if (isSelectedByUser) {
 +
     var { input, tab } = bonusVariation;
 +
 
 +
    inputDisplay.value = getTargetContent(targetParent, targetName, isSkill);
 +
 
 +
    input.value = targetName;
 +
    minValue.value = Math.max(targetValue - 10, targetMin);
 +
    maxValue.value = Math.min(targetValue + 10, targetMax);
 +
 
 +
    activation.checked = true;
 +
 
 +
    tab.click();
 +
    tab.scrollIntoView(true);
 +
 
 +
    input.dispatchEvent(new Event("change", { bubbles: true }));
 
   } else {
 
   } else {
     battle.attackerSelection.appendChild(createOption(name));
+
     if (minValue.value < targetMin) {
 +
      minValue.value = targetMin;
 +
      minValue.dispatchEvent(new Event("change", { bubbles: true }));
 +
    }
 +
 
 +
    if (maxValue.value > targetMax) {
 +
      maxValue.value = targetMax;
 +
      maxValue.dispatchEvent(new Event("change", { bubbles: true }));
 +
    }
 
   }
 
   }
  
   battle.victimSelection.appendChild(createOption(name));
+
   inputDisplay.style.width = inputDisplay.value.length * 0.55 + "em";
 +
  showElement(container);
 
}
 
}
  
function updateBattleChoice(characters, battle) {
+
function characterManagement(characters, battle) {
   var keys = Object.keys(characters.savedCharacters);
+
   var {
 
+
    newCharacterTemplate: characterTemplate,
  for (var index = 0; index < keys.length; index++) {
+
    charactersContainer,
     var pseudo = keys[index];
+
    addNewCharacterButton,
     addBattleChoice(battle, pseudo);
+
    saveButton,
   }
+
     characterCreation,
 +
     bonusVariation,
 +
   } = characters;
  
   characters.savedMonsters.forEach(function (monsterName) {
+
   Object.keys(characters.savedCharacters).forEach(function (pseudo) {
     addBattleChoice(battle, monsterName, true);
+
     handleNewCharacter(
 +
      characters,
 +
      characterTemplate,
 +
      charactersContainer,
 +
      battle,
 +
      pseudo
 +
    );
 
   });
 
   });
}
 
  
function isPC(character) {
+
  addNewCharacterButton.addEventListener("click", function (event) {
  if (character.race === 0 || character.race === 1) {
+
    if (!characters.unsavedChanges) {
    return false;
+
      addNewCharacter(
  }
+
        characters,
  return true;
+
        characterTemplate,
}
+
        charactersContainer,
 +
        battle
 +
      );
 +
    } else {
 +
      var result = confirm(
 +
        "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
 +
      );
  
function isBoss(character) {
+
      if (result) {
  return character.race === 0 && character.rank >= 5;
+
        addNewCharacter(
}
+
          characters,
 +
          characterTemplate,
 +
          charactersContainer,
 +
          battle
 +
        );
 +
        saveButtonGreen(saveButton);
 +
        characters.unsavedChanges = false;
 +
      }
 +
    }
 +
  });
  
function isStone(character) {
+
  handleUploadCharacter(
   return character.race === 1;
+
    characters,
}
+
    characterTemplate,
 +
    charactersContainer,
 +
    battle
 +
   );
  
function isMagicClass(character) {
+
  characterCreation.addEventListener("change", function () {
  return character.race === "shaman" || character.class === "black_magic";
+
    saveButtonOrange(saveButton);
}
+
    characters.unsavedChanges = true;
 +
  });
  
function isPolymorph(character) {
+
  function handleLongPress(target) {
  return character.state === "polymorph";
+
    if (target.tagName !== "INPUT" && target.tagName !== "SELECT") {
}
+
      target = target.querySelector("input");
 +
    }
  
function isRiding(character) {
+
    if (
  return character.state === "horse";
+
      !target ||
}
+
      (target.type !== "number" &&
 +
        !target.classList.contains("skill-select") &&
 +
        target.name !== "weaponUpgrade")
 +
    ) {
 +
      return;
 +
    }
  
function isBow(weapon) {
+
    handleBonusVariation(target, bonusVariation, true);
  return weapon[1] === 2;
 
}
 
 
 
function calcAttackFactor(attacker, victim) {
 
  function calcCoeffK(dex, level) {
 
    return Math.min(90, Math.floor((2 * dex + level) / 3));
 
 
   }
 
   }
  
   var K1 = calcCoeffK(attacker.polymorphDex, attacker.level);
+
   characterCreation.addEventListener("click", function (event) {
   var K2 = calcCoeffK(victim.polymorphDex, attacker.level);
+
    if (event.shiftKey || event.ctrlKey) {
 +
      handleLongPress(event.target);
 +
    }
 +
   });
  
   var AR = (K1 + 210) / 300;
+
   var longPressTimer;
  var ER = (((2 * K2 + 5) / (K2 + 95)) * 3) / 10;
 
  
   return AR - ER;
+
   characterCreation.addEventListener("touchstart", function (event) {
}
+
    longPressTimer = setTimeout(function () {
 +
      handleLongPress(event.target);
 +
    }, 800);
 +
  });
  
function calcMainAttackValue(attacker, attackerWeapon) {
+
  characterCreation.addEventListener("touchend", function () {
  var leadership = 0;
+
    clearTimeout(longPressTimer);
   var rawWeaponAttackValue = 0;
+
   });
  
   if (isPC(attacker)) {
+
   characterCreation.addEventListener("touchmove", function () {
     var rawWeaponAttackValue = attackerWeapon[3][attacker.upgrade];
+
     clearTimeout(longPressTimer);
 +
  });
  
    if (!rawWeaponAttackValue) {
+
  filterForm(characters, battle);
      rawWeaponAttackValue = 0;
+
  characterCreationListener(characters, battle);
    }
+
  handleFocus();
  
     leadership = attacker.leadership;
+
  window.addEventListener("beforeunload", function (event) {
  }
+
     if (characters.unsavedChanges) {
 
+
      event.preventDefault();
   return 2 * (attacker.level + rawWeaponAttackValue) + leadership;
+
      return "";
 +
    }
 +
   });
 
}
 
}
  
function calcStatAttackValue(character) {
+
function handleNewMonster(
   switch (character.race) {
+
   characters,
    case "warrior":
+
  monsterTemplate,
    case "sura":
+
  monstersContainer,
      return 2 * character.str;
+
  battle,
    case "ninja":
+
  monsterVnum,
      return Math.floor((1 / 4) * (character.str + 7 * character.dex));
+
  monsterList
    case "shaman":
+
) {
      return Math.floor((1 / 3) * (5 * character.int + character.dex));
+
  var newMonsterTemplate = monsterTemplate.cloneNode(true);
    case "lycan":
+
  var spanInput = newMonsterTemplate.querySelector("span.input");
      return character.vit + 2 * character.dex;
+
  var deleteSvg = newMonsterTemplate.querySelector("svg");
    default:
+
  var monsterName = getMonsterName(monsterVnum);
      return 2 * character.str;
 
  }
 
}
 
  
function calcSecondaryAttackValue(attacker, attackerWeapon) {
+
  var link = document.createElement("a");
   var attackValueOther = 0;
+
  link.href = mw.util.getUrl(monsterName);
 +
  link.title = monsterName;
 +
   link.textContent = monsterName;
  
   var minAttackValue = 0;
+
   spanInput.appendChild(link);
   var maxAttackValue = 0;
+
   monstersContainer.appendChild(newMonsterTemplate);
  
   var minAttackValueSlash = 0;
+
   newMonsterTemplate.setAttribute("tabindex", "0");
   var maxAttackValueSlash = 0;
+
   newMonsterTemplate.setAttribute("data-name", monsterVnum);
 +
  monstersContainer.appendChild(newMonsterTemplate);
  
   if (isPC(attacker)) {
+
   deleteSvg.addEventListener("click", function (event) {
     if (isValueInArray("serpent", attackerWeapon[0].toLowerCase())) {
+
     deleteMonster(characters, monsterVnum, newMonsterTemplate, battle);
       var rawAttackValue = attackerWeapon[3][attacker.upgrade];
+
    var inputMonster = monsterList.querySelector(
 +
       "input[name='" + monsterVnum + "']"
 +
    );
 +
    inputMonster.checked = false;
 +
  });
 +
}
  
       minAttackValue = attacker.minAttackValueRandom - rawAttackValue;
+
function monsterManagement(characters, battle) {
      maxAttackValue = attacker.maxAttackValueRandom - rawAttackValue;
+
  function handleDropdown(searchMonster, monsterList) {
 +
    searchMonster.addEventListener("focus", function (event) {
 +
       showElement(monsterList);
 +
    });
  
      minAttackValue = Math.max(0, minAttackValue);
+
    document.addEventListener("mousedown", function (event) {
       maxAttackValue = Math.max(minAttackValue, maxAttackValue);
+
      var target = event.target;
    } else {
+
       if (!monsterList.contains(target) && !searchMonster.contains(target)) {
      minAttackValue = attackerWeapon[2][2];
+
        hideElement(monsterList);
       maxAttackValue = attackerWeapon[2][3];
+
       }
    }
+
    });
 +
  }
  
     minAttackValueSlash = Math.min(
+
  function addMonsterNames(monsterList) {
       attacker.minAttackValueSlash,
+
     var lastMonsterAttributeIndex = monsterData[101].length - 1;
       attacker.maxAttackValueSlash
+
 
    );
+
    for (var monsterVnum in monsterData) {
    maxAttackValueSlash = Math.max(
+
       var li = document.createElement("li");
       attacker.minAttackValueSlash,
+
       var label = document.createElement("label");
       attacker.maxAttackValueSlash
+
      var input = document.createElement("input");
    );
+
      var textNode = document.createTextNode(
 +
        monsterData[monsterVnum][lastMonsterAttributeIndex]
 +
       );
 +
 
 +
      label.htmlFor = "monster" + monsterVnum;
 +
       input.id = "monster" + monsterVnum;
 +
      input.type = "checkbox";
  
    attackValueOther += attacker.attackValue;
+
      input.name = monsterVnum;
  
    if (isBow(attackerWeapon) && !isPolymorph(attacker)) {
+
      label.appendChild(input);
       attackValueOther += 25;
+
      label.appendChild(textNode);
 +
      li.appendChild(label);
 +
       monsterList.appendChild(li);
 
     }
 
     }
  } else {
 
    minAttackValue = attacker.minAttackValue;
 
    maxAttackValue = attacker.maxAttackValue;
 
 
   }
 
   }
  
   minAttackValue += attacker.minAttackValuePolymorph;
+
   function filterNames(searchMonster, monsterList) {
  maxAttackValue += attacker.maxAttackValuePolymorph;
+
    var debounceTimer;
  
  attackValueOther += attacker.statAttackValue;
+
    searchMonster.addEventListener("input", function (event) {
  attackValueOther += attacker.horseAttackValue;
+
      clearTimeout(debounceTimer);
 +
      debounceTimer = setTimeout(function () {
 +
        var value = toNormalForm(event.target.value);
 +
        for (var element of monsterList.children) {
 +
          if (!isValueInArray(value, toNormalForm(element.textContent))) {
 +
            hideElement(element);
 +
          } else {
 +
            showElement(element);
 +
          }
 +
        }
 +
      }, 500);
 +
    });
 +
  }
  
   var weaponInterval = maxAttackValue - minAttackValue + 1;
+
   var monsterTemplate = characters.newMonsterTemplate;
   var slashInterval = maxAttackValueSlash - minAttackValueSlash + 1;
+
   var monstersContainer = characters.monstersContainer;
 +
  var monsterList = characters.monsterList;
 +
  var searchMonster = characters.searchMonster;
 +
  var monsterListForm = characters.monsterListForm;
  
   var totalCardinal = weaponInterval * slashInterval * 10000;
+
   document
  var minInterval = Math.min(weaponInterval, slashInterval);
+
    .getElementById("monster-link")
 +
    .querySelector("a")
 +
    .setAttribute("target", "_blank");
  
   minAttackValue += minAttackValueSlash;
+
   handleDropdown(searchMonster, monsterList);
   maxAttackValue += maxAttackValueSlash;
+
   addMonsterNames(monsterList, characters.monsterListTemplate);
 +
  filterNames(searchMonster, monsterList);
  
   return [
+
   characters.savedMonsters.slice().forEach(function (monsterVnum) {
     minAttackValue,
+
     var inputMonster = monsterList.querySelector(
    maxAttackValue,
+
      "input[name='" + monsterVnum + "']"
     attackValueOther,
+
     );
    minInterval,
 
    totalCardinal,
 
  ];
 
}
 
  
function calcMagicAttackValue(attacker, attackerWeapon) {
+
    if (inputMonster) {
  var minMagicAttackValue = 0;
+
      handleNewMonster(
   var maxMagicAttackValue = 0;
+
        characters,
 +
        monsterTemplate,
 +
        monstersContainer,
 +
        battle,
 +
        monsterVnum,
 +
        monsterList
 +
      );
 +
      inputMonster.checked = true;
 +
    } else {
 +
      deleteMonster(characters, monsterVnum, null, battle);
 +
    }
 +
   });
  
   var minMagicAttackValueSlash = 0;
+
   monsterListForm.addEventListener("submit", function (event) {
   var maxMagicAttackValueSlash = 0;
+
    event.preventDefault();
 +
   });
  
   if (isValueInArray("serpent", attackerWeapon[0].toLowerCase())) {
+
   monsterListForm.addEventListener("change", function (event) {
     minMagicAttackValue = attacker.minMagicAttackValueRandom;
+
     var target = event.target;
     maxMagicAttackValue = attacker.maxMagicAttackValueRandom;
+
     var monsterVnum = target.name;
  
     maxMagicAttackValue = Math.max(minMagicAttackValue, maxMagicAttackValue);
+
     if (monsterVnum === "search-monster") {
  } else {
+
       return;
    var rawWeaponAttackValue = attackerWeapon[3][attacker.upgrade];
 
 
 
    if (!rawWeaponAttackValue) {
 
       rawWeaponAttackValue = 0;
 
 
     }
 
     }
  
     minMagicAttackValue = attackerWeapon[2][0] + rawWeaponAttackValue;
+
     if (target.checked) {
    maxMagicAttackValue = attackerWeapon[2][1] + rawWeaponAttackValue;
+
      handleNewMonster(
  }
+
        characters,
 
+
        monsterTemplate,
  minMagicAttackValueSlash = Math.min(
+
        monstersContainer,
    attacker.minMagicAttackValueSlash,
+
        battle,
    attacker.maxMagicAttackValueSlash
+
        monsterVnum,
  );
+
        monsterList
  maxMagicAttackValueSlash = Math.max(
+
      );
    attacker.minMagicAttackValueSlash,
 
    attacker.maxMagicAttackValueSlash
 
  );
 
  
  var weaponInterval = maxMagicAttackValue - minMagicAttackValue + 1;
+
      characters.savedMonsters.push(monsterVnum);
   var slashInterval = maxMagicAttackValueSlash - minMagicAttackValueSlash + 1;
+
      updateSavedMonsters(characters.savedMonsters);
 +
      addBattleChoice(battle, monsterVnum, true);
 +
    } else {
 +
      var currentMonsterTemplate = monstersContainer.querySelector(
 +
        "[data-name='" + monsterVnum + "']"
 +
      );
 +
      deleteMonster(characters, monsterVnum, currentMonsterTemplate, battle);
 +
    }
 +
   });
  
   var totalCardinal = weaponInterval * slashInterval * 10000;
+
   addEventListener("storage", function (event) {
  var minInterval = Math.min(weaponInterval, slashInterval);
+
    if (event.key === "newMonsterCalculator") {
 +
      var monsterVnum = Number(event.newValue);
  
  minMagicAttackValue += minMagicAttackValueSlash;
+
      if (!monsterVnum) {
  maxMagicAttackValue += maxMagicAttackValueSlash;
+
        return;
 +
      }
  
  return [minMagicAttackValue, maxMagicAttackValue, minInterval, totalCardinal];
+
      var inputMonster = monsterList.querySelector(
}
+
        "input[name='" + Math.abs(monsterVnum) + "']"
 +
      );
  
function getPolymorphPower(polymorphPoint, polymorphPowerTable) {
+
      if (inputMonster) {
   return polymorphPowerTable[polymorphPoint];
+
        if (
 +
          (monsterVnum > 0 && !inputMonster.checked) ||
 +
          (monsterVnum < 0 && inputMonster.checked)
 +
        ) {
 +
          inputMonster.click();
 +
        }
 +
      }
 +
    }
 +
   });
 
}
 
}
  
function getSkillPower(skillPoint, skillPowerTable) {
+
function removeBattleChoice(battle, name) {
   return skillPowerTable[skillPoint];
+
   var battleSelects = [battle.attackerSelection, battle.victimSelection];
 +
 
 +
  battleSelects.forEach(function (battleSelect) {
 +
    for (
 +
      var optionIndex = 0;
 +
      optionIndex < battleSelect.options.length;
 +
      optionIndex++
 +
    ) {
 +
      if (battleSelect.options[optionIndex].value === name) {
 +
        battleSelect.remove(optionIndex);
 +
        break;
 +
      }
 +
    }
 +
  });
 
}
 
}
  
function getMarriageBonusValue(character, marriageTable, itemName) {
+
function addBattleChoice(battle, name, isMonster = false) {
   var index;
+
   function createOption(text, vnum) {
  var lovePoint = character.lovePoint;
+
    var option = document.createElement("option");
 +
    option.textContent = text;
 +
    option.value = vnum;
 +
 
 +
    if (!isMonster) {
 +
      option.classList.add("notranslate");
 +
    }
  
  if (lovePoint < 65) {
+
     return option;
     index = 0;
 
  } else if (lovePoint < 80) {
 
    index = 1;
 
  } else if (lovePoint < 100) {
 
    index = 2;
 
  } else {
 
    index = 3;
 
 
   }
 
   }
  
   return marriageTable[itemName][index];
+
   var vnum = name;
}
 
  
function calcDamageWithPrimaryBonuses(damages, battleValues) {
+
  if (isMonster) {
  damages = floorMultiplication(
+
     name = getMonsterName(name);
    damages * battleValues.attackValueCoeff + battleValues.adjustCoeff,
+
   }
     1
 
  );
 
  damages += battleValues.attackValueMarriage;
 
  damages = floorMultiplication(
 
    damages,
 
    battleValues.monsterResistanceMarriageCoeff
 
  );
 
  damages = floorMultiplication(damages, battleValues.monsterResistanceCoeff);
 
   damages = floorMultiplication(damages, battleValues.typeBonusCoeff);
 
  damages +=
 
    floorMultiplication(damages, battleValues.raceBonusCoeff) -
 
    floorMultiplication(damages, battleValues.raceResistanceCoeff);
 
  damages = floorMultiplication(damages, battleValues.stoneBonusCoeff);
 
  damages = floorMultiplication(damages, battleValues.monsterBonusCoeff);
 
  
   var elementDamages = 0;
+
   if (isMonster && monsterData[vnum][1]) {
   for (var elementBonusCoeff of battleValues.elementBonusCoeff) {
+
    // pass
     elementDamages += floorMultiplication(damages, elementBonusCoeff);
+
   } else {
 +
     battle.attackerSelection.appendChild(createOption(name, vnum));
 
   }
 
   }
  damages += elementDamages;
 
 
  damages = floorMultiplication(damages, battleValues.damageMultiplier);
 
  
   return damages;
+
   battle.victimSelection.appendChild(createOption(name, vnum));
 
}
 
}
  
function calcDamageWithSecondaryBonuses(
+
function updateBattleChoice(characters, battle) {
  damages,
+
   var keys = Object.keys(characters.savedCharacters);
  battleValues,
 
  damagesType,
 
  minPiercingDamages
 
) {
 
   damages = floorMultiplication(damages, battleValues.magicResistanceCoeff);
 
  damages = floorMultiplication(damages, battleValues.weaponDefenseCoeff);
 
  
   if (damagesType.criticalHit) {
+
   for (var index = 0; index < keys.length; index++) {
     damages *= 2;
+
     var pseudo = keys[index];
 +
    addBattleChoice(battle, pseudo);
 
   }
 
   }
  
   if (damagesType.piercingHit) {
+
   characters.savedMonsters.forEach(function (monsterVnum) {
     damages += battleValues.defense + Math.min(0, minPiercingDamages);
+
     addBattleChoice(battle, monsterVnum, true);
    damages = floorMultiplication(damages, battleValues.extraPiercingHitCoeff);
+
  });
  }
+
}
  
  damages = floorMultiplication(damages, battleValues.averageDamageCoeff);
+
function isPC(character) {
   damages = floorMultiplication(
+
   if (character.race === 0 || character.race === 1) {
     damages,
+
     return false;
    battleValues.averageDamageResistanceCoeff
+
   }
  );
+
   return true;
   damages = floorMultiplication(
+
}
    damages,
 
    battleValues.skillDamageResistanceCoeff
 
   );
 
  
  damages = floorMultiplication(damages, battleValues.rankBonusCoeff);
+
function isBoss(character) {
   damages = Math.max(0, damages + Math.floor(battleValues.defensePercent));
+
   return character.race === 0 && character.rank >= 5;
  damages += Math.min(
+
}
    300,
 
    floorMultiplication(damages, battleValues.damageBonusCoeff)
 
  );
 
  damages = floorMultiplication(damages, battleValues.empireMalusCoeff);
 
  
   return damages;
+
function isStone(character) {
 +
   return character.race === 1;
 
}
 
}
  
function calcSkillDamageWithSecondaryBonuses(
+
function isMeleeAttacker(monster) {
  damages,
+
   return monster.attack == 0;
  battleValues,
+
}
  damagesType,
 
  minPiercingDamages
 
) {
 
   damages = floorMultiplication(damages, battleValues.magicResistanceCoeff);
 
  damages = floorMultiplication(damages, battleValues.weaponDefenseCoeff);
 
  
   damages -= battleValues.defense;
+
function isRangeAttacker(monster) {
 +
   return monster.attack == 1;
 +
}
  
  if (damagesType.criticalHit) {
+
function isMagicAttacker(monster) {
    damages *= 2;
+
  return monster.attack == 2;
  }
+
}
  
  if (damagesType.piercingHit) {
+
function isMagicClass(character) {
    damages +=
+
  return character.race === "shaman" || character.class === "black_magic";
      battleValues.piercingHitDefense + Math.min(0, minPiercingDamages);
+
}
  }
 
  
  damages = floorMultiplication(damages, battleValues.skillDamageCoeff);
+
function isDispell(character, skillId) {
   damages = floorMultiplication(
+
   return character.class === "weaponary" && skillId === 6;
    damages,
+
}
    battleValues.skillDamageResistanceCoeff
 
  );
 
  
  damages = floorMultiplication(damages, battleValues.rankBonusCoeff);
+
function isPolymorph(character) {
   damages = Math.max(0, damages + Math.floor(battleValues.defensePercent));
+
   return character.state === "polymorph";
  damages += Math.min(
+
}
    300,
 
    floorMultiplication(damages, battleValues.damageBonusCoeff)
 
  );
 
  damages = floorMultiplication(damages, battleValues.empireMalusCoeff);
 
  
   return damages;
+
function isRiding(character) {
 +
   return character.state === "horse";
 
}
 
}
  
function computePolymorphPoint(attacker, victim, polymorphPowerTable) {
+
function isBow(weapon) {
   attacker.statAttackValue = 0;
+
   return weapon.type === 2;
 +
}
  
   attacker.polymorphDex = attacker.dex;
+
function calcAttackFactor(attacker, victim) {
   victim.polymorphDex = victim.dex;
+
   function calcCoeffK(dex, level) {
 +
    return Math.min(90, Math.floor((2 * dex + level) / 3));
 +
   }
  
   attacker.minAttackValuePolymorph = 0;
+
   var K1 = calcCoeffK(attacker.polymorphDex, attacker.level);
   attacker.maxAttackValuePolymorph = 0;
+
   var K2 = calcCoeffK(victim.polymorphDex, attacker.level);
  
   if (isPC(attacker) && isPolymorph(attacker) && polymorphPowerTable) {
+
   var AR = (K1 + 210) / 300;
    var polymorphPowerPct =
+
  var ER = (((2 * K2 + 5) / (K2 + 95)) * 3) / 10;
      getPolymorphPower(attacker.polymorphPoint, polymorphPowerTable) / 100;
 
    var polymorphMonster = createMonster(attacker.polymorphMonster);
 
  
    var polymorphStr = floorMultiplication(
+
  return truncateNumber(AR - ER, 8);
      polymorphPowerPct,
+
}
      polymorphMonster.str
 
    );
 
  
    attacker.polymorphDex += floorMultiplication(
+
function calcMainAttackValue(attacker) {
      polymorphPowerPct,
+
  var leadership = 0;
      polymorphMonster.dex
+
  var rawWeaponAttackValue = 0;
    );
 
  
     attacker.minAttackValuePolymorph = floorMultiplication(
+
  if (isPC(attacker)) {
      polymorphPowerPct,
+
     var weaponUpgrades = attacker.weapon.upgrades;
      polymorphMonster.minAttackValue
+
     var maxUpgrade = weaponUpgrades.length - 1;
    );
 
     attacker.maxAttackValuePolymorph = floorMultiplication(
 
      polymorphPowerPct,
 
      polymorphMonster.maxAttackValue
 
    );
 
  
     if (!attacker.weapon) {
+
     if (attacker.hasOwnProperty("weaponUpgrade")) {
       attacker.maxAttackValuePolymorph += 1;
+
       rawWeaponAttackValue =
    }
+
        weaponUpgrades[Math.min(attacker.weaponUpgrade, maxUpgrade)];
  
    attacker.attackValue = 0;
+
       // rare bug when weaponUpgrade is deleted
 
 
    if (isMagicClass(attacker)) {
 
       attacker.statAttackValue = 2 * (polymorphStr + attacker.int);
 
 
     } else {
 
     } else {
       attacker.statAttackValue = 2 * (polymorphStr + attacker.str);
+
       console.log("Warming: weaponUpgrade is missing.");
 +
      rawWeaponAttackValue = weaponUpgrades[maxUpgrade];
 
     }
 
     }
  } else {
+
 
     attacker.statAttackValue = calcStatAttackValue(attacker);
+
     leadership = attacker.leadership;
 
   }
 
   }
 +
 +
  return 2 * (attacker.level + rawWeaponAttackValue) + leadership;
 
}
 
}
  
function computeHorse(attacker) {
+
function calcStatAttackValue(character) {
   attacker.horseAttackValue = 0;
+
   switch (character.race) {
 +
    case "warrior":
 +
    case "sura":
 +
      return 2 * character.str;
 +
    case "ninja":
 +
      return Math.floor((1 / 4) * (character.str + 7 * character.dex));
 +
    case "shaman":
 +
      return Math.floor((1 / 3) * (5 * character.int + character.dex));
 +
    case "lycan":
 +
      return character.vit + 2 * character.dex;
 +
    default:
 +
      return 2 * character.str;
 +
  }
 +
}
  
  if (isPC(attacker) && isRiding(attacker)) {
+
function calcSecondaryAttackValue(attacker) {
    var horseConstant = 30;
+
  var attackValueOther = 0;
  
    if (attacker.class === "weaponary") {
+
  var minAttackValue = 0;
      horseConstant = 60;
+
  var maxAttackValue = 0;
    }
 
  
    attacker.horseAttackValue = floorMultiplication(
+
  var minAttackValueSlash = 0;
      2 * attacker.level + attacker.statAttackValue,
+
   var maxAttackValueSlash = 0;
      attacker.horsePoint / horseConstant
 
    );
 
   }
 
}
 
  
function getRankBonus(attacker) {
+
   var attackerWeapon = attacker.weapon;
   if (attacker.lowRank === "on") {
 
    switch (attacker.playerRank) {
 
      case "aggressive":
 
        return 1;
 
      case "fraudulent":
 
        return 2;
 
      case "malicious":
 
        return 3;
 
      case "cruel":
 
        return 5;
 
    }
 
  }
 
  return 0;
 
}
 
  
function skillChanceReduction(value) {
+
  if (isPC(attacker)) {
  if (value <= 9) {
+
    if (attackerWeapon.isSerpent) {
    return Math.floor(value / 2);
+
      var rawAttackValue = attackerWeapon.upgrades[attacker.weaponUpgrade];
  }
+
 
  return 5 + Math.floor((value - 10) / 4);
+
      minAttackValue = attacker.minAttackValueRandom - rawAttackValue;
}
+
      maxAttackValue = attacker.maxAttackValueRandom - rawAttackValue;
  
function magicResistanceToCoeff(magicResistance) {
+
      minAttackValue = Math.max(0, minAttackValue);
  if (magicResistance) {
+
      maxAttackValue = Math.max(minAttackValue, maxAttackValue);
     return 2000 / (6 * magicResistance + 1000) - 1
+
     } else {
  }
+
      minAttackValue = attackerWeapon.minAttackValue;
  return 1
+
      maxAttackValue = attackerWeapon.maxAttackValue;
}
+
    }
  
function createPhysicalBattleValues(
+
    minAttackValueSlash = Math.min(
  attacker,
+
      attacker.minAttackValueSlash,
  attackerWeapon,
+
      attacker.maxAttackValueSlash
  victim,
+
    );
  mapping,
+
    maxAttackValueSlash = Math.max(
  polymorphPowerTable,
+
      attacker.minAttackValueSlash,
  marriageTable
+
      attacker.maxAttackValueSlash
) {
+
    );
  var missPercentage = 0;
 
  var attackValuePercent = 0;
 
  var attackMeleeMagic = 0;
 
  var attackValueMarriage = 0;
 
  var monsterResistanceMarriage = 0;
 
  var monsterResistance = 0;
 
  var typeBonus = 0;
 
  var raceBonus = 0;
 
  var raceResistance = 0;
 
  var stoneBonus = 0;
 
  var monsterBonus = 0;
 
  var elementBonus = [0, 0, 0, 0, 0, 0]; // fire, ice, lightning, earth, darkness, wind, order doesn't matter
 
  var defenseMarriage = 0;
 
  var damageMultiplier = 1;
 
  var magicResistance = 0;
 
  var weaponDefense = 0;
 
  var criticalHitPercentage = attacker.criticalHit;
 
  var criticalHitPercentageMarriage = 0;
 
  var piercingHitPercentage = attacker.piercingHit;
 
  var piercingHitPercentageMarriage = 0;
 
  var extraPiercingHitPercentage = Math.max(0, piercingHitPercentage - 100);
 
  var averageDamage = 0;
 
  var averageDamageResistance = 0;
 
  var skillDamageResistance = 0;
 
  var rankBonus = 0;
 
  var defensePercent = 0;
 
  var damageBonus = 0;
 
  var empireMalus = 0;
 
  
  computePolymorphPoint(attacker, victim, polymorphPowerTable);
+
    attackValueOther += attacker.attackValue;
  computeHorse(attacker);
 
  
  if (isPC(attacker)) {
+
    if (isBow(attackerWeapon) && !isPolymorph(attacker)) {
     attackValuePercent = attacker.attackValuePercent;
+
      attackValueOther += 25;
     attackMeleeMagic = attacker.attackMeleeMagic;
+
    }
 +
  } else {
 +
     minAttackValue = attacker.minAttackValue;
 +
     maxAttackValue = attacker.maxAttackValue;
 +
  }
  
    var weaponType = attackerWeapon[1];
+
  minAttackValue += attacker.minAttackValuePolymorph;
 +
  maxAttackValue += attacker.maxAttackValuePolymorph;
  
    var weaponDefenseName = mapping.defenseWeapon[weaponType];
+
  attackValueOther += attacker.statAttackValue;
    var weaponDefenseBreakName = mapping.breakWeapon[weaponType];
+
  attackValueOther += attacker.horseAttackValue;
  
    if (victim.hasOwnProperty(weaponDefenseName)) {
+
  var weaponInterval = maxAttackValue - minAttackValue + 1;
      weaponDefense = victim[weaponDefenseName];
+
  var slashInterval = maxAttackValueSlash - minAttackValueSlash + 1;
    }
 
  
    if (isPC(victim)) {
+
  var totalCardinal = weaponInterval * slashInterval * 1_000_000;
      if (weaponType === 2 && !isPolymorph(attacker)) {
+
  var minInterval = Math.min(weaponInterval, slashInterval);
        missPercentage = victim.arrowBlock;
 
      } else {
 
        missPercentage = victim.meleeBlock;
 
      }
 
  
      missPercentage +=
+
  minAttackValue += minAttackValueSlash;
        victim.meleeArrowBlock -
+
  maxAttackValue += maxAttackValueSlash;
        (missPercentage * victim.meleeArrowBlock) / 100;
 
  
      typeBonus = Math.max(
+
  return {
        0,
+
    minAttackValue: minAttackValue,
        Math.max(1, attacker.humanBonus) - victim.humanResistance
+
    maxAttackValue: maxAttackValue,
      );
+
    attackValueOther: attackValueOther,
      raceBonus = attacker[mapping.raceBonus[victim.race]];
+
    totalCardinal: totalCardinal,
      raceResistance = victim[mapping.raceResistance[attacker.race]];
+
    weights: calcWeights(minAttackValue, maxAttackValue, minInterval),
 +
    possibleDamagesCount: maxAttackValue - minAttackValue + 1,
 +
  };
 +
}
  
      for (var index = 0; index <= 5; index++) {
+
function calcMagicAttackValue(attacker) {
        elementBonus[index] =
+
  var minMagicAttackValue = 0;
          Math.max(
+
  var maxMagicAttackValue = 0;
            0,
 
            attacker[mapping.elementBonus[index]] -
 
              victim[mapping.elementResistance[index]]
 
          ) / 1000;
 
      }
 
  
      if (attacker.hasOwnProperty(weaponDefenseBreakName)) {
+
  var minMagicAttackValueSlash = 0;
        weaponDefense -= attacker[weaponDefenseBreakName];
+
  var maxMagicAttackValueSlash = 0;
      }
 
  
      averageDamageResistance = victim.averageDamageResistance;
+
  var attackerWeapon = attacker.weapon;
    } else {
 
      if (attacker.loveNecklace === "on") {
 
        attackValueMarriage = getMarriageBonusValue(
 
          attacker,
 
          marriageTable,
 
          "loveNecklace"
 
        );
 
      }
 
  
      if (attacker.loveEarrings === "on") {
+
  if (attackerWeapon.isSerpent) {
        criticalHitPercentageMarriage = getMarriageBonusValue(
+
    minMagicAttackValue = attacker.minMagicAttackValueRandom;
          attacker,
+
    maxMagicAttackValue = attacker.maxMagicAttackValueRandom;
          marriageTable,
 
          "loveEarrings"
 
        );
 
      }
 
  
      if (attacker.harmonyEarrings === "on") {
+
    maxMagicAttackValue = Math.max(minMagicAttackValue, maxMagicAttackValue);
        piercingHitPercentageMarriage = getMarriageBonusValue(
+
  } else {
          attacker,
+
    var rawWeaponAttackValue = attackerWeapon.upgrades[attacker.weaponUpgrade];
          marriageTable,
 
          "harmonyEarrings"
 
        );
 
      }
 
  
      for (var index = 0; index <= 5; index++) {
+
    if (!rawWeaponAttackValue) {
        var elementBonusName = mapping.elementBonus[index];
+
      rawWeaponAttackValue = 0;
        var elementResistanceName = mapping.elementResistance[index];
+
    }
  
        if (attacker[elementBonusName] && victim[elementBonusName]) {
+
    minMagicAttackValue =
          elementBonus[index] =
+
      attackerWeapon.minMagicAttackValue + rawWeaponAttackValue;
            (attacker[elementBonusName] - victim[elementResistanceName]) / 200;
+
    maxMagicAttackValue =
        } else {
+
      attackerWeapon.maxMagicAttackValue + rawWeaponAttackValue;
          elementBonus[index] = attacker[elementBonusName] / 2000;
+
  }
        }
 
      }
 
  
      var victimType = victim.type;
+
  minMagicAttackValueSlash = Math.min(
 +
    attacker.minMagicAttackValueSlash,
 +
    attacker.maxMagicAttackValueSlash
 +
  );
 +
  maxMagicAttackValueSlash = Math.max(
 +
    attacker.minMagicAttackValueSlash,
 +
    attacker.maxMagicAttackValueSlash
 +
  );
  
      if (victimType !== -1) {
+
  var weaponInterval = maxMagicAttackValue - minMagicAttackValue + 1;
        typeBonus = attacker[mapping.typeFlag[victimType]];
+
  var slashInterval = maxMagicAttackValueSlash - minMagicAttackValueSlash + 1;
      }
 
  
      monsterBonus = attacker.monsterBonus;
+
  var totalCardinal = weaponInterval * slashInterval * 1_000_000;
 +
  var minInterval = Math.min(weaponInterval, slashInterval);
  
      if (isStone(victim)) {
+
  minMagicAttackValue += minMagicAttackValueSlash;
        stoneBonus = attacker.stoneBonus;
+
  maxMagicAttackValue += maxMagicAttackValueSlash;
      }
 
  
       if (isBoss(victim)) {
+
  return {
        averageDamage += attacker.bossDamage;
+
    minMagicAttackValue: minMagicAttackValue,
      }
+
    maxMagicAttackValue: maxMagicAttackValue,
    }
+
    magicAttackValueAugmentation: getMagicAttackValueAugmentation(
 +
      minMagicAttackValue,
 +
      maxMagicAttackValue,
 +
       attacker.magicAttackValue
 +
    ),
 +
    totalCardinal: totalCardinal,
 +
    weights: calcWeights(minMagicAttackValue, maxMagicAttackValue, minInterval),
 +
    possibleDamagesCount: maxMagicAttackValue - minMagicAttackValue + 1,
 +
  };
 +
}
  
    averageDamage += attacker.averageDamage;
+
function getPolymorphPower(polymorphPoint, polymorphPowerTable) {
    rankBonus = getRankBonus(attacker);
+
  return polymorphPowerTable[polymorphPoint];
    damageBonus = attacker.damageBonus;
+
}
  
    if (attacker.empireMalus === "on") {
+
function getSkillPower(skillPoint, skillPowerTable) {
      empireMalus = 10;
+
   return skillPowerTable[skillPoint];
    }
+
}
   } else {
 
    if (isPC(victim)) {
 
      if (victim.harmonyBracelet === "on") {
 
        monsterResistanceMarriage = getMarriageBonusValue(
 
          victim,
 
          marriageTable,
 
          "harmonyBracelet"
 
        );
 
      }
 
  
      if (victim.harmonyNecklace === "on") {
+
function getMarriageBonusValue(character, marriageTable, itemName) {
        defenseMarriage = getMarriageBonusValue(
+
  var index;
          victim,
+
  var lovePoint = character.lovePoint;
          marriageTable,
 
          "harmonyNecklace"
 
        );
 
      }
 
  
      monsterResistance = victim.monsterResistance;
+
  if (lovePoint < 65) {
 
+
    index = 0;
      for (var index = 0; index <= 5; index++) {
+
  } else if (lovePoint < 80) {
        var elementBonusName = mapping.elementBonus[index];
+
    index = 1;
        var elementResistanceName = mapping.elementResistance[index];
+
  } else if (lovePoint < 100) {
 +
    index = 2;
 +
  } else {
 +
    index = 3;
 +
  }
  
        if (attacker[elementBonusName]) {
+
  return marriageTable[itemName][index];
          elementBonus[index] =
+
}
            (attacker[elementBonusName] - victim[elementResistanceName]) / 125;
 
        }
 
      }
 
  
      if (attacker.attack == 0) {
+
function calcDamageWithPrimaryBonuses(damages, bonusValues) {
        missPercentage = victim.meleeBlock;
+
  damages = Math.floor((damages * bonusValues.attackValueCoeff) / 100);
        averageDamageResistance = victim.averageDamageResistance;
 
      } else if (attacker.attack == 1) {
 
        missPercentage = victim.arrowBlock;
 
        weaponDefense = victim.arrowDefense;
 
        averageDamageResistance = victim.averageDamageResistance;
 
      } else {
 
        missPercentage = victim.arrowBlock;
 
        skillDamageResistance = victim.skillDamageResistance;
 
        magicResistance = victim.magicResistance;
 
      }
 
  
      missPercentage +=
+
  damages += bonusValues.attackValueMarriage;
        victim.meleeArrowBlock -
 
        (missPercentage * victim.meleeArrowBlock) / 100;
 
    }
 
  
    typeBonus = 1;
+
  damages = Math.floor(
     damageMultiplier = attacker.damageMultiplier;
+
     (damages * bonusValues.monsterResistanceMarriageCoeff) / 100
   }
+
  );
 +
   damages = Math.floor((damages * bonusValues.monsterResistanceCoeff) / 100);
  
   if (isPC(victim)) {
+
   damages += Math.floor((damages * bonusValues.typeBonusCoeff) / 100);
     if (victim.biologist70 === "on") {
+
  damages +=
      victim.defense = floorMultiplication(victim.defense, 1.1);
+
     Math.floor((damages * bonusValues.raceBonusCoeff) / 100) -
    }
+
    Math.floor((damages * bonusValues.raceResistanceCoeff) / 100);
    criticalHitPercentage = Math.max(
+
  damages += Math.floor((damages * bonusValues.stoneBonusCoeff) / 100);
      0,
+
  damages += Math.floor((damages * bonusValues.monsterBonusCoeff) / 100);
      criticalHitPercentage - victim.criticalHitResistance
 
    );
 
    piercingHitPercentage = Math.max(
 
      0,
 
      piercingHitPercentage - victim.piercingHitResistance
 
    );
 
  
     if (isMagicClass(victim)) {
+
  var elementBonusCoeff = bonusValues.elementBonusCoeff;
      defensePercent = (-2 * victim.magicDefense * victim.defensePercent) / 100;
+
 
    } else {
+
  damages +=
      defensePercent = (-2 * victim.defense * victim.defensePercent) / 100;
+
    Math.trunc((damages * elementBonusCoeff[0]) / 10000) +
     }
+
     Math.trunc((damages * elementBonusCoeff[1]) / 10000) +
 +
    Math.trunc((damages * elementBonusCoeff[2]) / 10000) +
 +
    Math.trunc((damages * elementBonusCoeff[3]) / 10000) +
 +
    Math.trunc((damages * elementBonusCoeff[4]) / 10000) +
 +
    Math.trunc((damages * elementBonusCoeff[5]) / 10000);
 +
 
 +
  damages = Math.floor(damages * bonusValues.damageMultiplier);
 +
 
 +
  return damages;
 +
}
 +
 
 +
function calcDamageWithSecondaryBonuses(
 +
  damages,
 +
  bonusValues,
 +
  damagesType,
 +
  minPiercingDamages,
 +
  damagesWithPrimaryBonuses
 +
) {
 +
  damages = Math.floor(damages * bonusValues.magicResistanceCoeff);
 +
  damages = Math.trunc((damages * bonusValues.weaponDefenseCoeff) / 100);
 +
  damages = Math.floor((damages * bonusValues.tigerStrengthCoeff) / 100);
 +
  damages = Math.floor((damages * bonusValues.blessingBonusCoeff) / 100);
 +
 
 +
  if (damagesType.criticalHit) {
 +
     damages *= 2;
 
   }
 
   }
  
   missPercentage = Math.min(100, missPercentage);
+
   if (damagesType.piercingHit) {
 
+
     damages += bonusValues.defenseBoost + Math.min(0, minPiercingDamages);
  var battleValues = {
+
     damages += Math.floor(
     missPercentage: missPercentage,
+
       (damagesWithPrimaryBonuses * bonusValues.extraPiercingHitCoeff) / 1000
    adjustCoeff: 0,
+
     );
    attackValueCoeff:
+
   }
      1 + (attackValuePercent + Math.min(100, attackMeleeMagic)) / 100,
 
    attackValueMarriage: attackValueMarriage,
 
     monsterResistanceMarriageCoeff: 1 - monsterResistanceMarriage / 100,
 
    monsterResistanceCoeff: 1 - monsterResistance / 100,
 
    typeBonusCoeff: 1 + typeBonus / 100,
 
    raceBonusCoeff: raceBonus / 100,
 
    raceResistanceCoeff: raceResistance / 100,
 
    monsterBonusCoeff: 1 + monsterBonus / 100,
 
    stoneBonusCoeff: 1 + stoneBonus / 100,
 
    elementBonusCoeff: elementBonus,
 
    damageMultiplier: damageMultiplier,
 
    defense: victim.defense,
 
    defenseMarriage: defenseMarriage,
 
    magicResistanceCoeff: magicResistanceToCoeff(magicResistance),
 
    weaponDefenseCoeff: 1 - weaponDefense / 100,
 
    extraPiercingHitCoeff: 1 + extraPiercingHitPercentage / 200,
 
    averageDamageCoeff: 1 + averageDamage / 100,
 
    averageDamageResistanceCoeff:
 
       1 - Math.min(99, averageDamageResistance) / 100,
 
     skillDamageResistanceCoeff: 1 - Math.min(99, skillDamageResistance) / 100,
 
    rankBonusCoeff: 1 + rankBonus / 100,
 
    defensePercent: defensePercent,
 
    damageBonusCoeff: damageBonus / 100,
 
    empireMalusCoeff: 1 - empireMalus / 100,
 
   };
 
  
   criticalHitPercentage = Math.min(
+
   damages = Math.floor((damages * bonusValues.averageDamageCoeff) / 100);
    criticalHitPercentage + criticalHitPercentageMarriage,
+
  damages = Math.floor(
     100
+
     (damages * bonusValues.averageDamageResistanceCoeff) / 100
 
   );
 
   );
   piercingHitPercentage = Math.min(
+
   damages = Math.floor(
     piercingHitPercentage + piercingHitPercentageMarriage,
+
     (damages * bonusValues.skillDamageResistanceCoeff) / 100
    100
 
 
   );
 
   );
  
   battleValues.damagesTypeCombinaison = [
+
   damages = Math.floor((damages * bonusValues.rankBonusCoeff) / 100);
    {
+
  damages = Math.max(0, damages + bonusValues.defensePercent);
      criticalHit: false,
+
  damages += Math.min(
      piercingHit: false,
+
     300,
      weight:
+
     Math.floor((damages * bonusValues.damageBonusCoeff) / 100)
        (100 - criticalHitPercentage) *
+
  );
        (100 - piercingHitPercentage) *
+
  damages = Math.floor((damages * bonusValues.empireMalusCoeff) / 10);
        (100 - missPercentage),
+
  damages = Math.floor((damages * bonusValues.sungMaStrBonusCoeff) / 10000);
      name: "Coup classique",
+
  damages -= Math.floor(damages * bonusValues.sungmaStrMalusCoeff);
     },
+
 
     {
+
  damages = Math.floor((damages * bonusValues.whiteDragonElixirCoeff) / 100);
      criticalHit: true,
+
   damages = Math.floor((damages * bonusValues.steelDragonElixirCoeff) / 100);
      piercingHit: false,
 
      weight:
 
        criticalHitPercentage *
 
        (100 - piercingHitPercentage) *
 
        (100 - missPercentage),
 
      name: "Coup critique",
 
    },
 
    {
 
      criticalHit: false,
 
      piercingHit: true,
 
      weight:
 
        (100 - criticalHitPercentage) *
 
        piercingHitPercentage *
 
        (100 - missPercentage),
 
      name: "Coup perçant",
 
    },
 
    {
 
      criticalHit: true,
 
      piercingHit: true,
 
      weight:
 
        criticalHitPercentage * piercingHitPercentage * (100 - missPercentage),
 
      name: "Coup critique + coup perçant",
 
    },
 
   ];
 
  
   return battleValues;
+
   return damages;
 
}
 
}
  
function createSkillBattleValues(
+
function calcSkillDamageWithSecondaryBonuses(
   attacker,
+
   damages,
   attackerWeapon,
+
   bonusValues,
   victim,
+
   damagesType,
   mapping,
+
   minPiercingDamages
  marriageTable,
 
  magicSkill
 
 
) {
 
) {
   var adjustCoeff = 0;
+
   damages = Math.floor(damages * bonusValues.magicResistanceCoeff);
  var attackValuePercent = 0;
+
   damages = Math.trunc((damages * bonusValues.weaponDefenseCoeff) / 100);
  var attackMeleeMagic = 0;
 
  var attackValueMarriage = 0;
 
  var monsterResistanceMarriage = 0;
 
  var monsterResistance = 0;
 
  var typeBonus = 0;
 
  var raceBonus = 0;
 
  var raceResistance = 0;
 
  var stoneBonus = 0;
 
  var monsterBonus = 0;
 
  var elementBonus = [0, 0, 0, 0, 0, 0]; // fire, ice, lightning, earth, darkness, wind, order doesn't matter
 
  var damageMultiplier = 1;
 
  var defense = victim.defense;
 
   var magicResistance = 0;
 
  var weaponDefense = 0;
 
  var criticalHitPercentage = attacker.criticalHit;
 
  var piercingHitPercentage = attacker.piercingHit;
 
  var skillDamage = 0;
 
  var skillDamageResistance = 0;
 
  var rankBonus = 0;
 
  var defensePercent = 0;
 
  var damageBonus = 0;
 
  var empireMalus = 0;
 
  
   computePolymorphPoint(attacker, victim);
+
   damages -= bonusValues.defense;
  computeHorse(attacker);
 
  
   if (isPC(attacker)) {
+
   damages = floorMultiplication(damages, bonusValues.skillWardCoeff);
    attackValuePercent = attacker.attackValuePercent;
+
  damages = floorMultiplication(damages, bonusValues.skillBonusCoeff);
    attackMeleeMagic = attacker.attackMeleeMagic;
 
  
     var weaponType = attackerWeapon[1];
+
  var tempDamages = Math.floor(
 +
     (damages * bonusValues.skillBonusByBonusCoeff) / 100
 +
  );
 +
 
 +
  damages = Math.floor(
 +
    (tempDamages * bonusValues.magicAttackValueCoeff) / 100 + 0.5
 +
  );
 +
  damages = Math.floor((damages * bonusValues.tigerStrengthCoeff) / 100);
  
    var weaponDefenseName = mapping.defenseWeapon[weaponType];
+
  if (damagesType.criticalHit) {
     var weaponDefenseBreakName = mapping.breakWeapon[weaponType];
+
     damages *= 2;
 +
  }
  
    if (victim.hasOwnProperty(weaponDefenseName)) {
+
  if (damagesType.piercingHit) {
      weaponDefense = victim[weaponDefenseName];
+
    damages += bonusValues.defenseBoost + Math.min(0, minPiercingDamages);
     }
+
     damages += Math.floor(
 +
      (tempDamages * bonusValues.extraPiercingHitCoeff) / 1000
 +
    );
 +
  }
  
     if (attacker.class === "archery") {
+
  damages = Math.floor((damages * bonusValues.skillDamageCoeff) / 100);
      defense = 0;
+
  damages = Math.floor(
    }
+
     (damages * bonusValues.skillDamageResistanceCoeff) / 100
 +
  );
 +
  damages = Math.floor((damages * bonusValues.rankBonusCoeff) / 100);
  
    if (isPC(victim)) {
+
  damages = Math.max(0, damages + bonusValues.defensePercent);
      typeBonus = Math.max(
+
  damages += Math.min(
        0,
+
    300,
        Math.max(1, attacker.humanBonus) - victim.humanResistance
+
    Math.floor((damages * bonusValues.damageBonusCoeff) / 100)
      );
+
  );
      raceBonus = attacker[mapping.raceBonus[victim.race]];
+
  damages = Math.floor((damages * bonusValues.empireMalusCoeff) / 10);
      raceResistance = victim[mapping.raceResistance[attacker.race]];
+
  damages = Math.floor((damages * bonusValues.sungMaStrBonusCoeff) / 10000);
 +
  damages -= Math.floor(damages * bonusValues.sungmaStrMalusCoeff);
  
      for (var index = 0; index <= 5; index++) {
+
  damages = Math.floor((damages * bonusValues.whiteDragonElixirCoeff) / 100);
        elementBonus[index] =
+
  damages = Math.floor((damages * bonusValues.steelDragonElixirCoeff) / 100);
          Math.max(
 
            0,
 
            attacker[mapping.elementBonus[index]] -
 
              victim[mapping.elementResistance[index]]
 
          ) / 1000;
 
      }
 
  
      if (attacker.hasOwnProperty(weaponDefenseBreakName)) {
+
  return damages;
        weaponDefense -= attacker[weaponDefenseBreakName];
+
}
      }
 
  
      criticalHitPercentage = 0;
+
function computePolymorphPoint(attacker, victim, polymorphPowerTable) {
    } else {
+
  attacker.statAttackValue = 0;
      if (attacker.loveNecklace === "on") {
 
        attackValueMarriage = getMarriageBonusValue(
 
          attacker,
 
          marriageTable,
 
          "loveNecklace"
 
        );
 
      }
 
  
      if (attacker.loveEarrings === "on") {
+
  attacker.polymorphDex = attacker.dex;
        criticalHitPercentage += getMarriageBonusValue(
+
  victim.polymorphDex = victim.dex;
          attacker,
 
          marriageTable,
 
          "loveEarrings"
 
        );
 
      }
 
  
      if (attacker.harmonyEarrings === "on") {
+
  attacker.minAttackValuePolymorph = 0;
        piercingHitPercentage += getMarriageBonusValue(
+
  attacker.maxAttackValuePolymorph = 0;
          attacker,
 
          marriageTable,
 
          "harmonyEarrings"
 
        );
 
      }
 
  
      for (var index = 0; index <= 5; index++) {
+
  if (isPC(attacker) && isPolymorph(attacker)) {
        var elementBonusName = mapping.elementBonus[index];
+
    var polymorphPowerPct =
        var elementResistanceName = mapping.elementResistance[index];
+
      getPolymorphPower(attacker.polymorphPoint, polymorphPowerTable) / 100;
 +
    var polymorphMonster = createMonster(attacker.polymorphMonster);
  
        if (attacker[elementBonusName] && victim[elementBonusName]) {
+
    var polymorphStr = floorMultiplication(
          elementBonus[index] =
+
      polymorphPowerPct,
            (attacker[elementBonusName] - victim[elementResistanceName]) / 200;
+
      polymorphMonster.str
        } else {
+
    );
          elementBonus[index] = attacker[elementBonusName] / 2000;
 
        }
 
      }
 
  
       var victimType = victim.type;
+
    attacker.polymorphDex += floorMultiplication(
 +
      polymorphPowerPct,
 +
       polymorphMonster.dex
 +
    );
  
       if (victimType !== -1) {
+
    attacker.minAttackValuePolymorph = floorMultiplication(
        typeBonus = attacker[mapping.typeFlag[victimType]];
+
       polymorphPowerPct,
       }
+
      polymorphMonster.minAttackValue
 
+
    );
       monsterBonus = attacker.monsterBonus;
+
    attacker.maxAttackValuePolymorph = floorMultiplication(
 +
       polymorphPowerPct,
 +
       polymorphMonster.maxAttackValue
 +
    );
  
      if (isStone(victim)) {
+
    if (!attacker.weapon) {
        stoneBonus = attacker.stoneBonus;
+
      attacker.maxAttackValuePolymorph += 1;
      }
 
 
 
      if (isBoss(victim)) {
 
        skillDamage += attacker.skillBossDamage;
 
      }
 
 
     }
 
     }
  
     skillDamage += attacker.skillDamage;
+
     attacker.attackValue = 0;
    rankBonus = getRankBonus(attacker);
 
    damageBonus = attacker.damageBonus;
 
  
     if (attacker.empireMalus === "on") {
+
     if (isMagicClass(attacker)) {
       empireMalus = 10;
+
      attacker.statAttackValue = 2 * (polymorphStr + attacker.int);
 +
    } else {
 +
       attacker.statAttackValue = 2 * (polymorphStr + attacker.str);
 
     }
 
     }
 
   } else {
 
   } else {
     if (isPC(victim)) {
+
     attacker.statAttackValue = calcStatAttackValue(attacker);
      if (victim.harmonyBracelet === "on") {
+
  }
        monsterResistanceMarriage = getMarriageBonusValue(
+
}
          victim,
 
          marriageTable,
 
          "harmonyBracelet"
 
        );
 
      }
 
      monsterResistance = victim.monsterResistance;
 
  
      for (var index = 0; index <= 5; index++) {
+
function computeHorse(attacker) {
        var elementBonusName = mapping.elementBonus[index];
+
  attacker.horseAttackValue = 0;
        var elementResistanceName = mapping.elementResistance[index];
 
  
        if (attacker[elementBonusName]) {
+
  if (isPC(attacker) && isRiding(attacker)) {
          elementBonus[index] =
+
    var horseConstant = 30;
            (attacker[elementBonusName] - victim[elementResistanceName]) / 125;
+
 
        }
+
    if (attacker.class === "weaponary") {
       }
+
       horseConstant = 60;
 
     }
 
     }
  
     typeBonus = 1;
+
     attacker.horseAttackValue = floorMultiplication(
    damageMultiplier = attacker.damageMultiplier;
+
      2 * attacker.level + attacker.statAttackValue,
 +
      attacker.horsePoint / horseConstant
 +
    );
 
   }
 
   }
 +
}
  
  criticalHitPercentage = skillChanceReduction(criticalHitPercentage);
+
function getRankBonus(attacker) {
  piercingHitPercentage = skillChanceReduction(piercingHitPercentage);
+
   if (attacker.lowRank !== "on") {
 
+
     return 0;
   if (isPC(victim)) {
 
    criticalHitPercentage = Math.max(
 
      0,
 
      criticalHitPercentage - victim.criticalHitResistance
 
    );
 
    piercingHitPercentage = Math.max(
 
      0,
 
      piercingHitPercentage - victim.piercingHitResistance
 
    );
 
    skillDamageResistance = victim.skillDamageResistance;
 
 
 
    if (isMagicClass(victim)) {
 
      defensePercent = (-2 * victim.magicDefense * victim.defensePercent) / 100;
 
     } else {
 
      defensePercent = (-2 * victim.defense * victim.defensePercent) / 100;
 
    }
 
 
   }
 
   }
  
   if (magicSkill) {
+
   switch (attacker.playerRank) {
     adjustCoeff = 0.5;
+
     case "aggressive":
     attackValuePercent = attacker.attackMagic;
+
      return 1;
     attackValueMarriage = 0;
+
     case "fraudulent":
    defense = 0;
+
      return 2;
     magicResistance = victim.magicResistance;
+
     case "malicious":
    weaponDefense = 0;
+
      return 3;
 +
     case "cruel":
 +
      return 5;
 
   }
 
   }
  
   var battleValues = {
+
   return 0;
    weaponBonusCoeff: 1,
+
}
    adjustCoeff: adjustCoeff,
 
    attackValueCoeff:
 
      1 + (attackValuePercent + Math.min(100, attackMeleeMagic)) / 100,
 
    attackValueMarriage: attackValueMarriage,
 
    monsterResistanceMarriageCoeff: 1 - monsterResistanceMarriage / 100,
 
    monsterResistanceCoeff: 1 - monsterResistance / 100,
 
    typeBonusCoeff: 1 + typeBonus / 100,
 
    raceBonusCoeff: raceBonus / 100,
 
    raceResistanceCoeff: raceResistance / 100,
 
    monsterBonusCoeff: 1 + monsterBonus / 100,
 
    stoneBonusCoeff: 1 + stoneBonus / 100,
 
    elementBonusCoeff: elementBonus,
 
    damageMultiplier: damageMultiplier,
 
    defense: defense,
 
    piercingHitDefense: victim.defense,
 
    magicResistanceCoeff: magicResistanceToCoeff(magicResistance),
 
    weaponDefenseCoeff: 1 - weaponDefense / 100,
 
    skillDamageCoeff: 1 + skillDamage / 100,
 
    skillDamageResistanceCoeff: 1 - Math.min(99, skillDamageResistance) / 100,
 
    rankBonusCoeff: 1 + rankBonus / 100,
 
    defensePercent: defensePercent,
 
    damageBonusCoeff: damageBonus / 100,
 
    empireMalusCoeff: 1 - empireMalus / 100,
 
  };
 
  
  criticalHitPercentage = Math.min(criticalHitPercentage, 100);
+
function calcElementCoeffPvP(elementBonus, mapping, attacker, victim) {
   piercingHitPercentage = Math.min(piercingHitPercentage, 100);
+
  var minElementMalus = 0;
 +
  var maxDifference = 0;
 +
   var savedElementDifferences = [];
 +
  var elementBonusIndex = 0;
  
   battleValues.damagesTypeCombinaison = [
+
   for (var index = 0; index < elementBonus.length; index++) {
    {
+
     if (!attacker[mapping.elementBonus[index]]) {
      criticalHit: false,
+
       continue;
      piercingHit: false,
+
     }
      weight: (100 - criticalHitPercentage) * (100 - piercingHitPercentage),
 
      name: "Coup classique",
 
    },
 
    {
 
      criticalHit: true,
 
      piercingHit: false,
 
      weight: criticalHitPercentage * (100 - piercingHitPercentage),
 
      name: "Coup critique",
 
     },
 
    {
 
      criticalHit: false,
 
      piercingHit: true,
 
      weight: (100 - criticalHitPercentage) * piercingHitPercentage,
 
      name: "Coup perçant",
 
    },
 
    {
 
       criticalHit: true,
 
      piercingHit: true,
 
      weight: criticalHitPercentage * piercingHitPercentage,
 
      name: "Coup critique + coup perçant",
 
     },
 
  ];
 
  
  return battleValues;
+
    var elementDifference =
}
+
      attacker[mapping.elementBonus[index]] -
 +
      victim[mapping.elementResistance[index]];
  
function updateBattleValues(battleValues, skillInfo, attackerWeapon) {
+
    if (elementDifference >= 0) {
   var weaponBonus = 0;
+
      elementBonus[elementBonusIndex] = 10 * elementDifference;
 +
      minElementMalus -= elementDifference;
 +
      maxDifference = Math.max(maxDifference, elementDifference);
 +
      elementBonusIndex++;
 +
    } else {
 +
      savedElementDifferences.push(elementDifference);
 +
    }
 +
   }
  
   if (skillInfo.hasOwnProperty("weaponBonus")) {
+
   if (!savedElementDifferences.length) {
     var [weaponType, weaponBonusValue] = skillInfo.weaponBonus;
+
     return;
 
 
    if (weaponType === attackerWeapon[1]) {
 
      weaponBonus = weaponBonusValue;
 
    }
 
 
   }
 
   }
  
   battleValues.weaponBonusCoeff = 1 + weaponBonus / 100;
+
   minElementMalus += maxDifference;
}
+
  savedElementDifferences.sort(compareNumbers);
  
function calcPhysicalDamages(
+
  for (var index = 0; index < savedElementDifferences.length; index++) {
  attacker,
+
    var elementDifference = savedElementDifferences[index];
  attackerWeapon,
 
  victim,
 
  tableResult,
 
  mapping,
 
  constants
 
) {
 
  var battleValues = createPhysicalBattleValues(
 
    attacker,
 
    attackerWeapon,
 
    victim,
 
    mapping,
 
    constants.polymorphPowerTable,
 
    constants.marriageTable
 
  );
 
  
  var sumDamages = 0;
+
    elementBonus[elementBonusIndex + index] =
  var minMaxDamages = { min: Infinity, max: 0 };
+
      10 * Math.max(minElementMalus, elementDifference);
  clearTableResult(tableResult);
 
  
  var attackFactor = calcAttackFactor(attacker, victim);
+
    minElementMalus = Math.min(
  var mainAttackValue = calcMainAttackValue(attacker, attackerWeapon);
+
      0,
   var [
+
      Math.max(minElementMalus, minElementMalus - elementDifference)
    minAttackValue,
+
    );
    maxAttackValue,
+
   }
    attackValueOther,
+
}
    minInterval,
 
    totalCardinal,
 
  ] = calcSecondaryAttackValue(attacker, attackerWeapon);
 
  
   totalCardinal *= 100;
+
function skillChanceReduction(value) {
 +
   if (value <= 9) {
 +
    return Math.floor(value / 2);
 +
  }
 +
  return 5 + Math.floor((value - 10) / 4);
 +
}
  
  if (battleValues.missPercentage) {
+
function magicResistanceToCoeff(magicResistance) {
    addRowToTableResult(tableResult, "Miss");
+
  if (magicResistance) {
     addToTableResult(tableResult, { 0: battleValues.missPercentage / 100 });
+
     return 2000 / (6 * magicResistance + 1000) - 1;
 
   }
 
   }
 +
  return 1;
 +
}
  
   var lastWeightsLimit = maxAttackValue - minInterval + 1;
+
function createBattleValues(attacker, victim, battle, skillType) {
   var firstWeightLimit = minAttackValue + minInterval - 1;
+
   var { mapping, constants } = battle;
 +
   var calcAttackValues;
  
   for (var damagesType of battleValues.damagesTypeCombinaison) {
+
   var missPercentage = 0;
     if (!damagesType.weight) {
+
  var attackValueMeleeMagic = 0;
       continue;
+
  var attackValueMarriage = 0;
 +
  var monsterResistanceMarriage = 0;
 +
  var monsterResistance = 0;
 +
  var typeBonus = 0;
 +
  var raceBonus = 0;
 +
  var raceResistance = 0;
 +
  var stoneBonus = 0;
 +
  var monsterBonus = 0;
 +
  var elementBonus = [0, 0, 0, 0, 0, 0]; // fire, ice, lightning, earth, darkness, wind, order doesn't matter
 +
  var defenseMarriage = 0;
 +
  var damageMultiplier = 1;
 +
  var useDamages = 1;
 +
  var defense = victim.defense;
 +
  var defenseBoost = defense;
 +
  var magicResistance = 0;
 +
  var weaponDefense = 0;
 +
  var tigerStrength = 0;
 +
  var blessingBonus = 0;
 +
  var magicAttackValueMeleeMagic = 0;
 +
  var criticalHitPercentage = attacker.criticalHit;
 +
  var piercingHitPercentage = attacker.piercingHit;
 +
  var extraPiercingHitPercentage = Math.max(0, piercingHitPercentage - 100);
 +
  var averageDamage = 0;
 +
  var averageDamageResistance = 0;
 +
  var skillDamage = 0;
 +
  var skillDamageResistance = 0;
 +
  var rankBonus = 0;
 +
  var defensePercent = 0;
 +
  var damageBonus = 0;
 +
  var empireMalus = 0;
 +
  var sungMaStrBonus = 0;
 +
  var sungmaStrMalus = 0;
 +
  var whiteDragonElixir = 0;
 +
  var steelDragonElixir = 0;
 +
 
 +
  computePolymorphPoint(attacker, victim, constants.polymorphPowerTable);
 +
  computeHorse(attacker);
 +
 
 +
  if (isPC(attacker)) {
 +
     if (weaponData.hasOwnProperty(attacker.weapon)) {
 +
       attacker.weapon = createWeapon(attacker.weapon);
 +
    } else {
 +
      attacker.weapon = createWeapon(0);
 
     }
 
     }
  
     var damagesWeighted = {};
+
     attackValueMeleeMagic =
    addRowToTableResult(tableResult, damagesType.name);
+
      attacker.attackValuePercent + Math.min(100, attacker.attackMeleeMagic);
 +
 
 +
    var weaponType = attacker.weapon.type;
  
     for (
+
     if (skillType && attacker.class === "archery") {
       var attackValue = minAttackValue;
+
       if (weaponType !== 2) {
       attackValue <= maxAttackValue;
+
        useDamages = 0;
      attackValue++
+
        weaponType = 2;
     ) {
+
       }
      var weight;
+
      defense = 0;
 +
    }
 +
 
 +
     var weaponDefenseName = mapping.defenseWeapon[weaponType];
 +
    var weaponDefenseBreakName = mapping.breakWeapon[weaponType];
  
      if (attackValue > lastWeightsLimit) {
+
    if (victim.hasOwnProperty(weaponDefenseName)) {
        weight = maxAttackValue - attackValue + 1;
+
       weaponDefense = victim[weaponDefenseName];
      } else if (attackValue < firstWeightLimit) {
+
    }
        weight = attackValue - minAttackValue + 1;
 
       } else {
 
        weight = minInterval;
 
      }
 
  
      var secondaryAttackValue = 2 * attackValue + attackValueOther;
+
    if (isChecked(attacker.whiteDragonElixir)) {
      var rawDamages =
+
       whiteDragonElixir = 10;
        mainAttackValue +
+
    }
        floorMultiplication(attackFactor, secondaryAttackValue);
 
       var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
 
        rawDamages,
 
        battleValues
 
      );
 
  
       damagesWithPrimaryBonuses -=
+
    if (isPC(victim)) {
         battleValues.defense + battleValues.defenseMarriage;
+
       if (!skillType) {
 +
        if (weaponType === 2 && !isPolymorph(attacker)) {
 +
          missPercentage = victim.arrowBlock;
 +
         } else {
 +
          missPercentage = victim.meleeBlock;
 +
        }
 +
        missPercentage +=
 +
          victim.meleeArrowBlock -
 +
          (missPercentage * victim.meleeArrowBlock) / 100;
  
      if (damagesWithPrimaryBonuses <= 2) {
+
        blessingBonus = calcBlessingBonus(constants.skillPowerTable, victim);
         for (var damages = 1; damages <= 5; damages++) {
+
         averageDamageResistance = victim.averageDamageResistance;
          var finalDamages = calcDamageWithSecondaryBonuses(
+
      }
            damages,
 
            battleValues,
 
            damagesType,
 
            damagesWithPrimaryBonuses
 
          );
 
  
          addKeyValue(
+
      typeBonus = Math.max(1, attacker.humanBonus - victim.humanResistance);
            damagesWeighted,
+
      raceBonus = attacker[mapping.raceBonus[victim.race]];
            finalDamages,
+
      raceResistance = victim[mapping.raceResistance[attacker.race]];
            (weight * damagesType.weight) / (5 * totalCardinal)
+
 
          );
+
       calcElementCoeffPvP(elementBonus, mapping, attacker, victim);
          sumDamages += (finalDamages * weight * damagesType.weight) / 5;
 
        }
 
       } else {
 
        var finalDamages = calcDamageWithSecondaryBonuses(
 
          damagesWithPrimaryBonuses,
 
          battleValues,
 
          damagesType,
 
          damagesWithPrimaryBonuses
 
        );
 
  
        addKeyValue(
+
      if (weaponType !== 2 && attacker.hasOwnProperty(weaponDefenseBreakName)) {
          damagesWeighted,
+
         weaponDefense -= attacker[weaponDefenseBreakName];
          finalDamages,
 
          (weight * damagesType.weight) / totalCardinal
 
        );
 
         sumDamages += finalDamages * weight * damagesType.weight;
 
 
       }
 
       }
    }
 
  
     addToTableResult(tableResult, damagesWeighted, minMaxDamages);
+
      criticalHitPercentage = 0;
  }
+
     } else {
 +
      if (isChecked(attacker.isMarried)) {
 +
        if (isChecked(attacker.loveNecklace)) {
 +
          attackValueMarriage = getMarriageBonusValue(
 +
            attacker,
 +
            constants.marriageTable,
 +
            "loveNecklace"
 +
          );
 +
        }
  
  if (minMaxDamages.min === Infinity) {
+
        if (isChecked(attacker.loveEarrings)) {
    minMaxDamages.min = 0;
+
          criticalHitPercentage += getMarriageBonusValue(
  }
+
            attacker,
 +
            constants.marriageTable,
 +
            "loveEarrings"
 +
          );
 +
        }
  
  return [sumDamages / totalCardinal, minMaxDamages];
+
        if (isChecked(attacker.harmonyEarrings)) {
}
+
          piercingHitPercentage += getMarriageBonusValue(
 +
            attacker,
 +
            constants.marriageTable,
 +
            "harmonyEarrings"
 +
          );
 +
        }
 +
      }
  
function getSkillFormula(skillPowerTable, skillId, attacker, attackFactor) {
+
      if (isChecked(attacker.tigerStrength)) {
  var skillFormula;
+
        tigerStrength = 40;
  var skillInfo = {};
+
      }
  
  var attackerClass = attacker.class;
+
      for (var index = 0; index < elementBonus.length; index++) {
  var lv = attacker.level;
+
        var elementBonusName = mapping.elementBonus[index];
  var vit = attacker.vit;
+
        var elementResistanceName = mapping.elementResistance[index];
  var str = attacker.str;
 
  var int = attacker.int;
 
  var dex = attacker.dex;
 
  
  var skillPower = getSkillPower(
+
        if (attacker[elementBonusName] && victim[elementBonusName]) {
    attacker["attackSkill" + skillId],
+
          elementBonus[index] =
    skillPowerTable
+
            50 * (attacker[elementBonusName] - victim[elementResistanceName]);
  );
+
        } else {
 +
          elementBonus[index] = 5 * attacker[elementBonusName];
 +
        }
 +
      }
 +
 
 +
      var victimType = victim.type;
 +
 
 +
      if (victimType !== -1) {
 +
        typeBonus = attacker[mapping.typeFlag[victimType]];
 +
      }
 +
 
 +
      monsterBonus = attacker.monsterBonus;
 +
 
 +
      if (isStone(victim)) {
 +
        stoneBonus = attacker.stoneBonus;
 +
      }
  
  if (attackerClass === "body") {
+
      if (isBoss(victim)) {
    switch (skillId) {
+
         if (skillType) {
      // Triple lacération
+
           skillDamage += attacker.skillBossDamage;
      case 1:
+
        } else {
         skillFormula = function (atk) {
+
           averageDamage += attacker.bossDamage;
           return floorMultiplication(
+
         }
            1.1 * atk + (0.5 * atk + 1.5 * str) * skillPower,
+
      }
            1
+
 
           );
+
       if (isChecked(attacker.onYohara)) {
         };
+
         var sungmaStrDifference = attacker.sungmaStr - attacker.sungmaStrMalus;
        break;
+
 
      // Moulinet à l'épée
+
        if (sungmaStrDifference >= 0) {
       case 2:
+
           sungMaStrBonus = sungmaStrDifference;
         skillFormula = function (atk) {
+
         } else {
          return floorMultiplication(
+
          sungmaStrMalus = 0.5;
            3 * atk + (0.8 * atk + 5 * str + 3 * dex + vit) * skillPower,
+
         }
            1
+
       }
           );
+
    }
         };
+
 
         break;
+
    if (skillType) {
       // Accélération
+
      skillDamage += attacker.skillDamage;
      case 5:
+
    } else {
        skillFormula = function (atk) {
+
      averageDamage += attacker.averageDamage;
          return floorMultiplication(
+
    }
            2 * atk + (atk + dex * 3 + str * 7 + vit) * skillPower,
+
 
            1
+
    rankBonus = getRankBonus(attacker);
          );
+
     damageBonus = attacker.damageBonus;
        };
+
 
        break;
+
    if (isChecked(attacker.empireMalus)) {
      // Volonté de vivre
+
       empireMalus = 1;
      // case 6:
 
      //  skillFormula = function (atk) {
 
      //     return floorMultiplication(
 
      //      (3 * atk + (atk + 1.5 * str) * k) *
 
      //        1.07(3 * atk + (atk + 1.5 * str) * skillPower) *
 
       //        1.07,
 
      //      1
 
      //    );
 
      //  };
 
      //  break;
 
 
     }
 
     }
   } else if (attackerClass === "mental") {
+
   } else {
    switch (skillId) {
+
    if (isPC(victim)) {
      // Attaque de l'esprit
+
      if (isChecked(victim.isMarried)) {
      case 1:
+
         if (isChecked(victim.harmonyBracelet)) {
         skillFormula = function (atk) {
+
           monsterResistanceMarriage = getMarriageBonusValue(
           return floorMultiplication(
+
             victim,
             2.3 * atk + (4 * atk + 4 * str + vit) * skillPower,
+
            constants.marriageTable,
             1
+
             "harmonyBracelet"
 
           );
 
           );
         };
+
         }
        break;
+
 
      // Attaque de la paume
+
         if (isChecked(victim.harmonyNecklace) && !skillType) {
      case 2:
+
           defenseMarriage = getMarriageBonusValue(
         skillFormula = function (atk) {
+
             victim,
           return floorMultiplication(
+
            constants.marriageTable,
             2.3 * atk + (3 * atk + 4 * str + 3 * vit) * skillPower,
+
             "harmonyNecklace"
             1
 
 
           );
 
           );
         };
+
         }
         break;
+
      }
      // Charge
+
 
      case 3:
+
      monsterResistance = victim.monsterResistance;
         skillFormula = function (atk) {
+
 
           return floorMultiplication(
+
      for (var index = 0; index < elementBonus.length; index++) {
             2 * atk + (2 * atk + 2 * dex + 2 * vit + 4 * str) * skillPower,
+
         var elementBonusName = mapping.elementBonus[index];
            1
+
        var elementResistanceName = mapping.elementResistance[index];
          );
+
 
         };
+
         if (attacker[elementBonusName]) {
        break;
+
           elementBonus[index] =
      // Coup d'épée
+
             80 * (attacker[elementBonusName] - victim[elementResistanceName]);
       case 5:
+
         }
         skillFormula = function (atk) {
+
      }
           return floorMultiplication(
+
 
            2 * atk + (atk + 3 * dex + 5 * str + vit) * skillPower,
+
       if (!skillType) {
            1
+
         if (isMeleeAttacker(attacker)) {
          );
+
           missPercentage = victim.meleeBlock;
         };
+
          averageDamageResistance = victim.averageDamageResistance;
        break;
+
          blessingBonus = calcBlessingBonus(constants.skillPowerTable, victim);
      // Orbe de l'épée
+
         } else if (isRangeAttacker(attacker)) {
      // case 6:
+
          missPercentage = victim.arrowBlock;
      //  skillFormula = function (atk) {
+
          weaponDefense = victim.arrowDefense;
      //    return floorMultiplication(
+
          averageDamageResistance = victim.averageDamageResistance;
      //      (2 * atk + (2 * atk + 2 * dex + 2 * vit + 4 * str) * skillPower) *
+
          blessingBonus = calcBlessingBonus(constants.skillPowerTable, victim);
      //        1.1,
+
        } else if (isMagicAttacker(attacker)) {
      //      1
+
          missPercentage = victim.arrowBlock;
      //    );
+
          skillDamageResistance = victim.skillDamageResistance;
      //  };
+
          magicResistance = victim.magicResistance;
       //  break;
+
        }
 +
 
 +
        missPercentage +=
 +
          victim.meleeArrowBlock -
 +
          (missPercentage * victim.meleeArrowBlock) / 100;
 +
       }
 
     }
 
     }
   } else if (attackerClass === "blade_fight") {
+
 
     switch (skillId) {
+
    typeBonus = 1;
      // Dague filante
+
    damageMultiplier = attacker.damageMultiplier;
      case 3:
+
   }
        skillFormula = function (atk) {
+
 
          return floorMultiplication(
+
  if (skillType) {
            2 * atk + (0.5 * atk + 9 * dex + 7 * str) * skillPower,
+
     criticalHitPercentage = skillChanceReduction(criticalHitPercentage);
            1
+
    piercingHitPercentage = skillChanceReduction(piercingHitPercentage);
          );
+
  }
        };
+
 
        break;
+
  if (isPC(victim)) {
      // Brume empoisonnée
+
    if (!skillType && isChecked(victim.biologist70)) {
      case 5:
+
       defenseBoost = Math.floor((defenseBoost * 110) / 100);
        skillFormula = function (atk) {
 
          return floorMultiplication(
 
            2 * lv + (atk + 3 * str + 18 * dex) * skillPower,
 
            1
 
          );
 
        };
 
        break;
 
      // Poison insidieux
 
       case 6:
 
        skillFormula = function (atk) {
 
          return floorMultiplication(
 
            (2 * lv + (atk + 3 * str + 18 * dex) * skillPower) * 1.1,
 
            1
 
          );
 
        };
 
        break;
 
 
     }
 
     }
  } else if (attackerClass === "archery") {
+
 
     switch (skillId) {
+
     criticalHitPercentage = Math.max(
       // Tir à répétition
+
       0,
       // case 1:
+
       criticalHitPercentage - victim.criticalHitResistance
      //  skillFormula = function (atk) {
+
    );
      //     return floorMultiplication(
+
     piercingHitPercentage = Math.max(
      //      atk +
+
       0,
      //        0.2 * atk * Math.floor(2 + 6 * skillPower) +
+
       piercingHitPercentage - victim.piercingHitResistance
       //        (0.8 * atk + 8 * dex * attackFactor + 2 * int) * skillPower,
+
     );
       //      1
+
 
      //     );
+
    if (skillType) {
      //  };
+
      skillDamageResistance = victim.skillDamageResistance;
      //  break;
 
      // Pluie de flèches
 
      case 2:
 
        skillFormula = function (atk) {
 
          return floorMultiplication(
 
            atk + (1.7 * atk + 5 * dex + str) * skillPower,
 
            1
 
          );
 
        };
 
        break;
 
 
     }
 
     }
  } else if (attackerClass === "weaponary") {
+
 
    switch (skillId) {
+
    if (isMagicClass(victim)) {
       // Toucher brûlant
+
       defensePercent = (-2 * victim.magicDefense * victim.defensePercent) / 100;
      case 1:
+
    } else {
        skillFormula = function (atk) {
+
       defensePercent = (-2 * defenseBoost * victim.defensePercent) / 100;
          return floorMultiplication(
 
            atk +
 
              2 * lv +
 
              2 * int +
 
              (2 * atk + 4 * str + 14 * int) * skillPower,
 
            1
 
          );
 
        };
 
        break;
 
       // Tourbillon du dragon
 
      case 2:
 
        skillFormula = function (atk) {
 
          return floorMultiplication(
 
            1.1 * atk +
 
              2 * lv +
 
              2 * int +
 
              (1.5 * atk + str + 12 * int) * skillPower,
 
            1
 
          );
 
        };
 
        break;
 
 
     }
 
     }
  } else if (attackerClass === "black_magic") {
+
 
    switch (skillId) {
+
    if (isChecked(victim.steelDragonElixir)) {
       // Orbe des ténèbres
+
       steelDragonElixir = 10;
      case 6:
 
        skillFormula = function (mav) {
 
          return floorMultiplication(
 
            120 +
 
              6 * lv +
 
              (5 * vit + 5 * dex + 29 * int + 9 * mav) *
 
                attackFactor *
 
                skillPower,
 
            1
 
          );
 
        };
 
        break;
 
 
     }
 
     }
   } else if (attackerClass === "dragon") {
+
   }
     switch (skillId) {
+
 
      // Talisman volant
+
  if (skillType === "magic") {
       case 1:
+
     attackValueMeleeMagic = 0;
        skillFormula = function (mav) {
+
    magicAttackValueMeleeMagic =
          return floorMultiplication(
+
       attacker.attackMagic + Math.min(100, attacker.attackMeleeMagic);
            70 +
+
    attackValueMarriage = 0;
              5 * lv +
+
    defense = 0;
              (18 * int + 7 * str + 5 * mav + 50) * attackFactor * skillPower,
+
    if (!isDispell(attacker, 6)) {
            1
+
       magicResistance = victim.magicResistance;
          );
 
        };
 
        skillInfo.weaponBonus = [4, 10];
 
        break;
 
      // Dragon chassant
 
      case 2:
 
        skillFormula = function (mav) {
 
          return floorMultiplication(
 
            60 +
 
              5 * lv +
 
              (16 * int + 6 * dex + 6 * mav + 120) * attackFactor * skillPower,
 
            1
 
          );
 
        };
 
        skillInfo.weaponBonus = [4, 10];
 
        break;
 
      // Rugissement du dragon
 
       case 3:
 
        skillFormula = function (mav) {
 
          return floorMultiplication(
 
            70 +
 
              3 * lv +
 
              (20 * int + 3 * str + 10 * mav + 100) * attackFactor * skillPower,
 
            1
 
          );
 
        };
 
        skillInfo.weaponBonus = [4, 10];
 
        break;
 
 
     }
 
     }
   } else if (attackerClass === "heal") {
+
    weaponDefense = 0;
     switch (skillId) {
+
    calcAttackValues = calcMagicAttackValue;
      // Jet de foudre
+
   } else {
      case 1:
+
     calcAttackValues = calcSecondaryAttackValue;
        skillFormula = function (mav) {
+
  }
          return floorMultiplication(
+
 
            60 + 5 * lv + (8 * int + 2 * dex + 8 * mav + 10 * int) * attackFactor * skillPower,
+
  missPercentage = Math.min(100, missPercentage);
            1
+
 
          );
+
  var bonusValues = {
        };
+
    missPercentage: missPercentage,
        skillInfo.weaponBonus = [6, 10];
+
    weaponBonusCoeff: 1,
        break;
+
    attackValueCoeff: 100 + attackValueMeleeMagic,
      // Invocation de foudre
+
    attackValueMarriage: attackValueMarriage,
      case 2:
+
    monsterResistanceMarriageCoeff: 100 - monsterResistanceMarriage,
        skillFormula = function (mav) {
+
    monsterResistanceCoeff: 100 - monsterResistance,
          return floorMultiplication(
+
    typeBonusCoeff: typeBonus,
            40 + 4 * lv + (13 * int + 2 * str + 10 * mav + 10.5 * int) * attackFactor * skillPower,
+
    raceBonusCoeff: raceBonus,
            1
+
    raceResistanceCoeff: raceResistance,
          );
+
    stoneBonusCoeff: stoneBonus,
        };
+
    monsterBonusCoeff: monsterBonus,
        skillInfo.weaponBonus = [6, 10];
+
    elementBonusCoeff: elementBonus,
        break;
+
    damageMultiplier: damageMultiplier,
      // Griffe de foudre
+
    useDamages: useDamages,
      case 3:
+
    defense: defense,
        skillFormula = function (mav) {
+
    defenseBoost: defenseBoost,
          return floorMultiplication(
+
    defenseMarriage: defenseMarriage,
            50 + 5 * lv + (8 * int + 2 * str + 8 * mav + 400.5) * attackFactor * skillPower,
+
    tigerStrengthCoeff: 100 + tigerStrength,
            1
+
    magicResistanceCoeff: magicResistanceToCoeff(magicResistance),
          );
+
    weaponDefenseCoeff: 100 - weaponDefense,
        };
+
    blessingBonusCoeff: 100 - blessingBonus,
        break;
+
    magicAttackValueCoeff: 100 + magicAttackValueMeleeMagic,
      }
+
    extraPiercingHitCoeff: 5 * extraPiercingHitPercentage,
   } else if (attackerClass === "lycan") {
+
    averageDamageCoeff: 100 + averageDamage,
     switch (skillId) {
+
    averageDamageResistanceCoeff: 100 - Math.min(99, averageDamageResistance),
       // Déchiqueter
+
    skillDamageCoeff: 100 + skillDamage,
       // case 1:
+
    skillDamageResistanceCoeff: 100 - Math.min(99, skillDamageResistance),
       //  skillFormula = function (atk) {
+
    rankBonusCoeff: 100 + rankBonus,
      //    return floorMultiplication(
+
    defensePercent: Math.floor(defensePercent),
      //      1.1 * atk + (0.3 * atk + 1.5 * str) * skillPower,
+
    damageBonusCoeff: damageBonus,
       //      1
+
    empireMalusCoeff: 10 - empireMalus,
      //     );
+
    sungMaStrBonusCoeff: 10000 + sungMaStrBonus,
      //  };
+
    sungmaStrMalusCoeff: sungmaStrMalus,
       //  skillInfo.weaponBonus = [5, 54];
+
    whiteDragonElixirCoeff: 100 + whiteDragonElixir,
       //  break;
+
    steelDragonElixirCoeff: 100 - steelDragonElixir,
       // Souffle de loup
+
  };
      case 2:
+
 
         skillFormula = function (atk) {
+
  criticalHitPercentage = Math.min(criticalHitPercentage, 100);
          return floorMultiplication(
+
  piercingHitPercentage = Math.min(piercingHitPercentage, 100);
            2 * atk + (atk + 3 * dex + 5 * str + vit) * skillPower,
+
 
            1
+
   var damagesTypeCombinaison = [
          );
+
     {
        };
+
       criticalHit: false,
        skillInfo.weaponBonus = [5, 35];
+
       piercingHit: false,
        break;
+
       weight:
       // Bond de loup
+
        (100 - criticalHitPercentage) *
       case 3:
+
        (100 - piercingHitPercentage) *
         skillFormula = function (atk) {
+
        (100 - missPercentage),
          return floorMultiplication(
+
       name: "normalHit",
            atk + (1.6 * atk + 200 + 7 * dex + 7 * str) * skillPower,
+
     },
            1
+
    {
          );
+
       criticalHit: true,
        };
+
       piercingHit: false,
        skillInfo.weaponBonus = [5, 35];
+
       weight:
        break;
+
        criticalHitPercentage *
       // Griffe de loup
+
         (100 - piercingHitPercentage) *
       case 4:
+
        (100 - missPercentage),
         skillFormula = function (atk) {
+
      name: "criticalHit",
          return floorMultiplication(
+
    },
            3 * atk + (0.8 * atk + 6 * str + 2 * dex + vit) * skillPower,
+
    {
            1
+
      criticalHit: false,
          );
+
       piercingHit: true,
        };
+
       weight:
        break;
+
         (100 - criticalHitPercentage) *
     }
+
        piercingHitPercentage *
   }
+
        (100 - missPercentage),
 
+
      name: "piercingHit",
  return [skillFormula, skillInfo];
+
    },
 +
    {
 +
      criticalHit: true,
 +
       piercingHit: true,
 +
       weight:
 +
         criticalHitPercentage * piercingHitPercentage * (100 - missPercentage),
 +
      name: "criticalPiercingHit",
 +
    },
 +
  ];
 +
 
 +
  return {
 +
    attacker: attacker,
 +
    victim: victim,
 +
    attackFactor: calcAttackFactor(attacker, victim),
 +
    mainAttackValue: calcMainAttackValue(attacker),
 +
    attackValues: calcAttackValues(attacker),
 +
    bonusValues: bonusValues,
 +
     damagesTypeCombinaison: damagesTypeCombinaison,
 +
   };
 
}
 
}
  
function calcPhysicalSkillDamages(
+
function updateBattleValues(battleValues, skillFormula, skillInfo) {
  attacker,
+
   var weaponBonus = 0;
  attackerWeapon,
+
   var skillWard = 0;
   victim,
+
   var skillBonus = 0;
   tableResult,
+
   var skillBonusByBonus = 0;
   mapping,
+
   var { attacker: attacker, bonusValues: bonusValues } = battleValues;
   constants,
+
   var {
   skillId
+
     range: [minVariation, maxVariation],
) {
+
  } = skillInfo;
   var battleValues = createSkillBattleValues(
+
   var variationLength = maxVariation - minVariation + 1;
     attacker,
 
    attackerWeapon,
 
    victim,
 
    mapping,
 
    constants.marriageTable
 
   );
 
  
   var sumDamages = 0;
+
   if (skillInfo.hasOwnProperty("weaponBonus")) {
  var minMaxDamages = { min: Infinity, max: 0 };
+
    var [weaponType, weaponBonusValue] = skillInfo.weaponBonus;
  clearTableResult(tableResult);
 
  
  var attackFactor = calcAttackFactor(attacker, victim);
+
    if (weaponType === attacker.weapon.type) {
  var mainAttackValue = calcMainAttackValue(attacker, attackerWeapon);
+
      weaponBonus = weaponBonusValue;
  var [
+
     }
    minAttackValue,
+
   }
    maxAttackValue,
 
     attackValueOther,
 
    minInterval,
 
    totalCardinal,
 
   ] = calcSecondaryAttackValue(attacker, attackerWeapon);
 
  
   var lastWeightsLimit = maxAttackValue - minInterval + 1;
+
   if (skillInfo.skillBonus) {
   var firstWeightLimit = minAttackValue + minInterval - 1;
+
    skillBonus = skillInfo.skillBonus;
 +
   }
  
   var [skillFormula, skillInfo] = getSkillFormula(
+
   if (skillInfo.skillWard) {
     constants.skillPowerTable,
+
     skillWard = skillInfo.skillWard;
    skillId,
+
   }
    attacker,
 
    attackFactor
 
   );
 
  
   updateBattleValues(battleValues, skillInfo, attackerWeapon);
+
   if (skillInfo.skillBonusByBonus) {
 +
    skillBonusByBonus = skillInfo.skillBonusByBonus;
 +
  }
  
   for (var damagesType of battleValues.damagesTypeCombinaison) {
+
   if (skillInfo.removeWeaponReduction) {
     if (!damagesType.weight) {
+
     bonusValues.weaponDefenseCoeff = 100;
      continue;
+
  }
    }
 
  
    var damagesWeighted = {};
+
  bonusValues.weaponBonusCoeff = 100 + weaponBonus;
    addRowToTableResult(tableResult, damagesType.name);
+
  bonusValues.skillWardCoeff = 1 - skillWard / 100;
 +
  bonusValues.skillBonusCoeff = 1 + skillBonus / 100;
 +
  bonusValues.skillBonusByBonusCoeff = 100 + skillBonusByBonus;
  
    for (
+
  battleValues.skillFormula = skillFormula;
      var attackValue = minAttackValue;
+
  battleValues.skillRange = skillInfo.range;
      attackValue <= maxAttackValue;
+
  battleValues.attackValues.totalCardinal *= variationLength;
      attackValue++
+
  battleValues.attackValues.possibleDamagesCount *= variationLength;
    ) {
+
}
      var weight;
 
  
      if (attackValue > lastWeightsLimit) {
+
function calcWeights(minValue, maxValue, minInterval) {
        weight = maxAttackValue - attackValue + 1;
+
  var firstWeightLimit = minValue + minInterval - 1;
      } else if (attackValue < firstWeightLimit) {
+
  var lastWeightsLimit = maxValue - minInterval + 1;
        weight = attackValue - minAttackValue + 1;
+
  var weights = [];
      } else {
 
        weight = minInterval;
 
      }
 
  
      var secondaryAttackValue = 2 * attackValue + attackValueOther;
+
  for (var value = minValue; value < firstWeightLimit; value++) {
      var rawDamages =
+
    weights.push(value - minValue + 1);
        mainAttackValue +
+
  }
        floorMultiplication(attackFactor, secondaryAttackValue);
 
      var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
 
        rawDamages,
 
        battleValues
 
      );
 
  
      if (damagesWithPrimaryBonuses <= 2) {
+
  for (var value = firstWeightLimit; value <= lastWeightsLimit; value++) {
        for (var damages = 1; damages <= 5; damages++) {
+
    weights.push(minInterval);
          var damagesWithFormula = skillFormula(damages);
+
  }
  
          damagesWithFormula = floorMultiplication(
+
  for (var value = lastWeightsLimit + 1; value <= maxValue; value++) {
            damagesWithFormula,
+
    weights.push(maxValue - value + 1);
            battleValues.weaponBonusCoeff
+
  }
          );
 
  
          var finalDamages = calcSkillDamageWithSecondaryBonuses(
+
  return weights;
            damagesWithFormula,
+
}
            battleValues,
 
            damagesType,
 
            damagesWithPrimaryBonuses
 
          );
 
  
          addKeyValue(
+
function calcBlessingBonus(skillPowerTable, victim) {
            damagesWeighted,
+
  if (victim.isBlessed !== "on") {
            finalDamages,
+
    return 0;
            (weight * damagesType.weight) / (5 * totalCardinal)
+
  }
          );
 
          sumDamages += (finalDamages * weight * damagesType.weight) / 5;
 
        }
 
      } else {
 
        var damagesWithFormula = skillFormula(damagesWithPrimaryBonuses);
 
  
        damagesWithFormula = floorMultiplication(
+
  var int = victim.intBlessing;
          damagesWithFormula,
+
  var dex = victim.dexBlessing;
          battleValues.weaponBonusCoeff
+
  var skillPower = getSkillPower(victim["skillBlessing"], skillPowerTable);
        );
 
  
        var finalDamages = calcSkillDamageWithSecondaryBonuses(
+
  if (!skillPower) {
          damagesWithFormula,
+
    return 0;
          battleValues,
+
  }
          damagesType,
 
          damagesWithPrimaryBonuses
 
        );
 
  
        addKeyValue(
+
  var blessingBonus = floorMultiplication(
          damagesWeighted,
+
    ((int * 0.3 + 5) * (2 * skillPower + 0.5) + 0.3 * dex) / (skillPower + 2.3),
          finalDamages,
+
     1
          (weight * damagesType.weight) / totalCardinal
+
  );
        );
 
        sumDamages += finalDamages * weight * damagesType.weight;
 
      }
 
     }
 
 
 
    addToTableResult(tableResult, damagesWeighted, minMaxDamages);
 
  }
 
  
   if (minMaxDamages.min === Infinity) {
+
   if (victim.class === "dragon" && isChecked(ictim.blessingOnself)) {
     minMaxDamages.min = 0;
+
     blessingBonus = floorMultiplication(blessingBonus, 1.1);
 
   }
 
   }
  
   return [sumDamages / totalCardinal, minMaxDamages];
+
   return blessingBonus;
 
}
 
}
  
function calcMagicSkillDamages(
+
function getSkillFormula(battle, skillId, battleValues, removeSkillVariation) {
  attacker,
+
   var { attacker, victim, attackFactor } = battleValues;
  attackerWeapon,
+
  var skillPowerTable = battle.constants.skillPowerTable;
  victim,
 
  tableResult,
 
  mapping,
 
  constants,
 
  skillId
 
) {
 
   var battleValues = createSkillBattleValues(
 
    attacker,
 
    attackerWeapon,
 
    victim,
 
    mapping,
 
    constants.marriageTable,
 
    true
 
  );
 
  
   var sumDamages = 0;
+
   var skillFormula;
   var minMaxDamages = { min: Infinity, max: 0 };
+
   var skillInfo = { range: [0, 0] };
  clearTableResult(tableResult);
 
  
   var attackFactor = calcAttackFactor(attacker, victim);
+
   var { class: attackerClass, level: lv, vit, str, int, dex } = attacker;
  var [minMagicAttackValue, maxMagicAttackValue, minInterval, totalCardinal] =
 
    calcMagicAttackValue(attacker, attackerWeapon);
 
  
   var lastWeightsLimit = maxMagicAttackValue - minInterval + 1;
+
   if (skillId <= 9) {
  var firstWeightLimit = minMagicAttackValue + minInterval - 1;
+
    var skillPower = getSkillPower(
 +
      attacker["attackSkill" + skillId],
 +
      skillPowerTable
 +
    );
  
  var [skillFormula, skillInfo] = getSkillFormula(
+
    var improvedBySkillBonus = false;
     constants.skillPowerTable,
+
     var improvedByBonus = false;
    skillId,
 
    attacker,
 
    attackFactor
 
  );
 
  
  updateBattleValues(battleValues, skillInfo, attackerWeapon);
+
    if (attackerClass === "body") {
 
+
      switch (skillId) {
  for (var damagesType of battleValues.damagesTypeCombinaison) {
+
        // Triple lacération
    if (!damagesType.weight) {
+
        case 1:
      continue;
+
          skillFormula = function (atk) {
    }
+
            return floorMultiplication(
 
+
              1.1 * atk + (0.5 * atk + 1.5 * str) * skillPower,
    var damagesWeighted = {};
+
              1
    addRowToTableResult(tableResult, damagesType.name);
+
            );
 
+
          };
     for (
+
          improvedByBonus = true;
       var magicAttackValue = minMagicAttackValue;
+
          break;
      magicAttackValue <= maxMagicAttackValue;
+
        // Moulinet à l'épée
      magicAttackValue++
+
        case 2:
    ) {
+
          skillFormula = function (atk) {
      var weight;
+
            return floorMultiplication(
 
+
              3 * atk + (0.8 * atk + 5 * str + 3 * dex + vit) * skillPower,
      if (magicAttackValue > lastWeightsLimit) {
+
              1
         weight = maxMagicAttackValue - magicAttackValue + 1;
+
            );
      } else if (magicAttackValue < firstWeightLimit) {
+
          };
         weight = magicAttackValue - minMagicAttackValue + 1;
+
          improvedByBonus = true;
      } else {
+
          improvedBySkillBonus = true;
        weight = minInterval;
+
          break;
 +
        // Accélération
 +
        case 5:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              2 * atk + (atk + dex * 3 + str * 7 + vit) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Volonté de vivre
 +
        case 6:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              (3 * atk + (atk + 1.5 * str) * skillPower) * 1.07,
 +
              1
 +
            );
 +
          };
 +
          break;
 +
        // Tremblement de terre
 +
        case 9:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              3 * atk +
 +
                (0.9 * atk + variation + 5 * str + 3 * dex + lv) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 +
      }
 +
     } else if (attackerClass === "mental") {
 +
       switch (skillId) {
 +
        // Attaque de l'esprit
 +
        case 1:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              2.3 * atk + (4 * atk + 4 * str + vit) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          improvedBySkillBonus = true;
 +
          break;
 +
        // Attaque de la paume
 +
        case 2:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              2.3 * atk + (3 * atk + 4 * str + 3 * vit) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Charge
 +
        case 3:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              2 * atk + (2 * atk + 2 * dex + 2 * vit + 4 * str) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          break;
 +
         // Coup d'épée
 +
        case 5:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              2 * atk + (atk + 3 * dex + 5 * str + vit) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Orbe de l'épée
 +
        case 6:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              (2 * atk + (2 * atk + 2 * dex + 2 * vit + 4 * str) * skillPower) *
 +
                1.1,
 +
              1
 +
            );
 +
          };
 +
          break;
 +
         // Tremblement de terre
 +
        case 9:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              3 * atk +
 +
                (0.9 * atk + variation + 5 * str + 3 * dex + lv) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 
       }
 
       }
 
+
    } else if (attackerClass === "blade_fight") {
       var rawDamages = skillFormula(magicAttackValue);
+
       switch (skillId) {
 
+
        // Embuscade
      rawDamages = floorMultiplication(
+
        case 1:
        rawDamages,
+
          skillFormula = function (atk, variation) {
        battleValues.weaponBonusCoeff
+
            return floorMultiplication(
      );
+
              atk + (1.2 * atk + variation + 4 * dex + 4 * str) * skillPower,
 
+
              1
      var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
+
            );
        rawDamages,
+
          };
        battleValues
+
          skillInfo.weaponBonus = [1, 50];
      );
+
          skillInfo.range = [500, 700];
 
+
          improvedByBonus = true;
      if (damagesWithPrimaryBonuses <= 2) {
+
          improvedBySkillBonus = true;
        for (var damages = 1; damages <= 5; damages++) {
+
          break;
           var finalDamages = calcSkillDamageWithSecondaryBonuses(
+
        // Attaque rapide
             damages,
+
        case 2:
             battleValues,
+
          skillFormula = function (atk, variation) {
             damagesType,
+
            return floorMultiplication(
            damagesWithPrimaryBonuses,
+
              atk + (1.6 * atk + variation + 7 * dex + 7 * str) * skillPower,
             skillFormula
+
              1
           );
+
            );
 
+
          };
           addKeyValue(
+
          skillInfo.weaponBonus = [1, 35];
             damagesWeighted,
+
          skillInfo.range = [200, 300];
             finalDamages,
+
          improvedByBonus = true;
            (weight * damagesType.weight) / (5 * totalCardinal)
+
          break;
          );
+
        // Dague filante
           sumDamages += (finalDamages * weight * damagesType.weight) / 5;
+
        case 3:
        }
+
          skillFormula = function (atk) {
      } else {
+
            return floorMultiplication(
         var finalDamages = calcSkillDamageWithSecondaryBonuses(
+
              2 * atk + (0.5 * atk + 9 * dex + 7 * str) * skillPower,
           damagesWithPrimaryBonuses,
+
              1
           battleValues,
+
            );
           damagesType,
+
          };
           damagesWithPrimaryBonuses,
+
          improvedByBonus = true;
           skillFormula
+
          break;
        );
+
        // Brume empoisonnée
 
+
        case 5:
         addKeyValue(
+
           skillFormula = function (atk) {
           damagesWeighted,
+
             return floorMultiplication(
           finalDamages,
+
              2 * lv + (atk + 3 * str + 18 * dex) * skillPower,
          (weight * damagesType.weight) / totalCardinal
+
              1
         );
+
             );
        sumDamages += finalDamages * weight * damagesType.weight;
+
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Poison insidieux
 +
        case 6:
 +
          skillFormula = function (atk) {
 +
             return floorMultiplication(
 +
              (2 * lv + (atk + 3 * str + 18 * dex) * skillPower) * 1.1,
 +
              1
 +
             );
 +
           };
 +
          break;
 +
        // Étoiles brillantes
 +
        case 9:
 +
           skillFormula = function (atk, variation) {
 +
             return floorMultiplication(
 +
              atk + (1.7 * atk + variation + 6 * dex + 5 * lv) * skillPower,
 +
              1
 +
             );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 +
      }
 +
    } else if (attackerClass === "archery") {
 +
      switch (skillId) {
 +
        // Tir à répétition
 +
        // case 1:
 +
        //  skillFormula = function (atk) {
 +
        //    return floorMultiplication(
 +
        //      atk + 0.2 * atk * Math.floor(2 + 6 * skillPower) + (0.8 * atk + 8 * dex * attackFactor + 2 * int) * skillPower,
 +
        //      1
 +
        //    );
 +
        //  };
 +
        //  improvedByBonus = true;
 +
        //  break;
 +
        // Pluie de flèches
 +
        case 2:
 +
           skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              atk + (1.7 * atk + 5 * dex + str) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Flèche de feu
 +
         case 3:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              1.5 * atk + (2.6 * atk + 0.9 * int + variation) * skillPower,
 +
              1
 +
            );
 +
          };
 +
           skillInfo.range = [100, 300];
 +
           improvedByBonus = true;
 +
           improvedBySkillBonus = true;
 +
           break;
 +
        // Foulée de plume
 +
        case 4:
 +
           skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              (3 * dex + 200 + 2 * str + 2 * int) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.removeWeaponReduction = true;
 +
          break;
 +
         // Flèche empoisonnée
 +
        case 5:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              atk +
 +
                (1.4 * atk + variation + 7 * dex + 4 * str + 4 * int) *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
           skillInfo.range = [100, 200];
 +
           improvedByBonus = true;
 +
          break;
 +
        // Coup étincelant
 +
        case 6:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              (atk +
 +
                (1.2 * atk + variation + 6 * dex + 3 * str + 3 * int) *
 +
                  skillPower) *
 +
                1.2,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [100, 200];
 +
          improvedByBonus = true;
 +
          break;
 +
        // Tir tempête
 +
         case 9:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              1.9 * atk + (2.6 * atk + variation) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 
       }
 
       }
     }
+
     } else if (attackerClass === "weaponary") {
 
+
      switch (skillId) {
     addToTableResult(tableResult, damagesWeighted, minMaxDamages);
+
        // Toucher brûlant
   }
+
        case 1:
 
+
          skillFormula = function (atk) {
   if (minMaxDamages.min === Infinity) {
+
            return floorMultiplication(
     minMaxDamages.min = 0;
+
              atk +
   }
+
                2 * lv +
 
+
                2 * int +
   return [sumDamages / totalCardinal, minMaxDamages];
+
                (2 * atk + 4 * str + 14 * int) * skillPower,
}
+
              1
 
+
            );
function createMonster(name) {
+
          };
  var data = monsterData[name];
+
          improvedByBonus = true;
 +
          improvedBySkillBonus = true;
 +
          break;
 +
        // Tourbillon du dragon
 +
        case 2:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              1.1 * atk +
 +
                2 * lv +
 +
                2 * int +
 +
                (1.5 * atk + str + 12 * int) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Contre-sort
 +
        case 6:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              40 +
 +
                5 * lv +
 +
                2 * int +
 +
                (10 * int + 7 * mav + variation) * attackFactor * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [50, 100];
 +
          break;
 +
        // Coup démoniaque
 +
        case 9:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              1.9 * atk + (2.6 * atk + variation) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 +
      }
 +
    } else if (attackerClass === "black_magic") {
 +
      switch (skillId) {
 +
        // Attaque des ténèbres
 +
        case 1:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              40 +
 +
                5 * lv +
 +
                2 * int +
 +
                (13 * int + 6 * mav + variation) * attackFactor * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [50, 100];
 +
          improvedByBonus = true;
 +
          improvedBySkillBonus = true;
 +
          break;
 +
        // Attaque de flammes
 +
        // case 2:
 +
        //  skillFormula = function (mav, variation) {
 +
        //    return floorMultiplication(
 +
        //      5 * lv + 2 * int + (7 * int + 8 * mav + 4 * str + 2 * vit + variation) * skillPower,
 +
        //      1
 +
        //     );
 +
        //  };
 +
        //  skillInfo.range = [180, 100];
 +
        //  improvedByBonus = true;
 +
        //  break;
 +
        // Esprit de flammes
 +
        case 3:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              30 +
 +
                2 * lv +
 +
                2 * int +
 +
                (7 * int + 6 * mav + variation) * attackFactor * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [200, 500];
 +
          break;
 +
        // Frappe de l'esprit
 +
        // case 5:
 +
        //  skillFormula = function (mav, variation) {
 +
        //    return floorMultiplication(
 +
        //      40 + 2 * lv + 2 * int + (2 * vit + 2 * dex + 13 * int + 6 * mav + variation) * attackFactor * skillPower,
 +
        //      1
 +
        //    );
 +
        //   };
 +
        //  skillInfo.range = [180, 200];
 +
        //   break;
 +
        // Orbe des ténèbres
 +
        case 6:
 +
          skillFormula = function (mav) {
 +
            return floorMultiplication(
 +
              120 +
 +
                6 * lv +
 +
                (5 * vit + 5 * dex + 29 * int + 9 * mav) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Vague mortelle
 +
        case 9:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              120 +
 +
                6 * lv +
 +
                (5 * vit + 5 * dex + 30 * int + variation + 9 * mav) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 +
      }
 +
    } else if (attackerClass === "dragon") {
 +
      switch (skillId) {
 +
        // Talisman volant
 +
        case 1:
 +
          skillFormula = function (mav) {
 +
            return floorMultiplication(
 +
              70 +
 +
                5 * lv +
 +
                (18 * int + 7 * str + 5 * mav + 50) * attackFactor * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [4, 10];
 +
          improvedByBonus = true;
 +
          break;
 +
        // Dragon chassant
 +
        case 2:
 +
          skillFormula = function (mav) {
 +
            return floorMultiplication(
 +
              60 +
 +
                5 * lv +
 +
                (16 * int + 6 * dex + 6 * mav + 120) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [4, 10];
 +
          improvedByBonus = true;
 +
          improvedBySkillBonus = true;
 +
          break;
 +
        // Rugissement du dragon
 +
        case 3:
 +
          skillFormula = function (mav) {
 +
            return floorMultiplication(
 +
              70 +
 +
                3 * lv +
 +
                (20 * int + 3 * str + 10 * mav + 100) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [4, 10];
 +
          improvedByBonus = true;
 +
          break;
 +
        // Météore
 +
        case 9:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              120 +
 +
                6 * lv +
 +
                (5 * vit + 5 * dex + 30 * int + variation + 9 * mav) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 +
      }
 +
     } else if (attackerClass === "heal") {
 +
      switch (skillId) {
 +
        // Jet de foudre
 +
        case 1:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              60 +
 +
                5 * lv +
 +
                (8 * int + 2 * dex + 8 * mav + variation) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [6, 10];
 +
          skillInfo.range = [5 * int, 15 * int];
 +
          improvedByBonus = true;
 +
          break;
 +
        // Invocation de foudre
 +
        case 2:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              40 +
 +
                4 * lv +
 +
                (13 * int + 2 * str + 10 * mav + variation) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [6, 10];
 +
          skillInfo.range = [5 * int, 16 * int];
 +
          improvedByBonus = true;
 +
          improvedBySkillBonus = true;
 +
          break;
 +
        // Griffe de foudre
 +
        case 3:
 +
          skillFormula = function (mav, variation) {
 +
            return floorMultiplication(
 +
              50 +
 +
                5 * lv +
 +
                (8 * int + 2 * str + 8 * mav + variation) *
 +
                  attackFactor *
 +
                  skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 800];
 +
          improvedByBonus = true;
 +
          break;
 +
      }
 +
    } else if (attackerClass === "lycan") {
 +
      switch (skillId) {
 +
        // Déchiqueter
 +
        // case 1:
 +
        //  skillFormula = function (atk) {
 +
        //    return floorMultiplication(
 +
        //      1.1 * atk + (0.3 * atk + 1.5 * str) * skillPower,
 +
        //      1
 +
        //    );
 +
        //   };
 +
        //  skillInfo.weaponBonus = [5, 54];
 +
        //  improvedByBonus = true;
 +
        //   break;
 +
        // Souffle de loup
 +
        case 2:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              2 * atk + (atk + 3 * dex + 5 * str + vit) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [5, 35];
 +
          improvedByBonus = true;
 +
          improvedBySkillBonus = true;
 +
          break;
 +
        // Bond de loup
 +
        case 3:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              atk + (1.6 * atk + 200 + 7 * dex + 7 * str) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.weaponBonus = [5, 35];
 +
          improvedByBonus = true;
 +
          break;
 +
        // Griffe de loup
 +
        case 4:
 +
          skillFormula = function (atk) {
 +
            return floorMultiplication(
 +
              3 * atk + (0.8 * atk + 6 * str + 2 * dex + vit) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          improvedByBonus = true;
 +
          break;
 +
        // Tempête cinglante
 +
        case 9:
 +
          skillFormula = function (atk, variation) {
 +
            return floorMultiplication(
 +
              1.8 * atk +
 +
                (atk + 6 * dex + variation + 3 * str + lv) * skillPower,
 +
              1
 +
            );
 +
          };
 +
          skillInfo.range = [1, 1000];
 +
          break;
 +
      }
 +
    }
 +
    if (improvedBySkillBonus) {
 +
      skillInfo.skillBonus =
 +
        16 * getSkillPower(attacker.skillBonus, skillPowerTable);
  
  var monster = {
+
      var skillWardChoice = victim.skillWardChoice;
    name: name,
 
    rank: data[0],
 
    race: data[1],
 
    attack: data[2],
 
    level: data[3],
 
    type: data[4],
 
    str: data[5],
 
    dex: data[6],
 
    vit: data[7],
 
    int: data[8],
 
    minAttackValue: data[9],
 
    maxAttackValue: data[10],
 
    defense: data[11] + data[3] + data[7],
 
    criticalHit: data[12],
 
    piercingHit: data[13],
 
    fistDefense: data[14],
 
    swordDefense: data[15],
 
    twoHandedSwordDefense: data[16],
 
    daggerDefense: data[17],
 
    bellDefense: data[18],
 
    fanDefense: data[19],
 
    arrowDefense: data[20],
 
    clawDefense: data[21],
 
    fireResistance: data[22],
 
    lightningResistance: data[23],
 
    magicResistance: data[24],
 
    windResistance: data[25],
 
    lightningBonus: data[26],
 
    fireBonus: data[27],
 
    iceBonus: data[28],
 
    windBonus: data[29],
 
    earthBonus: data[30],
 
    darknessBonus: data[31],
 
    darknessResistance: data[32],
 
    iceResistance: data[33],
 
    earthResistance: data[34],
 
    damageMultiplier: data[35],
 
  };
 
  
  return monster;
+
      if (skillWardChoice && skillWardChoice === attackerClass) {
}
+
        skillInfo.skillWard =
 +
          24 * getSkillPower(victim.skillWard, skillPowerTable);
 +
      }
 +
    }
  
function createBattle(characters, battle) {
+
    if (improvedByBonus) {
  function isPseudoSaved(pseudo) {
+
      skillInfo.skillBonusByBonus = attacker["skillBonus" + skillId];
    return characters.savedCharacters.hasOwnProperty(pseudo);
+
    }
  }
 
  
  battle.battleForm.addEventListener("submit", function (event) {
+
    if (removeSkillVariation) {
     event.preventDefault();
+
      var averageVariation = (skillInfo.range[0] + skillInfo.range[0]) / 2;
 +
      skillInfo.range = [averageVariation, averageVariation];
 +
    }
 +
  } else {
 +
    var skillPower = getSkillPower(
 +
      attacker["horseSkill" + skillId],
 +
      skillPowerTable
 +
     );
  
     var battleInfo = new FormData(event.target);
+
     switch (skillId) {
    var attackerName = battleInfo.get("attacker");
+
      // Combat équestre
    var attackType = battleInfo.get("attackTypeSelection");
+
      case 137:
    var victimName = battleInfo.get("victim");
+
        skillFormula = function (atk) {
 
+
          return floorMultiplication(atk + 2 * atk * skillPower, 1);
    if (!attackerName && !attackType && !victimName) {
+
        };
      return;
+
        break;
 +
      // Charge à cheval
 +
      case 138:
 +
        skillFormula = function (atk) {
 +
          return floorMultiplication(
 +
            2.4 * (200 + 1.5 * lv) + 600 * skillPower,
 +
            1
 +
          );
 +
        };
 +
        break;
 +
      // Vague de Pouvoir
 +
      case 139:
 +
        skillFormula = function (atk) {
 +
          return floorMultiplication(
 +
            2 * (200 + 1.5 * lv) + 600 * skillPower,
 +
            1
 +
          );
 +
        };
 +
        break;
 +
      // Grêle de flèches
 +
      case 140:
 +
        skillFormula = function (atk) {
 +
          return floorMultiplication(atk + 2 * atk * skillPower, 1);
 +
        };
 +
        break;
 
     }
 
     }
 +
  }
  
    var attackerWeapon = null;
+
  updateBattleValues(battleValues, skillFormula, skillInfo);
 +
}
  
    if (isPseudoSaved(attackerName)) {
+
function calcMagicAttackValueAugmentation(
       var attacker = copyObject(characters.savedCharacters[attackerName]);
+
  magicAttackValueWeapon,
 +
  magicAttackValueBonus
 +
) {
 +
  if (magicAttackValueBonus) {
 +
    return Math.max(
 +
       1,
 +
      0.0025056 *
 +
        magicAttackValueBonus ** 0.602338 *
 +
        magicAttackValueWeapon ** 1.20476
 +
    );
 +
  }
 +
  return 0;
 +
}
  
      if (weaponData.hasOwnProperty(attacker.weapon)) {
+
function getMagicAttackValueAugmentation(
        attackerWeapon = weaponData[attacker.weapon];
+
  minMagicAttackValue,
      } else {
+
  maxMagicAttackValue,
        attackerWeapon = weaponData[0];
+
  magicAttackValueBonus
      }
+
) {
    } else {
+
  var magicAttackValueAugmentation = [];
      var attacker = createMonster(attackerName);
 
    }
 
  
    if (isPseudoSaved(victimName)) {
+
  for (
      var victim = copyObject(characters.savedCharacters[victimName]);
+
    var magicAttackValue = minMagicAttackValue;
     } else {
+
    magicAttackValue <= maxMagicAttackValue;
       var victim = createMonster(victimName);
+
     magicAttackValue++
    }
+
  ) {
 +
    magicAttackValueAugmentation.push(
 +
       calcMagicAttackValueAugmentation(magicAttackValue, magicAttackValueBonus)
 +
    );
 +
  }
  
    var meanDamages, minMaxDamages;
+
  return magicAttackValueAugmentation;
    var calcDamages;
+
}
    var skillId = 0;
 
  
    if (attackType === "physical") {
+
function calcPhysicalDamages(battleValues) {
      calcDamages = calcPhysicalDamages;
+
  var {
     } else if (attackType.startsWith("attackSkill")) {
+
    attackFactor,
      skillId = parseInt(attackType.split("attackSkill")[1]);
+
    mainAttackValue,
 +
     attackValues: { minAttackValue, maxAttackValue, attackValueOther, weights },
 +
    bonusValues,
 +
    damagesTypeCombinaison,
 +
  } = battleValues;
  
      if (isMagicClass(attacker)) {
+
  var damagesWeightedByType = {};
        calcDamages = calcMagicSkillDamages;
 
      } else {
 
        calcDamages = calcPhysicalSkillDamages;
 
      }
 
    }
 
  
    [meanDamages, minMaxDamages] = calcDamages(
+
  if (bonusValues.missPercentage) {
      attacker,
+
    damagesWeightedByType.miss = bonusValues.missPercentage / 100;
      attackerWeapon,
+
  }
      victim,
 
      battle.tableResult,
 
      battle.mapping,
 
      battle.constants,
 
      skillId
 
    );
 
  
    battle.damageResult.textContent =
+
  for (var damagesType of damagesTypeCombinaison) {
      attacker.name +
+
    if (!damagesType.weight) {
      " inflige " +
+
       continue;
      numberFormat(meanDamages, 1) +
+
    }
      " dégâts en moyenne à " +
 
      victim.name +
 
      " (minimum : " +
 
      minMaxDamages.min +
 
       ", maximum : " +
 
      minMaxDamages.max +
 
      ").";
 
  
     showElement(battle.tableContainer);
+
     var damagesWeighted = {};
  });
+
    damagesWeightedByType[damagesType.name] = damagesWeighted;
  
  battle.attackerSelection.addEventListener("change", function (event) {
+
    for (
    var attackerName = event.target.value;
+
      var attackValue = minAttackValue;
     var attackTypeSelection = battle.attackTypeSelection;
+
      attackValue <= maxAttackValue;
 +
      attackValue++
 +
     ) {
 +
      var weight = weights[attackValue - minAttackValue] * damagesType.weight;
  
    if (isPseudoSaved(attackerName)) {
+
      var secondaryAttackValue = 2 * attackValue + attackValueOther;
       var attacker = characters.savedCharacters[attackerName];
+
      var rawDamages =
       filterAttackTypeSelection(attacker, attackTypeSelection);
+
        mainAttackValue +
    } else {
+
        floorMultiplication(attackFactor, secondaryAttackValue);
      for (var option of attackTypeSelection.options) {
+
 
        if (option.dataset.class) {
+
      var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
           hideElement(option);
+
        rawDamages,
 +
        bonusValues
 +
      );
 +
 
 +
       var minPiercingDamages =
 +
        damagesWithPrimaryBonuses -
 +
        bonusValues.defenseBoost +
 +
        bonusValues.defenseMarriage;
 +
 
 +
       if (minPiercingDamages <= 2) {
 +
        for (var damages = 1; damages <= 5; damages++) {
 +
          var finalDamages = calcDamageWithSecondaryBonuses(
 +
            damages,
 +
            bonusValues,
 +
            damagesType,
 +
            minPiercingDamages,
 +
            damagesWithPrimaryBonuses
 +
          );
 +
 
 +
           addKeyValue(damagesWeighted, finalDamages, weight / 5);
 
         }
 
         }
 +
      } else {
 +
        var finalDamages = calcDamageWithSecondaryBonuses(
 +
          minPiercingDamages,
 +
          bonusValues,
 +
          damagesType,
 +
          minPiercingDamages,
 +
          damagesWithPrimaryBonuses
 +
        );
 +
 +
        addKeyValue(damagesWeighted, finalDamages, weight);
 
       }
 
       }
      attackTypeSelection.selectedIndex = 0;
 
 
     }
 
     }
   });
+
   }
 +
 
 +
  return damagesWeightedByType;
 
}
 
}
  
function createMapping() {
+
function calcPhysicalSkillDamages(battleValues) {
   mapping = {
+
   var {
     typeFlag: [
+
     attackFactor,
      "animalBonus", // 0
+
    mainAttackValue,
      "humanBonus", // 1
+
    attackValues: { minAttackValue, maxAttackValue, attackValueOther, weights },
      "orcBonus", // 2
+
    bonusValues,
      "mysticBonus", // 3
+
    damagesTypeCombinaison,
      "undeadBonus", // 4
+
    skillFormula,
      "insectBonus", // 5
+
     skillRange: [minVariation, maxVariation],
      "desertBonus", // 6
+
  } = battleValues;
      "devilBonus", // 7
+
 
     ],
+
  var damagesWeightedByType = {};
    raceBonus: {
+
 
      warrior: "warriorBonus",
+
  for (var damagesType of damagesTypeCombinaison) {
      sura: "suraBonus",
+
    if (!damagesType.weight) {
       ninja: "ninjaBonus",
+
       continue;
      shaman: "shamanBonus",
+
    }
      lycan: "lycanBonus",
+
 
     },
+
     var damagesWeighted = {};
     raceResistance: {
+
     var savedDamages = {};
      warrior: "warriorResistance",
+
 
      sura: "suraResistance",
+
    damagesWeightedByType[damagesType.name] = damagesWeighted;
       ninja: "ninjaResistance",
+
 
       shaman: "shamanResistance",
+
    for (
       lycan: "lycanResistance",
+
       var attackValue = minAttackValue;
     },
+
       attackValue <= maxAttackValue;
    defenseWeapon: [
+
       attackValue++
       "swordDefense", // 0
+
     ) {
       "daggerDefense", // 1
+
      var weight = weights[attackValue - minAttackValue] * damagesType.weight;
      "arrowDefense", // 2
+
 
       "twoHandedSwordDefense", // 3
+
       var secondaryAttackValue = 2 * attackValue + attackValueOther;
      "bellDefense", // 4
+
       var rawDamages =
      "clawDefense", // 5
+
        mainAttackValue +
       "fanDefense", // 6
+
        floorMultiplication(attackFactor, secondaryAttackValue);
      "swordDefense", // 7
+
 
       "fistDefense", // 8
+
       var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
    ],
+
        rawDamages,
    breakWeapon: [
+
        bonusValues
      "breakSwordDefense", // 0
+
       );
       "breakDaggerDefense", // 1
+
 
      "breakArrowDefense", // 2
+
       for (
      "breakTwoHandedSwordDefense", // 3
+
        var variation = minVariation;
      "breakBellDefense", // 4
+
        variation <= maxVariation;
      "breakClawDefense", // 5
+
        variation++
      "breakFanDefense", // 6
+
       ) {
      "breakSwordDefense", // 7
+
        if (damagesWithPrimaryBonuses <= 2) {
    ],
+
          for (var damages = 1; damages <= 5; damages++) {
    elementBonus: [
+
            damages *= bonusValues.useDamages;
      "fireBonus", // 0
+
 
      "iceBonus", // 1
+
            var damagesWithFormula = skillFormula(damages, variation);
      "windBonus", // 2
+
 
      "lightningBonus", // 3
+
            damagesWithFormula = Math.floor(
      "earthBonus", // 4
+
              (damagesWithFormula * bonusValues.weaponBonusCoeff) / 100
      "darknessBonus", // 5
+
            );
    ],
+
 
    elementResistance: [
+
            var finalDamages = calcSkillDamageWithSecondaryBonuses(
      "fireResistance", // 0
+
              damagesWithFormula,
      "iceResistance", // 1
+
              bonusValues,
      "windResistance", // 2
+
              damagesType,
      "lightningResistance", // 3
+
              damagesWithPrimaryBonuses
      "earthResistance", // 4
+
            );
      "darknessResistance", // 5
+
 
    ],
+
            addKeyValue(damagesWeighted, finalDamages, weight / 5);
  };
+
          }
  return mapping;
+
        } else {
}
+
          damagesWithPrimaryBonuses *= bonusValues.useDamages;
 +
 
 +
          var damagesWithFormula = skillFormula(
 +
            damagesWithPrimaryBonuses,
 +
            variation
 +
          );
  
function createConstants() {
+
          if (savedDamages.hasOwnProperty(damagesWithFormula)) {
  var constants = {
+
            var finalDamages = savedDamages[damagesWithFormula];
    polymorphPowerTable: [
+
            damagesWeighted[finalDamages] += weight;
      10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 26, 27,
+
            continue;
      29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 59, 62, 66, 70, 74, 79,
+
          }
      84, 89, 94, 100, 0,
+
 
    ],
+
          var finalDamages = Math.floor(
    skillPowerTable: [
+
            (damagesWithFormula * bonusValues.weaponBonusCoeff) / 100
      0, 0.05, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26,
+
          );
      0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.5, 0.52, 0.54, 0.56, 0.58, 0.6,
 
      0.63, 0.66, 0.69, 0.72, 0.82, 0.85, 0.88, 0.91, 0.94, 0.98, 1.02, 1.06,
 
      1.1, 1.15, 1.25,
 
    ],
 
    marriageTable: {
 
      harmonyEarrings: [4, 5, 6, 8],
 
      loveEarrings: [4, 5, 6, 8],
 
      harmonyBracelet: [4, 5, 6, 8],
 
      loveNecklace: [20, 25, 30, 40],
 
      harmonyNecklace: [12, 16, 20, 30],
 
    },
 
  };
 
  return constants;
 
}
 
  
function createDamageCalculatorInformation() {
+
          finalDamages = calcSkillDamageWithSecondaryBonuses(
  var characters = {
+
            finalDamages,
    unsavedChanges: false,
+
            bonusValues,
    savedCharacters: {},
+
            damagesType,
    currentCharacter: null,
+
            damagesWithPrimaryBonuses
    characterCreation: document.getElementById("character-creation"),
+
          );
    addNewCharacterButton: document.getElementById("add-new-character"),
+
 
    uploadCharacter: document.getElementById("upload-character"),
+
          savedDamages[damagesWithFormula] = finalDamages;
    newCharacterTemplate: document.getElementById("new-character-template")
+
          addKeyValue(damagesWeighted, finalDamages, weight);
      .children[0],
+
        }
    charactersContainer: document.getElementById("characters-container"),
+
       }
    newMonsterTemplate: document.getElementById("new-monster-template")
+
     }
       .children[0],
+
  }
     monstersContainer: document.getElementById("monsters-container"),
+
 
    monsterListForm: document.getElementById("monster-list-form"),
+
  return damagesWeightedByType;
    searchMonster: document.getElementById("search-monster"),
+
}
    monsterList: document.getElementById("monster-list"),
+
 
    saveButton: document.getElementById("save-button"),
+
function calcMagicSkillDamages(battleValues) {
     classChoice: document.getElementById("class-choice"),
+
  var {
    stateChoice: document.getElementById("state-choice"),
+
     attackValues: {
    polymorphMonster: document.getElementById("polymorph-monster"),
+
      minMagicAttackValue,
    weaponCategory: document.getElementById("weapon-category"),
+
      maxMagicAttackValue,
    weaponDisplay: document.getElementById("weapon-display"),
+
      magicAttackValueAugmentation,
     weaponUpgrade: document.getElementById("upgrade-choice"),
+
      weights,
     randomAttackValue: document.getElementById("random-attack-value"),
+
     },
     randomMagicAttackValue: document.getElementById(
+
     bonusValues,
      "random-magic-attack-value"
+
     damagesTypeCombinaison,
    ),
+
     skillFormula,
     lowRankCheckbox: document.getElementById("low-rank"),
+
     skillRange: [minVariation, maxVariation],
     playerRankChoice: document.getElementById("player-rank"),
+
   } = battleValues;
    skillContainer: document.getElementById("skill-container"),
+
 
   };
+
   var damagesWeightedByType = {};
  characters.race = characters.characterCreation.race;
 
   characters.weapon = characters.characterCreation.weapon;
 
  
   delete characters.newCharacterTemplate.dataset.click;
+
   for (var damagesType of damagesTypeCombinaison) {
 +
    if (!damagesType.weight) {
 +
      continue;
 +
    }
  
  var savedCharacters = getSavedCharacters();
+
    var damagesWeighted = {};
  var savedMonsters = getSavedMonsters();
+
    var savedDamages = {};
 
+
 
  for (var [pseudo, character] of Object.entries(savedCharacters)) {
+
    damagesWeightedByType[damagesType.name] = damagesWeighted;
     characters.savedCharacters[pseudo] = character;
+
 
  }
+
     for (
 
+
      var magicAttackValue = minMagicAttackValue;
  characters.savedMonsters = savedMonsters;
+
      magicAttackValue <= maxMagicAttackValue;
 
+
      magicAttackValue++
  var skillContainer = document.getElementById("skill-container");
+
    ) {
  characters.skillElementsToFilter =
+
      var index = magicAttackValue - minMagicAttackValue;
    skillContainer.querySelectorAll("[data-class]");
+
      var weight = weights[index] * damagesType.weight;
 
+
 
  var mapping = createMapping();
+
      for (
  var constants = createConstants();
+
        var variation = minVariation;
 
+
        variation <= maxVariation;
  var battle = {
+
        variation++
    resetAttackType: false,
+
      ) {
    battleForm: document.getElementById("create-battle"),
+
        var rawDamages = skillFormula(
    attackerSelection: document.getElementById("attacker-selection"),
+
          magicAttackValue + magicAttackValueAugmentation[index],
    attackTypeSelection: document.getElementById("attack-type-selection"),
+
          variation
    victimSelection: document.getElementById("victim-selection"),
+
        );
    damageResult: document.getElementById("result-damage"),
+
 
    tableContainer: document.getElementById("result-table-container"),
+
        if (savedDamages.hasOwnProperty(rawDamages)) {
    tableResult: document.getElementById("result-table").children[0],
+
          var finalDamages = savedDamages[rawDamages];
    mapping: mapping,
+
          damagesWeighted[finalDamages] += weight;
    constants: constants,
+
          continue;
  };
+
        }
 
+
 
  return [characters, battle];
+
        var damagesWithPrimaryBonuses = Math.floor(
}
+
          (rawDamages * bonusValues.weaponBonusCoeff) / 100
 
+
        );
function loadScript(src, callback) {
+
 
  var script = document.createElement("script");
+
        damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
  script.src = src;
+
          damagesWithPrimaryBonuses,
 
+
          bonusValues
  function onComplete() {
+
        );
     if (script.parentNode) {
+
 
       script.parentNode.removeChild(script);
+
        if (damagesWithPrimaryBonuses <= 2) {
 +
          for (var damages = 1; damages <= 5; damages++) {
 +
            var finalDamages = calcSkillDamageWithSecondaryBonuses(
 +
              damages,
 +
              bonusValues,
 +
              damagesType,
 +
              damagesWithPrimaryBonuses
 +
            );
 +
            addKeyValue(damagesWeighted, finalDamages, weight / 5);
 +
          }
 +
        } else {
 +
          var finalDamages = calcSkillDamageWithSecondaryBonuses(
 +
            damagesWithPrimaryBonuses,
 +
            bonusValues,
 +
            damagesType,
 +
            damagesWithPrimaryBonuses
 +
          );
 +
 
 +
          savedDamages[rawDamages] = finalDamages;
 +
          addKeyValue(damagesWeighted, finalDamages, weight);
 +
        }
 +
      }
 +
    }
 +
  }
 +
 
 +
  return damagesWeightedByType;
 +
}
 +
 
 +
function calcDamages(
 +
  attacker,
 +
  victim,
 +
  attackType,
 +
  battle,
 +
  removeSkillVariation
 +
) {
 +
  var damagesCalculator, skillId, skillType;
 +
 
 +
  if (attackType === "physical") {
 +
    damagesCalculator = calcPhysicalDamages;
 +
  } else if (attackType.startsWith("attackSkill")) {
 +
    skillId = Number(attackType.split("attackSkill")[1]);
 +
 
 +
    if (isMagicClass(attacker) || isDispell(attacker, skillId)) {
 +
      skillType = "magic";
 +
      damagesCalculator = calcMagicSkillDamages;
 +
    } else {
 +
      skillType = "physical";
 +
      damagesCalculator = calcPhysicalSkillDamages;
 +
    }
 +
  } else if (attackType.startsWith("horseSkill")) {
 +
    skillType = "physical";
 +
    skillId = Number(attackType.split("horseSkill")[1]);
 +
    damagesCalculator = calcPhysicalSkillDamages;
 +
  }
 +
 
 +
  var battleValues = createBattleValues(attacker, victim, battle, skillType);
 +
 
 +
  if (skillId) {
 +
    getSkillFormula(battle, skillId, battleValues, removeSkillVariation);
 +
  }
 +
 
 +
  var {
 +
    attackValues: { totalCardinal, possibleDamagesCount },
 +
  } = battleValues;
 +
 
 +
  return {
 +
    damagesWeightedByType: damagesCalculator(battleValues),
 +
    totalCardinal: totalCardinal,
 +
    possibleDamagesCount: possibleDamagesCount,
 +
    skillType: skillType,
 +
  };
 +
}
 +
 
 +
function damagesWithoutVariation(
 +
  attacker,
 +
  victim,
 +
  attackType,
 +
  battle,
 +
  characters
 +
) {
 +
  startDamagesTime = performance.now();
 +
 
 +
  var {
 +
    damagesWeightedByType,
 +
    totalCardinal,
 +
    possibleDamagesCount,
 +
    skillType,
 +
  } = calcDamages(attacker, victim, attackType, battle);
 +
 
 +
  endDamagesTime = performance.now();
 +
 
 +
  possibleDamagesCount = displayResults(
 +
    possibleDamagesCount,
 +
    totalCardinal,
 +
    damagesWeightedByType,
 +
    battle,
 +
    attacker.name,
 +
    victim.name
 +
  );
 +
 
 +
  endDisplayTime = performance.now();
 +
 
 +
  displayFightInfo(
 +
    possibleDamagesCount,
 +
    endDamagesTime - startDamagesTime,
 +
    endDisplayTime - endDamagesTime,
 +
    battle
 +
  );
 +
  addPotentialErrorInformation(
 +
    battle.errorInformation,
 +
    attacker,
 +
    victim,
 +
    skillType,
 +
    characters
 +
  );
 +
 
 +
  hideElement(battle.bonusVariationResultContainer);
 +
  showElement(battle.fightResultContainer);
 +
}
 +
 
 +
function damagesWithVariation(
 +
  attacker,
 +
  victim,
 +
  attackType,
 +
  battle,
 +
  entity,
 +
  entityVariation
 +
) {
 +
  startTime = performance.now();
 +
  var damagesByBonus = [];
 +
  var augmentationByBonus = [];
 +
  var {
 +
    bonusVariationMinValue: minVariation,
 +
    bonusVariationMaxValue: maxVariation,
 +
  } = entity;
 +
  var step = Math.ceil((maxVariation - minVariation + 1) / 500);
 +
  var simulationCount = 0;
 +
  var simulationTime;
 +
 
 +
  for (
 +
    var bonusValue = minVariation;
 +
    bonusValue <= maxVariation;
 +
    bonusValue += step
 +
  ) {
 +
    entity[entityVariation] = bonusValue;
 +
 
 +
    var { damagesWeightedByType, totalCardinal } = calcDamages(
 +
      copyObject(attacker),
 +
      copyObject(victim),
 +
      attackType,
 +
      battle,
 +
      true
 +
    );
 +
 
 +
    var meanDamages = calcMeanDamages(damagesWeightedByType, totalCardinal);
 +
 
 +
    if (bonusValue === minVariation) {
 +
      var firstDamages = Math.max(meanDamages, 1e-3);
 +
    }
 +
 
 +
    damagesByBonus.push({ x: bonusValue, y: meanDamages });
 +
    augmentationByBonus.push({
 +
      x: bonusValue,
 +
      y: meanDamages / firstDamages - 1,
 +
    });
 +
    simulationCount++;
 +
  }
 +
 
 +
  endTime = performance.now();
 +
 
 +
  battle.damagesByBonus = damagesByBonus.concat(entityVariation);
 +
 
 +
  addToBonusVariationChart(
 +
    damagesByBonus,
 +
    augmentationByBonus,
 +
    entity.bonusVariationDisplay,
 +
    battle.bonusVariationChart
 +
  );
 +
 
 +
  simulationCount = battle.numberFormats.default.format(simulationCount);
 +
  simulationTime = battle.numberFormats.second.format(
 +
    (endTime - startTime) / 1000
 +
  );
 +
 
 +
  battle.simulationCounter.textContent = simulationCount;
 +
  battle.simulationTime.textContent = simulationTime;
 +
 
 +
  hideElement(battle.fightResultContainer);
 +
  showElement(battle.bonusVariationResultContainer);
 +
 
 +
  if (
 +
    isChecked(attacker.bonusVariationActivation) &&
 +
    isChecked(victim.bonusVariationActivation)
 +
  ) {
 +
    showElement(battle.errorInformation["attacker-victim-variation"]);
 +
  } else {
 +
    hideElement(battle.errorInformation["attacker-victim-variation"]);
 +
  }
 +
}
 +
 
 +
function changeMonsterValues(monster, instance, attacker) {
 +
  switch (instance) {
 +
    case "SungMahiTower":
 +
      var sungMahiFloor = 1;
 +
      var sungMahiStep = 1;
 +
      var rawDefense = 120;
 +
 
 +
      if (isPC(attacker)) {
 +
        sungMahiFloor = attacker.sungMahiFloor;
 +
        sungMahiStep = attacker.sungMahiStep;
 +
      }
 +
 
 +
      if (monster.rank === 5) {
 +
        monster.level = 121;
 +
        monster.dex = 75;
 +
        rawDefense += 1;
 +
      } else if (monster.rank === 6) {
 +
        monster.level = 123;
 +
        monster.dex = 75;
 +
        rawDefense += 1;
 +
      } else {
 +
        monster.level = 120;
 +
        monster.dex = 68;
 +
      }
 +
      monster.vit = 100;
 +
      monster.rawDefense = rawDefense + (sungMahiStep - 1) * 6;
 +
      monster.fistDefense = 0;
 +
      monster.swordDefense = 0;
 +
      monster.twoHandedSwordDefense = 0;
 +
      monster.daggerDefense = 0;
 +
      monster.bellDefense = 0;
 +
      monster.fanDefense = 0;
 +
      monster.arrowDefense = 0;
 +
      monster.clawDefense = 0;
 +
      monster.magicResistance = 0;
 +
      monster.fireResistance = -20;
 +
  }
 +
}
 +
 
 +
function createWeapon(weaponVnum) {
 +
  var weapon = weaponData[weaponVnum];
 +
  var weaponName = weapon[0];
 +
 
 +
  return {
 +
    name: weaponName,
 +
    type: weapon[1],
 +
    minAttackValue: weapon[2][2],
 +
    maxAttackValue: weapon[2][3],
 +
    minMagicAttackValue: weapon[2][0],
 +
    maxMagicAttackValue: weapon[2][1],
 +
    upgrades: weapon[3],
 +
    isSerpent: isValueInArray("serpent", weaponName.toLowerCase()),
 +
  };
 +
}
 +
 
 +
function createMonster(monsterVnum, attacker) {
 +
  var monsterAttributes = monsterData[monsterVnum];
 +
 
 +
  var monster = {
 +
    name: monsterAttributes[36],
 +
    rank: monsterAttributes[0],
 +
    race: monsterAttributes[1],
 +
    attack: monsterAttributes[2],
 +
    level: monsterAttributes[3],
 +
    type: monsterAttributes[4],
 +
    str: monsterAttributes[5],
 +
    dex: monsterAttributes[6],
 +
    vit: monsterAttributes[7],
 +
    int: monsterAttributes[8],
 +
    minAttackValue: monsterAttributes[9],
 +
    maxAttackValue: monsterAttributes[10],
 +
    rawDefense: monsterAttributes[11],
 +
    criticalHit: monsterAttributes[12],
 +
    piercingHit: monsterAttributes[13],
 +
    fistDefense: monsterAttributes[14],
 +
    swordDefense: monsterAttributes[15],
 +
    twoHandedSwordDefense: monsterAttributes[16],
 +
    daggerDefense: monsterAttributes[17],
 +
    bellDefense: monsterAttributes[18],
 +
    fanDefense: monsterAttributes[19],
 +
    arrowDefense: monsterAttributes[20],
 +
    clawDefense: monsterAttributes[21],
 +
    fireResistance: monsterAttributes[22],
 +
    lightningResistance: monsterAttributes[23],
 +
    magicResistance: monsterAttributes[24],
 +
    windResistance: monsterAttributes[25],
 +
    lightningBonus: monsterAttributes[26],
 +
    fireBonus: monsterAttributes[27],
 +
    iceBonus: monsterAttributes[28],
 +
    windBonus: monsterAttributes[29],
 +
    earthBonus: monsterAttributes[30],
 +
    darknessBonus: monsterAttributes[31],
 +
    darknessResistance: monsterAttributes[32],
 +
    iceResistance: monsterAttributes[33],
 +
    earthResistance: monsterAttributes[34],
 +
    damageMultiplier: monsterAttributes[35],
 +
  };
 +
 
 +
  // monster.instance = 0;
 +
 
 +
  // if (attacker && monster.instance === 0) {
 +
  //  changeMonsterValues(monster, "SungMahiTower", attacker);
 +
  // }
 +
 
 +
  monster.defense = monster.rawDefense + monster.level + monster.vit;
 +
 
 +
  return monster;
 +
}
 +
 
 +
function addPotentialErrorInformation(
 +
  errorInformation,
 +
  attacker,
 +
  victim,
 +
  skillType,
 +
  characters
 +
) {
 +
  for (var error of Object.values(errorInformation)) {
 +
    hideElement(error);
 +
  }
 +
 
 +
  if (isPC(attacker)) {
 +
    if (isRiding(attacker)) {
 +
      if (attacker.horsePoint === 0) {
 +
        showElement(errorInformation["horse-level"]);
 +
      }
 +
      showElement(errorInformation["horse-stat"]);
 +
    } else if (isPolymorph(attacker)) {
 +
      if (attacker.polymorphPoint === 0) {
 +
        showElement(errorInformation["polymorph-level"]);
 +
      }
 +
 
 +
      if (
 +
        (attacker.polymorphPoint <= 39 && attacker.attackValuePercent <= 199) ||
 +
        (attacker.polymorphPoint === 40 && attacker.attackValuePercent <= 299)
 +
      ) {
 +
        showElement(errorInformation["polymorph-bonus"]);
 +
      }
 +
    }
 +
    if (skillType === "magic") {
 +
      if (attacker.magicAttackValue) {
 +
        showElement(errorInformation["magic-attack-value-bonus"]);
 +
      }
 +
      if (victim.magicResistance) {
 +
        showElement(errorInformation["magic-resistance"]);
 +
      }
 +
    }
 +
  } else {
 +
    showElement(errorInformation["monster-attacker"]);
 +
    if (isMagicAttacker(attacker) && victim.magicResistance) {
 +
      showElement(errorInformation["magic-resistance"]);
 +
    }
 +
  }
 +
 
 +
  if (isPC(victim)) {
 +
    if (isRiding(victim)) {
 +
      showElement(errorInformation["horse-stat"]);
 +
    } else if (isPolymorph(victim)) {
 +
      if (attacker.polymorphPoint === 0) {
 +
        showElement(errorInformation["polymorph-level"]);
 +
      }
 +
      showElement(errorInformation["polymorph-defense"]);
 +
    }
 +
  }
 +
 
 +
  if (characters.unsavedChanges) {
 +
    showElement(errorInformation["save"]);
 +
  }
 +
}
 +
 
 +
function reduceChartPointsListener(battle) {
 +
  var {
 +
    reduceChartPointsContainer,
 +
    reduceChartPoints,
 +
    numberFormats: { second: numberFormat },
 +
    displayTime,
 +
  } = battle;
 +
 
 +
  reduceChartPoints.addEventListener("change", function () {
 +
    var startDisplayTime = performance.now();
 +
    var scatterDataByType = battle.scatterDataByType;
 +
    var {
 +
      chart,
 +
      maxPoints,
 +
      chart: {
 +
        data: { datasets },
 +
      },
 +
    } = battle.damagesChart;
 +
    var addAnimations = false;
 +
 
 +
    for (var index = 0; index < datasets.length; index++) {
 +
      var dataset = datasets[index];
 +
      var scatterData = scatterDataByType[dataset.name];
 +
 
 +
      if (dataset.canBeReduced && reduceChartPoints.checked) {
 +
        dataset.data = aggregateDamages(scatterData, maxPoints);
 +
        addAnimations = true;
 +
      } else {
 +
        dataset.data = scatterData;
 +
      }
 +
    }
 +
 
 +
    handleChartAnimations(chart, addAnimations);
 +
    chart.update();
 +
 
 +
    displayTime.textContent = numberFormat.format(
 +
      (performance.now() - startDisplayTime) / 1000
 +
    );
 +
  });
 +
 
 +
  reduceChartPointsContainer.addEventListener("pointerup", function (event) {
 +
    if (event.pointerType === "mouse") {
 +
      reduceChartPoints.click();
 +
    }
 +
  });
 +
}
 +
 
 +
function downloadRawDataListener(battle) {
 +
  var { downLoadRawData, downLoadRawDataVariation } = battle;
 +
  var fileType = "text/csv;charset=utf-8;";
 +
 
 +
  downLoadRawData.addEventListener("click", function () {
 +
    var damagesWeightedByType = battle.damagesWeightedByType;
 +
    var filename = "raw_damages.csv";
 +
    var csvContent = "damage,probabilities,damageType\n";
 +
 
 +
    for (var damagesType in damagesWeightedByType) {
 +
      var damagesWeighted = damagesWeightedByType[damagesType];
 +
 
 +
      for (var damages in damagesWeighted) {
 +
        csvContent +=
 +
          damages + "," + damagesWeighted[damages] + "," + damagesType + "\n";
 +
      }
 +
    }
 +
 
 +
    downloadData(csvContent, fileType, filename);
 +
  });
 +
 
 +
  downLoadRawDataVariation.addEventListener("click", function () {
 +
    var damagesByBonus = battle.damagesByBonus;
 +
    var damagesByBonusLength = damagesByBonus.length;
 +
    var filename = "damages_variation.csv";
 +
 
 +
    if (!damagesByBonusLength) {
 +
      return;
 +
    }
 +
 
 +
    var csvContent =
 +
      damagesByBonus[damagesByBonusLength - 1] + ",averageDamage\n";
 +
 
 +
    for (var index = 0; index < damagesByBonusLength - 1; index++) {
 +
      var row = damagesByBonus[index];
 +
 
 +
      csvContent += row.x + "," + row.y + "\n";
 +
    }
 +
 
 +
    downloadData(csvContent, fileType, filename);
 +
  });
 +
}
 +
 
 +
function displayResults(
 +
  possibleDamagesCount,
 +
  totalCardinal,
 +
  damagesWeightedByType,
 +
  battle,
 +
  attackerName,
 +
  victimName
 +
) {
 +
  var [
 +
    meanDamages,
 +
    minDamages,
 +
    maxDamages,
 +
    scatterDataByType,
 +
    possibleDamagesCount,
 +
    uniqueDamagesCount,
 +
  ] = prepareDamagesData(
 +
    damagesWeightedByType,
 +
    possibleDamagesCount,
 +
    totalCardinal
 +
  );
 +
 
 +
  addToDamagesChart(
 +
    scatterDataByType,
 +
    battle.damagesChart,
 +
    battle.reduceChartPoints.checked
 +
  );
 +
  updateDamagesChartDescription(
 +
    battle.uniqueDamagesCounters,
 +
    uniqueDamagesCount,
 +
    battle.numberFormats.default
 +
  );
 +
  displayFightResults(
 +
    battle,
 +
    attackerName,
 +
    victimName,
 +
    meanDamages,
 +
    minDamages,
 +
    maxDamages
 +
  );
 +
  battle.damagesWeightedByType = damagesWeightedByType;
 +
  battle.scatterDataByType = scatterDataByType;
 +
 
 +
  return possibleDamagesCount;
 +
}
 +
 
 +
function displayFightResults(
 +
  battle,
 +
  attackerName,
 +
  victimName,
 +
  meanDamages,
 +
  minDamages,
 +
  maxDamages
 +
) {
 +
  var {
 +
    tableResultFight,
 +
    tableResultHistory,
 +
    attackTypeSelection,
 +
    savedFights,
 +
    numberFormats: { default: numberFormat },
 +
    deleteFightTemplate,
 +
  } = battle;
 +
 
 +
  hideElement(tableResultHistory.rows[1]);
 +
 
 +
  var valuesToDisplay = [
 +
    attackerName,
 +
    victimName,
 +
    attackTypeSelection.options[attackTypeSelection.selectedIndex].textContent,
 +
    meanDamages,
 +
    minDamages,
 +
    maxDamages,
 +
  ];
 +
 
 +
  savedFights.push(valuesToDisplay);
 +
  updateSavedFights(savedFights);
 +
 
 +
  editTableResultRow(tableResultFight.rows[1], valuesToDisplay, numberFormat);
 +
  addRowToTableResultHistory(
 +
    tableResultHistory,
 +
    valuesToDisplay,
 +
    deleteFightTemplate,
 +
    numberFormat
 +
  );
 +
}
 +
 
 +
function displayFightInfo(
 +
  possibleDamagesCount,
 +
  damagesTime,
 +
  displayTime,
 +
  battle
 +
) {
 +
  var container = battle.possibleDamagesCounter.parentElement;
 +
 
 +
  if (possibleDamagesCount <= 1) {
 +
    hideElement(container);
 +
    return;
 +
  } else {
 +
    showElement(container);
 +
  }
 +
 
 +
  possibleDamagesCount =
 +
    battle.numberFormats.default.format(possibleDamagesCount);
 +
  damagesTime = battle.numberFormats.second.format(damagesTime / 1000);
 +
  displayTime = battle.numberFormats.second.format(displayTime / 1000);
 +
 
 +
  battle.possibleDamagesCounter.textContent = possibleDamagesCount;
 +
  battle.damagesTime.textContent = damagesTime;
 +
  battle.displayTime.textContent = displayTime;
 +
}
 +
 
 +
function isPseudoSaved(characters, pseudo) {
 +
  return characters.savedCharacters.hasOwnProperty(pseudo);
 +
}
 +
 
 +
function createBattle(characters, battle) {
 +
  battle.battleForm.addEventListener("submit", function (event) {
 +
    event.preventDefault();
 +
 
 +
    // auto save
 +
    if (characters.unsavedChanges) {
 +
      characters.saveButton.click();
 +
    }
 +
 
 +
    var battleInfo = new FormData(event.target);
 +
    var attackerName = battleInfo.get("attacker");
 +
    var attackType = battleInfo.get("attackTypeSelection");
 +
    var victimName = battleInfo.get("victim");
 +
    var attackerVariation;
 +
    var victimVariation;
 +
 
 +
    if (!attackerName && !attackType && !victimName) {
 +
      return;
 +
    }
 +
 
 +
    if (isPseudoSaved(characters, attackerName)) {
 +
      var attacker = copyObject(characters.savedCharacters[attackerName]);
 +
      attackerVariation = attacker.bonusVariation;
 +
    } else {
 +
      var attacker = createMonster(attackerName);
 +
    }
 +
 
 +
    if (isPseudoSaved(characters, victimName)) {
 +
      var victim = copyObject(characters.savedCharacters[victimName]);
 +
      victimVariation = victim.bonusVariation;
 +
    } else {
 +
      var victim = createMonster(victimName, attacker);
 +
    }
 +
 
 +
    if (
 +
      isChecked(attacker.bonusVariationActivation) &&
 +
      attacker.hasOwnProperty(attackerVariation) &&
 +
      attacker.bonusVariationMinValue < attacker.bonusVariationMaxValue
 +
    ) {
 +
      damagesWithVariation(
 +
        attacker,
 +
        victim,
 +
        attackType,
 +
        battle,
 +
        attacker,
 +
        attackerVariation
 +
      );
 +
    } else if (
 +
      isChecked(victim.bonusVariationActivation) &&
 +
      victim.hasOwnProperty(victimVariation) &&
 +
      victim.bonusVariationMinValue < victim.bonusVariationMaxValue
 +
    ) {
 +
      damagesWithVariation(
 +
        attacker,
 +
        victim,
 +
        attackType,
 +
        battle,
 +
        victim,
 +
        victimVariation
 +
      );
 +
    } else {
 +
      damagesWithoutVariation(attacker, victim, attackType, battle, characters);
 +
    }
 +
  });
 +
}
 +
 
 +
function createMapping() {
 +
  mapping = {
 +
    typeFlag: [
 +
      "animalBonus", // 0
 +
      "humanBonus", // 1
 +
      "orcBonus", // 2
 +
      "mysticBonus", // 3
 +
      "undeadBonus", // 4
 +
      "insectBonus", // 5
 +
      "desertBonus", // 6
 +
      "devilBonus", // 7
 +
    ],
 +
    raceBonus: {
 +
      warrior: "warriorBonus",
 +
      sura: "suraBonus",
 +
      ninja: "ninjaBonus",
 +
      shaman: "shamanBonus",
 +
      lycan: "lycanBonus",
 +
    },
 +
    raceResistance: {
 +
      warrior: "warriorResistance",
 +
      sura: "suraResistance",
 +
      ninja: "ninjaResistance",
 +
      shaman: "shamanResistance",
 +
      lycan: "lycanResistance",
 +
    },
 +
    defenseWeapon: [
 +
      "swordDefense", // 0
 +
      "daggerDefense", // 1
 +
      "arrowDefense", // 2
 +
      "twoHandedSwordDefense", // 3
 +
      "bellDefense", // 4
 +
      "clawDefense", // 5
 +
      "fanDefense", // 6
 +
      "swordDefense", // 7
 +
      "fistDefense", // 8
 +
    ],
 +
    breakWeapon: [
 +
      "breakSwordDefense", // 0
 +
      "breakDaggerDefense", // 1
 +
      "breakArrowDefense", // 2
 +
      "breakTwoHandedSwordDefense", // 3
 +
      "breakBellDefense", // 4
 +
      "breakClawDefense", // 5
 +
      "breakFanDefense", // 6
 +
      "breakSwordDefense", // 7
 +
    ],
 +
    elementBonus: [
 +
      "fireBonus", // 0
 +
      "iceBonus", // 1
 +
      "windBonus", // 2
 +
      "lightningBonus", // 3
 +
      "earthBonus", // 4
 +
      "darknessBonus", // 5
 +
    ],
 +
    elementResistance: [
 +
      "fireResistance", // 0
 +
      "iceResistance", // 1
 +
      "windResistance", // 2
 +
      "lightningResistance", // 3
 +
      "earthResistance", // 4
 +
      "darknessResistance", // 5
 +
    ],
 +
  };
 +
  return mapping;
 +
}
 +
 
 +
function createConstants() {
 +
  var constants = {
 +
    polymorphPowerTable: [
 +
      10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 26, 27,
 +
      29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 59, 62, 66, 70, 74, 79,
 +
      84, 89, 94, 100, 0,
 +
    ],
 +
    skillPowerTable: [
 +
      0, 0.05, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26,
 +
      0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.5, 0.52, 0.54, 0.56, 0.58, 0.6,
 +
      0.63, 0.66, 0.69, 0.72, 0.82, 0.85, 0.88, 0.91, 0.94, 0.98, 1.02, 1.06,
 +
      1.1, 1.15, 1.25,
 +
    ],
 +
    marriageTable: {
 +
      harmonyEarrings: [4, 5, 6, 8],
 +
      loveEarrings: [4, 5, 6, 8],
 +
      harmonyBracelet: [4, 5, 6, 8],
 +
      loveNecklace: [20, 25, 30, 40],
 +
      harmonyNecklace: [12, 16, 20, 30],
 +
    },
 +
    allowedWeaponsPerRace: {
 +
      warrior: [0, 3, 8],
 +
      ninja: [0, 1, 2, 8],
 +
      sura: [0, 7, 8],
 +
      shaman: [4, 6, 8],
 +
      lycan: [5, 8],
 +
    },
 +
    translation: {
 +
      fr: {
 +
        damages: "Dégâts",
 +
        percentage: "Pourcentage",
 +
        miss: "Miss",
 +
        normalHit: "Coup classique",
 +
        criticalHit: "Coup critique",
 +
        piercingHit: "Coup perçant",
 +
        criticalPiercingHit: "Coup critique perçant",
 +
        damagesRepartition: "Distribution des dégâts",
 +
        averageDamages: "Dégâts moyens",
 +
        damagesAugmentation: "Augmentation des dégâts",
 +
        bonusVariationTitle: [
 +
          "Évolution des dégâts moyens",
 +
          "par rapport à la valeur d'un bonus",
 +
        ],
 +
      },
 +
      en: {
 +
        damages: "Damage",
 +
        percentage: "Percentage",
 +
        miss: "Miss",
 +
        normalHit: "Normal Hit",
 +
        criticalHit: "Critical Hit",
 +
        piercingHit: "Piercing Hit",
 +
        criticalPiercingHit: "Critical Piercing Hit",
 +
        damagesRepartition: "Damage Repartition",
 +
        averageDamages: "Average Damage",
 +
        damagesAugmentation: "Damage Augmentation",
 +
        bonusVariationTitle: [
 +
          "Evolution of Average Damage",
 +
          "Relative to a Bonus Value",
 +
        ],
 +
      },
 +
      tr: {
 +
        damages: "Hasar",
 +
        percentage: "Yüzde",
 +
        miss: "Miss Vuruş",
 +
        normalHit: "Düz Vuruş",
 +
        criticalHit: "Kritik Vuruş",
 +
        piercingHit: "Delici Vuruş",
 +
        criticalPiercingHit: "Kritikli Delici Vuruş",
 +
        damagesRepartition: "Hasar Dağılımı",
 +
        averageDamages: "Ortalama Hasar",
 +
        damagesAugmentation: "Ortalama Hasar Artışı",
 +
        bonusVariationTitle: [
 +
          "Bir bonusun değerine kıyasla",
 +
          "Ortalama Hasar Çizelgesi",
 +
        ],
 +
      },
 +
      ro: {
 +
        damages: "Daune",
 +
        percentage: "Procent",
 +
        miss: "Miss",
 +
        normalHit: "Lovitura normala",
 +
        criticalHit: "Lovitura critica",
 +
        piercingHit: "Lovitura patrunzatoare",
 +
        criticalPiercingHit: "Lovitura critica si patrunzatoare",
 +
        damagesRepartition: "Distribuția daunelor",
 +
        averageDamages: "Media damageului",
 +
        damagesAugmentation: "Damage imbunatatit",
 +
        bonusVariationTitle: [
 +
          "Evolutia mediei damageului",
 +
          "relativ la o valoare bonus",
 +
        ],
 +
      },
 +
      de: {
 +
        damages: "Schäden",
 +
        percentage: "Prozentsatz",
 +
        miss: "Verfehlen",
 +
        normalHit: "Normaler Treffer",
 +
        criticalHit: "Kritischer Treffer",
 +
        piercingHit: "Durchdringender Treffer",
 +
        criticalPiercingHit: "Kritischer durchdringender Treffer",
 +
        damagesRepartition: "Schadensverteilung",
 +
        averageDamages: "Durchschnittlicher Schaden",
 +
        damagesAugmentation: "Schadenserhöhung",
 +
        bonusVariationTitle: [
 +
          "Entwicklung des durchschnittlichen Schadens",
 +
          "im Verhältnis zu einem Bonus",
 +
        ],
 +
      },
 +
      pt: {
 +
        damages: "Dano",
 +
        percentage: "Percentagem",
 +
        miss: "Miss",
 +
        normalHit: "Dano normal",
 +
        criticalHit: "Dano crítico",
 +
        piercingHit: "Dano perfurante",
 +
        criticalPiercingHit: "Dano crítico perfurante",
 +
        damagesRepartition: "Repartição de dano",
 +
        averageDamages: "Dano médio",
 +
        damagesAugmentation: "Aumento de dano",
 +
        bonusVariationTitle: ["Evolução do dano médio", "relativo a um bónus"],
 +
      },
 +
      // es: {
 +
      //  damages: "Daño",
 +
      //  percentage: "Porcentaje",
 +
      //  miss: "Miss",
 +
      //  normalHit: "Daño normal",
 +
      //  criticalHit: "Daño crítico",
 +
      //  piercingHit: "Daño perforante",
 +
      //  criticalPiercingHit: "Daño crítico perforante",
 +
      //  damagesRepartition: "Repartición de daños",
 +
      //  averageDamages: "Daño medio",
 +
      //  damagesAugmentation: "Aumento de daño",
 +
      //  bonusVariationTitle: ["Evolución del daño medio", "Relativo a una bonificación"]
 +
      // },
 +
    },
 +
  };
 +
  return constants;
 +
}
 +
 
 +
function initResultTableHistory(battle) {
 +
  var {
 +
    tableResultHistory,
 +
    savedFights,
 +
    deleteFightTemplate,
 +
    numberFormats: { default: numberFormat },
 +
  } = battle;
 +
  var startIndex = 3;
 +
 
 +
  if (savedFights.length) {
 +
    hideElement(tableResultHistory.rows[1]);
 +
 
 +
    for (var savedFight of savedFights) {
 +
      addRowToTableResultHistory(
 +
        tableResultHistory,
 +
        savedFight,
 +
        deleteFightTemplate,
 +
        numberFormat
 +
      );
 +
    }
 +
  }
 +
 
 +
  tableResultHistory.addEventListener("click", function (event) {
 +
    var deleteButton = event.target.closest(".svg-icon-delete");
 +
 
 +
    if (deleteButton) {
 +
      var row = deleteButton.closest("tr");
 +
 
 +
      if (row) {
 +
        savedFights.splice(row.rowIndex - startIndex, 1);
 +
        updateSavedFights(savedFights);
 +
 
 +
        row.remove();
 +
 
 +
        if (tableResultHistory.rows.length === startIndex) {
 +
          showElement(tableResultHistory.rows[1]);
 +
        }
 +
      }
 +
    }
 +
  });
 +
}
 +
 
 +
function initDamagesChart(battle) {
 +
  var { translation, reduceChartPointsContainer, reduceChartPoints } = battle;
 +
  var percentFormat = battle.numberFormats.percent;
 +
  var customPlugins = {
 +
    id: "customPlugins",
 +
    afterDraw(chart) {
 +
      var missPercentage = chart.data.missPercentage;
 +
 
 +
      if (!missPercentage) {
 +
        return;
 +
      }
 +
 
 +
      var {
 +
        ctx,
 +
        chartArea: { top, right },
 +
      } = chart;
 +
      ctx.save();
 +
      var text =
 +
        translation.miss + " : " + percentFormat.format(missPercentage);
 +
      var padding = 4;
 +
      var fontSize = 14;
 +
 
 +
      ctx.font = fontSize + "px Helvetica Neue";
 +
 
 +
      var textWidth = ctx.measureText(text).width;
 +
      var xPosition = right - textWidth - 5;
 +
      var yPosition = top + 5;
 +
 
 +
      ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
 +
      ctx.fillRect(
 +
        xPosition - padding,
 +
        yPosition - padding,
 +
        textWidth + 2 * padding,
 +
        fontSize + 2 * padding
 +
      );
 +
 
 +
      ctx.strokeStyle = "red";
 +
      ctx.strokeRect(
 +
        xPosition - padding,
 +
        yPosition - padding,
 +
        textWidth + 2 * padding,
 +
        fontSize + 2 * padding
 +
      );
 +
 
 +
      ctx.fillStyle = "#666";
 +
      ctx.textBaseline = "top";
 +
      ctx.fillText(text, xPosition, yPosition + 1);
 +
 
 +
      ctx.restore();
 +
    },
 +
  };
 +
 
 +
  Chart.register(customPlugins);
 +
 
 +
  var ctx = battle.plotDamages.getContext("2d");
 +
  var maxLabelsInTooltip = 10;
 +
  var nullLabelText = " ...";
 +
 
 +
  var chart = new Chart(ctx, {
 +
    type: "scatter",
 +
    data: {
 +
      missPercentage: 0,
 +
      datasets: [],
 +
    },
 +
    options: {
 +
      responsive: true,
 +
      maintainAspectRatio: false,
 +
      plugins: {
 +
        legend: {
 +
          display: true,
 +
          onHover: function (e) {
 +
            e.native.target.style.cursor = "pointer";
 +
          },
 +
          onLeave: function (e) {
 +
            e.native.target.style.cursor = "default";
 +
          },
 +
          onClick: function (e, legendItem, legend) {
 +
            var currentIndex = legendItem.datasetIndex;
 +
            var ci = legend.chart;
 +
            var isCurrentDatasetVisible = ci.isDatasetVisible(currentIndex);
 +
            var datasets = ci.data.datasets;
 +
            var hideReducePoints = true;
 +
            var isReducePointsChecked = reduceChartPoints.checked;
 +
 
 +
            datasets[currentIndex].hidden = isCurrentDatasetVisible;
 +
            legendItem.hidden = isCurrentDatasetVisible;
 +
 
 +
            for (var index in datasets) {
 +
              if (ci.isDatasetVisible(index) && datasets[index].canBeReduced) {
 +
                showElement(reduceChartPointsContainer);
 +
                hideReducePoints = false;
 +
                break;
 +
              }
 +
            }
 +
 
 +
            if (hideReducePoints) {
 +
              hideElement(reduceChartPointsContainer);
 +
              handleChartAnimations(ci, true);
 +
            } else {
 +
              handleChartAnimations(ci, isReducePointsChecked);
 +
            }
 +
 
 +
            ci.update();
 +
          },
 +
        },
 +
        title: {
 +
          display: true,
 +
          text: translation.damagesRepartition,
 +
          font: {
 +
            size: 20,
 +
          },
 +
        },
 +
        tooltip: {
 +
          callbacks: {
 +
            label: function (context) {
 +
              if (context.label === null) {
 +
                return nullLabelText;
 +
              }
 +
 
 +
              var xValue = battle.numberFormats.default.format(
 +
                context.parsed.x
 +
              );
 +
              var yValue = battle.numberFormats.percent.format(
 +
                context.parsed.y
 +
              );
 +
 
 +
              label =
 +
                " " +
 +
                context.dataset.label +
 +
                " : (" +
 +
                xValue +
 +
                ", " +
 +
                yValue +
 +
                ")";
 +
 
 +
              return label;
 +
            },
 +
            beforeBody: function (tooltipItems) {
 +
              if (tooltipItems.length > maxLabelsInTooltip + 1) {
 +
                tooltipItems.splice(maxLabelsInTooltip + 1);
 +
                tooltipItems[maxLabelsInTooltip].label = null;
 +
              }
 +
            },
 +
          },
 +
          caretPadding: 10,
 +
        },
 +
      },
 +
      scales: {
 +
        x: {
 +
          type: "linear",
 +
          position: "bottom",
 +
          title: {
 +
            display: true,
 +
            text: translation.damages,
 +
            font: {
 +
              size: 16,
 +
            },
 +
          },
 +
        },
 +
        y: {
 +
          title: {
 +
            display: true,
 +
            text: translation.percentage,
 +
            font: {
 +
              size: 16,
 +
            },
 +
          },
 +
          ticks: {
 +
            format: {
 +
              style: "percent",
 +
            },
 +
          },
 +
        },
 +
      },
 +
      elements: {
 +
        point: {
 +
          borderWidth: 1,
 +
          radius: 3,
 +
          hitRadius: 3,
 +
          hoverRadius: 6,
 +
          hoverBorderWidth: 2,
 +
        },
 +
      },
 +
    },
 +
  });
 +
 
 +
  var datasetsStyle = [
 +
    {
 +
      name: "normalHit",
 +
      canBeReduced: false,
 +
      label: translation.normalHit,
 +
      backgroundColor: "rgba(75, 192, 192, 0.2)",
 +
      borderColor: "rgba(75, 192, 192, 1)",
 +
    },
 +
    {
 +
      name: "piercingHit",
 +
      canBeReduced: false,
 +
      label: translation.piercingHit,
 +
      backgroundColor: "rgba(192, 192, 75, 0.2)",
 +
      borderColor: "rgba(192, 192, 75, 1)",
 +
    },
 +
    {
 +
      name: "criticalHit",
 +
      canBeReduced: false,
 +
      label: translation.criticalHit,
 +
      backgroundColor: "rgba(192, 75, 192, 0.2)",
 +
      borderColor: "rgba(192, 75, 192, 1)",
 +
    },
 +
    {
 +
      name: "criticalPiercingHit",
 +
      canBeReduced: false,
 +
      label: translation.criticalPiercingHit,
 +
      backgroundColor: "rgba(75, 75, 192, 0.2)",
 +
      borderColor: "rgba(75, 75, 192, 1)",
 +
    },
 +
  ];
 +
  battle.damagesChart = {
 +
    chart: chart,
 +
    datasetsStyle: datasetsStyle,
 +
    maxPoints: 500,
 +
    reduceChartPointsContainer: reduceChartPointsContainer,
 +
  };
 +
}
 +
 
 +
function initBonusVariationChart(battle) {
 +
  var translation = battle.translation;
 +
 
 +
  var ctx = battle.plotBonusVariation.getContext("2d");
 +
 
 +
  var chart = new Chart(ctx, {
 +
    type: "line",
 +
    data: {
 +
      datasets: [
 +
        {
 +
          label: translation.averageDamages,
 +
          backgroundColor: "rgba(75, 192, 192, 0.2)",
 +
          borderColor: "rgba(75, 192, 192, 1)",
 +
          fill: true,
 +
        },
 +
        {
 +
          label: translation.damagesAugmentation,
 +
          backgroundColor: "rgba(192, 192, 75, 0.2)",
 +
          borderColor: "rgba(192, 192, 75, 1)",
 +
          hidden: true,
 +
          yTicksFormat: { style: "percent" },
 +
          fill: true,
 +
        },
 +
      ],
 +
    },
 +
    options: {
 +
      responsive: true,
 +
      maintainAspectRatio: false,
 +
      plugins: {
 +
        legend: {
 +
          display: true,
 +
          onHover: function (e) {
 +
            e.native.target.style.cursor = "pointer";
 +
          },
 +
          onLeave: function (e) {
 +
            e.native.target.style.cursor = "default";
 +
          },
 +
          onClick: function (e, legendItem, legend) {
 +
            var currentIndex = legendItem.datasetIndex;
 +
            var ci = legend.chart;
 +
            var datasets = ci.data.datasets;
 +
            var isCurrentDatasetVisible = ci.isDatasetVisible(currentIndex);
 +
            var yAxis = ci.options.scales.y;
 +
 
 +
            var otherIndex = currentIndex === 0 ? 1 : 0;
 +
            var visibleDataset = isCurrentDatasetVisible
 +
              ? datasets[otherIndex]
 +
              : datasets[currentIndex];
 +
 
 +
            datasets[currentIndex].hidden = isCurrentDatasetVisible;
 +
            datasets[otherIndex].hidden = !isCurrentDatasetVisible;
 +
 
 +
            yAxis.title.text = visibleDataset.label;
 +
            yAxis.ticks.format = visibleDataset.yTicksFormat;
 +
 
 +
            ci.update();
 +
          },
 +
        },
 +
        title: {
 +
          display: true,
 +
          text: translation.bonusVariationTitle,
 +
          font: {
 +
            size: 18,
 +
          },
 +
        },
 +
        tooltip: {
 +
          caretPadding: 10,
 +
        },
 +
      },
 +
      scales: {
 +
        x: {
 +
          type: "linear",
 +
          position: "bottom",
 +
          title: {
 +
            display: true,
 +
            text: "Bonus",
 +
            font: {
 +
              size: 16,
 +
            },
 +
          },
 +
          ticks: {
 +
            callback: function (value) {
 +
              if (Number.isInteger(value)) {
 +
                return Number(value);
 +
              }
 +
            },
 +
          },
 +
        },
 +
        y: {
 +
          title: {
 +
            display: true,
 +
            text: translation.averageDamages,
 +
            font: {
 +
              size: 16,
 +
            },
 +
          },
 +
        },
 +
      },
 +
      elements: {
 +
        point: {
 +
          borderWidth: 1,
 +
          radius: 3,
 +
          hitRadius: 3,
 +
          hoverRadius: 6,
 +
          hoverBorderWidth: 2,
 +
        },
 +
      },
 +
    },
 +
  });
 +
 
 +
  battle.bonusVariationChart = chart;
 +
}
 +
 
 +
function attackSelectonListener(
 +
  characters,
 +
  attackerSelection,
 +
  attackTypeSelection
 +
) {
 +
  attackerSelection.addEventListener("change", function (event) {
 +
    var attackerName = event.target.value;
 +
 
 +
    if (isPseudoSaved(characters, attackerName)) {
 +
      var attacker = characters.savedCharacters[attackerName];
 +
      filterAttackTypeSelection(attacker, attackTypeSelection);
 +
    } else {
 +
      filterAttackTypeSelectionMonster(attackTypeSelection);
 +
    }
 +
  });
 +
}
 +
 
 +
function getTranslation(translation) {
 +
  var userLanguage = navigator.language;
 +
  var langToUse = "en";
 +
 
 +
  for (var lang in translation) {
 +
    if (userLanguage.startsWith(lang)) {
 +
      langToUse = lang;
 +
      break;
 +
    }
 +
  }
 +
 
 +
  return translation[langToUse];
 +
}
 +
 
 +
function createDamageCalculatorInformation(chartSource) {
 +
  var characters = {
 +
    unsavedChanges: false,
 +
    savedCharacters: {},
 +
    currentCharacter: null,
 +
    savedMonsters: getSavedMonsters(),
 +
    characterCreation: document.getElementById("character-creation"),
 +
    addNewCharacterButton: document.getElementById("add-new-character"),
 +
    dropZone: document.getElementById("character-drop-zone"),
 +
    characterInput: document.getElementById("character-input"),
 +
    newCharacterTemplate: document.getElementById("new-character-template")
 +
      .children[0],
 +
    charactersContainer: document.getElementById("characters-container"),
 +
    newMonsterTemplate: document.getElementById("new-monster-template")
 +
      .children[0],
 +
    monstersContainer: document.getElementById("monsters-container"),
 +
    monsterListForm: document.getElementById("monster-list-form"),
 +
    searchMonster: document.getElementById("search-monster"),
 +
    monsterList: document.getElementById("monster-list"),
 +
    saveButton: document.getElementById("save-character"),
 +
    weaponCategory: document.getElementById("weapon-category"),
 +
    weaponDisplay: document.getElementById("weapon-display"),
 +
    randomAttackValue: document.getElementById("random-attack-value"),
 +
    randomMagicAttackValue: document.getElementById(
 +
      "random-magic-attack-value"
 +
    ),
 +
    yoharaCreation: document.getElementById("yohara-creation"),
 +
    blessingCreation: document.getElementById("blessing-creation"),
 +
    marriageCreation: document.getElementById("marriage-creation"),
 +
    bonusVariation: {
 +
      tab: document.getElementById("Variation"),
 +
      activation: document.getElementById("bonus-variation-activation"),
 +
      input: document.getElementById("bonus-variation"),
 +
      inputDisplay: document.getElementById("bonus-variation-display"),
 +
      container: document.getElementById("bonus-variation-range"),
 +
      minValue: document.getElementById("bonus-variation-min-value"),
 +
      maxValue: document.getElementById("bonus-variation-max-value"),
 +
    },
 +
  };
 +
 
 +
  characters.bonusVariation.inputDisplay.setAttribute("readonly", "");
 +
 
 +
  for (var [pseudo, character] of Object.entries(getSavedCharacters())) {
 +
    characters.savedCharacters[pseudo] = character;
 +
  }
 +
 
 +
  var skillContainer = document.getElementById("skill-container");
 +
  characters.skillElementsToFilter =
 +
    skillContainer.querySelectorAll("[data-class]");
 +
 
 +
  var mapping = createMapping();
 +
  var constants = createConstants();
 +
 
 +
  var battle = {
 +
    resetAttackType: false,
 +
    savedFights: getSavedFights(),
 +
    battleForm: document.getElementById("create-battle"),
 +
    attackerSelection: document.getElementById("attacker-selection"),
 +
    attackTypeSelection: document.getElementById("attack-type-selection"),
 +
    victimSelection: document.getElementById("victim-selection"),
 +
    damagesWeightedByType: {},
 +
    scatterDataByType: {},
 +
    damagesByBonus: [],
 +
    tableResultFight: document.getElementById("result-table-fight"),
 +
    tableResultHistory: document.getElementById("result-table-history"),
 +
    deleteFightTemplate: document.getElementById("delete-fight-template")
 +
      .children[0],
 +
    errorInformation: {},
 +
    fightResultContainer: document.getElementById("fight-result-container"),
 +
    downLoadRawData: document.getElementById("download-raw-data"),
 +
    downLoadRawDataVariation: document.getElementById(
 +
      "download-raw-data-variation"
 +
    ),
 +
    bonusVariationResultContainer: document.getElementById(
 +
      "bonus-variation-result-container"
 +
    ),
 +
    reduceChartPointsContainer: document.getElementById(
 +
      "reduce-chart-points-container"
 +
    ),
 +
    reduceChartPoints: document.getElementById("reduce-chart-points"),
 +
    plotDamages: document.getElementById("plot-damages"),
 +
    plotBonusVariation: document.getElementById("plot-bonus-variation"),
 +
    uniqueDamagesCounters: document.querySelectorAll(".unique-damages-counter"),
 +
    possibleDamagesCounter: document.getElementById("possible-damages-counter"),
 +
    damagesTime: document.getElementById("damages-time"),
 +
    displayTime: document.getElementById("display-time"),
 +
    simulationCounter: document.getElementById("simulation-counter"),
 +
    simulationTime: document.getElementById("simulation-time"),
 +
    numberFormats: {
 +
      default: new Intl.NumberFormat(undefined, {
 +
        minimumFractionDigits: 0,
 +
        maximumFractionDigits: 1,
 +
      }),
 +
      percent: new Intl.NumberFormat(undefined, {
 +
        style: "percent",
 +
        maximumFractionDigits: 3,
 +
      }),
 +
      second: new Intl.NumberFormat(undefined, {
 +
        style: "unit",
 +
        unit: "second",
 +
        unitDisplay: "long",
 +
        maximumFractionDigits: 3,
 +
      }),
 +
    },
 +
    mapping: mapping,
 +
    constants: constants,
 +
    translation: getTranslation(constants.translation),
 +
  };
 +
 
 +
  attackSelectonListener(
 +
    characters,
 +
    battle.attackerSelection,
 +
    battle.attackTypeSelection
 +
  );
 +
  initResultTableHistory(battle);
 +
  loadScript(chartSource, function () {
 +
    initDamagesChart(battle);
 +
    initBonusVariationChart(battle);
 +
  });
 +
  reduceChartPointsListener(battle);
 +
  downloadRawDataListener(battle);
 +
 
 +
  var errorElements = document.querySelectorAll("[data-error]");
 +
 
 +
  for (var index = 0; index < errorElements.length; index++) {
 +
    var errorElement = errorElements[index];
 +
    battle.errorInformation[errorElement.dataset.error] = errorElement;
 +
  }
 +
 
 +
  return [characters, battle];
 +
}
 +
 
 +
function loadScript(src, callback) {
 +
  var script = document.createElement("script");
 +
  script.src = src;
 +
 
 +
  function onComplete() {
 +
     if (script.parentNode) {
 +
       script.parentNode.removeChild(script);
 +
    }
 +
    if (callback) {
 +
      callback();
 
     }
 
     }
    callback();
 
 
   }
 
   }
  
Ligne 3 169 : Ligne 5 048 :
 
   var cssSource =
 
   var cssSource =
 
     "/index.php?title=Utilisateur:Ankhseram/Style.css&action=raw&ctype=text/css";
 
     "/index.php?title=Utilisateur:Ankhseram/Style.css&action=raw&ctype=text/css";
 +
  var chartSource = "https://cdn.jsdelivr.net/npm/chart.js";
  
 
   loadStyle(cssSource);
 
   loadStyle(cssSource);
  
 
   function main() {
 
   function main() {
     var [characters, battle] = createDamageCalculatorInformation();
+
     var [characters, battle] = createDamageCalculatorInformation(chartSource);
  
 
     characterManagement(characters, battle);
 
     characterManagement(characters, battle);
Ligne 3 183 : Ligne 5 063 :
 
     loading();
 
     loading();
 
   }
 
   }
 
 
   loadScript(javascriptSource, main);
 
   loadScript(javascriptSource, main);
 
})();
 
})();

Version actuelle datée du 20 novembre 2024 à 17:07

function showElement(element) {
  element.classList.remove("tabber-noactive");
}

function hideElement(element) {
  element.classList.add("tabber-noactive");
}

function removeAccent(str) {
  return str.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
}

function toNormalForm(str) {
  return removeAccent(str)
    .replace("-", " ")
    .replace(/[^a-zA-Z0-9 ]/g, "")
    .toLowerCase();
}

function pseudoFormat(str) {
  return removeAccent(str).replace(/[^A-Za-z0-9 \(\)\+_-]+/g, "");
}

function isValueInArray(value, array) {
  return array.indexOf(value) !== -1;
}

function copyObject(object) {
  var copy = {};
  for (var key in object) {
    copy[key] = object[key];
  }
  return copy;
}

function compareNumbers(a, b) {
  return b - a;
}

function isChecked(attribute) {
  return attribute === "on";
}

function floorMultiplication(firstFactor, secondFactor) {
  return Math.floor((firstFactor * secondFactor).toFixed(8));
}

function truncateNumber(number, precision) {
  return Math.floor(number * 10 ** precision) / 10 ** precision;
}

function addKeyValue(object, key, value) {
  if (object.hasOwnProperty(key)) {
    object[key] += value;
  } else {
    object[key] = value;
  }
}

function editTableResultRow(row, valuesToDisplay, numberFormat) {
  row.innerHTML = "";
  for (var index = 0; index < valuesToDisplay.length; index++) {
    var cell = row.insertCell();
    var textContent;

    if (index >= 3) {
      textContent = numberFormat.format(valuesToDisplay[index]);
    } else {
      textContent = valuesToDisplay[index];
    }

    cell.textContent = textContent;
  }

  return row;
}

function addRowToTableResultHistory(
  tableResultHistory,
  valuesToDisplay,
  deleteFightTemplate,
  numberFormat
) {
  var row = tableResultHistory.insertRow();
  editTableResultRow(row, valuesToDisplay, numberFormat);
  var cell = row.insertCell();
  cell.appendChild(deleteFightTemplate.cloneNode(true));
}

function calcMeanDamages(damagesWeightedByType, totalCardinal) {
  var sumDamages = 0;

  for (var damagesTypeName in damagesWeightedByType) {
    if (damagesTypeName === "miss") {
      continue;
    }

    var damagesWeighted = damagesWeightedByType[damagesTypeName];

    for (var damages in damagesWeighted) {
      sumDamages += damages * damagesWeighted[damages];
    }
  }

  return sumDamages / totalCardinal;
}

function prepareDamagesData(
  damagesWeightedByType,
  possibleDamagesCountTemp,
  totalCardinal
) {
  var minDamages = Infinity;
  var maxDamages = 0;
  var scatterDataByType = {};
  var sumDamages = 0;
  var possibleDamagesCount = 0;
  var uniqueDamagesCount = 0;

  for (var damagesTypeName in damagesWeightedByType) {
    if (damagesTypeName === "miss") {
      scatterDataByType.miss = damagesWeightedByType.miss;
      possibleDamagesCount++;
      uniqueDamagesCount++;
      continue;
    }

    var firstIteration = true;
    var damagesWeighted = damagesWeightedByType[damagesTypeName];
    var scatterData = [];
    scatterDataByType[damagesTypeName] = scatterData;

    for (var damages in damagesWeighted) {
      damages = +damages;

      if (firstIteration) {
        if (damages < minDamages) {
          minDamages = damages;
        }
        firstIteration = false;
      }

      var weight = damagesWeighted[damages];
      var probability = weight / totalCardinal;

      sumDamages += damages * weight;
      damagesWeighted[damages] = probability;
      scatterData.push({ x: damages, y: probability });
    }

    var scatterDataLength = scatterData.length;

    possibleDamagesCount += possibleDamagesCountTemp;
    uniqueDamagesCount += scatterDataLength;

    if (damages > maxDamages) {
      maxDamages = damages;
    }
  }

  if (minDamages === Infinity) {
    minDamages = 0;
  }

  return [
    sumDamages / totalCardinal,
    minDamages,
    maxDamages,
    scatterDataByType,
    possibleDamagesCount,
    uniqueDamagesCount,
  ];
}

function aggregateDamages(scatterData, maxPoints) {
  var dataLength = scatterData.length;
  var remainingData = dataLength;
  var aggregateScatterData = [];

  for (var groupIndex = 0; groupIndex < maxPoints; groupIndex++) {
    var groupLength = Math.floor(remainingData / (maxPoints - groupIndex));
    var startIndex = dataLength - remainingData;
    var aggregateDamages = 0;
    var aggregateProbability = 0;

    for (var index = startIndex; index < startIndex + groupLength; index++) {
      var { x: damages, y: probability } = scatterData[index];
      aggregateDamages += damages * probability;
      aggregateProbability += probability;
    }

    aggregateScatterData.push({
      x: aggregateDamages / aggregateProbability,
      y: aggregateProbability,
    });

    remainingData -= groupLength;
  }

  return aggregateScatterData;
}

function addToDamagesChart(
  scatterDataByType,
  damagesChart,
  isReducePointsChecked
) {
  var { chart, datasetsStyle, maxPoints, reduceChartPointsContainer } =
    damagesChart;
  var isFirstDataset = true;
  var datasets = chart.data.datasets;

  datasets.length = 0;

  for (var index = 0; index < datasetsStyle.length; index++) {
    var dataset = copyObject(datasetsStyle[index]);

    if (!scatterDataByType.hasOwnProperty(dataset.name)) {
      continue;
    }

    var scatterData = scatterDataByType[dataset.name];
    var canBeReduced = scatterData.length > 2 * maxPoints;

    dataset.hidden = !isFirstDataset;
    dataset.canBeReduced = canBeReduced;

    if (canBeReduced && isReducePointsChecked) {
      dataset.data = aggregateDamages(scatterData, maxPoints);
    } else {
      dataset.data = scatterData;
    }

    if (isFirstDataset) {
      isFirstDataset = false;

      if (canBeReduced) {
        showElement(reduceChartPointsContainer);

        if (!isReducePointsChecked) {
          handleChartAnimations(chart, false);
        }
      } else {
        hideElement(reduceChartPointsContainer);
        handleChartAnimations(chart, true);
      }
    }

    datasets.push(dataset);
  }

  chart.data.missPercentage = scatterDataByType.miss;
  chart.update();
}

function addToBonusVariationChart(
  damagesByBonus,
  augmentationByBonus,
  xLabel,
  chart
) {
  chart.data.datasets[0].data = damagesByBonus;
  chart.data.datasets[1].data = augmentationByBonus;
  chart.options.scales.x.title.text = xLabel;
  chart.update();
}

function handleChartAnimations(chart, addAnimations) {
  chart.options.animation = addAnimations;
  chart.options.animations.colors = addAnimations;
  chart.options.animations.x = addAnimations;
  chart.options.transitions.active.animation.duration = addAnimations * 1000;
}

function updateDamagesChartDescription(
  uniqueDamagesCounters,
  uniqueDamagesCount,
  formatNumber
) {
  uniqueDamagesCounters.forEach(function (element) {
    if (uniqueDamagesCount <= 1) {
      hideElement(element.parentElement);
    } else {
      showElement(element.parentElement);
      element.textContent = formatNumber.format(uniqueDamagesCount);
    }
  });
}

function getMonsterName(monsterVnum) {
  var monsterAttributes = monsterData[monsterVnum];
  return monsterAttributes[monsterAttributes.length - 1];
}

function filterClass(selectedRace, classChoice, selectValueIsChanged = false) {
  showElement(classChoice.parentElement);

  for (var option of classChoice.options) {
    if (option.getAttribute("data-race") === selectedRace) {
      if (!selectValueIsChanged) {
        classChoice.value = option.value;
        selectValueIsChanged = true;
      }
      showElement(option);
    } else {
      hideElement(option);
    }
  }
  if (selectedRace == "lycan") {
    hideElement(classChoice.parentElement);
  }
}

function filterWeapon(
  selectedRace,
  weaponElement,
  weaponCategory,
  allowedWeaponsPerRace,
  selectValueIsChanged = false
) {
  var allowedWeapons = allowedWeaponsPerRace[selectedRace];

  if (!selectValueIsChanged) {
    var weaponType = weaponData[weaponElement.value][1];

    if (!isValueInArray(weaponType, allowedWeapons)) {
      weaponElement.value = 0;
    }
  }

  var children = weaponCategory.children;

  for (var index = 0; index < children.length; index++) {
    var child = children[index];

    if (isValueInArray(index, allowedWeapons)) {
      showElement(child);
    } else {
      hideElement(child);
    }
  }
}

function getSelectedWeapon(weaponCategory) {
  return weaponCategory.querySelector("input[type='radio']:checked");
}

function handleWeaponDisplay(weaponDisplay, newWeapon, weaponVnum) {
  var newImage = newWeapon.nextElementSibling.cloneNode();
  var newText = document.createElement("span");
  var oldImage = weaponDisplay.firstChild;
  var oldText = oldImage.nextElementSibling;
  var weaponName = createWeapon(weaponVnum).name;

  if (weaponVnum == 0) {
    newText.textContent = " " + weaponName + " ";
  } else {
    var weaponLink = document.createElement("a");
    weaponLink.href = mw.util.getUrl(weaponName);
    weaponLink.title = weaponName;
    weaponLink.textContent = weaponName;

    newText.appendChild(document.createTextNode(" "));
    newText.appendChild(weaponLink);
    newText.appendChild(document.createTextNode(" "));
  }

  weaponDisplay.replaceChild(newImage, oldImage);
  weaponDisplay.replaceChild(newText, oldText);
}

function filterUpgrade(
  selectedRace,
  weaponUpgrade,
  weaponVnum,
  randomAttackValue,
  randomMagicAttackValue,
  currentUpgrade
) {
  var weapon = createWeapon(weaponVnum);

  if (weapon.isSerpent) {
    showElement(randomAttackValue);

    if (selectedRace === "sura" || selectedRace === "shaman") {
      showElement(randomMagicAttackValue);
    }
  } else {
    hideElement(randomAttackValue);
    hideElement(randomMagicAttackValue);
  }

  var upgradeNumber = weapon.upgrades.length;

  if (upgradeNumber <= 1) {
    hideElement(weaponUpgrade.parentElement);
  } else {
    showElement(weaponUpgrade.parentElement);
  }

  weaponUpgrade.innerHTML = "";

  for (var upgrade = 0; upgrade < upgradeNumber; upgrade++) {
    var option = document.createElement("option");
    option.value = upgrade;
    option.textContent = "+" + upgrade;
    weaponUpgrade.appendChild(option);
  }
  if (currentUpgrade === undefined) {
    option.selected = true;
  } else {
    weaponUpgrade.value = currentUpgrade;
    currentUpgrade = undefined;
  }
}

function filterState(selectedState, polymorphMonster) {
  if (selectedState === "polymorph") {
    showElement(polymorphMonster.parentElement);
  } else {
    hideElement(polymorphMonster.parentElement);
  }
}

function filterCheckbox(checkbox, element) {
  if (checkbox.checked) {
    showElement(element);
  } else {
    hideElement(element);
  }
}

function filterSkills(selectedClass, skillElementsToFilter) {
  for (var element of skillElementsToFilter) {
    if (isValueInArray(selectedClass, element.dataset.class)) {
      showElement(element);
    } else {
      hideElement(element);
    }
  }
}

function filterAttackTypeSelection(attacker, attackTypeSelection) {
  var attackerClass = attacker.class;
  var selectedOption =
    attackTypeSelection.options[attackTypeSelection.selectedIndex];
  var attackerIsNotPolymorph = !isPolymorph(attacker);

  for (var index = 2; index < attackTypeSelection.options.length; index++) {
    var option = attackTypeSelection.options[index];
    var optionClass = option.dataset.class;
    var optionValue = option.value;

    if (
      attackerIsNotPolymorph &&
      attacker[optionValue] &&
      (attackerClass === optionClass ||
        (optionValue.startsWith("horseSkill") &&
          isRiding(attacker) &&
          (!optionClass || isValueInArray(attackerClass, optionClass))))
    ) {
      showElement(option);
    } else {
      hideElement(option);

      if (selectedOption === option) {
        attackTypeSelection.selectedIndex = 0;
      }
    }
  }
}

function filterAttackTypeSelectionMonster(attackTypeSelection) {
  for (var index = 2; index < attackTypeSelection.options.length; index++) {
    hideElement(attackTypeSelection.options[index]);
  }

  if (attackTypeSelection.selectedIndex !== 1) {
    attackTypeSelection.selectedIndex = 0;
  }
}

function filterForm(characters, battle) {
  var characterCreation = characters.characterCreation;
  var allowedWeaponsPerRace = battle.constants.allowedWeaponsPerRace;

  characterCreation.addEventListener("change", function (event) {
    var target = event.target;
    var targetName = target.name;

    switch (targetName) {
      case "race":
        var selectedRace = target.value;
        var classChoice = characterCreation.class;
        var weaponElement = characterCreation.weapon;

        filterClass(selectedRace, classChoice);
        filterWeapon(
          selectedRace,
          weaponElement,
          characters.weaponCategory,
          allowedWeaponsPerRace
        );

        var newWeapon = getSelectedWeapon(characters.weaponCategory);
        handleWeaponDisplay(
          characters.weaponDisplay,
          newWeapon,
          weaponElement.value
        );
        filterUpgrade(
          selectedRace,
          characterCreation.weaponUpgrade,
          weaponElement.value,
          characters.randomAttackValue,
          characters.randomMagicAttackValue
        );
        filterSkills(classChoice.value, characters.skillElementsToFilter);

        if (characterCreation.name.value === battle.attackerSelection.value) {
          battle.resetAttackType = true;
        }
        break;
      case "class":
        filterSkills(target.value, characters.skillElementsToFilter);

        if (characterCreation.name.value === battle.attackerSelection.value) {
          battle.resetAttackType = true;
        }
        break;
      case "weapon":
        handleWeaponDisplay(
          characters.weaponDisplay,
          target,
          characterCreation.weapon.value
        );
        filterUpgrade(
          characterCreation.race.value,
          characterCreation.weaponUpgrade,
          target.value,
          characters.randomAttackValue,
          characters.randomMagicAttackValue
        );
        break;
      case "state":
        filterState(target.value, characterCreation.polymorphMonster);
        if (characterCreation.name.value === battle.attackerSelection.value) {
          battle.resetAttackType = true;
        }
        break;
      case "lowRank":
        filterCheckbox(target, characterCreation.playerRank.parentElement);
        break;
      case "isBlessed":
        filterCheckbox(target, characters.blessingCreation);
        break;
      case "onYohara":
        filterCheckbox(target, characters.yoharaCreation);
        break;
      case "isMarried":
        filterCheckbox(target, characters.marriageCreation);
        break;
    }

    if (
      targetName.startsWith("attackSkill") ||
      targetName.startsWith("horseSkill")
    ) {
      battle.resetAttackType = true;
    }
  });
}

function addUniquePseudo(characterDataObject, savedCharactersPseudo) {
  var characterPseudo = String(characterDataObject.name);
  var originalPseudo = characterPseudo;
  var count = 0;

  var regex = /(.*)(\d)$/;
  var match = characterPseudo.match(regex);

  if (match) {
    originalPseudo = match[1];
    count = match[2];
  }

  while (isValueInArray(characterPseudo, savedCharactersPseudo)) {
    characterPseudo = originalPseudo + count;
    count++;
  }

  characterDataObject.name = characterPseudo;
  return [characterDataObject, characterPseudo];
}

function convertToNumber(value) {
  var valueNumber = Number(value);
  return isNaN(valueNumber) ? value : valueNumber;
}

function getLocalStorageValue(key, defaultValue) {
  var storedValue = localStorage.getItem(key);

  if (storedValue) {
    return JSON.parse(storedValue);
  }

  return defaultValue;
}

function getSavedCharacters() {
  return getLocalStorageValue("savedCharactersCalculator", {});
}

function getSavedMonsters() {
  return getLocalStorageValue("savedMonstersCalculator", []).filter(function (
    num
  ) {
    return !isNaN(Number(num));
  });
}

function getSavedFights() {
  return getLocalStorageValue("savedFightsCalculator", []);
}

function saveToLocalStorage(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

function updateSavedCharacters(savedCharacters) {
  saveToLocalStorage("savedCharactersCalculator", savedCharacters);
}

function updateSavedMonsters(savedMonsters) {
  saveToLocalStorage("savedMonstersCalculator", savedMonsters);
}

function updateSavedFights(savedFights) {
  saveToLocalStorage("savedFightsCalculator", savedFights);
}

function saveCharacter(
  savedCharacters,
  characterCreation,
  battle,
  newCharacter,
  characterDataObject
) {
  if (!characterDataObject) {
    var characterData = new FormData(characterCreation);
    var characterDataObject = {};

    characterData.forEach(function (value, key) {
      characterDataObject[key] = convertToNumber(value);
    });
  }

  savedCharacters[characterDataObject.name] = characterDataObject;
  updateSavedCharacters(savedCharacters);

  if (newCharacter) {
    addBattleChoice(battle, characterDataObject.name);
  }

  if (battle.resetAttackType) {
    filterAttackTypeSelection(characterDataObject, battle.attackTypeSelection);
    battle.resetAttackType = false;
  }
}

function saveButtonGreen(saveButton) {
  saveButton.classList.remove("unsaved-character");
}

function saveButtonOrange(saveButton) {
  saveButton.classList.add("unsaved-character");
}

function characterCreationListener(characters, battle) {
  var { characterCreation, saveButton, weaponCategory } = characters;

  characterCreation.addEventListener("submit", function (event) {
    event.preventDefault();

    if (characters.unsavedChanges) {
      saveCharacter(characters.savedCharacters, characterCreation, battle);
      saveButtonGreen(saveButton);
      characters.unsavedChanges = false;
    }
  });

  document.addEventListener("keydown", function (event) {
    if (event.ctrlKey && event.key === "s") {
      event.preventDefault();
      saveButton.click();
    }
  });

  weaponCategory.addEventListener("mouseover", function (event) {
    label = event.target.closest("label");

    if (label) {
      var tooltip = label.lastChild;

      if (tooltip.classList.contains("popContenu")) {
        var tooltipRect = tooltip.getBoundingClientRect();
        var modalRect = weaponCategory.getBoundingClientRect();

        if (tooltipRect.right > modalRect.right) {
          tooltip.style.left = "-100%";
        } else if (tooltipRect.left < modalRect.left) {
          tooltip.style.left = "200%";
        }
      }
    }
  });
}

function downloadData(content, type, filename) {
  var link = document.createElement("a");
  var blob = new Blob([content], { type: type });
  var blobURL = URL.createObjectURL(blob);

  link.href = blobURL;
  link.download = filename;
  document.body.appendChild(link);

  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(blobURL);
}

function uploadCharacter(
  selectedFiles,
  characters,
  characterTemplate,
  charactersContainer,
  battle
) {
  var selectFilesLength = selectedFiles.length;

  for (var fileIndex = 0; fileIndex < selectFilesLength; fileIndex++) {
    var selectedFile = selectedFiles[fileIndex];

    if (selectedFile.type === "text/plain") {
      var reader = new FileReader();
      reader.onload = function (e) {
        var fileContent = e.target.result;
        try {
          var characterDataObject = JSON.parse(fileContent);

          if (characterDataObject.hasOwnProperty("name")) {
            var characterPseudo = String(characterDataObject.name);

            hideElement(characters.characterCreation);
            characterPseudo = validPseudo(characterPseudo);

            [characterDataObject, characterPseudo] = addUniquePseudo(
              characterDataObject,
              Object.keys(characters.savedCharacters)
            );
            var selectedCharacter = handleNewCharacter(
              characters,
              characterTemplate,
              charactersContainer,
              battle,
              characterPseudo
            )[0];

            if (selectFilesLength === 1) {
              updateForm(
                characterDataObject,
                characters.characterCreation,
                characters,
                selectedCharacter,
                battle
              );
            }

            saveCharacter(
              characters.savedCharacters,
              characters.characterCreation,
              battle,
              true,
              characterDataObject
            );
          }
        } catch (error) {
          console.log(error);
          if (error.name === "TypeError") {
            // delete the character
          }
        }
      };
      reader.readAsText(selectedFile);
    }
  }
}

function handleUploadCharacter(
  characters,
  characterTemplate,
  charactersContainer,
  battle
) {
  var characterInput = characters.characterInput;
  var dropZone = characters.dropZone;

  characterInput.accept = ".txt";
  characterInput.multiple = true;
  dropZone.setAttribute("tabindex", "0");

  dropZone.addEventListener("click", function () {
    characterInput.click();
  });

  dropZone.addEventListener("dragover", function (event) {
    event.preventDefault();
    dropZone.classList.add("drop-zone--dragover");
  });

  ["dragleave", "dragend"].forEach(function (type) {
    dropZone.addEventListener(type, function () {
      dropZone.classList.remove("drop-zone--dragover");
    });
  });

  dropZone.addEventListener("drop", function (event) {
    event.preventDefault();
    uploadCharacter(
      event.dataTransfer.files,
      characters,
      characterTemplate,
      charactersContainer,
      battle
    );
    dropZone.classList.remove("drop-zone--dragover");
  });

  characterInput.addEventListener("change", function (event) {
    uploadCharacter(
      event.target.files,
      characters,
      characterTemplate,
      charactersContainer,
      battle
    );
  });
}

function deleteCharacter(characters, pseudo, element, battle) {
  battle.battleForm.reset();
  delete characters.savedCharacters[pseudo];
  element.remove();

  updateSavedCharacters(characters.savedCharacters);
  removeBattleChoice(battle, pseudo);

  if (
    !Object.keys(characters.savedCharacters).length ||
    characters.characterCreation.name.value === pseudo
  ) {
    saveButtonGreen(characters.saveButton);
    characters.unsavedChanges = false;
    hideElement(characters.characterCreation);
    showElement(characters.characterCreation.previousElementSibling);
  }
}

function deleteMonster(characters, monsterVnum, element, battle) {
  battle.battleForm.reset();
  characters.savedMonsters.splice(
    characters.savedMonsters.indexOf(monsterVnum),
    1
  );

  if (element) {
    element.remove();
  }

  updateSavedMonsters(characters.savedMonsters);
  removeBattleChoice(battle, monsterVnum);
}

function handleStyle(characters, selectedElement) {
  var currentCharacter = characters.currentCharacter;

  if (currentCharacter) {
    currentCharacter.classList.remove("selected-character");
  }

  selectedElement.classList.add("selected-character");
  characters.currentCharacter = selectedElement;
}

function updateForm(
  formData,
  characterCreation,
  characters,
  selectedElement,
  battle
) {
  saveButtonGreen(characters.saveButton);
  hideElement(characterCreation.previousElementSibling);
  showElement(characterCreation);
  handleStyle(characters, selectedElement);

  characterCreation.reset();

  for (var [name, value] of Object.entries(formData)) {
    var formElement = characterCreation[name];

    if (!formElement) {
      continue;
    }

    if (formElement.type === "checkbox") {
      if (isChecked(value)) {
        formElement.checked = true;
      }
    } else {
      formElement.value = value;
    }
  }
  var selectedRace = characterCreation.race.value;
  var classChoice = characterCreation.class;
  var weaponElement = characterCreation.weapon;

  filterClass(selectedRace, classChoice, true);
  filterWeapon(
    selectedRace,
    weaponElement,
    characters.weaponCategory,
    battle.constants.allowedWeaponsPerRace,
    true
  );

  var newWeapon = getSelectedWeapon(characters.weaponCategory);

  handleWeaponDisplay(characters.weaponDisplay, newWeapon, weaponElement.value);
  filterUpgrade(
    selectedRace,
    characterCreation.weaponUpgrade,
    weaponElement.value,
    characters.randomAttackValue,
    characters.randomMagicAttackValue,
    formData.weaponUpgrade
  );
  filterState(
    characterCreation.state.value,
    characterCreation.polymorphMonster
  );
  filterCheckbox(
    characterCreation.lowRank,
    characterCreation.playerRank.parentElement
  );
  filterCheckbox(characterCreation.onYohara, characters.yoharaCreation);
  filterCheckbox(characterCreation.isBlessed, characters.blessingCreation);
  filterCheckbox(characterCreation.isMarried, characters.marriageCreation);
  filterSkills(classChoice.value, characters.skillElementsToFilter);
  handleBonusVariationUpdate(characterCreation, characters.bonusVariation);
}

function handleClickOnCharacter(
  spanInput,
  target,
  characters,
  characterElement,
  battle,
  edition
) {
  var displayedPseudo = characters.characterCreation.name.value;
  var pseudo = spanInput.dataset.name;

  if (edition) {
    if (!characters.unsavedChanges) {
      updateForm(
        characters.savedCharacters[pseudo],
        characters.characterCreation,
        characters,
        characterElement,
        battle
      );
    } else if (displayedPseudo === pseudo) {
      // pass
    } else {
      var result = confirm(
        "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
      );

      if (result) {
        updateForm(
          characters.savedCharacters[pseudo],
          characters.characterCreation,
          characters,
          characterElement,
          battle
        );
        characters.unsavedChanges = false;
      }
    }
  } else {
    if (target.tagName === "path") {
      target = target.parentElement;
    }

    switch (target.dataset.icon) {
      case "duplicate":
        if (!characters.unsavedChanges) {
          addNewCharacter(
            characters,
            characters.newCharacterTemplate,
            characters.charactersContainer,
            battle,
            pseudo
          );
        } else {
          var result = confirm(
            "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
          );

          if (result) {
            addNewCharacter(
              characters,
              characters.newCharacterTemplate,
              characters.charactersContainer,
              battle,
              pseudo
            );
            saveButtonGreen(characters.saveButton);
            characters.unsavedChanges = false;
          }
        }
        break;

      case "download":
        var character = characters.savedCharacters[pseudo];
        downloadData(
          JSON.stringify(character),
          "text/plain",
          character.name + ".txt"
        );
        break;

      case "delete":
        var result = confirm(
          "Voulez-vous vraiment supprimer définitivement le personnage " +
            pseudo +
            " ?"
        );
        if (result) {
          deleteCharacter(characters, pseudo, characterElement, battle);
        }
        break;
    }
  }
}

function handleNewCharacter(
  characters,
  characterTemplate,
  charactersContainer,
  battle,
  pseudo
) {
  var newCharacterTemplate = characterTemplate.cloneNode(true);
  var spanInput = newCharacterTemplate.querySelector("span.input");

  newCharacterTemplate.setAttribute("tabindex", "0");
  charactersContainer.appendChild(newCharacterTemplate);

  if (pseudo) {
    spanInput.textContent = pseudo;
    spanInput.setAttribute("data-name", pseudo);
  }

  newCharacterTemplate.addEventListener("click", function (event) {
    var target = event.target;

    if (target.tagName === "path" || target.tagName === "svg") {
      handleClickOnCharacter(
        spanInput,
        target,
        characters,
        newCharacterTemplate,
        battle
      );
    } else {
      handleClickOnCharacter(
        spanInput,
        null,
        characters,
        newCharacterTemplate,
        battle,
        true
      );
    }
  });

  newCharacterTemplate.addEventListener("keydown", function (event) {
    if (event.keyCode === 13) {
      event.target.click();
    }
  });

  return [newCharacterTemplate, spanInput];
}

function validPseudo(pseudo) {
  var newPseudo = pseudoFormat(pseudo);

  if (!newPseudo) {
    return "Pseudo";
  }

  return newPseudo;
}

function addNewCharacter(
  characters,
  characterTemplate,
  charactersContainer,
  battle,
  pseudoToDuplicate
) {
  function editAndSetCharacterPseudoInput(selectedCharacter, spanInput) {
    var maxPseudoLength = 20;

    var selection = window.getSelection();
    var range = document.createRange();

    if (pseudoToDuplicate) {
      spanInput.textContent = pseudoToDuplicate;
    }

    spanInput.contentEditable = true;
    spanInput.focus();
    range.selectNodeContents(spanInput);
    selection.removeAllRanges();
    selection.addRange(range);

    function pseudoValidation() {
      var characterPseudo = validPseudo(spanInput.textContent);
      var characterDataObject = { name: characterPseudo };

      if (pseudoToDuplicate) {
        characterDataObject = copyObject(
          characters.savedCharacters[pseudoToDuplicate]
        );
        characterDataObject.name = characterPseudo;
      }

      [characterDataObject, characterPseudo] = addUniquePseudo(
        characterDataObject,
        Object.keys(characters.savedCharacters)
      );

      selection.removeAllRanges();
      spanInput.contentEditable = false;
      spanInput.textContent = characterPseudo;
      spanInput.setAttribute("data-name", characterPseudo);

      updateForm(
        characterDataObject,
        characters.characterCreation,
        characters,
        selectedCharacter,
        battle
      );
      saveCharacter(
        characters.savedCharacters,
        characters.characterCreation,
        battle,
        true
      );
    }

    function handleMaxLength(event) {
      if (spanInput.textContent.length > maxPseudoLength) {
        spanInput.textContent = spanInput.textContent.slice(0, maxPseudoLength);
        range.setStart(spanInput.childNodes[0], maxPseudoLength);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    }

    function handleBlur() {
      spanInput.removeEventListener("blur", handleBlur);
      spanInput.removeEventListener("input", handleMaxLength);
      pseudoValidation();
    }

    function handleKeyDown(event) {
      if (event.key === "Enter") {
        event.preventDefault();

        spanInput.removeEventListener("keydown", handleKeyDown);
        spanInput.removeEventListener("blur", handleBlur);
        spanInput.removeEventListener("input", handleMaxLength);

        pseudoValidation();
      }
    }

    spanInput.addEventListener("input", handleMaxLength);
    spanInput.addEventListener("keydown", handleKeyDown);
    spanInput.addEventListener("blur", handleBlur);
  }

  hideElement(characters.characterCreation);
  var [selectedCharacter, spanInput] = handleNewCharacter(
    characters,
    characterTemplate,
    charactersContainer,
    battle
  );

  editAndSetCharacterPseudoInput(selectedCharacter, spanInput);
}

function handleFocus() {
  var tooltipLinks = document.querySelectorAll("div.tooltip a");
  tooltipLinks.forEach(function (link) {
    link.setAttribute("tabindex", -1);
  });
}

function handleBonusVariationUpdate(characterCreation, bonusVariation) {
  var selectedBonus = characterCreation.bonusVariation.value;

  if (characterCreation.hasOwnProperty(selectedBonus)) {
    handleBonusVariation(characterCreation[selectedBonus], bonusVariation);
  } else {
    var { minValue, maxValue } = bonusVariation;

    minValue.removeAttribute("min");
    minValue.removeAttribute("max");

    maxValue.removeAttribute("min");
    maxValue.removeAttribute("max");

    hideElement(bonusVariation.container);
  }
}

function getTargetContent(targetParent, targetName, isSkill) {
  var targetContent = "";

  if (targetParent.children.length <= 1) {
    targetContent = targetParent.textContent;
  } else if (targetName === "weaponUpgrade") {
    targetContent = targetParent.children[1].textContent;
  } else if (isSkill) {
    var container = targetParent.children[1];

    for (var index = 1; index < container.children.length; index++) {
      var element = container.children[index];

      if (element.checkVisibility()) {
        targetContent += element.textContent;
      }
    }
  } else {
    for (var index = 1; index < targetParent.children.length; index++) {
      var element = targetParent.children[index];

      if (element.checkVisibility()) {
        targetContent += element.textContent;
      }
    }
  }

  return targetContent;
}

function handleBonusVariation(target, bonusVariation, isSelectedByUser) {
  var { activation, inputDisplay, minValue, maxValue, container } =
    bonusVariation;

  var {
    min: targetMin,
    max: targetMax,
    name: targetName,
    value: targetValue,
    parentElement: targetParent,
    tagName,
  } = target;

  targetMin = Number(targetMin);
  targetMax = Number(targetMax);
  targetValue = Number(targetValue);

  var isSkill = tagName === "SELECT";

  if (container.contains(target) || targetName == 0) {
    if (!isSelectedByUser) {
      hideElement(container);
    }
    return;
  }

  if (isSkill) {
    var options = target.options;

    targetMin = options[0].value;
    targetMax = options[options.length - 1].value;
  }

  minValue.min = targetMin;
  minValue.max = targetMax;

  maxValue.min = targetMin;
  maxValue.max = targetMax;

  if (isSelectedByUser) {
    var { input, tab } = bonusVariation;

    inputDisplay.value = getTargetContent(targetParent, targetName, isSkill);

    input.value = targetName;
    minValue.value = Math.max(targetValue - 10, targetMin);
    maxValue.value = Math.min(targetValue + 10, targetMax);

    activation.checked = true;

    tab.click();
    tab.scrollIntoView(true);

    input.dispatchEvent(new Event("change", { bubbles: true }));
  } else {
    if (minValue.value < targetMin) {
      minValue.value = targetMin;
      minValue.dispatchEvent(new Event("change", { bubbles: true }));
    }

    if (maxValue.value > targetMax) {
      maxValue.value = targetMax;
      maxValue.dispatchEvent(new Event("change", { bubbles: true }));
    }
  }

  inputDisplay.style.width = inputDisplay.value.length * 0.55 + "em";
  showElement(container);
}

function characterManagement(characters, battle) {
  var {
    newCharacterTemplate: characterTemplate,
    charactersContainer,
    addNewCharacterButton,
    saveButton,
    characterCreation,
    bonusVariation,
  } = characters;

  Object.keys(characters.savedCharacters).forEach(function (pseudo) {
    handleNewCharacter(
      characters,
      characterTemplate,
      charactersContainer,
      battle,
      pseudo
    );
  });

  addNewCharacterButton.addEventListener("click", function (event) {
    if (!characters.unsavedChanges) {
      addNewCharacter(
        characters,
        characterTemplate,
        charactersContainer,
        battle
      );
    } else {
      var result = confirm(
        "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
      );

      if (result) {
        addNewCharacter(
          characters,
          characterTemplate,
          charactersContainer,
          battle
        );
        saveButtonGreen(saveButton);
        characters.unsavedChanges = false;
      }
    }
  });

  handleUploadCharacter(
    characters,
    characterTemplate,
    charactersContainer,
    battle
  );

  characterCreation.addEventListener("change", function () {
    saveButtonOrange(saveButton);
    characters.unsavedChanges = true;
  });

  function handleLongPress(target) {
    if (target.tagName !== "INPUT" && target.tagName !== "SELECT") {
      target = target.querySelector("input");
    }

    if (
      !target ||
      (target.type !== "number" &&
        !target.classList.contains("skill-select") &&
        target.name !== "weaponUpgrade")
    ) {
      return;
    }

    handleBonusVariation(target, bonusVariation, true);
  }

  characterCreation.addEventListener("click", function (event) {
    if (event.shiftKey || event.ctrlKey) {
      handleLongPress(event.target);
    }
  });

  var longPressTimer;

  characterCreation.addEventListener("touchstart", function (event) {
    longPressTimer = setTimeout(function () {
      handleLongPress(event.target);
    }, 800);
  });

  characterCreation.addEventListener("touchend", function () {
    clearTimeout(longPressTimer);
  });

  characterCreation.addEventListener("touchmove", function () {
    clearTimeout(longPressTimer);
  });

  filterForm(characters, battle);
  characterCreationListener(characters, battle);
  handleFocus();

  window.addEventListener("beforeunload", function (event) {
    if (characters.unsavedChanges) {
      event.preventDefault();
      return "";
    }
  });
}

function handleNewMonster(
  characters,
  monsterTemplate,
  monstersContainer,
  battle,
  monsterVnum,
  monsterList
) {
  var newMonsterTemplate = monsterTemplate.cloneNode(true);
  var spanInput = newMonsterTemplate.querySelector("span.input");
  var deleteSvg = newMonsterTemplate.querySelector("svg");
  var monsterName = getMonsterName(monsterVnum);

  var link = document.createElement("a");
  link.href = mw.util.getUrl(monsterName);
  link.title = monsterName;
  link.textContent = monsterName;

  spanInput.appendChild(link);
  monstersContainer.appendChild(newMonsterTemplate);

  newMonsterTemplate.setAttribute("tabindex", "0");
  newMonsterTemplate.setAttribute("data-name", monsterVnum);
  monstersContainer.appendChild(newMonsterTemplate);

  deleteSvg.addEventListener("click", function (event) {
    deleteMonster(characters, monsterVnum, newMonsterTemplate, battle);
    var inputMonster = monsterList.querySelector(
      "input[name='" + monsterVnum + "']"
    );
    inputMonster.checked = false;
  });
}

function monsterManagement(characters, battle) {
  function handleDropdown(searchMonster, monsterList) {
    searchMonster.addEventListener("focus", function (event) {
      showElement(monsterList);
    });

    document.addEventListener("mousedown", function (event) {
      var target = event.target;
      if (!monsterList.contains(target) && !searchMonster.contains(target)) {
        hideElement(monsterList);
      }
    });
  }

  function addMonsterNames(monsterList) {
    var lastMonsterAttributeIndex = monsterData[101].length - 1;

    for (var monsterVnum in monsterData) {
      var li = document.createElement("li");
      var label = document.createElement("label");
      var input = document.createElement("input");
      var textNode = document.createTextNode(
        monsterData[monsterVnum][lastMonsterAttributeIndex]
      );

      label.htmlFor = "monster" + monsterVnum;
      input.id = "monster" + monsterVnum;
      input.type = "checkbox";

      input.name = monsterVnum;

      label.appendChild(input);
      label.appendChild(textNode);
      li.appendChild(label);
      monsterList.appendChild(li);
    }
  }

  function filterNames(searchMonster, monsterList) {
    var debounceTimer;

    searchMonster.addEventListener("input", function (event) {
      clearTimeout(debounceTimer);
      debounceTimer = setTimeout(function () {
        var value = toNormalForm(event.target.value);
        for (var element of monsterList.children) {
          if (!isValueInArray(value, toNormalForm(element.textContent))) {
            hideElement(element);
          } else {
            showElement(element);
          }
        }
      }, 500);
    });
  }

  var monsterTemplate = characters.newMonsterTemplate;
  var monstersContainer = characters.monstersContainer;
  var monsterList = characters.monsterList;
  var searchMonster = characters.searchMonster;
  var monsterListForm = characters.monsterListForm;

  document
    .getElementById("monster-link")
    .querySelector("a")
    .setAttribute("target", "_blank");

  handleDropdown(searchMonster, monsterList);
  addMonsterNames(monsterList, characters.monsterListTemplate);
  filterNames(searchMonster, monsterList);

  characters.savedMonsters.slice().forEach(function (monsterVnum) {
    var inputMonster = monsterList.querySelector(
      "input[name='" + monsterVnum + "']"
    );

    if (inputMonster) {
      handleNewMonster(
        characters,
        monsterTemplate,
        monstersContainer,
        battle,
        monsterVnum,
        monsterList
      );
      inputMonster.checked = true;
    } else {
      deleteMonster(characters, monsterVnum, null, battle);
    }
  });

  monsterListForm.addEventListener("submit", function (event) {
    event.preventDefault();
  });

  monsterListForm.addEventListener("change", function (event) {
    var target = event.target;
    var monsterVnum = target.name;

    if (monsterVnum === "search-monster") {
      return;
    }

    if (target.checked) {
      handleNewMonster(
        characters,
        monsterTemplate,
        monstersContainer,
        battle,
        monsterVnum,
        monsterList
      );

      characters.savedMonsters.push(monsterVnum);
      updateSavedMonsters(characters.savedMonsters);
      addBattleChoice(battle, monsterVnum, true);
    } else {
      var currentMonsterTemplate = monstersContainer.querySelector(
        "[data-name='" + monsterVnum + "']"
      );
      deleteMonster(characters, monsterVnum, currentMonsterTemplate, battle);
    }
  });

  addEventListener("storage", function (event) {
    if (event.key === "newMonsterCalculator") {
      var monsterVnum = Number(event.newValue);

      if (!monsterVnum) {
        return;
      }

      var inputMonster = monsterList.querySelector(
        "input[name='" + Math.abs(monsterVnum) + "']"
      );

      if (inputMonster) {
        if (
          (monsterVnum > 0 && !inputMonster.checked) ||
          (monsterVnum < 0 && inputMonster.checked)
        ) {
          inputMonster.click();
        }
      }
    }
  });
}

function removeBattleChoice(battle, name) {
  var battleSelects = [battle.attackerSelection, battle.victimSelection];

  battleSelects.forEach(function (battleSelect) {
    for (
      var optionIndex = 0;
      optionIndex < battleSelect.options.length;
      optionIndex++
    ) {
      if (battleSelect.options[optionIndex].value === name) {
        battleSelect.remove(optionIndex);
        break;
      }
    }
  });
}

function addBattleChoice(battle, name, isMonster = false) {
  function createOption(text, vnum) {
    var option = document.createElement("option");
    option.textContent = text;
    option.value = vnum;

    if (!isMonster) {
      option.classList.add("notranslate");
    }

    return option;
  }

  var vnum = name;

  if (isMonster) {
    name = getMonsterName(name);
  }

  if (isMonster && monsterData[vnum][1]) {
    // pass
  } else {
    battle.attackerSelection.appendChild(createOption(name, vnum));
  }

  battle.victimSelection.appendChild(createOption(name, vnum));
}

function updateBattleChoice(characters, battle) {
  var keys = Object.keys(characters.savedCharacters);

  for (var index = 0; index < keys.length; index++) {
    var pseudo = keys[index];
    addBattleChoice(battle, pseudo);
  }

  characters.savedMonsters.forEach(function (monsterVnum) {
    addBattleChoice(battle, monsterVnum, true);
  });
}

function isPC(character) {
  if (character.race === 0 || character.race === 1) {
    return false;
  }
  return true;
}

function isBoss(character) {
  return character.race === 0 && character.rank >= 5;
}

function isStone(character) {
  return character.race === 1;
}

function isMeleeAttacker(monster) {
  return monster.attack == 0;
}

function isRangeAttacker(monster) {
  return monster.attack == 1;
}

function isMagicAttacker(monster) {
  return monster.attack == 2;
}

function isMagicClass(character) {
  return character.race === "shaman" || character.class === "black_magic";
}

function isDispell(character, skillId) {
  return character.class === "weaponary" && skillId === 6;
}

function isPolymorph(character) {
  return character.state === "polymorph";
}

function isRiding(character) {
  return character.state === "horse";
}

function isBow(weapon) {
  return weapon.type === 2;
}

function calcAttackFactor(attacker, victim) {
  function calcCoeffK(dex, level) {
    return Math.min(90, Math.floor((2 * dex + level) / 3));
  }

  var K1 = calcCoeffK(attacker.polymorphDex, attacker.level);
  var K2 = calcCoeffK(victim.polymorphDex, attacker.level);

  var AR = (K1 + 210) / 300;
  var ER = (((2 * K2 + 5) / (K2 + 95)) * 3) / 10;

  return truncateNumber(AR - ER, 8);
}

function calcMainAttackValue(attacker) {
  var leadership = 0;
  var rawWeaponAttackValue = 0;

  if (isPC(attacker)) {
    var weaponUpgrades = attacker.weapon.upgrades;
    var maxUpgrade = weaponUpgrades.length - 1;

    if (attacker.hasOwnProperty("weaponUpgrade")) {
      rawWeaponAttackValue =
        weaponUpgrades[Math.min(attacker.weaponUpgrade, maxUpgrade)];

      // rare bug when weaponUpgrade is deleted
    } else {
      console.log("Warming: weaponUpgrade is missing.");
      rawWeaponAttackValue = weaponUpgrades[maxUpgrade];
    }

    leadership = attacker.leadership;
  }

  return 2 * (attacker.level + rawWeaponAttackValue) + leadership;
}

function calcStatAttackValue(character) {
  switch (character.race) {
    case "warrior":
    case "sura":
      return 2 * character.str;
    case "ninja":
      return Math.floor((1 / 4) * (character.str + 7 * character.dex));
    case "shaman":
      return Math.floor((1 / 3) * (5 * character.int + character.dex));
    case "lycan":
      return character.vit + 2 * character.dex;
    default:
      return 2 * character.str;
  }
}

function calcSecondaryAttackValue(attacker) {
  var attackValueOther = 0;

  var minAttackValue = 0;
  var maxAttackValue = 0;

  var minAttackValueSlash = 0;
  var maxAttackValueSlash = 0;

  var attackerWeapon = attacker.weapon;

  if (isPC(attacker)) {
    if (attackerWeapon.isSerpent) {
      var rawAttackValue = attackerWeapon.upgrades[attacker.weaponUpgrade];

      minAttackValue = attacker.minAttackValueRandom - rawAttackValue;
      maxAttackValue = attacker.maxAttackValueRandom - rawAttackValue;

      minAttackValue = Math.max(0, minAttackValue);
      maxAttackValue = Math.max(minAttackValue, maxAttackValue);
    } else {
      minAttackValue = attackerWeapon.minAttackValue;
      maxAttackValue = attackerWeapon.maxAttackValue;
    }

    minAttackValueSlash = Math.min(
      attacker.minAttackValueSlash,
      attacker.maxAttackValueSlash
    );
    maxAttackValueSlash = Math.max(
      attacker.minAttackValueSlash,
      attacker.maxAttackValueSlash
    );

    attackValueOther += attacker.attackValue;

    if (isBow(attackerWeapon) && !isPolymorph(attacker)) {
      attackValueOther += 25;
    }
  } else {
    minAttackValue = attacker.minAttackValue;
    maxAttackValue = attacker.maxAttackValue;
  }

  minAttackValue += attacker.minAttackValuePolymorph;
  maxAttackValue += attacker.maxAttackValuePolymorph;

  attackValueOther += attacker.statAttackValue;
  attackValueOther += attacker.horseAttackValue;

  var weaponInterval = maxAttackValue - minAttackValue + 1;
  var slashInterval = maxAttackValueSlash - minAttackValueSlash + 1;

  var totalCardinal = weaponInterval * slashInterval * 1_000_000;
  var minInterval = Math.min(weaponInterval, slashInterval);

  minAttackValue += minAttackValueSlash;
  maxAttackValue += maxAttackValueSlash;

  return {
    minAttackValue: minAttackValue,
    maxAttackValue: maxAttackValue,
    attackValueOther: attackValueOther,
    totalCardinal: totalCardinal,
    weights: calcWeights(minAttackValue, maxAttackValue, minInterval),
    possibleDamagesCount: maxAttackValue - minAttackValue + 1,
  };
}

function calcMagicAttackValue(attacker) {
  var minMagicAttackValue = 0;
  var maxMagicAttackValue = 0;

  var minMagicAttackValueSlash = 0;
  var maxMagicAttackValueSlash = 0;

  var attackerWeapon = attacker.weapon;

  if (attackerWeapon.isSerpent) {
    minMagicAttackValue = attacker.minMagicAttackValueRandom;
    maxMagicAttackValue = attacker.maxMagicAttackValueRandom;

    maxMagicAttackValue = Math.max(minMagicAttackValue, maxMagicAttackValue);
  } else {
    var rawWeaponAttackValue = attackerWeapon.upgrades[attacker.weaponUpgrade];

    if (!rawWeaponAttackValue) {
      rawWeaponAttackValue = 0;
    }

    minMagicAttackValue =
      attackerWeapon.minMagicAttackValue + rawWeaponAttackValue;
    maxMagicAttackValue =
      attackerWeapon.maxMagicAttackValue + rawWeaponAttackValue;
  }

  minMagicAttackValueSlash = Math.min(
    attacker.minMagicAttackValueSlash,
    attacker.maxMagicAttackValueSlash
  );
  maxMagicAttackValueSlash = Math.max(
    attacker.minMagicAttackValueSlash,
    attacker.maxMagicAttackValueSlash
  );

  var weaponInterval = maxMagicAttackValue - minMagicAttackValue + 1;
  var slashInterval = maxMagicAttackValueSlash - minMagicAttackValueSlash + 1;

  var totalCardinal = weaponInterval * slashInterval * 1_000_000;
  var minInterval = Math.min(weaponInterval, slashInterval);

  minMagicAttackValue += minMagicAttackValueSlash;
  maxMagicAttackValue += maxMagicAttackValueSlash;

  return {
    minMagicAttackValue: minMagicAttackValue,
    maxMagicAttackValue: maxMagicAttackValue,
    magicAttackValueAugmentation: getMagicAttackValueAugmentation(
      minMagicAttackValue,
      maxMagicAttackValue,
      attacker.magicAttackValue
    ),
    totalCardinal: totalCardinal,
    weights: calcWeights(minMagicAttackValue, maxMagicAttackValue, minInterval),
    possibleDamagesCount: maxMagicAttackValue - minMagicAttackValue + 1,
  };
}

function getPolymorphPower(polymorphPoint, polymorphPowerTable) {
  return polymorphPowerTable[polymorphPoint];
}

function getSkillPower(skillPoint, skillPowerTable) {
  return skillPowerTable[skillPoint];
}

function getMarriageBonusValue(character, marriageTable, itemName) {
  var index;
  var lovePoint = character.lovePoint;

  if (lovePoint < 65) {
    index = 0;
  } else if (lovePoint < 80) {
    index = 1;
  } else if (lovePoint < 100) {
    index = 2;
  } else {
    index = 3;
  }

  return marriageTable[itemName][index];
}

function calcDamageWithPrimaryBonuses(damages, bonusValues) {
  damages = Math.floor((damages * bonusValues.attackValueCoeff) / 100);

  damages += bonusValues.attackValueMarriage;

  damages = Math.floor(
    (damages * bonusValues.monsterResistanceMarriageCoeff) / 100
  );
  damages = Math.floor((damages * bonusValues.monsterResistanceCoeff) / 100);

  damages += Math.floor((damages * bonusValues.typeBonusCoeff) / 100);
  damages +=
    Math.floor((damages * bonusValues.raceBonusCoeff) / 100) -
    Math.floor((damages * bonusValues.raceResistanceCoeff) / 100);
  damages += Math.floor((damages * bonusValues.stoneBonusCoeff) / 100);
  damages += Math.floor((damages * bonusValues.monsterBonusCoeff) / 100);

  var elementBonusCoeff = bonusValues.elementBonusCoeff;

  damages +=
    Math.trunc((damages * elementBonusCoeff[0]) / 10000) +
    Math.trunc((damages * elementBonusCoeff[1]) / 10000) +
    Math.trunc((damages * elementBonusCoeff[2]) / 10000) +
    Math.trunc((damages * elementBonusCoeff[3]) / 10000) +
    Math.trunc((damages * elementBonusCoeff[4]) / 10000) +
    Math.trunc((damages * elementBonusCoeff[5]) / 10000);

  damages = Math.floor(damages * bonusValues.damageMultiplier);

  return damages;
}

function calcDamageWithSecondaryBonuses(
  damages,
  bonusValues,
  damagesType,
  minPiercingDamages,
  damagesWithPrimaryBonuses
) {
  damages = Math.floor(damages * bonusValues.magicResistanceCoeff);
  damages = Math.trunc((damages * bonusValues.weaponDefenseCoeff) / 100);
  damages = Math.floor((damages * bonusValues.tigerStrengthCoeff) / 100);
  damages = Math.floor((damages * bonusValues.blessingBonusCoeff) / 100);

  if (damagesType.criticalHit) {
    damages *= 2;
  }

  if (damagesType.piercingHit) {
    damages += bonusValues.defenseBoost + Math.min(0, minPiercingDamages);
    damages += Math.floor(
      (damagesWithPrimaryBonuses * bonusValues.extraPiercingHitCoeff) / 1000
    );
  }

  damages = Math.floor((damages * bonusValues.averageDamageCoeff) / 100);
  damages = Math.floor(
    (damages * bonusValues.averageDamageResistanceCoeff) / 100
  );
  damages = Math.floor(
    (damages * bonusValues.skillDamageResistanceCoeff) / 100
  );

  damages = Math.floor((damages * bonusValues.rankBonusCoeff) / 100);
  damages = Math.max(0, damages + bonusValues.defensePercent);
  damages += Math.min(
    300,
    Math.floor((damages * bonusValues.damageBonusCoeff) / 100)
  );
  damages = Math.floor((damages * bonusValues.empireMalusCoeff) / 10);
  damages = Math.floor((damages * bonusValues.sungMaStrBonusCoeff) / 10000);
  damages -= Math.floor(damages * bonusValues.sungmaStrMalusCoeff);

  damages = Math.floor((damages * bonusValues.whiteDragonElixirCoeff) / 100);
  damages = Math.floor((damages * bonusValues.steelDragonElixirCoeff) / 100);

  return damages;
}

function calcSkillDamageWithSecondaryBonuses(
  damages,
  bonusValues,
  damagesType,
  minPiercingDamages
) {
  damages = Math.floor(damages * bonusValues.magicResistanceCoeff);
  damages = Math.trunc((damages * bonusValues.weaponDefenseCoeff) / 100);

  damages -= bonusValues.defense;

  damages = floorMultiplication(damages, bonusValues.skillWardCoeff);
  damages = floorMultiplication(damages, bonusValues.skillBonusCoeff);

  var tempDamages = Math.floor(
    (damages * bonusValues.skillBonusByBonusCoeff) / 100
  );
  
  damages = Math.floor(
    (tempDamages * bonusValues.magicAttackValueCoeff) / 100 + 0.5
  );
  damages = Math.floor((damages * bonusValues.tigerStrengthCoeff) / 100);

  if (damagesType.criticalHit) {
    damages *= 2;
  }

  if (damagesType.piercingHit) {
    damages += bonusValues.defenseBoost + Math.min(0, minPiercingDamages);
    damages += Math.floor(
      (tempDamages * bonusValues.extraPiercingHitCoeff) / 1000
    );
  }

  damages = Math.floor((damages * bonusValues.skillDamageCoeff) / 100);
  damages = Math.floor(
    (damages * bonusValues.skillDamageResistanceCoeff) / 100
  );
  damages = Math.floor((damages * bonusValues.rankBonusCoeff) / 100);

  damages = Math.max(0, damages + bonusValues.defensePercent);
  damages += Math.min(
    300,
    Math.floor((damages * bonusValues.damageBonusCoeff) / 100)
  );
  damages = Math.floor((damages * bonusValues.empireMalusCoeff) / 10);
  damages = Math.floor((damages * bonusValues.sungMaStrBonusCoeff) / 10000);
  damages -= Math.floor(damages * bonusValues.sungmaStrMalusCoeff);

  damages = Math.floor((damages * bonusValues.whiteDragonElixirCoeff) / 100);
  damages = Math.floor((damages * bonusValues.steelDragonElixirCoeff) / 100);

  return damages;
}

function computePolymorphPoint(attacker, victim, polymorphPowerTable) {
  attacker.statAttackValue = 0;

  attacker.polymorphDex = attacker.dex;
  victim.polymorphDex = victim.dex;

  attacker.minAttackValuePolymorph = 0;
  attacker.maxAttackValuePolymorph = 0;

  if (isPC(attacker) && isPolymorph(attacker)) {
    var polymorphPowerPct =
      getPolymorphPower(attacker.polymorphPoint, polymorphPowerTable) / 100;
    var polymorphMonster = createMonster(attacker.polymorphMonster);

    var polymorphStr = floorMultiplication(
      polymorphPowerPct,
      polymorphMonster.str
    );

    attacker.polymorphDex += floorMultiplication(
      polymorphPowerPct,
      polymorphMonster.dex
    );

    attacker.minAttackValuePolymorph = floorMultiplication(
      polymorphPowerPct,
      polymorphMonster.minAttackValue
    );
    attacker.maxAttackValuePolymorph = floorMultiplication(
      polymorphPowerPct,
      polymorphMonster.maxAttackValue
    );

    if (!attacker.weapon) {
      attacker.maxAttackValuePolymorph += 1;
    }

    attacker.attackValue = 0;

    if (isMagicClass(attacker)) {
      attacker.statAttackValue = 2 * (polymorphStr + attacker.int);
    } else {
      attacker.statAttackValue = 2 * (polymorphStr + attacker.str);
    }
  } else {
    attacker.statAttackValue = calcStatAttackValue(attacker);
  }
}

function computeHorse(attacker) {
  attacker.horseAttackValue = 0;

  if (isPC(attacker) && isRiding(attacker)) {
    var horseConstant = 30;

    if (attacker.class === "weaponary") {
      horseConstant = 60;
    }

    attacker.horseAttackValue = floorMultiplication(
      2 * attacker.level + attacker.statAttackValue,
      attacker.horsePoint / horseConstant
    );
  }
}

function getRankBonus(attacker) {
  if (attacker.lowRank !== "on") {
    return 0;
  }

  switch (attacker.playerRank) {
    case "aggressive":
      return 1;
    case "fraudulent":
      return 2;
    case "malicious":
      return 3;
    case "cruel":
      return 5;
  }

  return 0;
}

function calcElementCoeffPvP(elementBonus, mapping, attacker, victim) {
  var minElementMalus = 0;
  var maxDifference = 0;
  var savedElementDifferences = [];
  var elementBonusIndex = 0;

  for (var index = 0; index < elementBonus.length; index++) {
    if (!attacker[mapping.elementBonus[index]]) {
      continue;
    }

    var elementDifference =
      attacker[mapping.elementBonus[index]] -
      victim[mapping.elementResistance[index]];

    if (elementDifference >= 0) {
      elementBonus[elementBonusIndex] = 10 * elementDifference;
      minElementMalus -= elementDifference;
      maxDifference = Math.max(maxDifference, elementDifference);
      elementBonusIndex++;
    } else {
      savedElementDifferences.push(elementDifference);
    }
  }

  if (!savedElementDifferences.length) {
    return;
  }

  minElementMalus += maxDifference;
  savedElementDifferences.sort(compareNumbers);

  for (var index = 0; index < savedElementDifferences.length; index++) {
    var elementDifference = savedElementDifferences[index];

    elementBonus[elementBonusIndex + index] =
      10 * Math.max(minElementMalus, elementDifference);

    minElementMalus = Math.min(
      0,
      Math.max(minElementMalus, minElementMalus - elementDifference)
    );
  }
}

function skillChanceReduction(value) {
  if (value <= 9) {
    return Math.floor(value / 2);
  }
  return 5 + Math.floor((value - 10) / 4);
}

function magicResistanceToCoeff(magicResistance) {
  if (magicResistance) {
    return 2000 / (6 * magicResistance + 1000) - 1;
  }
  return 1;
}

function createBattleValues(attacker, victim, battle, skillType) {
  var { mapping, constants } = battle;
  var calcAttackValues;

  var missPercentage = 0;
  var attackValueMeleeMagic = 0;
  var attackValueMarriage = 0;
  var monsterResistanceMarriage = 0;
  var monsterResistance = 0;
  var typeBonus = 0;
  var raceBonus = 0;
  var raceResistance = 0;
  var stoneBonus = 0;
  var monsterBonus = 0;
  var elementBonus = [0, 0, 0, 0, 0, 0]; // fire, ice, lightning, earth, darkness, wind, order doesn't matter
  var defenseMarriage = 0;
  var damageMultiplier = 1;
  var useDamages = 1;
  var defense = victim.defense;
  var defenseBoost = defense;
  var magicResistance = 0;
  var weaponDefense = 0;
  var tigerStrength = 0;
  var blessingBonus = 0;
  var magicAttackValueMeleeMagic = 0;
  var criticalHitPercentage = attacker.criticalHit;
  var piercingHitPercentage = attacker.piercingHit;
  var extraPiercingHitPercentage = Math.max(0, piercingHitPercentage - 100);
  var averageDamage = 0;
  var averageDamageResistance = 0;
  var skillDamage = 0;
  var skillDamageResistance = 0;
  var rankBonus = 0;
  var defensePercent = 0;
  var damageBonus = 0;
  var empireMalus = 0;
  var sungMaStrBonus = 0;
  var sungmaStrMalus = 0;
  var whiteDragonElixir = 0;
  var steelDragonElixir = 0;

  computePolymorphPoint(attacker, victim, constants.polymorphPowerTable);
  computeHorse(attacker);

  if (isPC(attacker)) {
    if (weaponData.hasOwnProperty(attacker.weapon)) {
      attacker.weapon = createWeapon(attacker.weapon);
    } else {
      attacker.weapon = createWeapon(0);
    }

    attackValueMeleeMagic =
      attacker.attackValuePercent + Math.min(100, attacker.attackMeleeMagic);

    var weaponType = attacker.weapon.type;

    if (skillType && attacker.class === "archery") {
      if (weaponType !== 2) {
        useDamages = 0;
        weaponType = 2;
      }
      defense = 0;
    }

    var weaponDefenseName = mapping.defenseWeapon[weaponType];
    var weaponDefenseBreakName = mapping.breakWeapon[weaponType];

    if (victim.hasOwnProperty(weaponDefenseName)) {
      weaponDefense = victim[weaponDefenseName];
    }

    if (isChecked(attacker.whiteDragonElixir)) {
      whiteDragonElixir = 10;
    }

    if (isPC(victim)) {
      if (!skillType) {
        if (weaponType === 2 && !isPolymorph(attacker)) {
          missPercentage = victim.arrowBlock;
        } else {
          missPercentage = victim.meleeBlock;
        }
        missPercentage +=
          victim.meleeArrowBlock -
          (missPercentage * victim.meleeArrowBlock) / 100;

        blessingBonus = calcBlessingBonus(constants.skillPowerTable, victim);
        averageDamageResistance = victim.averageDamageResistance;
      }

      typeBonus = Math.max(1, attacker.humanBonus - victim.humanResistance);
      raceBonus = attacker[mapping.raceBonus[victim.race]];
      raceResistance = victim[mapping.raceResistance[attacker.race]];

      calcElementCoeffPvP(elementBonus, mapping, attacker, victim);

      if (weaponType !== 2 && attacker.hasOwnProperty(weaponDefenseBreakName)) {
        weaponDefense -= attacker[weaponDefenseBreakName];
      }

      criticalHitPercentage = 0;
    } else {
      if (isChecked(attacker.isMarried)) {
        if (isChecked(attacker.loveNecklace)) {
          attackValueMarriage = getMarriageBonusValue(
            attacker,
            constants.marriageTable,
            "loveNecklace"
          );
        }

        if (isChecked(attacker.loveEarrings)) {
          criticalHitPercentage += getMarriageBonusValue(
            attacker,
            constants.marriageTable,
            "loveEarrings"
          );
        }

        if (isChecked(attacker.harmonyEarrings)) {
          piercingHitPercentage += getMarriageBonusValue(
            attacker,
            constants.marriageTable,
            "harmonyEarrings"
          );
        }
      }

      if (isChecked(attacker.tigerStrength)) {
        tigerStrength = 40;
      }

      for (var index = 0; index < elementBonus.length; index++) {
        var elementBonusName = mapping.elementBonus[index];
        var elementResistanceName = mapping.elementResistance[index];

        if (attacker[elementBonusName] && victim[elementBonusName]) {
          elementBonus[index] =
            50 * (attacker[elementBonusName] - victim[elementResistanceName]);
        } else {
          elementBonus[index] = 5 * attacker[elementBonusName];
        }
      }

      var victimType = victim.type;

      if (victimType !== -1) {
        typeBonus = attacker[mapping.typeFlag[victimType]];
      }

      monsterBonus = attacker.monsterBonus;

      if (isStone(victim)) {
        stoneBonus = attacker.stoneBonus;
      }

      if (isBoss(victim)) {
        if (skillType) {
          skillDamage += attacker.skillBossDamage;
        } else {
          averageDamage += attacker.bossDamage;
        }
      }

      if (isChecked(attacker.onYohara)) {
        var sungmaStrDifference = attacker.sungmaStr - attacker.sungmaStrMalus;

        if (sungmaStrDifference >= 0) {
          sungMaStrBonus = sungmaStrDifference;
        } else {
          sungmaStrMalus = 0.5;
        }
      }
    }

    if (skillType) {
      skillDamage += attacker.skillDamage;
    } else {
      averageDamage += attacker.averageDamage;
    }

    rankBonus = getRankBonus(attacker);
    damageBonus = attacker.damageBonus;

    if (isChecked(attacker.empireMalus)) {
      empireMalus = 1;
    }
  } else {
    if (isPC(victim)) {
      if (isChecked(victim.isMarried)) {
        if (isChecked(victim.harmonyBracelet)) {
          monsterResistanceMarriage = getMarriageBonusValue(
            victim,
            constants.marriageTable,
            "harmonyBracelet"
          );
        }

        if (isChecked(victim.harmonyNecklace) && !skillType) {
          defenseMarriage = getMarriageBonusValue(
            victim,
            constants.marriageTable,
            "harmonyNecklace"
          );
        }
      }

      monsterResistance = victim.monsterResistance;

      for (var index = 0; index < elementBonus.length; index++) {
        var elementBonusName = mapping.elementBonus[index];
        var elementResistanceName = mapping.elementResistance[index];

        if (attacker[elementBonusName]) {
          elementBonus[index] =
            80 * (attacker[elementBonusName] - victim[elementResistanceName]);
        }
      }

      if (!skillType) {
        if (isMeleeAttacker(attacker)) {
          missPercentage = victim.meleeBlock;
          averageDamageResistance = victim.averageDamageResistance;
          blessingBonus = calcBlessingBonus(constants.skillPowerTable, victim);
        } else if (isRangeAttacker(attacker)) {
          missPercentage = victim.arrowBlock;
          weaponDefense = victim.arrowDefense;
          averageDamageResistance = victim.averageDamageResistance;
          blessingBonus = calcBlessingBonus(constants.skillPowerTable, victim);
        } else if (isMagicAttacker(attacker)) {
          missPercentage = victim.arrowBlock;
          skillDamageResistance = victim.skillDamageResistance;
          magicResistance = victim.magicResistance;
        }

        missPercentage +=
          victim.meleeArrowBlock -
          (missPercentage * victim.meleeArrowBlock) / 100;
      }
    }

    typeBonus = 1;
    damageMultiplier = attacker.damageMultiplier;
  }

  if (skillType) {
    criticalHitPercentage = skillChanceReduction(criticalHitPercentage);
    piercingHitPercentage = skillChanceReduction(piercingHitPercentage);
  }

  if (isPC(victim)) {
    if (!skillType && isChecked(victim.biologist70)) {
      defenseBoost = Math.floor((defenseBoost * 110) / 100);
    }

    criticalHitPercentage = Math.max(
      0,
      criticalHitPercentage - victim.criticalHitResistance
    );
    piercingHitPercentage = Math.max(
      0,
      piercingHitPercentage - victim.piercingHitResistance
    );

    if (skillType) {
      skillDamageResistance = victim.skillDamageResistance;
    }

    if (isMagicClass(victim)) {
      defensePercent = (-2 * victim.magicDefense * victim.defensePercent) / 100;
    } else {
      defensePercent = (-2 * defenseBoost * victim.defensePercent) / 100;
    }

    if (isChecked(victim.steelDragonElixir)) {
      steelDragonElixir = 10;
    }
  }

  if (skillType === "magic") {
    attackValueMeleeMagic = 0;
    magicAttackValueMeleeMagic =
      attacker.attackMagic + Math.min(100, attacker.attackMeleeMagic);
    attackValueMarriage = 0;
    defense = 0;
    if (!isDispell(attacker, 6)) {
      magicResistance = victim.magicResistance;
    }
    weaponDefense = 0;
    calcAttackValues = calcMagicAttackValue;
  } else {
    calcAttackValues = calcSecondaryAttackValue;
  }

  missPercentage = Math.min(100, missPercentage);

  var bonusValues = {
    missPercentage: missPercentage,
    weaponBonusCoeff: 1,
    attackValueCoeff: 100 + attackValueMeleeMagic,
    attackValueMarriage: attackValueMarriage,
    monsterResistanceMarriageCoeff: 100 - monsterResistanceMarriage,
    monsterResistanceCoeff: 100 - monsterResistance,
    typeBonusCoeff: typeBonus,
    raceBonusCoeff: raceBonus,
    raceResistanceCoeff: raceResistance,
    stoneBonusCoeff: stoneBonus,
    monsterBonusCoeff: monsterBonus,
    elementBonusCoeff: elementBonus,
    damageMultiplier: damageMultiplier,
    useDamages: useDamages,
    defense: defense,
    defenseBoost: defenseBoost,
    defenseMarriage: defenseMarriage,
    tigerStrengthCoeff: 100 + tigerStrength,
    magicResistanceCoeff: magicResistanceToCoeff(magicResistance),
    weaponDefenseCoeff: 100 - weaponDefense,
    blessingBonusCoeff: 100 - blessingBonus,
    magicAttackValueCoeff: 100 + magicAttackValueMeleeMagic,
    extraPiercingHitCoeff: 5 * extraPiercingHitPercentage,
    averageDamageCoeff: 100 + averageDamage,
    averageDamageResistanceCoeff: 100 - Math.min(99, averageDamageResistance),
    skillDamageCoeff: 100 + skillDamage,
    skillDamageResistanceCoeff: 100 - Math.min(99, skillDamageResistance),
    rankBonusCoeff: 100 + rankBonus,
    defensePercent: Math.floor(defensePercent),
    damageBonusCoeff: damageBonus,
    empireMalusCoeff: 10 - empireMalus,
    sungMaStrBonusCoeff: 10000 + sungMaStrBonus,
    sungmaStrMalusCoeff: sungmaStrMalus,
    whiteDragonElixirCoeff: 100 + whiteDragonElixir,
    steelDragonElixirCoeff: 100 - steelDragonElixir,
  };

  criticalHitPercentage = Math.min(criticalHitPercentage, 100);
  piercingHitPercentage = Math.min(piercingHitPercentage, 100);

  var damagesTypeCombinaison = [
    {
      criticalHit: false,
      piercingHit: false,
      weight:
        (100 - criticalHitPercentage) *
        (100 - piercingHitPercentage) *
        (100 - missPercentage),
      name: "normalHit",
    },
    {
      criticalHit: true,
      piercingHit: false,
      weight:
        criticalHitPercentage *
        (100 - piercingHitPercentage) *
        (100 - missPercentage),
      name: "criticalHit",
    },
    {
      criticalHit: false,
      piercingHit: true,
      weight:
        (100 - criticalHitPercentage) *
        piercingHitPercentage *
        (100 - missPercentage),
      name: "piercingHit",
    },
    {
      criticalHit: true,
      piercingHit: true,
      weight:
        criticalHitPercentage * piercingHitPercentage * (100 - missPercentage),
      name: "criticalPiercingHit",
    },
  ];

  return {
    attacker: attacker,
    victim: victim,
    attackFactor: calcAttackFactor(attacker, victim),
    mainAttackValue: calcMainAttackValue(attacker),
    attackValues: calcAttackValues(attacker),
    bonusValues: bonusValues,
    damagesTypeCombinaison: damagesTypeCombinaison,
  };
}

function updateBattleValues(battleValues, skillFormula, skillInfo) {
  var weaponBonus = 0;
  var skillWard = 0;
  var skillBonus = 0;
  var skillBonusByBonus = 0;
  var { attacker: attacker, bonusValues: bonusValues } = battleValues;
  var {
    range: [minVariation, maxVariation],
  } = skillInfo;
  var variationLength = maxVariation - minVariation + 1;

  if (skillInfo.hasOwnProperty("weaponBonus")) {
    var [weaponType, weaponBonusValue] = skillInfo.weaponBonus;

    if (weaponType === attacker.weapon.type) {
      weaponBonus = weaponBonusValue;
    }
  }

  if (skillInfo.skillBonus) {
    skillBonus = skillInfo.skillBonus;
  }

  if (skillInfo.skillWard) {
    skillWard = skillInfo.skillWard;
  }

  if (skillInfo.skillBonusByBonus) {
    skillBonusByBonus = skillInfo.skillBonusByBonus;
  }

  if (skillInfo.removeWeaponReduction) {
    bonusValues.weaponDefenseCoeff = 100;
  }

  bonusValues.weaponBonusCoeff = 100 + weaponBonus;
  bonusValues.skillWardCoeff = 1 - skillWard / 100;
  bonusValues.skillBonusCoeff = 1 + skillBonus / 100;
  bonusValues.skillBonusByBonusCoeff = 100 + skillBonusByBonus;

  battleValues.skillFormula = skillFormula;
  battleValues.skillRange = skillInfo.range;
  battleValues.attackValues.totalCardinal *= variationLength;
  battleValues.attackValues.possibleDamagesCount *= variationLength;
}

function calcWeights(minValue, maxValue, minInterval) {
  var firstWeightLimit = minValue + minInterval - 1;
  var lastWeightsLimit = maxValue - minInterval + 1;
  var weights = [];

  for (var value = minValue; value < firstWeightLimit; value++) {
    weights.push(value - minValue + 1);
  }

  for (var value = firstWeightLimit; value <= lastWeightsLimit; value++) {
    weights.push(minInterval);
  }

  for (var value = lastWeightsLimit + 1; value <= maxValue; value++) {
    weights.push(maxValue - value + 1);
  }

  return weights;
}

function calcBlessingBonus(skillPowerTable, victim) {
  if (victim.isBlessed !== "on") {
    return 0;
  }

  var int = victim.intBlessing;
  var dex = victim.dexBlessing;
  var skillPower = getSkillPower(victim["skillBlessing"], skillPowerTable);

  if (!skillPower) {
    return 0;
  }

  var blessingBonus = floorMultiplication(
    ((int * 0.3 + 5) * (2 * skillPower + 0.5) + 0.3 * dex) / (skillPower + 2.3),
    1
  );

  if (victim.class === "dragon" && isChecked(ictim.blessingOnself)) {
    blessingBonus = floorMultiplication(blessingBonus, 1.1);
  }

  return blessingBonus;
}

function getSkillFormula(battle, skillId, battleValues, removeSkillVariation) {
  var { attacker, victim, attackFactor } = battleValues;
  var skillPowerTable = battle.constants.skillPowerTable;

  var skillFormula;
  var skillInfo = { range: [0, 0] };

  var { class: attackerClass, level: lv, vit, str, int, dex } = attacker;

  if (skillId <= 9) {
    var skillPower = getSkillPower(
      attacker["attackSkill" + skillId],
      skillPowerTable
    );

    var improvedBySkillBonus = false;
    var improvedByBonus = false;

    if (attackerClass === "body") {
      switch (skillId) {
        // Triple lacération
        case 1:
          skillFormula = function (atk) {
            return floorMultiplication(
              1.1 * atk + (0.5 * atk + 1.5 * str) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Moulinet à l'épée
        case 2:
          skillFormula = function (atk) {
            return floorMultiplication(
              3 * atk + (0.8 * atk + 5 * str + 3 * dex + vit) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Accélération
        case 5:
          skillFormula = function (atk) {
            return floorMultiplication(
              2 * atk + (atk + dex * 3 + str * 7 + vit) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Volonté de vivre
        case 6:
          skillFormula = function (atk) {
            return floorMultiplication(
              (3 * atk + (atk + 1.5 * str) * skillPower) * 1.07,
              1
            );
          };
          break;
        // Tremblement de terre
        case 9:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              3 * atk +
                (0.9 * atk + variation + 5 * str + 3 * dex + lv) * skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "mental") {
      switch (skillId) {
        // Attaque de l'esprit
        case 1:
          skillFormula = function (atk) {
            return floorMultiplication(
              2.3 * atk + (4 * atk + 4 * str + vit) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Attaque de la paume
        case 2:
          skillFormula = function (atk) {
            return floorMultiplication(
              2.3 * atk + (3 * atk + 4 * str + 3 * vit) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Charge
        case 3:
          skillFormula = function (atk) {
            return floorMultiplication(
              2 * atk + (2 * atk + 2 * dex + 2 * vit + 4 * str) * skillPower,
              1
            );
          };
          break;
        // Coup d'épée
        case 5:
          skillFormula = function (atk) {
            return floorMultiplication(
              2 * atk + (atk + 3 * dex + 5 * str + vit) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Orbe de l'épée
        case 6:
          skillFormula = function (atk) {
            return floorMultiplication(
              (2 * atk + (2 * atk + 2 * dex + 2 * vit + 4 * str) * skillPower) *
                1.1,
              1
            );
          };
          break;
        // Tremblement de terre
        case 9:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              3 * atk +
                (0.9 * atk + variation + 5 * str + 3 * dex + lv) * skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "blade_fight") {
      switch (skillId) {
        // Embuscade
        case 1:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              atk + (1.2 * atk + variation + 4 * dex + 4 * str) * skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [1, 50];
          skillInfo.range = [500, 700];
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Attaque rapide
        case 2:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              atk + (1.6 * atk + variation + 7 * dex + 7 * str) * skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [1, 35];
          skillInfo.range = [200, 300];
          improvedByBonus = true;
          break;
        // Dague filante
        case 3:
          skillFormula = function (atk) {
            return floorMultiplication(
              2 * atk + (0.5 * atk + 9 * dex + 7 * str) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Brume empoisonnée
        case 5:
          skillFormula = function (atk) {
            return floorMultiplication(
              2 * lv + (atk + 3 * str + 18 * dex) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Poison insidieux
        case 6:
          skillFormula = function (atk) {
            return floorMultiplication(
              (2 * lv + (atk + 3 * str + 18 * dex) * skillPower) * 1.1,
              1
            );
          };
          break;
        // Étoiles brillantes
        case 9:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              atk + (1.7 * atk + variation + 6 * dex + 5 * lv) * skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "archery") {
      switch (skillId) {
        // Tir à répétition
        // case 1:
        //   skillFormula = function (atk) {
        //     return floorMultiplication(
        //       atk + 0.2 * atk * Math.floor(2 + 6 * skillPower) + (0.8 * atk + 8 * dex * attackFactor + 2 * int) * skillPower,
        //       1
        //     );
        //   };
        //   improvedByBonus = true;
        //   break;
        // Pluie de flèches
        case 2:
          skillFormula = function (atk) {
            return floorMultiplication(
              atk + (1.7 * atk + 5 * dex + str) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Flèche de feu
        case 3:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              1.5 * atk + (2.6 * atk + 0.9 * int + variation) * skillPower,
              1
            );
          };
          skillInfo.range = [100, 300];
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Foulée de plume
        case 4:
          skillFormula = function (atk) {
            return floorMultiplication(
              (3 * dex + 200 + 2 * str + 2 * int) * skillPower,
              1
            );
          };
          skillInfo.removeWeaponReduction = true;
          break;
        // Flèche empoisonnée
        case 5:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              atk +
                (1.4 * atk + variation + 7 * dex + 4 * str + 4 * int) *
                  skillPower,
              1
            );
          };
          skillInfo.range = [100, 200];
          improvedByBonus = true;
          break;
        // Coup étincelant
        case 6:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              (atk +
                (1.2 * atk + variation + 6 * dex + 3 * str + 3 * int) *
                  skillPower) *
                1.2,
              1
            );
          };
          skillInfo.range = [100, 200];
          improvedByBonus = true;
          break;
        // Tir tempête
        case 9:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              1.9 * atk + (2.6 * atk + variation) * skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "weaponary") {
      switch (skillId) {
        // Toucher brûlant
        case 1:
          skillFormula = function (atk) {
            return floorMultiplication(
              atk +
                2 * lv +
                2 * int +
                (2 * atk + 4 * str + 14 * int) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Tourbillon du dragon
        case 2:
          skillFormula = function (atk) {
            return floorMultiplication(
              1.1 * atk +
                2 * lv +
                2 * int +
                (1.5 * atk + str + 12 * int) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Contre-sort
        case 6:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              40 +
                5 * lv +
                2 * int +
                (10 * int + 7 * mav + variation) * attackFactor * skillPower,
              1
            );
          };
          skillInfo.range = [50, 100];
          break;
        // Coup démoniaque
        case 9:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              1.9 * atk + (2.6 * atk + variation) * skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "black_magic") {
      switch (skillId) {
        // Attaque des ténèbres
        case 1:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              40 +
                5 * lv +
                2 * int +
                (13 * int + 6 * mav + variation) * attackFactor * skillPower,
              1
            );
          };
          skillInfo.range = [50, 100];
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Attaque de flammes
        // case 2:
        //   skillFormula = function (mav, variation) {
        //     return floorMultiplication(
        //       5 * lv + 2 * int + (7 * int + 8 * mav + 4 * str + 2 * vit + variation) * skillPower,
        //       1
        //     );
        //   };
        //   skillInfo.range = [180, 100];
        //   improvedByBonus = true;
        //   break;
        // Esprit de flammes
        case 3:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              30 +
                2 * lv +
                2 * int +
                (7 * int + 6 * mav + variation) * attackFactor * skillPower,
              1
            );
          };
          skillInfo.range = [200, 500];
          break;
        // Frappe de l'esprit
        // case 5:
        //   skillFormula = function (mav, variation) {
        //     return floorMultiplication(
        //       40 + 2 * lv + 2 * int + (2 * vit + 2 * dex + 13 * int + 6 * mav + variation) * attackFactor * skillPower,
        //       1
        //     );
        //   };
        //   skillInfo.range = [180, 200];
        //   break;
        // Orbe des ténèbres
        case 6:
          skillFormula = function (mav) {
            return floorMultiplication(
              120 +
                6 * lv +
                (5 * vit + 5 * dex + 29 * int + 9 * mav) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Vague mortelle
        case 9:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              120 +
                6 * lv +
                (5 * vit + 5 * dex + 30 * int + variation + 9 * mav) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "dragon") {
      switch (skillId) {
        // Talisman volant
        case 1:
          skillFormula = function (mav) {
            return floorMultiplication(
              70 +
                5 * lv +
                (18 * int + 7 * str + 5 * mav + 50) * attackFactor * skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [4, 10];
          improvedByBonus = true;
          break;
        // Dragon chassant
        case 2:
          skillFormula = function (mav) {
            return floorMultiplication(
              60 +
                5 * lv +
                (16 * int + 6 * dex + 6 * mav + 120) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [4, 10];
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Rugissement du dragon
        case 3:
          skillFormula = function (mav) {
            return floorMultiplication(
              70 +
                3 * lv +
                (20 * int + 3 * str + 10 * mav + 100) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [4, 10];
          improvedByBonus = true;
          break;
        // Météore
        case 9:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              120 +
                6 * lv +
                (5 * vit + 5 * dex + 30 * int + variation + 9 * mav) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    } else if (attackerClass === "heal") {
      switch (skillId) {
        // Jet de foudre
        case 1:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              60 +
                5 * lv +
                (8 * int + 2 * dex + 8 * mav + variation) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [6, 10];
          skillInfo.range = [5 * int, 15 * int];
          improvedByBonus = true;
          break;
        // Invocation de foudre
        case 2:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              40 +
                4 * lv +
                (13 * int + 2 * str + 10 * mav + variation) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [6, 10];
          skillInfo.range = [5 * int, 16 * int];
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Griffe de foudre
        case 3:
          skillFormula = function (mav, variation) {
            return floorMultiplication(
              50 +
                5 * lv +
                (8 * int + 2 * str + 8 * mav + variation) *
                  attackFactor *
                  skillPower,
              1
            );
          };
          skillInfo.range = [1, 800];
          improvedByBonus = true;
          break;
      }
    } else if (attackerClass === "lycan") {
      switch (skillId) {
        // Déchiqueter
        // case 1:
        //   skillFormula = function (atk) {
        //     return floorMultiplication(
        //       1.1 * atk + (0.3 * atk + 1.5 * str) * skillPower,
        //       1
        //     );
        //   };
        //   skillInfo.weaponBonus = [5, 54];
        //   improvedByBonus = true;
        //   break;
        // Souffle de loup
        case 2:
          skillFormula = function (atk) {
            return floorMultiplication(
              2 * atk + (atk + 3 * dex + 5 * str + vit) * skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [5, 35];
          improvedByBonus = true;
          improvedBySkillBonus = true;
          break;
        // Bond de loup
        case 3:
          skillFormula = function (atk) {
            return floorMultiplication(
              atk + (1.6 * atk + 200 + 7 * dex + 7 * str) * skillPower,
              1
            );
          };
          skillInfo.weaponBonus = [5, 35];
          improvedByBonus = true;
          break;
        // Griffe de loup
        case 4:
          skillFormula = function (atk) {
            return floorMultiplication(
              3 * atk + (0.8 * atk + 6 * str + 2 * dex + vit) * skillPower,
              1
            );
          };
          improvedByBonus = true;
          break;
        // Tempête cinglante
        case 9:
          skillFormula = function (atk, variation) {
            return floorMultiplication(
              1.8 * atk +
                (atk + 6 * dex + variation + 3 * str + lv) * skillPower,
              1
            );
          };
          skillInfo.range = [1, 1000];
          break;
      }
    }
    if (improvedBySkillBonus) {
      skillInfo.skillBonus =
        16 * getSkillPower(attacker.skillBonus, skillPowerTable);

      var skillWardChoice = victim.skillWardChoice;

      if (skillWardChoice && skillWardChoice === attackerClass) {
        skillInfo.skillWard =
          24 * getSkillPower(victim.skillWard, skillPowerTable);
      }
    }

    if (improvedByBonus) {
      skillInfo.skillBonusByBonus = attacker["skillBonus" + skillId];
    }

    if (removeSkillVariation) {
      var averageVariation = (skillInfo.range[0] + skillInfo.range[0]) / 2;
      skillInfo.range = [averageVariation, averageVariation];
    }
  } else {
    var skillPower = getSkillPower(
      attacker["horseSkill" + skillId],
      skillPowerTable
    );

    switch (skillId) {
      // Combat équestre
      case 137:
        skillFormula = function (atk) {
          return floorMultiplication(atk + 2 * atk * skillPower, 1);
        };
        break;
      // Charge à cheval
      case 138:
        skillFormula = function (atk) {
          return floorMultiplication(
            2.4 * (200 + 1.5 * lv) + 600 * skillPower,
            1
          );
        };
        break;
      // Vague de Pouvoir
      case 139:
        skillFormula = function (atk) {
          return floorMultiplication(
            2 * (200 + 1.5 * lv) + 600 * skillPower,
            1
          );
        };
        break;
      // Grêle de flèches
      case 140:
        skillFormula = function (atk) {
          return floorMultiplication(atk + 2 * atk * skillPower, 1);
        };
        break;
    }
  }

  updateBattleValues(battleValues, skillFormula, skillInfo);
}

function calcMagicAttackValueAugmentation(
  magicAttackValueWeapon,
  magicAttackValueBonus
) {
  if (magicAttackValueBonus) {
    return Math.max(
      1,
      0.0025056 *
        magicAttackValueBonus ** 0.602338 *
        magicAttackValueWeapon ** 1.20476
    );
  }
  return 0;
}

function getMagicAttackValueAugmentation(
  minMagicAttackValue,
  maxMagicAttackValue,
  magicAttackValueBonus
) {
  var magicAttackValueAugmentation = [];

  for (
    var magicAttackValue = minMagicAttackValue;
    magicAttackValue <= maxMagicAttackValue;
    magicAttackValue++
  ) {
    magicAttackValueAugmentation.push(
      calcMagicAttackValueAugmentation(magicAttackValue, magicAttackValueBonus)
    );
  }

  return magicAttackValueAugmentation;
}

function calcPhysicalDamages(battleValues) {
  var {
    attackFactor,
    mainAttackValue,
    attackValues: { minAttackValue, maxAttackValue, attackValueOther, weights },
    bonusValues,
    damagesTypeCombinaison,
  } = battleValues;

  var damagesWeightedByType = {};

  if (bonusValues.missPercentage) {
    damagesWeightedByType.miss = bonusValues.missPercentage / 100;
  }

  for (var damagesType of damagesTypeCombinaison) {
    if (!damagesType.weight) {
      continue;
    }

    var damagesWeighted = {};
    damagesWeightedByType[damagesType.name] = damagesWeighted;

    for (
      var attackValue = minAttackValue;
      attackValue <= maxAttackValue;
      attackValue++
    ) {
      var weight = weights[attackValue - minAttackValue] * damagesType.weight;

      var secondaryAttackValue = 2 * attackValue + attackValueOther;
      var rawDamages =
        mainAttackValue +
        floorMultiplication(attackFactor, secondaryAttackValue);

      var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
        rawDamages,
        bonusValues
      );

      var minPiercingDamages =
        damagesWithPrimaryBonuses -
        bonusValues.defenseBoost +
        bonusValues.defenseMarriage;

      if (minPiercingDamages <= 2) {
        for (var damages = 1; damages <= 5; damages++) {
          var finalDamages = calcDamageWithSecondaryBonuses(
            damages,
            bonusValues,
            damagesType,
            minPiercingDamages,
            damagesWithPrimaryBonuses
          );

          addKeyValue(damagesWeighted, finalDamages, weight / 5);
        }
      } else {
        var finalDamages = calcDamageWithSecondaryBonuses(
          minPiercingDamages,
          bonusValues,
          damagesType,
          minPiercingDamages,
          damagesWithPrimaryBonuses
        );

        addKeyValue(damagesWeighted, finalDamages, weight);
      }
    }
  }

  return damagesWeightedByType;
}

function calcPhysicalSkillDamages(battleValues) {
  var {
    attackFactor,
    mainAttackValue,
    attackValues: { minAttackValue, maxAttackValue, attackValueOther, weights },
    bonusValues,
    damagesTypeCombinaison,
    skillFormula,
    skillRange: [minVariation, maxVariation],
  } = battleValues;

  var damagesWeightedByType = {};

  for (var damagesType of damagesTypeCombinaison) {
    if (!damagesType.weight) {
      continue;
    }

    var damagesWeighted = {};
    var savedDamages = {};

    damagesWeightedByType[damagesType.name] = damagesWeighted;

    for (
      var attackValue = minAttackValue;
      attackValue <= maxAttackValue;
      attackValue++
    ) {
      var weight = weights[attackValue - minAttackValue] * damagesType.weight;

      var secondaryAttackValue = 2 * attackValue + attackValueOther;
      var rawDamages =
        mainAttackValue +
        floorMultiplication(attackFactor, secondaryAttackValue);

      var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
        rawDamages,
        bonusValues
      );

      for (
        var variation = minVariation;
        variation <= maxVariation;
        variation++
      ) {
        if (damagesWithPrimaryBonuses <= 2) {
          for (var damages = 1; damages <= 5; damages++) {
            damages *= bonusValues.useDamages;

            var damagesWithFormula = skillFormula(damages, variation);

            damagesWithFormula = Math.floor(
              (damagesWithFormula * bonusValues.weaponBonusCoeff) / 100
            );

            var finalDamages = calcSkillDamageWithSecondaryBonuses(
              damagesWithFormula,
              bonusValues,
              damagesType,
              damagesWithPrimaryBonuses
            );

            addKeyValue(damagesWeighted, finalDamages, weight / 5);
          }
        } else {
          damagesWithPrimaryBonuses *= bonusValues.useDamages;

          var damagesWithFormula = skillFormula(
            damagesWithPrimaryBonuses,
            variation
          );

          if (savedDamages.hasOwnProperty(damagesWithFormula)) {
            var finalDamages = savedDamages[damagesWithFormula];
            damagesWeighted[finalDamages] += weight;
            continue;
          }

          var finalDamages = Math.floor(
            (damagesWithFormula * bonusValues.weaponBonusCoeff) / 100
          );

          finalDamages = calcSkillDamageWithSecondaryBonuses(
            finalDamages,
            bonusValues,
            damagesType,
            damagesWithPrimaryBonuses
          );

          savedDamages[damagesWithFormula] = finalDamages;
          addKeyValue(damagesWeighted, finalDamages, weight);
        }
      }
    }
  }

  return damagesWeightedByType;
}

function calcMagicSkillDamages(battleValues) {
  var {
    attackValues: {
      minMagicAttackValue,
      maxMagicAttackValue,
      magicAttackValueAugmentation,
      weights,
    },
    bonusValues,
    damagesTypeCombinaison,
    skillFormula,
    skillRange: [minVariation, maxVariation],
  } = battleValues;

  var damagesWeightedByType = {};

  for (var damagesType of damagesTypeCombinaison) {
    if (!damagesType.weight) {
      continue;
    }

    var damagesWeighted = {};
    var savedDamages = {};

    damagesWeightedByType[damagesType.name] = damagesWeighted;

    for (
      var magicAttackValue = minMagicAttackValue;
      magicAttackValue <= maxMagicAttackValue;
      magicAttackValue++
    ) {
      var index = magicAttackValue - minMagicAttackValue;
      var weight = weights[index] * damagesType.weight;

      for (
        var variation = minVariation;
        variation <= maxVariation;
        variation++
      ) {
        var rawDamages = skillFormula(
          magicAttackValue + magicAttackValueAugmentation[index],
          variation
        );

        if (savedDamages.hasOwnProperty(rawDamages)) {
          var finalDamages = savedDamages[rawDamages];
          damagesWeighted[finalDamages] += weight;
          continue;
        }

        var damagesWithPrimaryBonuses = Math.floor(
          (rawDamages * bonusValues.weaponBonusCoeff) / 100
        );

        damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
          damagesWithPrimaryBonuses,
          bonusValues
        );

        if (damagesWithPrimaryBonuses <= 2) {
          for (var damages = 1; damages <= 5; damages++) {
            var finalDamages = calcSkillDamageWithSecondaryBonuses(
              damages,
              bonusValues,
              damagesType,
              damagesWithPrimaryBonuses
            );
            addKeyValue(damagesWeighted, finalDamages, weight / 5);
          }
        } else {
          var finalDamages = calcSkillDamageWithSecondaryBonuses(
            damagesWithPrimaryBonuses,
            bonusValues,
            damagesType,
            damagesWithPrimaryBonuses
          );

          savedDamages[rawDamages] = finalDamages;
          addKeyValue(damagesWeighted, finalDamages, weight);
        }
      }
    }
  }

  return damagesWeightedByType;
}

function calcDamages(
  attacker,
  victim,
  attackType,
  battle,
  removeSkillVariation
) {
  var damagesCalculator, skillId, skillType;

  if (attackType === "physical") {
    damagesCalculator = calcPhysicalDamages;
  } else if (attackType.startsWith("attackSkill")) {
    skillId = Number(attackType.split("attackSkill")[1]);

    if (isMagicClass(attacker) || isDispell(attacker, skillId)) {
      skillType = "magic";
      damagesCalculator = calcMagicSkillDamages;
    } else {
      skillType = "physical";
      damagesCalculator = calcPhysicalSkillDamages;
    }
  } else if (attackType.startsWith("horseSkill")) {
    skillType = "physical";
    skillId = Number(attackType.split("horseSkill")[1]);
    damagesCalculator = calcPhysicalSkillDamages;
  }

  var battleValues = createBattleValues(attacker, victim, battle, skillType);

  if (skillId) {
    getSkillFormula(battle, skillId, battleValues, removeSkillVariation);
  }

  var {
    attackValues: { totalCardinal, possibleDamagesCount },
  } = battleValues;

  return {
    damagesWeightedByType: damagesCalculator(battleValues),
    totalCardinal: totalCardinal,
    possibleDamagesCount: possibleDamagesCount,
    skillType: skillType,
  };
}

function damagesWithoutVariation(
  attacker,
  victim,
  attackType,
  battle,
  characters
) {
  startDamagesTime = performance.now();

  var {
    damagesWeightedByType,
    totalCardinal,
    possibleDamagesCount,
    skillType,
  } = calcDamages(attacker, victim, attackType, battle);

  endDamagesTime = performance.now();

  possibleDamagesCount = displayResults(
    possibleDamagesCount,
    totalCardinal,
    damagesWeightedByType,
    battle,
    attacker.name,
    victim.name
  );

  endDisplayTime = performance.now();

  displayFightInfo(
    possibleDamagesCount,
    endDamagesTime - startDamagesTime,
    endDisplayTime - endDamagesTime,
    battle
  );
  addPotentialErrorInformation(
    battle.errorInformation,
    attacker,
    victim,
    skillType,
    characters
  );

  hideElement(battle.bonusVariationResultContainer);
  showElement(battle.fightResultContainer);
}

function damagesWithVariation(
  attacker,
  victim,
  attackType,
  battle,
  entity,
  entityVariation
) {
  startTime = performance.now();
  var damagesByBonus = [];
  var augmentationByBonus = [];
  var {
    bonusVariationMinValue: minVariation,
    bonusVariationMaxValue: maxVariation,
  } = entity;
  var step = Math.ceil((maxVariation - minVariation + 1) / 500);
  var simulationCount = 0;
  var simulationTime;

  for (
    var bonusValue = minVariation;
    bonusValue <= maxVariation;
    bonusValue += step
  ) {
    entity[entityVariation] = bonusValue;

    var { damagesWeightedByType, totalCardinal } = calcDamages(
      copyObject(attacker),
      copyObject(victim),
      attackType,
      battle,
      true
    );

    var meanDamages = calcMeanDamages(damagesWeightedByType, totalCardinal);

    if (bonusValue === minVariation) {
      var firstDamages = Math.max(meanDamages, 1e-3);
    }

    damagesByBonus.push({ x: bonusValue, y: meanDamages });
    augmentationByBonus.push({
      x: bonusValue,
      y: meanDamages / firstDamages - 1,
    });
    simulationCount++;
  }

  endTime = performance.now();

  battle.damagesByBonus = damagesByBonus.concat(entityVariation);

  addToBonusVariationChart(
    damagesByBonus,
    augmentationByBonus,
    entity.bonusVariationDisplay,
    battle.bonusVariationChart
  );

  simulationCount = battle.numberFormats.default.format(simulationCount);
  simulationTime = battle.numberFormats.second.format(
    (endTime - startTime) / 1000
  );

  battle.simulationCounter.textContent = simulationCount;
  battle.simulationTime.textContent = simulationTime;

  hideElement(battle.fightResultContainer);
  showElement(battle.bonusVariationResultContainer);

  if (
    isChecked(attacker.bonusVariationActivation) &&
    isChecked(victim.bonusVariationActivation)
  ) {
    showElement(battle.errorInformation["attacker-victim-variation"]);
  } else {
    hideElement(battle.errorInformation["attacker-victim-variation"]);
  }
}

function changeMonsterValues(monster, instance, attacker) {
  switch (instance) {
    case "SungMahiTower":
      var sungMahiFloor = 1;
      var sungMahiStep = 1;
      var rawDefense = 120;

      if (isPC(attacker)) {
        sungMahiFloor = attacker.sungMahiFloor;
        sungMahiStep = attacker.sungMahiStep;
      }

      if (monster.rank === 5) {
        monster.level = 121;
        monster.dex = 75;
        rawDefense += 1;
      } else if (monster.rank === 6) {
        monster.level = 123;
        monster.dex = 75;
        rawDefense += 1;
      } else {
        monster.level = 120;
        monster.dex = 68;
      }
      monster.vit = 100;
      monster.rawDefense = rawDefense + (sungMahiStep - 1) * 6;
      monster.fistDefense = 0;
      monster.swordDefense = 0;
      monster.twoHandedSwordDefense = 0;
      monster.daggerDefense = 0;
      monster.bellDefense = 0;
      monster.fanDefense = 0;
      monster.arrowDefense = 0;
      monster.clawDefense = 0;
      monster.magicResistance = 0;
      monster.fireResistance = -20;
  }
}

function createWeapon(weaponVnum) {
  var weapon = weaponData[weaponVnum];
  var weaponName = weapon[0];

  return {
    name: weaponName,
    type: weapon[1],
    minAttackValue: weapon[2][2],
    maxAttackValue: weapon[2][3],
    minMagicAttackValue: weapon[2][0],
    maxMagicAttackValue: weapon[2][1],
    upgrades: weapon[3],
    isSerpent: isValueInArray("serpent", weaponName.toLowerCase()),
  };
}

function createMonster(monsterVnum, attacker) {
  var monsterAttributes = monsterData[monsterVnum];

  var monster = {
    name: monsterAttributes[36],
    rank: monsterAttributes[0],
    race: monsterAttributes[1],
    attack: monsterAttributes[2],
    level: monsterAttributes[3],
    type: monsterAttributes[4],
    str: monsterAttributes[5],
    dex: monsterAttributes[6],
    vit: monsterAttributes[7],
    int: monsterAttributes[8],
    minAttackValue: monsterAttributes[9],
    maxAttackValue: monsterAttributes[10],
    rawDefense: monsterAttributes[11],
    criticalHit: monsterAttributes[12],
    piercingHit: monsterAttributes[13],
    fistDefense: monsterAttributes[14],
    swordDefense: monsterAttributes[15],
    twoHandedSwordDefense: monsterAttributes[16],
    daggerDefense: monsterAttributes[17],
    bellDefense: monsterAttributes[18],
    fanDefense: monsterAttributes[19],
    arrowDefense: monsterAttributes[20],
    clawDefense: monsterAttributes[21],
    fireResistance: monsterAttributes[22],
    lightningResistance: monsterAttributes[23],
    magicResistance: monsterAttributes[24],
    windResistance: monsterAttributes[25],
    lightningBonus: monsterAttributes[26],
    fireBonus: monsterAttributes[27],
    iceBonus: monsterAttributes[28],
    windBonus: monsterAttributes[29],
    earthBonus: monsterAttributes[30],
    darknessBonus: monsterAttributes[31],
    darknessResistance: monsterAttributes[32],
    iceResistance: monsterAttributes[33],
    earthResistance: monsterAttributes[34],
    damageMultiplier: monsterAttributes[35],
  };

  // monster.instance = 0;

  // if (attacker && monster.instance === 0) {
  //   changeMonsterValues(monster, "SungMahiTower", attacker);
  // }

  monster.defense = monster.rawDefense + monster.level + monster.vit;

  return monster;
}

function addPotentialErrorInformation(
  errorInformation,
  attacker,
  victim,
  skillType,
  characters
) {
  for (var error of Object.values(errorInformation)) {
    hideElement(error);
  }

  if (isPC(attacker)) {
    if (isRiding(attacker)) {
      if (attacker.horsePoint === 0) {
        showElement(errorInformation["horse-level"]);
      }
      showElement(errorInformation["horse-stat"]);
    } else if (isPolymorph(attacker)) {
      if (attacker.polymorphPoint === 0) {
        showElement(errorInformation["polymorph-level"]);
      }

      if (
        (attacker.polymorphPoint <= 39 && attacker.attackValuePercent <= 199) ||
        (attacker.polymorphPoint === 40 && attacker.attackValuePercent <= 299)
      ) {
        showElement(errorInformation["polymorph-bonus"]);
      }
    }
    if (skillType === "magic") {
      if (attacker.magicAttackValue) {
        showElement(errorInformation["magic-attack-value-bonus"]);
      }
      if (victim.magicResistance) {
        showElement(errorInformation["magic-resistance"]);
      }
    }
  } else {
    showElement(errorInformation["monster-attacker"]);
    if (isMagicAttacker(attacker) && victim.magicResistance) {
      showElement(errorInformation["magic-resistance"]);
    }
  }

  if (isPC(victim)) {
    if (isRiding(victim)) {
      showElement(errorInformation["horse-stat"]);
    } else if (isPolymorph(victim)) {
      if (attacker.polymorphPoint === 0) {
        showElement(errorInformation["polymorph-level"]);
      }
      showElement(errorInformation["polymorph-defense"]);
    }
  }

  if (characters.unsavedChanges) {
    showElement(errorInformation["save"]);
  }
}

function reduceChartPointsListener(battle) {
  var {
    reduceChartPointsContainer,
    reduceChartPoints,
    numberFormats: { second: numberFormat },
    displayTime,
  } = battle;

  reduceChartPoints.addEventListener("change", function () {
    var startDisplayTime = performance.now();
    var scatterDataByType = battle.scatterDataByType;
    var {
      chart,
      maxPoints,
      chart: {
        data: { datasets },
      },
    } = battle.damagesChart;
    var addAnimations = false;

    for (var index = 0; index < datasets.length; index++) {
      var dataset = datasets[index];
      var scatterData = scatterDataByType[dataset.name];

      if (dataset.canBeReduced && reduceChartPoints.checked) {
        dataset.data = aggregateDamages(scatterData, maxPoints);
        addAnimations = true;
      } else {
        dataset.data = scatterData;
      }
    }

    handleChartAnimations(chart, addAnimations);
    chart.update();

    displayTime.textContent = numberFormat.format(
      (performance.now() - startDisplayTime) / 1000
    );
  });

  reduceChartPointsContainer.addEventListener("pointerup", function (event) {
    if (event.pointerType === "mouse") {
      reduceChartPoints.click();
    }
  });
}

function downloadRawDataListener(battle) {
  var { downLoadRawData, downLoadRawDataVariation } = battle;
  var fileType = "text/csv;charset=utf-8;";

  downLoadRawData.addEventListener("click", function () {
    var damagesWeightedByType = battle.damagesWeightedByType;
    var filename = "raw_damages.csv";
    var csvContent = "damage,probabilities,damageType\n";

    for (var damagesType in damagesWeightedByType) {
      var damagesWeighted = damagesWeightedByType[damagesType];

      for (var damages in damagesWeighted) {
        csvContent +=
          damages + "," + damagesWeighted[damages] + "," + damagesType + "\n";
      }
    }

    downloadData(csvContent, fileType, filename);
  });

  downLoadRawDataVariation.addEventListener("click", function () {
    var damagesByBonus = battle.damagesByBonus;
    var damagesByBonusLength = damagesByBonus.length;
    var filename = "damages_variation.csv";

    if (!damagesByBonusLength) {
      return;
    }

    var csvContent =
      damagesByBonus[damagesByBonusLength - 1] + ",averageDamage\n";

    for (var index = 0; index < damagesByBonusLength - 1; index++) {
      var row = damagesByBonus[index];

      csvContent += row.x + "," + row.y + "\n";
    }

    downloadData(csvContent, fileType, filename);
  });
}

function displayResults(
  possibleDamagesCount,
  totalCardinal,
  damagesWeightedByType,
  battle,
  attackerName,
  victimName
) {
  var [
    meanDamages,
    minDamages,
    maxDamages,
    scatterDataByType,
    possibleDamagesCount,
    uniqueDamagesCount,
  ] = prepareDamagesData(
    damagesWeightedByType,
    possibleDamagesCount,
    totalCardinal
  );

  addToDamagesChart(
    scatterDataByType,
    battle.damagesChart,
    battle.reduceChartPoints.checked
  );
  updateDamagesChartDescription(
    battle.uniqueDamagesCounters,
    uniqueDamagesCount,
    battle.numberFormats.default
  );
  displayFightResults(
    battle,
    attackerName,
    victimName,
    meanDamages,
    minDamages,
    maxDamages
  );
  battle.damagesWeightedByType = damagesWeightedByType;
  battle.scatterDataByType = scatterDataByType;

  return possibleDamagesCount;
}

function displayFightResults(
  battle,
  attackerName,
  victimName,
  meanDamages,
  minDamages,
  maxDamages
) {
  var {
    tableResultFight,
    tableResultHistory,
    attackTypeSelection,
    savedFights,
    numberFormats: { default: numberFormat },
    deleteFightTemplate,
  } = battle;

  hideElement(tableResultHistory.rows[1]);

  var valuesToDisplay = [
    attackerName,
    victimName,
    attackTypeSelection.options[attackTypeSelection.selectedIndex].textContent,
    meanDamages,
    minDamages,
    maxDamages,
  ];

  savedFights.push(valuesToDisplay);
  updateSavedFights(savedFights);

  editTableResultRow(tableResultFight.rows[1], valuesToDisplay, numberFormat);
  addRowToTableResultHistory(
    tableResultHistory,
    valuesToDisplay,
    deleteFightTemplate,
    numberFormat
  );
}

function displayFightInfo(
  possibleDamagesCount,
  damagesTime,
  displayTime,
  battle
) {
  var container = battle.possibleDamagesCounter.parentElement;

  if (possibleDamagesCount <= 1) {
    hideElement(container);
    return;
  } else {
    showElement(container);
  }

  possibleDamagesCount =
    battle.numberFormats.default.format(possibleDamagesCount);
  damagesTime = battle.numberFormats.second.format(damagesTime / 1000);
  displayTime = battle.numberFormats.second.format(displayTime / 1000);

  battle.possibleDamagesCounter.textContent = possibleDamagesCount;
  battle.damagesTime.textContent = damagesTime;
  battle.displayTime.textContent = displayTime;
}

function isPseudoSaved(characters, pseudo) {
  return characters.savedCharacters.hasOwnProperty(pseudo);
}

function createBattle(characters, battle) {
  battle.battleForm.addEventListener("submit", function (event) {
    event.preventDefault();

    // auto save
    if (characters.unsavedChanges) {
      characters.saveButton.click();
    }

    var battleInfo = new FormData(event.target);
    var attackerName = battleInfo.get("attacker");
    var attackType = battleInfo.get("attackTypeSelection");
    var victimName = battleInfo.get("victim");
    var attackerVariation;
    var victimVariation;

    if (!attackerName && !attackType && !victimName) {
      return;
    }

    if (isPseudoSaved(characters, attackerName)) {
      var attacker = copyObject(characters.savedCharacters[attackerName]);
      attackerVariation = attacker.bonusVariation;
    } else {
      var attacker = createMonster(attackerName);
    }

    if (isPseudoSaved(characters, victimName)) {
      var victim = copyObject(characters.savedCharacters[victimName]);
      victimVariation = victim.bonusVariation;
    } else {
      var victim = createMonster(victimName, attacker);
    }

    if (
      isChecked(attacker.bonusVariationActivation) &&
      attacker.hasOwnProperty(attackerVariation) &&
      attacker.bonusVariationMinValue < attacker.bonusVariationMaxValue
    ) {
      damagesWithVariation(
        attacker,
        victim,
        attackType,
        battle,
        attacker,
        attackerVariation
      );
    } else if (
      isChecked(victim.bonusVariationActivation) &&
      victim.hasOwnProperty(victimVariation) &&
      victim.bonusVariationMinValue < victim.bonusVariationMaxValue
    ) {
      damagesWithVariation(
        attacker,
        victim,
        attackType,
        battle,
        victim,
        victimVariation
      );
    } else {
      damagesWithoutVariation(attacker, victim, attackType, battle, characters);
    }
  });
}

function createMapping() {
  mapping = {
    typeFlag: [
      "animalBonus", // 0
      "humanBonus", // 1
      "orcBonus", // 2
      "mysticBonus", // 3
      "undeadBonus", // 4
      "insectBonus", // 5
      "desertBonus", // 6
      "devilBonus", // 7
    ],
    raceBonus: {
      warrior: "warriorBonus",
      sura: "suraBonus",
      ninja: "ninjaBonus",
      shaman: "shamanBonus",
      lycan: "lycanBonus",
    },
    raceResistance: {
      warrior: "warriorResistance",
      sura: "suraResistance",
      ninja: "ninjaResistance",
      shaman: "shamanResistance",
      lycan: "lycanResistance",
    },
    defenseWeapon: [
      "swordDefense", // 0
      "daggerDefense", // 1
      "arrowDefense", // 2
      "twoHandedSwordDefense", // 3
      "bellDefense", // 4
      "clawDefense", // 5
      "fanDefense", // 6
      "swordDefense", // 7
      "fistDefense", // 8
    ],
    breakWeapon: [
      "breakSwordDefense", // 0
      "breakDaggerDefense", // 1
      "breakArrowDefense", // 2
      "breakTwoHandedSwordDefense", // 3
      "breakBellDefense", // 4
      "breakClawDefense", // 5
      "breakFanDefense", // 6
      "breakSwordDefense", // 7
    ],
    elementBonus: [
      "fireBonus", // 0
      "iceBonus", // 1
      "windBonus", // 2
      "lightningBonus", // 3
      "earthBonus", // 4
      "darknessBonus", // 5
    ],
    elementResistance: [
      "fireResistance", // 0
      "iceResistance", // 1
      "windResistance", // 2
      "lightningResistance", // 3
      "earthResistance", // 4
      "darknessResistance", // 5
    ],
  };
  return mapping;
}

function createConstants() {
  var constants = {
    polymorphPowerTable: [
      10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 26, 27,
      29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 59, 62, 66, 70, 74, 79,
      84, 89, 94, 100, 0,
    ],
    skillPowerTable: [
      0, 0.05, 0.06, 0.08, 0.1, 0.12, 0.14, 0.16, 0.18, 0.2, 0.22, 0.24, 0.26,
      0.28, 0.3, 0.32, 0.34, 0.36, 0.38, 0.4, 0.5, 0.52, 0.54, 0.56, 0.58, 0.6,
      0.63, 0.66, 0.69, 0.72, 0.82, 0.85, 0.88, 0.91, 0.94, 0.98, 1.02, 1.06,
      1.1, 1.15, 1.25,
    ],
    marriageTable: {
      harmonyEarrings: [4, 5, 6, 8],
      loveEarrings: [4, 5, 6, 8],
      harmonyBracelet: [4, 5, 6, 8],
      loveNecklace: [20, 25, 30, 40],
      harmonyNecklace: [12, 16, 20, 30],
    },
    allowedWeaponsPerRace: {
      warrior: [0, 3, 8],
      ninja: [0, 1, 2, 8],
      sura: [0, 7, 8],
      shaman: [4, 6, 8],
      lycan: [5, 8],
    },
    translation: {
      fr: {
        damages: "Dégâts",
        percentage: "Pourcentage",
        miss: "Miss",
        normalHit: "Coup classique",
        criticalHit: "Coup critique",
        piercingHit: "Coup perçant",
        criticalPiercingHit: "Coup critique perçant",
        damagesRepartition: "Distribution des dégâts",
        averageDamages: "Dégâts moyens",
        damagesAugmentation: "Augmentation des dégâts",
        bonusVariationTitle: [
          "Évolution des dégâts moyens",
          "par rapport à la valeur d'un bonus",
        ],
      },
      en: {
        damages: "Damage",
        percentage: "Percentage",
        miss: "Miss",
        normalHit: "Normal Hit",
        criticalHit: "Critical Hit",
        piercingHit: "Piercing Hit",
        criticalPiercingHit: "Critical Piercing Hit",
        damagesRepartition: "Damage Repartition",
        averageDamages: "Average Damage",
        damagesAugmentation: "Damage Augmentation",
        bonusVariationTitle: [
          "Evolution of Average Damage",
          "Relative to a Bonus Value",
        ],
      },
      tr: {
        damages: "Hasar",
        percentage: "Yüzde",
        miss: "Miss Vuruş",
        normalHit: "Düz Vuruş",
        criticalHit: "Kritik Vuruş",
        piercingHit: "Delici Vuruş",
        criticalPiercingHit: "Kritikli Delici Vuruş",
        damagesRepartition: "Hasar Dağılımı",
        averageDamages: "Ortalama Hasar",
        damagesAugmentation: "Ortalama Hasar Artışı",
        bonusVariationTitle: [
          "Bir bonusun değerine kıyasla",
          "Ortalama Hasar Çizelgesi",
        ],
      },
      ro: {
        damages: "Daune",
        percentage: "Procent",
        miss: "Miss",
        normalHit: "Lovitura normala",
        criticalHit: "Lovitura critica",
        piercingHit: "Lovitura patrunzatoare",
        criticalPiercingHit: "Lovitura critica si patrunzatoare",
        damagesRepartition: "Distribuția daunelor",
        averageDamages: "Media damageului",
        damagesAugmentation: "Damage imbunatatit",
        bonusVariationTitle: [
          "Evolutia mediei damageului",
          "relativ la o valoare bonus",
        ],
      },
      de: {
        damages: "Schäden",
        percentage: "Prozentsatz",
        miss: "Verfehlen",
        normalHit: "Normaler Treffer",
        criticalHit: "Kritischer Treffer",
        piercingHit: "Durchdringender Treffer",
        criticalPiercingHit: "Kritischer durchdringender Treffer",
        damagesRepartition: "Schadensverteilung",
        averageDamages: "Durchschnittlicher Schaden",
        damagesAugmentation: "Schadenserhöhung",
        bonusVariationTitle: [
          "Entwicklung des durchschnittlichen Schadens",
          "im Verhältnis zu einem Bonus",
        ],
      },
      pt: {
        damages: "Dano",
        percentage: "Percentagem",
        miss: "Miss",
        normalHit: "Dano normal",
        criticalHit: "Dano crítico",
        piercingHit: "Dano perfurante",
        criticalPiercingHit: "Dano crítico perfurante",
        damagesRepartition: "Repartição de dano",
        averageDamages: "Dano médio",
        damagesAugmentation: "Aumento de dano",
        bonusVariationTitle: ["Evolução do dano médio", "relativo a um bónus"],
      },
      // es: {
      //   damages: "Daño",
      //   percentage: "Porcentaje",
      //   miss: "Miss",
      //   normalHit: "Daño normal",
      //   criticalHit: "Daño crítico",
      //   piercingHit: "Daño perforante",
      //   criticalPiercingHit: "Daño crítico perforante",
      //   damagesRepartition: "Repartición de daños",
      //   averageDamages: "Daño medio",
      //   damagesAugmentation: "Aumento de daño",
      //   bonusVariationTitle: ["Evolución del daño medio", "Relativo a una bonificación"]
      // },
    },
  };
  return constants;
}

function initResultTableHistory(battle) {
  var {
    tableResultHistory,
    savedFights,
    deleteFightTemplate,
    numberFormats: { default: numberFormat },
  } = battle;
  var startIndex = 3;

  if (savedFights.length) {
    hideElement(tableResultHistory.rows[1]);

    for (var savedFight of savedFights) {
      addRowToTableResultHistory(
        tableResultHistory,
        savedFight,
        deleteFightTemplate,
        numberFormat
      );
    }
  }

  tableResultHistory.addEventListener("click", function (event) {
    var deleteButton = event.target.closest(".svg-icon-delete");

    if (deleteButton) {
      var row = deleteButton.closest("tr");

      if (row) {
        savedFights.splice(row.rowIndex - startIndex, 1);
        updateSavedFights(savedFights);

        row.remove();

        if (tableResultHistory.rows.length === startIndex) {
          showElement(tableResultHistory.rows[1]);
        }
      }
    }
  });
}

function initDamagesChart(battle) {
  var { translation, reduceChartPointsContainer, reduceChartPoints } = battle;
  var percentFormat = battle.numberFormats.percent;
  var customPlugins = {
    id: "customPlugins",
    afterDraw(chart) {
      var missPercentage = chart.data.missPercentage;

      if (!missPercentage) {
        return;
      }

      var {
        ctx,
        chartArea: { top, right },
      } = chart;
      ctx.save();
      var text =
        translation.miss + " : " + percentFormat.format(missPercentage);
      var padding = 4;
      var fontSize = 14;

      ctx.font = fontSize + "px Helvetica Neue";

      var textWidth = ctx.measureText(text).width;
      var xPosition = right - textWidth - 5;
      var yPosition = top + 5;

      ctx.fillStyle = "rgba(255, 0, 0, 0.2)";
      ctx.fillRect(
        xPosition - padding,
        yPosition - padding,
        textWidth + 2 * padding,
        fontSize + 2 * padding
      );

      ctx.strokeStyle = "red";
      ctx.strokeRect(
        xPosition - padding,
        yPosition - padding,
        textWidth + 2 * padding,
        fontSize + 2 * padding
      );

      ctx.fillStyle = "#666";
      ctx.textBaseline = "top";
      ctx.fillText(text, xPosition, yPosition + 1);

      ctx.restore();
    },
  };

  Chart.register(customPlugins);

  var ctx = battle.plotDamages.getContext("2d");
  var maxLabelsInTooltip = 10;
  var nullLabelText = " ...";

  var chart = new Chart(ctx, {
    type: "scatter",
    data: {
      missPercentage: 0,
      datasets: [],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: true,
          onHover: function (e) {
            e.native.target.style.cursor = "pointer";
          },
          onLeave: function (e) {
            e.native.target.style.cursor = "default";
          },
          onClick: function (e, legendItem, legend) {
            var currentIndex = legendItem.datasetIndex;
            var ci = legend.chart;
            var isCurrentDatasetVisible = ci.isDatasetVisible(currentIndex);
            var datasets = ci.data.datasets;
            var hideReducePoints = true;
            var isReducePointsChecked = reduceChartPoints.checked;

            datasets[currentIndex].hidden = isCurrentDatasetVisible;
            legendItem.hidden = isCurrentDatasetVisible;

            for (var index in datasets) {
              if (ci.isDatasetVisible(index) && datasets[index].canBeReduced) {
                showElement(reduceChartPointsContainer);
                hideReducePoints = false;
                break;
              }
            }

            if (hideReducePoints) {
              hideElement(reduceChartPointsContainer);
              handleChartAnimations(ci, true);
            } else {
              handleChartAnimations(ci, isReducePointsChecked);
            }

            ci.update();
          },
        },
        title: {
          display: true,
          text: translation.damagesRepartition,
          font: {
            size: 20,
          },
        },
        tooltip: {
          callbacks: {
            label: function (context) {
              if (context.label === null) {
                return nullLabelText;
              }

              var xValue = battle.numberFormats.default.format(
                context.parsed.x
              );
              var yValue = battle.numberFormats.percent.format(
                context.parsed.y
              );

              label =
                " " +
                context.dataset.label +
                " : (" +
                xValue +
                ", " +
                yValue +
                ")";

              return label;
            },
            beforeBody: function (tooltipItems) {
              if (tooltipItems.length > maxLabelsInTooltip + 1) {
                tooltipItems.splice(maxLabelsInTooltip + 1);
                tooltipItems[maxLabelsInTooltip].label = null;
              }
            },
          },
          caretPadding: 10,
        },
      },
      scales: {
        x: {
          type: "linear",
          position: "bottom",
          title: {
            display: true,
            text: translation.damages,
            font: {
              size: 16,
            },
          },
        },
        y: {
          title: {
            display: true,
            text: translation.percentage,
            font: {
              size: 16,
            },
          },
          ticks: {
            format: {
              style: "percent",
            },
          },
        },
      },
      elements: {
        point: {
          borderWidth: 1,
          radius: 3,
          hitRadius: 3,
          hoverRadius: 6,
          hoverBorderWidth: 2,
        },
      },
    },
  });

  var datasetsStyle = [
    {
      name: "normalHit",
      canBeReduced: false,
      label: translation.normalHit,
      backgroundColor: "rgba(75, 192, 192, 0.2)",
      borderColor: "rgba(75, 192, 192, 1)",
    },
    {
      name: "piercingHit",
      canBeReduced: false,
      label: translation.piercingHit,
      backgroundColor: "rgba(192, 192, 75, 0.2)",
      borderColor: "rgba(192, 192, 75, 1)",
    },
    {
      name: "criticalHit",
      canBeReduced: false,
      label: translation.criticalHit,
      backgroundColor: "rgba(192, 75, 192, 0.2)",
      borderColor: "rgba(192, 75, 192, 1)",
    },
    {
      name: "criticalPiercingHit",
      canBeReduced: false,
      label: translation.criticalPiercingHit,
      backgroundColor: "rgba(75, 75, 192, 0.2)",
      borderColor: "rgba(75, 75, 192, 1)",
    },
  ];
  battle.damagesChart = {
    chart: chart,
    datasetsStyle: datasetsStyle,
    maxPoints: 500,
    reduceChartPointsContainer: reduceChartPointsContainer,
  };
}

function initBonusVariationChart(battle) {
  var translation = battle.translation;

  var ctx = battle.plotBonusVariation.getContext("2d");

  var chart = new Chart(ctx, {
    type: "line",
    data: {
      datasets: [
        {
          label: translation.averageDamages,
          backgroundColor: "rgba(75, 192, 192, 0.2)",
          borderColor: "rgba(75, 192, 192, 1)",
          fill: true,
        },
        {
          label: translation.damagesAugmentation,
          backgroundColor: "rgba(192, 192, 75, 0.2)",
          borderColor: "rgba(192, 192, 75, 1)",
          hidden: true,
          yTicksFormat: { style: "percent" },
          fill: true,
        },
      ],
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: true,
          onHover: function (e) {
            e.native.target.style.cursor = "pointer";
          },
          onLeave: function (e) {
            e.native.target.style.cursor = "default";
          },
          onClick: function (e, legendItem, legend) {
            var currentIndex = legendItem.datasetIndex;
            var ci = legend.chart;
            var datasets = ci.data.datasets;
            var isCurrentDatasetVisible = ci.isDatasetVisible(currentIndex);
            var yAxis = ci.options.scales.y;

            var otherIndex = currentIndex === 0 ? 1 : 0;
            var visibleDataset = isCurrentDatasetVisible
              ? datasets[otherIndex]
              : datasets[currentIndex];

            datasets[currentIndex].hidden = isCurrentDatasetVisible;
            datasets[otherIndex].hidden = !isCurrentDatasetVisible;

            yAxis.title.text = visibleDataset.label;
            yAxis.ticks.format = visibleDataset.yTicksFormat;

            ci.update();
          },
        },
        title: {
          display: true,
          text: translation.bonusVariationTitle,
          font: {
            size: 18,
          },
        },
        tooltip: {
          caretPadding: 10,
        },
      },
      scales: {
        x: {
          type: "linear",
          position: "bottom",
          title: {
            display: true,
            text: "Bonus",
            font: {
              size: 16,
            },
          },
          ticks: {
            callback: function (value) {
              if (Number.isInteger(value)) {
                return Number(value);
              }
            },
          },
        },
        y: {
          title: {
            display: true,
            text: translation.averageDamages,
            font: {
              size: 16,
            },
          },
        },
      },
      elements: {
        point: {
          borderWidth: 1,
          radius: 3,
          hitRadius: 3,
          hoverRadius: 6,
          hoverBorderWidth: 2,
        },
      },
    },
  });

  battle.bonusVariationChart = chart;
}

function attackSelectonListener(
  characters,
  attackerSelection,
  attackTypeSelection
) {
  attackerSelection.addEventListener("change", function (event) {
    var attackerName = event.target.value;

    if (isPseudoSaved(characters, attackerName)) {
      var attacker = characters.savedCharacters[attackerName];
      filterAttackTypeSelection(attacker, attackTypeSelection);
    } else {
      filterAttackTypeSelectionMonster(attackTypeSelection);
    }
  });
}

function getTranslation(translation) {
  var userLanguage = navigator.language;
  var langToUse = "en";

  for (var lang in translation) {
    if (userLanguage.startsWith(lang)) {
      langToUse = lang;
      break;
    }
  }

  return translation[langToUse];
}

function createDamageCalculatorInformation(chartSource) {
  var characters = {
    unsavedChanges: false,
    savedCharacters: {},
    currentCharacter: null,
    savedMonsters: getSavedMonsters(),
    characterCreation: document.getElementById("character-creation"),
    addNewCharacterButton: document.getElementById("add-new-character"),
    dropZone: document.getElementById("character-drop-zone"),
    characterInput: document.getElementById("character-input"),
    newCharacterTemplate: document.getElementById("new-character-template")
      .children[0],
    charactersContainer: document.getElementById("characters-container"),
    newMonsterTemplate: document.getElementById("new-monster-template")
      .children[0],
    monstersContainer: document.getElementById("monsters-container"),
    monsterListForm: document.getElementById("monster-list-form"),
    searchMonster: document.getElementById("search-monster"),
    monsterList: document.getElementById("monster-list"),
    saveButton: document.getElementById("save-character"),
    weaponCategory: document.getElementById("weapon-category"),
    weaponDisplay: document.getElementById("weapon-display"),
    randomAttackValue: document.getElementById("random-attack-value"),
    randomMagicAttackValue: document.getElementById(
      "random-magic-attack-value"
    ),
    yoharaCreation: document.getElementById("yohara-creation"),
    blessingCreation: document.getElementById("blessing-creation"),
    marriageCreation: document.getElementById("marriage-creation"),
    bonusVariation: {
      tab: document.getElementById("Variation"),
      activation: document.getElementById("bonus-variation-activation"),
      input: document.getElementById("bonus-variation"),
      inputDisplay: document.getElementById("bonus-variation-display"),
      container: document.getElementById("bonus-variation-range"),
      minValue: document.getElementById("bonus-variation-min-value"),
      maxValue: document.getElementById("bonus-variation-max-value"),
    },
  };

  characters.bonusVariation.inputDisplay.setAttribute("readonly", "");

  for (var [pseudo, character] of Object.entries(getSavedCharacters())) {
    characters.savedCharacters[pseudo] = character;
  }

  var skillContainer = document.getElementById("skill-container");
  characters.skillElementsToFilter =
    skillContainer.querySelectorAll("[data-class]");

  var mapping = createMapping();
  var constants = createConstants();

  var battle = {
    resetAttackType: false,
    savedFights: getSavedFights(),
    battleForm: document.getElementById("create-battle"),
    attackerSelection: document.getElementById("attacker-selection"),
    attackTypeSelection: document.getElementById("attack-type-selection"),
    victimSelection: document.getElementById("victim-selection"),
    damagesWeightedByType: {},
    scatterDataByType: {},
    damagesByBonus: [],
    tableResultFight: document.getElementById("result-table-fight"),
    tableResultHistory: document.getElementById("result-table-history"),
    deleteFightTemplate: document.getElementById("delete-fight-template")
      .children[0],
    errorInformation: {},
    fightResultContainer: document.getElementById("fight-result-container"),
    downLoadRawData: document.getElementById("download-raw-data"),
    downLoadRawDataVariation: document.getElementById(
      "download-raw-data-variation"
    ),
    bonusVariationResultContainer: document.getElementById(
      "bonus-variation-result-container"
    ),
    reduceChartPointsContainer: document.getElementById(
      "reduce-chart-points-container"
    ),
    reduceChartPoints: document.getElementById("reduce-chart-points"),
    plotDamages: document.getElementById("plot-damages"),
    plotBonusVariation: document.getElementById("plot-bonus-variation"),
    uniqueDamagesCounters: document.querySelectorAll(".unique-damages-counter"),
    possibleDamagesCounter: document.getElementById("possible-damages-counter"),
    damagesTime: document.getElementById("damages-time"),
    displayTime: document.getElementById("display-time"),
    simulationCounter: document.getElementById("simulation-counter"),
    simulationTime: document.getElementById("simulation-time"),
    numberFormats: {
      default: new Intl.NumberFormat(undefined, {
        minimumFractionDigits: 0,
        maximumFractionDigits: 1,
      }),
      percent: new Intl.NumberFormat(undefined, {
        style: "percent",
        maximumFractionDigits: 3,
      }),
      second: new Intl.NumberFormat(undefined, {
        style: "unit",
        unit: "second",
        unitDisplay: "long",
        maximumFractionDigits: 3,
      }),
    },
    mapping: mapping,
    constants: constants,
    translation: getTranslation(constants.translation),
  };

  attackSelectonListener(
    characters,
    battle.attackerSelection,
    battle.attackTypeSelection
  );
  initResultTableHistory(battle);
  loadScript(chartSource, function () {
    initDamagesChart(battle);
    initBonusVariationChart(battle);
  });
  reduceChartPointsListener(battle);
  downloadRawDataListener(battle);

  var errorElements = document.querySelectorAll("[data-error]");

  for (var index = 0; index < errorElements.length; index++) {
    var errorElement = errorElements[index];
    battle.errorInformation[errorElement.dataset.error] = errorElement;
  }

  return [characters, battle];
}

function loadScript(src, callback) {
  var script = document.createElement("script");
  script.src = src;

  function onComplete() {
    if (script.parentNode) {
      script.parentNode.removeChild(script);
    }
    if (callback) {
      callback();
    }
  }

  document.head.appendChild(script);

  script.onload = onComplete;
  script.onerror = onComplete;
}

function loadStyle(src) {
  var link = document.createElement("link");
  link.href = src;
  link.rel = "stylesheet";

  document.head.appendChild(link);
}

function loading() {
  var mainContainer = document.getElementById("hide-all");
  var loadingAnimation = document.getElementById("loading-animation");

  mainContainer.classList.remove("tabber-noactive");
  loadingAnimation.classList.add("tabber-noactive");
}

(function () {
  var javascriptSource =
    "/index.php?title=Utilisateur:Ankhseram/Calculator.js&action=raw&ctype=text/javascript";
  var cssSource =
    "/index.php?title=Utilisateur:Ankhseram/Style.css&action=raw&ctype=text/css";
  var chartSource = "https://cdn.jsdelivr.net/npm/chart.js";

  loadStyle(cssSource);

  function main() {
    var [characters, battle] = createDamageCalculatorInformation(chartSource);

    characterManagement(characters, battle);
    monsterManagement(characters, battle);

    updateBattleChoice(characters, battle);
    createBattle(characters, battle);

    loading();
  }
  loadScript(javascriptSource, main);
})();