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

 
(6 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) {
 
function toNormalForm(str) {
   return removeAccent(str).replace(/[^a-zA-Z0-9 ]/g, "").toLowerCase();
+
   return removeAccent(str)
 +
    .replace("-", " ")
 +
    .replace(/[^a-zA-Z0-9 ]/g, "")
 +
    .toLowerCase();
 
}
 
}
  
Ligne 35 : Ligne 36 :
 
function compareNumbers(a, b) {
 
function compareNumbers(a, b) {
 
   return b - a;
 
   return b - a;
 +
}
 +
 +
function isChecked(attribute) {
 +
  return attribute === "on";
 
}
 
}
  
 
function floorMultiplication(firstFactor, secondFactor) {
 
function floorMultiplication(firstFactor, secondFactor) {
 
   return Math.floor((firstFactor * secondFactor).toFixed(8));
 
   return Math.floor((firstFactor * secondFactor).toFixed(8));
}
 
 
function floorMultiplicationWithNegative(firstFactor, secondFactor) {
 
  if (secondFactor < 0) {
 
    return -floorMultiplication(firstFactor, -secondFactor);
 
  } else {
 
    return floorMultiplication(firstFactor, secondFactor);
 
  }
 
 
}
 
}
  
Ligne 61 : 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;
 +
 
 +
    if (index >= 3) {
 +
      textContent = numberFormat.format(valuesToDisplay[index]);
 +
    } else {
 +
      textContent = valuesToDisplay[index];
 +
    }
  
  firstCell.textContent = value;
+
    cell.textContent = textContent;
   firstCell.colSpan = 2;
+
   }
  
   newRow.style.fontWeight = "bold";
+
   return row;
 
}
 
}
  
Ligne 78 : Ligne 83 :
 
) {
 
) {
 
   var row = tableResultHistory.insertRow();
 
   var row = tableResultHistory.insertRow();
 +
  editTableResultRow(row, valuesToDisplay, numberFormat);
 +
  var cell = row.insertCell();
 +
  cell.appendChild(deleteFightTemplate.cloneNode(true));
 +
}
  
  for (var index = 0; index < valuesToDisplay.length; index++) {
+
function calcMeanDamages(damagesWeightedByType, totalCardinal) {
    var cell = row.insertCell();
+
  var sumDamages = 0;
    var textContent;
 
  
     if (index >= 3) {
+
  for (var damagesTypeName in damagesWeightedByType) {
      textContent = numberFormat.default.format(valuesToDisplay[index]);
+
     if (damagesTypeName === "miss") {
    } else {
+
       continue;
       textContent = valuesToDisplay[index];
 
 
     }
 
     }
  
     cell.textContent = textContent;
+
     var damagesWeighted = damagesWeightedByType[damagesTypeName];
 +
 
 +
    for (var damages in damagesWeighted) {
 +
      sumDamages += damages * damagesWeighted[damages];
 +
    }
 
   }
 
   }
  
   var cell = row.insertCell();
+
   return sumDamages / totalCardinal;
  cell.appendChild(deleteFightTemplate.cloneNode(true));
 
 
}
 
}
  
function addToTableResult(
+
function prepareDamagesData(
   tableResult,
+
   damagesWeightedByType,
   damagesWeighted,
+
   possibleDamagesCountTemp,
   numberFormat,
+
   totalCardinal
  minMaxDamages
 
 
) {
 
) {
   var firstIteration = true;
+
   var minDamages = Infinity;
   var scatterData = [];
+
   var maxDamages = 0;
 +
  var scatterDataByType = {};
 +
  var sumDamages = 0;
 +
  var possibleDamagesCount = 0;
 +
  var uniqueDamagesCount = 0;
  
   for (var damages in damagesWeighted) {
+
   for (var damagesTypeName in damagesWeightedByType) {
    damages = parseInt(damages);
+
     if (damagesTypeName === "miss") {
 
+
       scatterDataByType.miss = damagesWeightedByType.miss;
     if (firstIteration && minMaxDamages) {
+
      possibleDamagesCount++;
       if (damages < minMaxDamages.min) {
+
       uniqueDamagesCount++;
        minMaxDamages.min = damages;
+
       continue;
       }
 
       firstIteration = false;
 
 
     }
 
     }
  
     var newRow = tableResult.insertRow(-1);
+
     var firstIteration = true;
     var firstCell = newRow.insertCell(0);
+
     var damagesWeighted = damagesWeightedByType[damagesTypeName];
 +
    var scatterData = [];
 +
    scatterDataByType[damagesTypeName] = scatterData;
  
     firstCell.textContent = numberFormat.default.format(damages);
+
     for (var damages in damagesWeighted) {
 +
      damages = +damages;
  
    var secondCell = newRow.insertCell(1);
+
      if (firstIteration) {
 +
        if (damages < minDamages) {
 +
          minDamages = damages;
 +
        }
 +
        firstIteration = false;
 +
      }
  
    secondCell.textContent = numberFormat.percent.format(
+
      var weight = damagesWeighted[damages];
      damagesWeighted[damages]
+
      var probability = weight / totalCardinal;
    );
 
  
    scatterData.push({ x: damages, y: damagesWeighted[damages] });
+
      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 (minMaxDamages && damages > minMaxDamages.max) {
+
   if (minDamages === Infinity) {
     minMaxDamages.max = damages;
+
     minDamages = 0;
 
   }
 
   }
  
   return scatterData;
+
   return [
 +
    sumDamages / totalCardinal,
 +
    minDamages,
 +
    maxDamages,
 +
    scatterDataByType,
 +
    possibleDamagesCount,
 +
    uniqueDamagesCount,
 +
  ];
 
}
 
}
  
function updateDamagesChart(scatterData, damagesChart, damagesTypeName) {
+
function aggregateDamages(scatterData, maxPoints) {
   var chart = damagesChart.chart;
+
   var dataLength = scatterData.length;
   var dataset = damagesChart.dataset[damagesTypeName];
+
  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,
 +
    });
  
  if (scatterData.length >= 10) {
+
     remainingData -= groupLength;
     dataset.data = scatterData;
 
    chart.data.datasets.push(dataset);
 
    chart.update();
 
 
   }
 
   }
 +
 +
  return aggregateScatterData;
 
}
 
}
  
function clearDamageChart(damagesChart) {
+
function addToDamagesChart(
   damagesChart.chart.data.datasets = [];
+
  scatterDataByType,
}
+
  damagesChart,
 +
  isReducePointsChecked
 +
) {
 +
   var { chart, datasetsStyle, maxPoints, reduceChartPointsContainer } =
 +
    damagesChart;
 +
  var isFirstDataset = true;
 +
  var datasets = chart.data.datasets;
  
function displayDamagesChart(damagesChart, chartContainer) {
+
   datasets.length = 0;
   if (damagesChart.chart.data.datasets.length) {
 
    showElement(chartContainer);
 
  } else {
 
    hideElement(chartContainer);
 
  }
 
}
 
  
function clearTableResult(tableResult) {
+
  for (var index = 0; index < datasetsStyle.length; index++) {
  var tableHeaderRowCount = 1;
+
    var dataset = copyObject(datasetsStyle[index]);
  var rowCount = tableResult.rows.length;
 
  
  for (var rowIndex = tableHeaderRowCount; rowIndex < rowCount; rowIndex++) {
+
    if (!scatterDataByType.hasOwnProperty(dataset.name)) {
    tableResult.deleteRow(tableHeaderRowCount);
+
      continue;
  }
+
    }
}
 
  
function getMonsterName(monsterVnum) {
+
    var scatterData = scatterDataByType[dataset.name];
  var monsterAttributes = monsterData[monsterVnum];
+
    var canBeReduced = scatterData.length > 2 * maxPoints;
  return monsterAttributes[monsterAttributes.length - 1];
 
}
 
  
function filterClass(selectedRace, classChoice, selectValueIsChanged = false) {
+
    dataset.hidden = !isFirstDataset;
  showElement(classChoice.parentElement);
+
    dataset.canBeReduced = canBeReduced;
  
  for (var option of classChoice.options) {
+
     if (canBeReduced && isReducePointsChecked) {
     if (option.getAttribute("data-race") === selectedRace) {
+
       dataset.data = aggregateDamages(scatterData, maxPoints);
       if (!selectValueIsChanged) {
 
        classChoice.value = option.value;
 
        selectValueIsChanged = true;
 
      }
 
      showElement(option);
 
 
     } else {
 
     } else {
       hideElement(option);
+
       dataset.data = scatterData;
 
     }
 
     }
  }
 
  if (selectedRace == "lycan") {
 
    hideElement(classChoice.parentElement);
 
  }
 
}
 
 
function filterWeapon(
 
  selectedRace,
 
  weapon,
 
  weaponCategory,
 
  allowedWeaponsPerRace,
 
  selectValueIsChanged = false
 
) {
 
  var allowedWeapons = allowedWeaponsPerRace[selectedRace];
 
  
  if (!selectValueIsChanged) {
+
    if (isFirstDataset) {
    var weaponType = weaponData[weapon.value][1];
+
      isFirstDataset = false;
 +
 
 +
      if (canBeReduced) {
 +
        showElement(reduceChartPointsContainer);
  
    if (!isValueInArray(weaponType, allowedWeapons)) {
+
        if (!isReducePointsChecked) {
       weapon.value = 0;
+
          handleChartAnimations(chart, false);
 +
        }
 +
      } else {
 +
        hideElement(reduceChartPointsContainer);
 +
        handleChartAnimations(chart, true);
 +
       }
 
     }
 
     }
 +
 +
    datasets.push(dataset);
 
   }
 
   }
  
   var children = weaponCategory.children;
+
   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();
 +
}
  
   for (var index = 0; index < children.length; index++) {
+
function handleChartAnimations(chart, addAnimations) {
    var child = children[index];
+
  chart.options.animation = addAnimations;
 +
   chart.options.animations.colors = addAnimations;
 +
  chart.options.animations.x = addAnimations;
 +
  chart.options.transitions.active.animation.duration = addAnimations * 1000;
 +
}
  
     if (isValueInArray(index, allowedWeapons)) {
+
function updateDamagesChartDescription(
       showElement(child);
+
  uniqueDamagesCounters,
 +
  uniqueDamagesCount,
 +
  formatNumber
 +
) {
 +
  uniqueDamagesCounters.forEach(function (element) {
 +
     if (uniqueDamagesCount <= 1) {
 +
       hideElement(element.parentElement);
 
     } else {
 
     } else {
       hideElement(child);
+
       showElement(element.parentElement);
 +
      element.textContent = formatNumber.format(uniqueDamagesCount);
 
     }
 
     }
   }
+
   });
 
}
 
}
  
function getSelectedWeapon(weaponCategory) {
+
function getMonsterName(monsterVnum) {
   return weaponCategory.querySelector("input[type='radio']:checked");
+
  var monsterAttributes = monsterData[monsterVnum];
 +
   return monsterAttributes[monsterAttributes.length - 1];
 
}
 
}
  
function handleWeaponDisplay(weaponDisplay, newWeapon, weaponValue) {
+
function filterClass(selectedRace, classChoice, selectValueIsChanged = false) {
   var newImage = newWeapon.nextElementSibling.cloneNode();
+
   showElement(classChoice.parentElement);
  var newText = document.createElement("span");
 
  var oldImage = weaponDisplay.firstChild;
 
  var oldText = oldImage.nextElementSibling;
 
  var weaponName = weaponData[weaponValue][0];
 
  
   if (weaponValue == 0) {
+
   for (var option of classChoice.options) {
     newText.textContent = " " + weaponName + " ";
+
     if (option.getAttribute("data-race") === selectedRace) {
  } else {
+
      if (!selectValueIsChanged) {
    var weaponLink = document.createElement("a");
+
        classChoice.value = option.value;
    weaponLink.href = mw.util.getUrl(weaponName);
+
        selectValueIsChanged = true;
    weaponLink.title = weaponName;
+
      }
    weaponLink.textContent = weaponName;
+
      showElement(option);
 
+
     } else {
    newText.appendChild(document.createTextNode(" "));
+
      hideElement(option);
     newText.appendChild(weaponLink);
+
     }
     newText.appendChild(document.createTextNode(" "));
+
  }
 +
  if (selectedRace == "lycan") {
 +
    hideElement(classChoice.parentElement);
 
   }
 
   }
 
  weaponDisplay.replaceChild(newImage, oldImage);
 
  weaponDisplay.replaceChild(newText, oldText);
 
 
}
 
}
  
function filterUpgrade(
+
function filterWeapon(
 
   selectedRace,
 
   selectedRace,
   weaponUpgrade,
+
   weaponElement,
   weaponValue,
+
   weaponCategory,
   randomAttackValue,
+
   allowedWeaponsPerRace,
   randomMagicAttackValue,
+
   selectValueIsChanged = false
  currentUpgrade
 
 
) {
 
) {
   var weapon = weaponData[weaponValue];
+
   var allowedWeapons = allowedWeaponsPerRace[selectedRace];
  
   if (isValueInArray("serpent", weapon[0].toLowerCase())) {
+
   if (!selectValueIsChanged) {
     showElement(randomAttackValue);
+
     var weaponType = weaponData[weaponElement.value][1];
  
     if (selectedRace === "sura" || selectedRace === "shaman") {
+
     if (!isValueInArray(weaponType, allowedWeapons)) {
       showElement(randomMagicAttackValue);
+
       weaponElement.value = 0;
 
     }
 
     }
  } else {
 
    hideElement(randomAttackValue);
 
    hideElement(randomMagicAttackValue);
 
 
   }
 
   }
  
   var upgradeNumber = weapon[3].length;
+
   var children = weaponCategory.children;
  
   if (upgradeNumber <= 1) {
+
   for (var index = 0; index < children.length; index++) {
    hideElement(weaponUpgrade.parentElement);
+
     var child = children[index];
  } else {
 
     showElement(weaponUpgrade.parentElement);
 
  
     weaponUpgrade.innerHTML = "";
+
     if (isValueInArray(index, allowedWeapons)) {
 
+
       showElement(child);
    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;
+
       hideElement(child);
      currentUpgrade = undefined;
 
 
     }
 
     }
 
   }
 
   }
 
}
 
}
  
function filterState(selectedState, polymorphMonster) {
+
function getSelectedWeapon(weaponCategory) {
   if (selectedState === "polymorph") {
+
   return weaponCategory.querySelector("input[type='radio']:checked");
    showElement(polymorphMonster.parentElement);
 
  } else {
 
    hideElement(polymorphMonster.parentElement);
 
  }
 
 
}
 
}
  
function filterCheckbox(checkbox, element) {
+
function handleWeaponDisplay(weaponDisplay, newWeapon, weaponVnum) {
   if (checkbox.checked) {
+
  var newImage = newWeapon.nextElementSibling.cloneNode();
     showElement(element);
+
  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 {
 
   } else {
     hideElement(element);
+
     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 filterSkills(selectedClass, skillElementsToFilter) {
+
function filterUpgrade(
   for (var element of skillElementsToFilter) {
+
  selectedRace,
    if (isValueInArray(selectedClass, element.dataset.class)) {
+
  weaponUpgrade,
      showElement(element);
+
  weaponVnum,
     } else {
+
  randomAttackValue,
       hideElement(element);
+
  randomMagicAttackValue,
 +
  currentUpgrade
 +
) {
 +
   var weapon = createWeapon(weaponVnum);
 +
 
 +
  if (weapon.isSerpent) {
 +
    showElement(randomAttackValue);
 +
 
 +
     if (selectedRace === "sura" || selectedRace === "shaman") {
 +
       showElement(randomMagicAttackValue);
 
     }
 
     }
 +
  } else {
 +
    hideElement(randomAttackValue);
 +
    hideElement(randomMagicAttackValue);
 
   }
 
   }
}
 
  
function filterAttackTypeSelection(attacker, attackTypeSelection) {
+
   var upgradeNumber = weapon.upgrades.length;
   var attackerClass = attacker.class;
 
  var selectedOption =
 
    attackTypeSelection.options[attackTypeSelection.selectedIndex];
 
  var attackerIsNotPolymorph = !isPolymorph(attacker);
 
  
   for (var index = 2; index < attackTypeSelection.options.length; index++) {
+
   if (upgradeNumber <= 1) {
     var option = attackTypeSelection.options[index];
+
     hideElement(weaponUpgrade.parentElement);
     var optionClass = option.dataset.class;
+
  } else {
    var optionValue = option.value;
+
     showElement(weaponUpgrade.parentElement);
 +
  }
  
    if (
+
  weaponUpgrade.innerHTML = "";
      attackerIsNotPolymorph &&
 
      attacker[optionValue] &&
 
      (attackerClass === optionClass ||
 
        (optionValue.startsWith("horseSkill") &&
 
          isRiding(attacker) &&
 
          (!optionClass || isValueInArray(attackerClass, optionClass))))
 
    ) {
 
      showElement(option);
 
    } else {
 
      hideElement(option);
 
  
      if (selectedOption === option) {
+
  for (var upgrade = 0; upgrade < upgradeNumber; upgrade++) {
        attackTypeSelection.selectedIndex = 0;
+
    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 filterAttackTypeSelectionMonster(attackTypeSelection) {
+
function filterState(selectedState, polymorphMonster) {
   for (var index = 2; index < attackTypeSelection.options.length; index++) {
+
   if (selectedState === "polymorph") {
     hideElement(attackTypeSelection.options[index]);
+
     showElement(polymorphMonster.parentElement);
   }
+
   } else {
 
+
    hideElement(polymorphMonster.parentElement);
  if (attackTypeSelection.selectedIndex !== 1) {
 
    attackTypeSelection.selectedIndex = 0;
 
 
   }
 
   }
 
}
 
}
  
function filterForm(characters, battle) {
+
function filterCheckbox(checkbox, element) {
   var characterCreation = characters.characterCreation;
+
   if (checkbox.checked) {
   var allowedWeaponsPerRace = battle.constants.allowedWeaponsPerRace;
+
    showElement(element);
 +
   } else {
 +
    hideElement(element);
 +
  }
 +
}
  
  characterCreation.addEventListener("change", function (event) {
+
function filterSkills(selectedClass, skillElementsToFilter) {
     var target = event.target;
+
  for (var element of skillElementsToFilter) {
     var targetName = target.name;
+
     if (isValueInArray(selectedClass, element.dataset.class)) {
 +
      showElement(element);
 +
     } else {
 +
      hideElement(element);
 +
    }
 +
  }
 +
}
  
    switch (targetName) {
+
function filterAttackTypeSelection(attacker, attackTypeSelection) {
      case "race":
+
  var attackerClass = attacker.class;
        var selectedRace = target.value;
+
  var selectedOption =
        var classChoice = characterCreation.class;
+
    attackTypeSelection.options[attackTypeSelection.selectedIndex];
        var weapon = characterCreation.weapon;
+
  var attackerIsNotPolymorph = !isPolymorph(attacker);
  
        filterClass(selectedRace, classChoice);
+
  for (var index = 2; index < attackTypeSelection.options.length; index++) {
        filterWeapon(
+
    var option = attackTypeSelection.options[index];
          selectedRace,
+
    var optionClass = option.dataset.class;
          weapon,
+
    var optionValue = option.value;
          characters.weaponCategory,
 
          allowedWeaponsPerRace
 
        );
 
  
        var newWeapon = getSelectedWeapon(characters.weaponCategory);
+
    if (
        handleWeaponDisplay(characters.weaponDisplay, newWeapon, weapon.value);
+
      attackerIsNotPolymorph &&
         filterUpgrade(
+
      attacker[optionValue] &&
          selectedRace,
+
      (attackerClass === optionClass ||
          characterCreation.weaponUpgrade,
+
         (optionValue.startsWith("horseSkill") &&
           weapon.value,
+
           isRiding(attacker) &&
           characters.randomAttackValue,
+
           (!optionClass || isValueInArray(attackerClass, optionClass))))
          characters.randomMagicAttackValue
+
    ) {
        );
+
      showElement(option);
        filterSkills(classChoice.value, characters.skillElementsToFilter);
+
    } else {
 +
      hideElement(option);
  
        if (characterCreation.name.value === battle.attackerSelection.value) {
+
      if (selectedOption === option) {
          battle.resetAttackType = true;
+
        attackTypeSelection.selectedIndex = 0;
        }
+
      }
        break;
+
    }
      case "class":
+
  }
        filterSkills(target.value, characters.skillElementsToFilter);
+
}
  
        if (characterCreation.name.value === battle.attackerSelection.value) {
+
function filterAttackTypeSelectionMonster(attackTypeSelection) {
          battle.resetAttackType = true;
+
  for (var index = 2; index < attackTypeSelection.options.length; index++) {
        }
+
    hideElement(attackTypeSelection.options[index]);
        break;
+
  }
       case "weapon":
+
 
 +
  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(
 
         handleWeaponDisplay(
 
           characters.weaponDisplay,
 
           characters.weaponDisplay,
           target,
+
           newWeapon,
           characterCreation.weapon.value
+
           weaponElement.value
 
         );
 
         );
 
         filterUpgrade(
 
         filterUpgrade(
           characterCreation.race.value,
+
           selectedRace,
 
           characterCreation.weaponUpgrade,
 
           characterCreation.weaponUpgrade,
           target.value,
+
           weaponElement.value,
 
           characters.randomAttackValue,
 
           characters.randomAttackValue,
 
           characters.randomMagicAttackValue
 
           characters.randomMagicAttackValue
 
         );
 
         );
         break;
+
        filterSkills(classChoice.value, characters.skillElementsToFilter);
       case "state":
+
 
 +
        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);
 
         filterState(target.value, characterCreation.polymorphMonster);
 
         if (characterCreation.name.value === battle.attackerSelection.value) {
 
         if (characterCreation.name.value === battle.attackerSelection.value) {
Ligne 449 : Ligne 573 :
  
 
function addUniquePseudo(characterDataObject, savedCharactersPseudo) {
 
function addUniquePseudo(characterDataObject, savedCharactersPseudo) {
   var characterPseudo = characterDataObject.name;
+
   var characterPseudo = String(characterDataObject.name);
 
   var originalPseudo = characterPseudo;
 
   var originalPseudo = characterPseudo;
 
   var count = 0;
 
   var count = 0;
Ligne 490 : Ligne 614 :
  
 
function getSavedMonsters() {
 
function getSavedMonsters() {
   return getLocalStorageValue("savedMonstersCalculator", []).filter(function (num) {
+
   return getLocalStorageValue("savedMonstersCalculator", []).filter(function (
 +
    num
 +
  ) {
 
     return !isNaN(Number(num));
 
     return !isNaN(Number(num));
 
   });
 
   });
Ligne 553 : Ligne 679 :
  
 
function characterCreationListener(characters, battle) {
 
function characterCreationListener(characters, battle) {
   characters.characterCreation.addEventListener("submit", function (event) {
+
   var { characterCreation, saveButton, weaponCategory } = characters;
 +
 
 +
  characterCreation.addEventListener("submit", function (event) {
 
     event.preventDefault();
 
     event.preventDefault();
  
 
     if (characters.unsavedChanges) {
 
     if (characters.unsavedChanges) {
       saveCharacter(
+
       saveCharacter(characters.savedCharacters, characterCreation, battle);
        characters.savedCharacters,
+
       saveButtonGreen(saveButton);
        characters.characterCreation,
 
        battle
 
      );
 
       saveButtonGreen(characters.saveButton);
 
 
       characters.unsavedChanges = false;
 
       characters.unsavedChanges = false;
 
     }
 
     }
Ligne 570 : Ligne 694 :
 
     if (event.ctrlKey && event.key === "s") {
 
     if (event.ctrlKey && event.key === "s") {
 
       event.preventDefault();
 
       event.preventDefault();
       characters.saveButton.click();
+
       saveButton.click();
 
     }
 
     }
 
   });
 
   });
}
 
  
function downloadCharacter(character) {
+
  weaponCategory.addEventListener("mouseover", function (event) {
  var content = JSON.stringify(character);
+
    label = event.target.closest("label");
   var link = document.createElement("a");
+
 
   var blob = new Blob([content], { type: "text/plain" });
+
    if (label) {
   var blobURL = URL.createObjectURL(blob);
+
      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.href = blobURL;
 
  link.download = character.name + ".txt";
 
 
   link.click();
 
   link.click();
 +
  document.body.removeChild(link);
 
   URL.revokeObjectURL(blobURL);
 
   URL.revokeObjectURL(blobURL);
 
}
 
}
Ligne 605 : Ligne 750 :
 
         try {
 
         try {
 
           var characterDataObject = JSON.parse(fileContent);
 
           var characterDataObject = JSON.parse(fileContent);
          var characterPseudo = characterDataObject.name;
 
  
           if (characterPseudo) {
+
           if (characterDataObject.hasOwnProperty("name")) {
 +
            var characterPseudo = String(characterDataObject.name);
 +
 
 
             hideElement(characters.characterCreation);
 
             hideElement(characters.characterCreation);
 
             characterPseudo = validPseudo(characterPseudo);
 
             characterPseudo = validPseudo(characterPseudo);
 +
 
             [characterDataObject, characterPseudo] = addUniquePseudo(
 
             [characterDataObject, characterPseudo] = addUniquePseudo(
 
               characterDataObject,
 
               characterDataObject,
Ligne 641 : Ligne 788 :
 
           }
 
           }
 
         } catch (error) {
 
         } catch (error) {
 +
          console.log(error);
 
           if (error.name === "TypeError") {
 
           if (error.name === "TypeError") {
 
             // delete the character
 
             // delete the character
Ligne 769 : Ligne 917 :
  
 
     if (formElement.type === "checkbox") {
 
     if (formElement.type === "checkbox") {
       if (value === "on") {
+
       if (isChecked(value)) {
 
         formElement.checked = true;
 
         formElement.checked = true;
 
       }
 
       }
Ligne 778 : Ligne 926 :
 
   var selectedRace = characterCreation.race.value;
 
   var selectedRace = characterCreation.race.value;
 
   var classChoice = characterCreation.class;
 
   var classChoice = characterCreation.class;
   var weapon = characterCreation.weapon;
+
   var weaponElement = characterCreation.weapon;
  
 
   filterClass(selectedRace, classChoice, true);
 
   filterClass(selectedRace, classChoice, true);
 
   filterWeapon(
 
   filterWeapon(
 
     selectedRace,
 
     selectedRace,
     weapon,
+
     weaponElement,
 
     characters.weaponCategory,
 
     characters.weaponCategory,
 
     battle.constants.allowedWeaponsPerRace,
 
     battle.constants.allowedWeaponsPerRace,
Ligne 791 : Ligne 939 :
 
   var newWeapon = getSelectedWeapon(characters.weaponCategory);
 
   var newWeapon = getSelectedWeapon(characters.weaponCategory);
  
   handleWeaponDisplay(characters.weaponDisplay, newWeapon, weapon.value);
+
   handleWeaponDisplay(characters.weaponDisplay, newWeapon, weaponElement.value);
 
   filterUpgrade(
 
   filterUpgrade(
 
     selectedRace,
 
     selectedRace,
 
     characterCreation.weaponUpgrade,
 
     characterCreation.weaponUpgrade,
     weapon.value,
+
     weaponElement.value,
 
     characters.randomAttackValue,
 
     characters.randomAttackValue,
 
     characters.randomMagicAttackValue,
 
     characters.randomMagicAttackValue,
Ligne 812 : Ligne 960 :
 
   filterCheckbox(characterCreation.isMarried, characters.marriageCreation);
 
   filterCheckbox(characterCreation.isMarried, characters.marriageCreation);
 
   filterSkills(classChoice.value, characters.skillElementsToFilter);
 
   filterSkills(classChoice.value, characters.skillElementsToFilter);
 +
  handleBonusVariationUpdate(characterCreation, characters.bonusVariation);
 
}
 
}
  
Ligne 887 : Ligne 1 036 :
  
 
       case "download":
 
       case "download":
         downloadCharacter(characters.savedCharacters[pseudo]);
+
         var character = characters.savedCharacters[pseudo];
 +
        downloadData(
 +
          JSON.stringify(character),
 +
          "text/plain",
 +
          character.name + ".txt"
 +
        );
 
         break;
 
         break;
  
Ligne 1 073 : Ligne 1 227 :
 
}
 
}
  
function characterManagement(characters, battle) {
+
function handleBonusVariationUpdate(characterCreation, bonusVariation) {
   var characterTemplate = characters.newCharacterTemplate;
+
   var selectedBonus = characterCreation.bonusVariation.value;
   var charactersContainer = characters.charactersContainer;
+
 
 +
  if (characterCreation.hasOwnProperty(selectedBonus)) {
 +
    handleBonusVariation(characterCreation[selectedBonus], bonusVariation);
 +
   } else {
 +
    var { minValue, maxValue } = bonusVariation;
  
  Object.keys(characters.savedCharacters).forEach(function (pseudo) {
+
    minValue.removeAttribute("min");
     handleNewCharacter(
+
     minValue.removeAttribute("max");
      characters,
 
      characterTemplate,
 
      charactersContainer,
 
      battle,
 
      pseudo
 
    );
 
  });
 
  
  characters.addNewCharacterButton.addEventListener("click", function (event) {
+
    maxValue.removeAttribute("min");
     if (!characters.unsavedChanges) {
+
     maxValue.removeAttribute("max");
      addNewCharacter(
 
        characters,
 
        characterTemplate,
 
        charactersContainer,
 
        battle
 
      );
 
    } else {
 
      var result = confirm(
 
        "Voulez-vous continuer ? Les dernières modifications ne seront pas sauvegardées."
 
      );
 
  
      if (result) {
+
    hideElement(bonusVariation.container);
        addNewCharacter(
+
  }
          characters,
+
}
          characterTemplate,
+
 
          charactersContainer,
+
function getTargetContent(targetParent, targetName, isSkill) {
          battle
+
  var targetContent = "";
        );
+
 
         saveButtonGreen(characters.saveButton);
+
  if (targetParent.children.length <= 1) {
         characters.unsavedChanges = false;
+
    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;
 +
}
  
  handleUploadCharacter(
+
function handleBonusVariation(target, bonusVariation, isSelectedByUser) {
    characters,
+
  var { activation, inputDisplay, minValue, maxValue, container } =
    characterTemplate,
+
     bonusVariation;
    charactersContainer,
 
     battle
 
  );
 
  
   characters.characterCreation.addEventListener("change", function () {
+
   var {
     saveButtonOrange(characters.saveButton);
+
    min: targetMin,
     characters.unsavedChanges = true;
+
    max: targetMax,
   });
+
    name: targetName,
 +
    value: targetValue,
 +
     parentElement: targetParent,
 +
     tagName,
 +
   } = target;
  
   filterForm(characters, battle);
+
   targetMin = Number(targetMin);
   characterCreationListener(characters, battle);
+
   targetMax = Number(targetMax);
   handleFocus();
+
   targetValue = Number(targetValue);
  
   window.addEventListener("beforeunload", function (event) {
+
   var isSkill = tagName === "SELECT";
    if (characters.unsavedChanges) {
 
      event.preventDefault();
 
      event.returnValue = "";
 
      return "";
 
    }
 
  });
 
}
 
  
function handleNewMonster(
+
  if (container.contains(target) || targetName == 0) {
  characters,
+
    if (!isSelectedByUser) {
  monsterTemplate,
+
      hideElement(container);
  monstersContainer,
+
    }
  battle,
+
    return;
  monsterVnum,
+
   }
  monsterList
+
 
) {
+
   if (isSkill) {
  var newMonsterTemplate = monsterTemplate.cloneNode(true);
+
    var options = target.options;
   var spanInput = newMonsterTemplate.querySelector("span.input");
 
   var deleteSvg = newMonsterTemplate.querySelector("svg");
 
  var monsterName = getMonsterName(monsterVnum);
 
  
  var link = document.createElement("a");
+
    targetMin = options[0].value;
  link.href = mw.util.getUrl(monsterName);
+
    targetMax = options[options.length - 1].value;
   link.title = monsterName;
+
   }
  link.textContent = monsterName;
 
  
   spanInput.appendChild(link);
+
   minValue.min = targetMin;
   monstersContainer.appendChild(newMonsterTemplate);
+
   minValue.max = targetMax;
  
   newMonsterTemplate.setAttribute("tabindex", "0");
+
   maxValue.min = targetMin;
   newMonsterTemplate.setAttribute("data-name", monsterVnum);
+
   maxValue.max = targetMax;
  monstersContainer.appendChild(newMonsterTemplate);
 
  
   deleteSvg.addEventListener("click", function (event) {
+
   if (isSelectedByUser) {
    deleteMonster(characters, monsterVnum, newMonsterTemplate, battle);
+
     var { input, tab } = bonusVariation;
     var inputMonster = monsterList.querySelector(
 
      "input[name='" + monsterVnum + "']"
 
    );
 
    inputMonster.checked = false;
 
  });
 
}
 
  
function monsterManagement(characters, battle) {
+
     inputDisplay.value = getTargetContent(targetParent, targetName, isSkill);
  function handleDropdown(searchMonster, monsterList) {
 
     searchMonster.addEventListener("focus", function (event) {
 
      showElement(monsterList);
 
    });
 
  
     document.addEventListener("mousedown", function (event) {
+
     input.value = targetName;
      var target = event.target;
+
    minValue.value = Math.max(targetValue - 10, targetMin);
      if (!monsterList.contains(target) && !searchMonster.contains(target)) {
+
     maxValue.value = Math.min(targetValue + 10, targetMax);
        hideElement(monsterList);
 
      }
 
     });
 
  }
 
  
  function addMonsterNames(monsterList) {
+
     activation.checked = true;
     var lastMonsterAttributeIndex = monsterData[101].length - 1;
 
  
     for (var monsterVnum in monsterData) {
+
     tab.click();
      var li = document.createElement("li");
+
    tab.scrollIntoView(true);
      var label = document.createElement("label");
 
      var input = document.createElement("input");
 
      var textNode = document.createTextNode(
 
        monsterData[monsterVnum][lastMonsterAttributeIndex]
 
      );
 
  
      label.htmlFor = "monster" + monsterVnum;
+
    input.dispatchEvent(new Event("change", { bubbles: true }));
       input.id = "monster" + monsterVnum;
+
  } else {
       input.type = "checkbox";
+
    if (minValue.value < targetMin) {
 +
       minValue.value = targetMin;
 +
       minValue.dispatchEvent(new Event("change", { bubbles: true }));
 +
    }
  
      input.name = monsterVnum;
+
    if (maxValue.value > targetMax) {
 
+
       maxValue.value = targetMax;
       label.appendChild(input);
+
       maxValue.dispatchEvent(new Event("change", { bubbles: true }));
       label.appendChild(textNode);
 
      li.appendChild(label);
 
      monsterList.appendChild(li);
 
 
     }
 
     }
 
   }
 
   }
  
   function filterNames(searchMonster, monsterList) {
+
   inputDisplay.style.width = inputDisplay.value.length * 0.55 + "em";
     var debounceTimer;
+
  showElement(container);
 +
}
 +
 
 +
function characterManagement(characters, battle) {
 +
  var {
 +
     newCharacterTemplate: characterTemplate,
 +
    charactersContainer,
 +
    addNewCharacterButton,
 +
    saveButton,
 +
    characterCreation,
 +
    bonusVariation,
 +
  } = characters;
  
    searchMonster.addEventListener("input", function (event) {
+
  Object.keys(characters.savedCharacters).forEach(function (pseudo) {
      clearTimeout(debounceTimer);
+
    handleNewCharacter(
      debounceTimer = setTimeout(function () {
+
       characters,
        var value = toNormalForm(event.target.value);
+
      characterTemplate,
        for (var element of monsterList.children) {
+
      charactersContainer,
          if (!isValueInArray(value, toNormalForm(element.textContent))) {
+
      battle,
            hideElement(element);
+
       pseudo
          } 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) {
+
  addNewCharacterButton.addEventListener("click", function (event) {
       handleNewMonster(
+
     if (!characters.unsavedChanges) {
 +
       addNewCharacter(
 
         characters,
 
         characters,
         monsterTemplate,
+
         characterTemplate,
         monstersContainer,
+
         charactersContainer,
         battle,
+
         battle
        monsterVnum,
 
        monsterList
 
 
       );
 
       );
      inputMonster.checked = true;
 
 
     } else {
 
     } else {
       deleteMonster(characters, monsterVnum, null, battle);
+
       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;
 +
      }
 
     }
 
     }
 
   });
 
   });
  
   monsterListForm.addEventListener("submit", function (event) {
+
   handleUploadCharacter(
     event.preventDefault();
+
    characters,
 +
    characterTemplate,
 +
    charactersContainer,
 +
    battle
 +
  );
 +
 
 +
  characterCreation.addEventListener("change", function () {
 +
     saveButtonOrange(saveButton);
 +
    characters.unsavedChanges = true;
 
   });
 
   });
  
   monsterListForm.addEventListener("change", function (event) {
+
   function handleLongPress(target) {
     var target = event.target;
+
     if (target.tagName !== "INPUT" && target.tagName !== "SELECT") {
    var monsterVnum = target.name;
+
       target = target.querySelector("input");
 
 
    if (monsterVnum === "search-monster") {
 
       return;
 
 
     }
 
     }
  
     if (target.checked) {
+
     if (
       handleNewMonster(
+
      !target ||
         characters,
+
       (target.type !== "number" &&
         monsterTemplate,
+
         !target.classList.contains("skill-select") &&
        monstersContainer,
+
         target.name !== "weaponUpgrade")
        battle,
+
    ) {
        monsterVnum,
+
      return;
        monsterList
+
    }
      );
+
 
 +
    handleBonusVariation(target, bonusVariation, true);
 +
  }
  
      characters.savedMonsters.push(monsterVnum);
+
  characterCreation.addEventListener("click", function (event) {
      updateSavedMonsters(characters.savedMonsters);
+
    if (event.shiftKey || event.ctrlKey) {
       addBattleChoice(battle, monsterVnum, true);
+
       handleLongPress(event.target);
    } else {
 
      var currentMonsterTemplate = monstersContainer.querySelector(
 
        "[data-name='" + monsterVnum + "']"
 
      );
 
      deleteMonster(characters, monsterVnum, currentMonsterTemplate, battle);
 
 
     }
 
     }
 
   });
 
   });
  
   addEventListener("storage", function (event) {
+
   var longPressTimer;
     if (event.key === "newMonsterCalculator") {
+
 
       var monsterVnum = Number(event.newValue);
+
  characterCreation.addEventListener("touchstart", function (event) {
 +
     longPressTimer = setTimeout(function () {
 +
       handleLongPress(event.target);
 +
    }, 800);
 +
  });
  
      if (!monsterVnum) {
+
  characterCreation.addEventListener("touchend", function () {
        return;
+
    clearTimeout(longPressTimer);
      }
+
  });
  
      var inputMonster = monsterList.querySelector(
+
  characterCreation.addEventListener("touchmove", function () {
        "input[name='" + Math.abs(monsterVnum) + "']"
+
    clearTimeout(longPressTimer);
      );
+
  });
  
      if (inputMonster) {
+
  filterForm(characters, battle);
        if (
+
  characterCreationListener(characters, battle);
          (monsterVnum > 0 && !inputMonster.checked) ||
+
  handleFocus();
          (monsterVnum < 0 && inputMonster.checked)
+
 
        ) {
+
  window.addEventListener("beforeunload", function (event) {
          inputMonster.click();
+
    if (characters.unsavedChanges) {
        }
+
      event.preventDefault();
       }
+
       return "";
 
     }
 
     }
 
   });
 
   });
 
}
 
}
  
function removeBattleChoice(battle, name) {
+
function handleNewMonster(
   var battleSelects = [battle.attackerSelection, battle.victimSelection];
+
  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);
  
   battleSelects.forEach(function (battleSelect) {
+
   var link = document.createElement("a");
    for (
+
  link.href = mw.util.getUrl(monsterName);
      var optionIndex = 0;
+
  link.title = monsterName;
      optionIndex < battleSelect.options.length;
+
   link.textContent = monsterName;
      optionIndex++
 
    ) {
 
      if (battleSelect.options[optionIndex].value === name) {
 
        battleSelect.remove(optionIndex);
 
        break;
 
      }
 
    }
 
   });
 
}
 
  
function addBattleChoice(battle, name, isMonster = false) {
+
  spanInput.appendChild(link);
   function createOption(text, vnum) {
+
   monstersContainer.appendChild(newMonsterTemplate);
    var option = document.createElement("option");
 
    option.textContent = text;
 
    option.value = vnum;
 
  
    if (!isMonster) {
+
  newMonsterTemplate.setAttribute("tabindex", "0");
      option.classList.add("notranslate");
+
  newMonsterTemplate.setAttribute("data-name", monsterVnum);
    }
+
  monstersContainer.appendChild(newMonsterTemplate);
  
     return option;
+
  deleteSvg.addEventListener("click", function (event) {
   }
+
     deleteMonster(characters, monsterVnum, newMonsterTemplate, battle);
 +
    var inputMonster = monsterList.querySelector(
 +
      "input[name='" + monsterVnum + "']"
 +
    );
 +
    inputMonster.checked = false;
 +
   });
 +
}
  
   var vnum = name;
+
function monsterManagement(characters, battle) {
 +
   function handleDropdown(searchMonster, monsterList) {
 +
    searchMonster.addEventListener("focus", function (event) {
 +
      showElement(monsterList);
 +
    });
  
  if (isMonster) {
+
    document.addEventListener("mousedown", function (event) {
     name = getMonsterName(name);
+
      var target = event.target;
 +
      if (!monsterList.contains(target) && !searchMonster.contains(target)) {
 +
        hideElement(monsterList);
 +
      }
 +
     });
 
   }
 
   }
  
   if (isMonster && monsterData[vnum][1]) {
+
   function addMonsterNames(monsterList) {
     // pass
+
    var lastMonsterAttributeIndex = monsterData[101].length - 1;
  } else {
+
 
    battle.attackerSelection.appendChild(createOption(name, vnum));
+
     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]
 +
      );
  
  battle.victimSelection.appendChild(createOption(name, vnum));
+
      label.htmlFor = "monster" + monsterVnum;
}
+
      input.id = "monster" + monsterVnum;
 +
      input.type = "checkbox";
  
function updateBattleChoice(characters, battle) {
+
      input.name = monsterVnum;
  var keys = Object.keys(characters.savedCharacters);
 
  
  for (var index = 0; index < keys.length; index++) {
+
      label.appendChild(input);
    var pseudo = keys[index];
+
      label.appendChild(textNode);
    addBattleChoice(battle, pseudo);
+
      li.appendChild(label);
 +
      monsterList.appendChild(li);
 +
    }
 
   }
 
   }
  
   characters.savedMonsters.forEach(function (monsterVnum) {
+
   function filterNames(searchMonster, monsterList) {
     addBattleChoice(battle, monsterVnum, true);
+
     var debounceTimer;
  });
+
 
}
+
    searchMonster.addEventListener("input", function (event) {
 
+
      clearTimeout(debounceTimer);
function isPC(character) {
+
      debounceTimer = setTimeout(function () {
  if (character.race === 0 || character.race === 1) {
+
        var value = toNormalForm(event.target.value);
     return false;
+
        for (var element of monsterList.children) {
 +
          if (!isValueInArray(value, toNormalForm(element.textContent))) {
 +
            hideElement(element);
 +
          } else {
 +
            showElement(element);
 +
          }
 +
        }
 +
      }, 500);
 +
     });
 
   }
 
   }
  return true;
 
}
 
  
function isBoss(character) {
+
  var monsterTemplate = characters.newMonsterTemplate;
   return character.race === 0 && character.rank >= 5;
+
   var monstersContainer = characters.monstersContainer;
}
+
  var monsterList = characters.monsterList;
 +
  var searchMonster = characters.searchMonster;
 +
  var monsterListForm = characters.monsterListForm;
  
function isStone(character) {
+
  document
  return character.race === 1;
+
    .getElementById("monster-link")
}
+
    .querySelector("a")
 +
    .setAttribute("target", "_blank");
  
function isMagicClass(character) {
+
  handleDropdown(searchMonster, monsterList);
   return character.race === "shaman" || character.class === "black_magic";
+
   addMonsterNames(monsterList, characters.monsterListTemplate);
}
+
  filterNames(searchMonster, monsterList);
  
function isDispell(character, skillId) {
+
  characters.savedMonsters.slice().forEach(function (monsterVnum) {
  return character.class === "weaponary" && skillId === 6;
+
    var inputMonster = monsterList.querySelector(
}
+
      "input[name='" + monsterVnum + "']"
 +
    );
  
function isPolymorph(character) {
+
    if (inputMonster) {
  return character.state === "polymorph";
+
      handleNewMonster(
}
+
        characters,
 +
        monsterTemplate,
 +
        monstersContainer,
 +
        battle,
 +
        monsterVnum,
 +
        monsterList
 +
      );
 +
      inputMonster.checked = true;
 +
    } else {
 +
      deleteMonster(characters, monsterVnum, null, battle);
 +
    }
 +
  });
  
function isRiding(character) {
+
  monsterListForm.addEventListener("submit", function (event) {
  return character.state === "horse";
+
    event.preventDefault();
}
+
  });
  
function isBow(weapon) {
+
  monsterListForm.addEventListener("change", function (event) {
  return weapon[1] === 2;
+
    var target = event.target;
}
+
    var monsterVnum = target.name;
  
function calcAttackFactor(attacker, victim) {
+
    if (monsterVnum === "search-monster") {
  function calcCoeffK(dex, level) {
+
      return;
    return Math.min(90, Math.floor((2 * dex + level) / 3));
+
    }
  }
 
  
  var K1 = calcCoeffK(attacker.polymorphDex, attacker.level);
+
    if (target.checked) {
  var K2 = calcCoeffK(victim.polymorphDex, attacker.level);
+
      handleNewMonster(
 +
        characters,
 +
        monsterTemplate,
 +
        monstersContainer,
 +
        battle,
 +
        monsterVnum,
 +
        monsterList
 +
      );
  
  var AR = (K1 + 210) / 300;
+
      characters.savedMonsters.push(monsterVnum);
  var ER = (((2 * K2 + 5) / (K2 + 95)) * 3) / 10;
+
      updateSavedMonsters(characters.savedMonsters);
 +
      addBattleChoice(battle, monsterVnum, true);
 +
    } else {
 +
      var currentMonsterTemplate = monstersContainer.querySelector(
 +
        "[data-name='" + monsterVnum + "']"
 +
      );
 +
      deleteMonster(characters, monsterVnum, currentMonsterTemplate, battle);
 +
    }
 +
  });
  
   return truncateNumber(AR - ER, 8);
+
   addEventListener("storage", function (event) {
}
+
    if (event.key === "newMonsterCalculator") {
 +
      var monsterVnum = Number(event.newValue);
  
function calcMainAttackValue(attacker, attackerWeapon) {
+
      if (!monsterVnum) {
  var leadership = 0;
+
        return;
  var rawWeaponAttackValue = 0;
+
      }
  
  if (isPC(attacker)) {
+
      var inputMonster = monsterList.querySelector(
    var rawWeaponAttackValue = attackerWeapon[3][attacker.weaponUpgrade];
+
        "input[name='" + Math.abs(monsterVnum) + "']"
 +
      );
  
    if (!rawWeaponAttackValue) {
+
      if (inputMonster) {
       rawWeaponAttackValue = 0;
+
        if (
 +
          (monsterVnum > 0 && !inputMonster.checked) ||
 +
          (monsterVnum < 0 && inputMonster.checked)
 +
        ) {
 +
          inputMonster.click();
 +
        }
 +
       }
 
     }
 
     }
 +
  });
 +
}
  
    leadership = attacker.leadership;
+
function removeBattleChoice(battle, name) {
  }
+
  var battleSelects = [battle.attackerSelection, battle.victimSelection];
  
   return 2 * (attacker.level + rawWeaponAttackValue) + leadership;
+
   battleSelects.forEach(function (battleSelect) {
 +
    for (
 +
      var optionIndex = 0;
 +
      optionIndex < battleSelect.options.length;
 +
      optionIndex++
 +
    ) {
 +
      if (battleSelect.options[optionIndex].value === name) {
 +
        battleSelect.remove(optionIndex);
 +
        break;
 +
      }
 +
    }
 +
  });
 
}
 
}
  
function calcStatAttackValue(character) {
+
function addBattleChoice(battle, name, isMonster = false) {
   switch (character.race) {
+
   function createOption(text, vnum) {
     case "warrior":
+
     var option = document.createElement("option");
     case "sura":
+
     option.textContent = text;
      return 2 * character.str;
+
     option.value = vnum;
     case "ninja":
+
 
      return Math.floor((1 / 4) * (character.str + 7 * character.dex));
+
     if (!isMonster) {
     case "shaman":
+
       option.classList.add("notranslate");
       return Math.floor((1 / 3) * (5 * character.int + character.dex));
+
     }
     case "lycan":
+
 
      return character.vit + 2 * character.dex;
+
     return option;
     default:
 
      return 2 * character.str;
 
 
   }
 
   }
}
 
  
function calcSecondaryAttackValue(attacker, attackerWeapon) {
+
   var vnum = name;
   var attackValueOther = 0;
 
  
   var minAttackValue = 0;
+
   if (isMonster) {
   var maxAttackValue = 0;
+
    name = getMonsterName(name);
 +
   }
  
   var minAttackValueSlash = 0;
+
   if (isMonster && monsterData[vnum][1]) {
   var maxAttackValueSlash = 0;
+
    // pass
 +
  } else {
 +
    battle.attackerSelection.appendChild(createOption(name, vnum));
 +
   }
  
   if (isPC(attacker)) {
+
   battle.victimSelection.appendChild(createOption(name, vnum));
    if (isValueInArray("serpent", attackerWeapon[0].toLowerCase())) {
+
}
      var rawAttackValue = attackerWeapon[3][attacker.weaponUpgrade];
 
 
 
      minAttackValue = attacker.minAttackValueRandom - rawAttackValue;
 
      maxAttackValue = attacker.maxAttackValueRandom - rawAttackValue;
 
  
      minAttackValue = Math.max(0, minAttackValue);
+
function updateBattleChoice(characters, battle) {
      maxAttackValue = Math.max(minAttackValue, maxAttackValue);
+
  var keys = Object.keys(characters.savedCharacters);
    } else {
 
      minAttackValue = attackerWeapon[2][2];
 
      maxAttackValue = attackerWeapon[2][3];
 
    }
 
  
    minAttackValueSlash = Math.min(
+
  for (var index = 0; index < keys.length; index++) {
      attacker.minAttackValueSlash,
+
     var pseudo = keys[index];
      attacker.maxAttackValueSlash
+
     addBattleChoice(battle, pseudo);
     );
+
  }
     maxAttackValueSlash = Math.max(
 
      attacker.minAttackValueSlash,
 
      attacker.maxAttackValueSlash
 
    );
 
  
     attackValueOther += attacker.attackValue;
+
  characters.savedMonsters.forEach(function (monsterVnum) {
 +
     addBattleChoice(battle, monsterVnum, true);
 +
  });
 +
}
  
    if (isBow(attackerWeapon) && !isPolymorph(attacker)) {
+
function isPC(character) {
      attackValueOther += 25;
+
  if (character.race === 0 || character.race === 1) {
    }
+
     return false;
  } else {
 
    minAttackValue = attacker.minAttackValue;
 
     maxAttackValue = attacker.maxAttackValue;
 
 
   }
 
   }
 +
  return true;
 +
}
  
   minAttackValue += attacker.minAttackValuePolymorph;
+
function isBoss(character) {
  maxAttackValue += attacker.maxAttackValuePolymorph;
+
   return character.race === 0 && character.rank >= 5;
 +
}
  
   attackValueOther += attacker.statAttackValue;
+
function isStone(character) {
  attackValueOther += attacker.horseAttackValue;
+
   return character.race === 1;
 +
}
  
   var weaponInterval = maxAttackValue - minAttackValue + 1;
+
function isMeleeAttacker(monster) {
  var slashInterval = maxAttackValueSlash - minAttackValueSlash + 1;
+
   return monster.attack == 0;
 +
}
  
   var totalCardinal = weaponInterval * slashInterval * 10000;
+
function isRangeAttacker(monster) {
  var minInterval = Math.min(weaponInterval, slashInterval);
+
   return monster.attack == 1;
 +
}
  
   minAttackValue += minAttackValueSlash;
+
function isMagicAttacker(monster) {
  maxAttackValue += maxAttackValueSlash;
+
   return monster.attack == 2;
 +
}
  
   return [
+
function isMagicClass(character) {
    minAttackValue,
+
   return character.race === "shaman" || character.class === "black_magic";
    maxAttackValue,
 
    attackValueOther,
 
    minInterval,
 
    totalCardinal,
 
  ];
 
 
}
 
}
  
function calcMagicAttackValue(attacker, attackerWeapon) {
+
function isDispell(character, skillId) {
   var minMagicAttackValue = 0;
+
   return character.class === "weaponary" && skillId === 6;
  var maxMagicAttackValue = 0;
+
}
  
   var minMagicAttackValueSlash = 0;
+
function isPolymorph(character) {
  var maxMagicAttackValueSlash = 0;
+
   return character.state === "polymorph";
 +
}
  
  if (isValueInArray("serpent", attackerWeapon[0].toLowerCase())) {
+
function isRiding(character) {
    minMagicAttackValue = attacker.minMagicAttackValueRandom;
+
  return character.state === "horse";
    maxMagicAttackValue = attacker.maxMagicAttackValueRandom;
+
}
  
    maxMagicAttackValue = Math.max(minMagicAttackValue, maxMagicAttackValue);
+
function isBow(weapon) {
   } else {
+
   return weapon.type === 2;
    var rawWeaponAttackValue = attackerWeapon[3][attacker.weaponUpgrade];
+
}
  
    if (!rawWeaponAttackValue) {
+
function calcAttackFactor(attacker, victim) {
      rawWeaponAttackValue = 0;
+
  function calcCoeffK(dex, level) {
     }
+
     return Math.min(90, Math.floor((2 * dex + level) / 3));
 
 
    minMagicAttackValue = attackerWeapon[2][0] + rawWeaponAttackValue;
 
    maxMagicAttackValue = attackerWeapon[2][1] + rawWeaponAttackValue;
 
 
   }
 
   }
  
   minMagicAttackValueSlash = Math.min(
+
   var K1 = calcCoeffK(attacker.polymorphDex, attacker.level);
    attacker.minMagicAttackValueSlash,
+
   var K2 = calcCoeffK(victim.polymorphDex, attacker.level);
    attacker.maxMagicAttackValueSlash
 
  );
 
   maxMagicAttackValueSlash = Math.max(
 
    attacker.minMagicAttackValueSlash,
 
    attacker.maxMagicAttackValueSlash
 
  );
 
  
   var weaponInterval = maxMagicAttackValue - minMagicAttackValue + 1;
+
   var AR = (K1 + 210) / 300;
   var slashInterval = maxMagicAttackValueSlash - minMagicAttackValueSlash + 1;
+
   var ER = (((2 * K2 + 5) / (K2 + 95)) * 3) / 10;
  
   var totalCardinal = weaponInterval * slashInterval * 10000;
+
   return truncateNumber(AR - ER, 8);
  var minInterval = Math.min(weaponInterval, slashInterval);
+
}
  
   minMagicAttackValue += minMagicAttackValueSlash;
+
function calcMainAttackValue(attacker) {
   maxMagicAttackValue += maxMagicAttackValueSlash;
+
   var leadership = 0;
 +
   var rawWeaponAttackValue = 0;
  
   return [minMagicAttackValue, maxMagicAttackValue, minInterval, totalCardinal];
+
   if (isPC(attacker)) {
}
+
    var weaponUpgrades = attacker.weapon.upgrades;
 +
    var maxUpgrade = weaponUpgrades.length - 1;
  
function getPolymorphPower(polymorphPoint, polymorphPowerTable) {
+
    if (attacker.hasOwnProperty("weaponUpgrade")) {
  return polymorphPowerTable[polymorphPoint];
+
      rawWeaponAttackValue =
}
+
        weaponUpgrades[Math.min(attacker.weaponUpgrade, maxUpgrade)];
  
function getSkillPower(skillPoint, skillPowerTable) {
+
      // rare bug when weaponUpgrade is deleted
  return skillPowerTable[skillPoint];
+
    } else {
}
+
      console.log("Warming: weaponUpgrade is missing.");
 +
      rawWeaponAttackValue = weaponUpgrades[maxUpgrade];
 +
    }
  
function getMarriageBonusValue(character, marriageTable, itemName) {
+
    leadership = attacker.leadership;
  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];
+
   return 2 * (attacker.level + rawWeaponAttackValue) + leadership;
 
}
 
}
  
function calcDamageWithPrimaryBonuses(damages, battleValues) {
+
function calcStatAttackValue(character) {
   damages = floorMultiplication(
+
   switch (character.race) {
     damages * battleValues.attackValueCoeff + battleValues.adjustCoeff,
+
     case "warrior":
     1
+
     case "sura":
  );
+
      return 2 * character.str;
  damages += battleValues.attackValueMarriage;
+
     case "ninja":
  damages = floorMultiplication(
+
      return Math.floor((1 / 4) * (character.str + 7 * character.dex));
     damages,
+
    case "shaman":
    battleValues.monsterResistanceMarriageCoeff
+
      return Math.floor((1 / 3) * (5 * character.int + character.dex));
  );
+
    case "lycan":
  damages = floorMultiplication(damages, battleValues.monsterResistanceCoeff);
+
      return character.vit + 2 * character.dex;
  damages = floorMultiplication(damages, battleValues.typeBonusCoeff);
+
     default:
  damages +=
+
       return 2 * character.str;
    floorMultiplication(damages, battleValues.raceBonusCoeff) -
 
    floorMultiplication(damages, battleValues.raceResistanceCoeff);
 
  damages = floorMultiplication(damages, battleValues.stoneBonusCoeff);
 
  damages = floorMultiplication(damages, battleValues.monsterBonusCoeff);
 
 
 
  var elementDamages = 0;
 
  for (var elementBonusCoeff of battleValues.elementBonusCoeff) {
 
     elementDamages += floorMultiplicationWithNegative(
 
       damages,
 
      elementBonusCoeff
 
    );
 
 
   }
 
   }
  damages += elementDamages;
+
}
  
   damages = floorMultiplication(damages, battleValues.damageMultiplier);
+
function calcSecondaryAttackValue(attacker) {
 +
   var attackValueOther = 0;
  
   return damages;
+
   var minAttackValue = 0;
}
+
  var maxAttackValue = 0;
  
function calcDamageWithSecondaryBonuses(
+
   var minAttackValueSlash = 0;
  damages,
+
   var maxAttackValueSlash = 0;
  battleValues,
 
  damagesType,
 
  minPiercingDamages,
 
  damagesWithPrimaryBonuses
 
) {
 
  damages = floorMultiplication(damages, battleValues.magicResistanceCoeff);
 
  damages = floorMultiplication(damages, battleValues.weaponDefenseCoeff);
 
   damages = floorMultiplication(damages, battleValues.tigerStrengthCoeff);
 
   damages = floorMultiplication(damages, battleValues.blessingBonusCoeff);
 
  
   if (damagesType.criticalHit) {
+
   var attackerWeapon = attacker.weapon;
    damages *= 2;
 
  }
 
  
   if (damagesType.piercingHit) {
+
   if (isPC(attacker)) {
     damages += battleValues.defense + Math.min(0, minPiercingDamages);
+
     if (attackerWeapon.isSerpent) {
    damages += floorMultiplication(
+
      var rawAttackValue = attackerWeapon.upgrades[attacker.weaponUpgrade];
      damagesWithPrimaryBonuses,
 
      battleValues.extraPiercingHitCoeff
 
    );
 
  }
 
  
  damages = floorMultiplication(damages, battleValues.averageDamageCoeff);
+
      minAttackValue = attacker.minAttackValueRandom - rawAttackValue;
  damages = floorMultiplication(
+
      maxAttackValue = attacker.maxAttackValueRandom - rawAttackValue;
    damages,
 
    battleValues.averageDamageResistanceCoeff
 
  );
 
  damages = floorMultiplication(
 
    damages,
 
    battleValues.skillDamageResistanceCoeff
 
  );
 
  
  damages = floorMultiplication(damages, battleValues.rankBonusCoeff);
+
      minAttackValue = Math.max(0, minAttackValue);
  damages = Math.max(0, damages + battleValues.defensePercent);
+
      maxAttackValue = Math.max(minAttackValue, maxAttackValue);
  damages += Math.min(
+
     } else {
    300,
+
      minAttackValue = attackerWeapon.minAttackValue;
     floorMultiplication(damages, battleValues.damageBonusCoeff)
+
      maxAttackValue = attackerWeapon.maxAttackValue;
  );
+
    }
  damages = floorMultiplication(damages, battleValues.empireMalusCoeff);
 
  damages = floorMultiplication(damages, battleValues.sungMaStrBonusCoeff);
 
  damages -= floorMultiplication(damages, battleValues.sungmaStrMalusCoeff);
 
  
  damages = floorMultiplication(damages, battleValues.whiteDragonElixirCoeff);
+
    minAttackValueSlash = Math.min(
  damages = floorMultiplication(damages, battleValues.steelDragonElixirCoeff);
+
      attacker.minAttackValueSlash,
 +
      attacker.maxAttackValueSlash
 +
    );
 +
    maxAttackValueSlash = Math.max(
 +
      attacker.minAttackValueSlash,
 +
      attacker.maxAttackValueSlash
 +
    );
  
  return damages;
+
    attackValueOther += attacker.attackValue;
}
 
  
function calcSkillDamageWithSecondaryBonuses(
+
    if (isBow(attackerWeapon) && !isPolymorph(attacker)) {
  damages,
+
      attackValueOther += 25;
  battleValues,
+
    }
  damagesType,
+
   } else {
   minPiercingDamages
+
    minAttackValue = attacker.minAttackValue;
) {
+
    maxAttackValue = attacker.maxAttackValue;
  damages = floorMultiplication(damages, battleValues.magicResistanceCoeff);
+
  }
  damages = floorMultiplication(damages, battleValues.weaponDefenseCoeff);
 
  
   damages -= battleValues.defense;
+
   minAttackValue += attacker.minAttackValuePolymorph;
 +
  maxAttackValue += attacker.maxAttackValuePolymorph;
  
   damages = floorMultiplication(damages, battleValues.skillWardCoeff);
+
   attackValueOther += attacker.statAttackValue;
   damages = floorMultiplication(damages, battleValues.skillBonusCoeff);
+
   attackValueOther += attacker.horseAttackValue;
  damages = floorMultiplication(damages, battleValues.skillBonusByBonusCoeff);
 
  damages = floorMultiplication(damages, battleValues.tigerStrengthCoeff);
 
  
   if (damagesType.criticalHit) {
+
   var weaponInterval = maxAttackValue - minAttackValue + 1;
    damages *= 2;
+
   var slashInterval = maxAttackValueSlash - minAttackValueSlash + 1;
   }
 
  
   if (damagesType.piercingHit) {
+
   var totalCardinal = weaponInterval * slashInterval * 1_000_000;
    damages +=
+
  var minInterval = Math.min(weaponInterval, slashInterval);
      battleValues.piercingHitDefense + Math.min(0, minPiercingDamages);
 
  }
 
  
   damages = floorMultiplication(damages, battleValues.skillDamageCoeff);
+
   minAttackValue += minAttackValueSlash;
   damages = floorMultiplication(
+
   maxAttackValue += maxAttackValueSlash;
    damages,
 
    battleValues.skillDamageResistanceCoeff
 
  );
 
  
   damages = floorMultiplication(damages, battleValues.rankBonusCoeff);
+
   return {
  damages = Math.max(0, damages + battleValues.defensePercent);
+
    minAttackValue: minAttackValue,
  damages += Math.min(
+
    maxAttackValue: maxAttackValue,
     300,
+
    attackValueOther: attackValueOther,
     floorMultiplication(damages, battleValues.damageBonusCoeff)
+
     totalCardinal: totalCardinal,
  );
+
     weights: calcWeights(minAttackValue, maxAttackValue, minInterval),
  damages = floorMultiplication(damages, battleValues.empireMalusCoeff);
+
    possibleDamagesCount: maxAttackValue - minAttackValue + 1,
   damages = floorMultiplication(damages, battleValues.sungMaStrBonusCoeff);
+
   };
  damages -= floorMultiplication(damages, battleValues.sungmaStrMalusCoeff);
+
}
  
   damages = floorMultiplication(damages, battleValues.whiteDragonElixirCoeff);
+
function calcMagicAttackValue(attacker) {
   damages = floorMultiplication(damages, battleValues.steelDragonElixirCoeff);
+
   var minMagicAttackValue = 0;
 +
   var maxMagicAttackValue = 0;
  
   return damages;
+
   var minMagicAttackValueSlash = 0;
}
+
  var maxMagicAttackValueSlash = 0;
  
function computePolymorphPoint(attacker, victim, polymorphPowerTable) {
+
   var attackerWeapon = attacker.weapon;
   attacker.statAttackValue = 0;
 
  
   attacker.polymorphDex = attacker.dex;
+
   if (attackerWeapon.isSerpent) {
  victim.polymorphDex = victim.dex;
+
    minMagicAttackValue = attacker.minMagicAttackValueRandom;
 +
    maxMagicAttackValue = attacker.maxMagicAttackValueRandom;
  
  attacker.minAttackValuePolymorph = 0;
+
    maxMagicAttackValue = Math.max(minMagicAttackValue, maxMagicAttackValue);
   attacker.maxAttackValuePolymorph = 0;
+
   } else {
 +
    var rawWeaponAttackValue = attackerWeapon.upgrades[attacker.weaponUpgrade];
  
  if (isPC(attacker) && isPolymorph(attacker) && polymorphPowerTable) {
+
    if (!rawWeaponAttackValue) {
    var polymorphPowerPct =
+
      rawWeaponAttackValue = 0;
      getPolymorphPower(attacker.polymorphPoint, polymorphPowerTable) / 100;
+
     }
     var polymorphMonster = createMonster(attacker.polymorphMonster);
 
  
     var polymorphStr = floorMultiplication(
+
     minMagicAttackValue =
       polymorphPowerPct,
+
       attackerWeapon.minMagicAttackValue + rawWeaponAttackValue;
       polymorphMonster.str
+
    maxMagicAttackValue =
    );
+
       attackerWeapon.maxMagicAttackValue + rawWeaponAttackValue;
 +
  }
  
     attacker.polymorphDex += floorMultiplication(
+
  minMagicAttackValueSlash = Math.min(
      polymorphPowerPct,
+
    attacker.minMagicAttackValueSlash,
      polymorphMonster.dex
+
     attacker.maxMagicAttackValueSlash
    );
+
  );
 +
  maxMagicAttackValueSlash = Math.max(
 +
    attacker.minMagicAttackValueSlash,
 +
    attacker.maxMagicAttackValueSlash
 +
  );
  
    attacker.minAttackValuePolymorph = floorMultiplication(
+
  var weaponInterval = maxMagicAttackValue - minMagicAttackValue + 1;
      polymorphPowerPct,
+
  var slashInterval = maxMagicAttackValueSlash - minMagicAttackValueSlash + 1;
      polymorphMonster.minAttackValue
 
    );
 
    attacker.maxAttackValuePolymorph = floorMultiplication(
 
      polymorphPowerPct,
 
      polymorphMonster.maxAttackValue
 
    );
 
  
    if (!attacker.weapon) {
+
  var totalCardinal = weaponInterval * slashInterval * 1_000_000;
      attacker.maxAttackValuePolymorph += 1;
+
  var minInterval = Math.min(weaponInterval, slashInterval);
    }
 
  
    attacker.attackValue = 0;
+
  minMagicAttackValue += minMagicAttackValueSlash;
 +
  maxMagicAttackValue += maxMagicAttackValueSlash;
  
     if (isMagicClass(attacker)) {
+
  return {
       attacker.statAttackValue = 2 * (polymorphStr + attacker.int);
+
    minMagicAttackValue: minMagicAttackValue,
    } else {
+
     maxMagicAttackValue: maxMagicAttackValue,
       attacker.statAttackValue = 2 * (polymorphStr + attacker.str);
+
    magicAttackValueAugmentation: getMagicAttackValueAugmentation(
     }
+
       minMagicAttackValue,
  } else {
+
      maxMagicAttackValue,
     attacker.statAttackValue = calcStatAttackValue(attacker);
+
       attacker.magicAttackValue
   }
+
    ),
 +
     totalCardinal: totalCardinal,
 +
     weights: calcWeights(minMagicAttackValue, maxMagicAttackValue, minInterval),
 +
    possibleDamagesCount: maxMagicAttackValue - minMagicAttackValue + 1,
 +
   };
 
}
 
}
  
function computeHorse(attacker) {
+
function getPolymorphPower(polymorphPoint, polymorphPowerTable) {
   attacker.horseAttackValue = 0;
+
   return polymorphPowerTable[polymorphPoint];
 +
}
  
  if (isPC(attacker) && isRiding(attacker)) {
+
function getSkillPower(skillPoint, skillPowerTable) {
    var horseConstant = 30;
+
  return skillPowerTable[skillPoint];
 +
}
  
    if (attacker.class === "weaponary") {
+
function getMarriageBonusValue(character, marriageTable, itemName) {
      horseConstant = 60;
+
  var index;
    }
+
  var lovePoint = character.lovePoint;
  
     attacker.horseAttackValue = floorMultiplication(
+
  if (lovePoint < 65) {
      2 * attacker.level + attacker.statAttackValue,
+
     index = 0;
      attacker.horsePoint / horseConstant
+
  } else if (lovePoint < 80) {
     );
+
    index = 1;
   }
+
  } else if (lovePoint < 100) {
 +
    index = 2;
 +
  } else {
 +
     index = 3;
 +
   }
 +
 
 +
  return marriageTable[itemName][index];
 
}
 
}
  
function getRankBonus(attacker) {
+
function calcDamageWithPrimaryBonuses(damages, bonusValues) {
   if (attacker.lowRank !== "on") {
+
   damages = Math.floor((damages * bonusValues.attackValueCoeff) / 100);
    return 0;
 
  }
 
  
   switch (attacker.playerRank) {
+
   damages += bonusValues.attackValueMarriage;
    case "aggressive":
 
      return 1;
 
    case "fraudulent":
 
      return 2;
 
    case "malicious":
 
      return 3;
 
    case "cruel":
 
      return 5;
 
  }
 
  
   return 0;
+
   damages = Math.floor(
}
+
    (damages * bonusValues.monsterResistanceMarriageCoeff) / 100
 +
  );
 +
  damages = Math.floor((damages * bonusValues.monsterResistanceCoeff) / 100);
  
function calcElementCoeffPvP(elementBonus, mapping, attacker, victim) {
+
  damages += Math.floor((damages * bonusValues.typeBonusCoeff) / 100);
   var minElementMalus = 0;
+
   damages +=
  var maxDifference = 0;
+
    Math.floor((damages * bonusValues.raceBonusCoeff) / 100) -
   var savedElementDifferences = [];
+
    Math.floor((damages * bonusValues.raceResistanceCoeff) / 100);
   var elementBonusIndex = 0;
+
   damages += Math.floor((damages * bonusValues.stoneBonusCoeff) / 100);
 +
   damages += Math.floor((damages * bonusValues.monsterBonusCoeff) / 100);
  
   for (var index = 0; index < elementBonus.length; index++) {
+
   var elementBonusCoeff = bonusValues.elementBonusCoeff;
    if (!attacker[mapping.elementBonus[index]]) {
 
      continue;
 
    }
 
  
    var elementDifference =
+
  damages +=
      attacker[mapping.elementBonus[index]] -
+
    Math.trunc((damages * elementBonusCoeff[0]) / 10000) +
      victim[mapping.elementResistance[index]];
+
    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);
  
    if (elementDifference >= 0) {
+
  damages = Math.floor(damages * bonusValues.damageMultiplier);
      elementBonus[elementBonusIndex] = elementDifference / 1000;
 
      minElementMalus -= elementDifference;
 
      maxDifference = Math.max(maxDifference, elementDifference);
 
      elementBonusIndex++;
 
    } else {
 
      savedElementDifferences.push(elementDifference);
 
    }
 
  }
 
  
   if (!savedElementDifferences.length) {
+
   return damages;
    return;
+
}
  }
 
  
   minElementMalus += maxDifference;
+
function calcDamageWithSecondaryBonuses(
   savedElementDifferences.sort(compareNumbers);
+
  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);
  
   for (var index = 0; index < savedElementDifferences.length; index++) {
+
   if (damagesType.criticalHit) {
     var elementDifference = savedElementDifferences[index];
+
     damages *= 2;
 +
  }
  
     elementBonus[elementBonusIndex + index] =
+
  if (damagesType.piercingHit) {
      Math.max(minElementMalus, elementDifference) / 1000;
+
     damages += bonusValues.defenseBoost + Math.min(0, minPiercingDamages);
 
+
     damages += Math.floor(
     minElementMalus = Math.min(
+
       (damagesWithPrimaryBonuses * bonusValues.extraPiercingHitCoeff) / 1000
       0,
 
      Math.max(minElementMalus, minElementMalus - elementDifference)
 
 
     );
 
     );
 
   }
 
   }
}
 
  
function skillChanceReduction(value) {
+
  damages = Math.floor((damages * bonusValues.averageDamageCoeff) / 100);
   if (value <= 9) {
+
  damages = Math.floor(
     return Math.floor(value / 2);
+
    (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;
 
   }
 
   }
  return 5 + Math.floor((value - 10) / 4);
 
}
 
  
function magicResistanceToCoeff(magicResistance) {
+
  if (damagesType.piercingHit) {
  if (magicResistance) {
+
    damages += bonusValues.defenseBoost + Math.min(0, minPiercingDamages);
     return 2000 / (6 * magicResistance + 1000) - 1;
+
     damages += Math.floor(
 +
      (tempDamages * bonusValues.extraPiercingHitCoeff) / 1000
 +
    );
 
   }
 
   }
   return 1;
+
 
 +
  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 createPhysicalBattleValues(
+
function computePolymorphPoint(attacker, victim, polymorphPowerTable) {
  attacker,
+
   attacker.statAttackValue = 0;
  attackerWeapon,
 
  victim,
 
  mapping,
 
  polymorphPowerTable,
 
  marriageTable,
 
  skillPowerTable
 
) {
 
   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 tigerStrength = 0;
 
  var blessingBonus = 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;
 
  var sungMaStrBonus = 0;
 
  var sungmaStrMalus = 0;
 
  var whiteDragonElixir = 0;
 
  var steelDragonElixir = 0;
 
  
   computePolymorphPoint(attacker, victim, polymorphPowerTable);
+
   attacker.polymorphDex = attacker.dex;
   computeHorse(attacker);
+
   victim.polymorphDex = victim.dex;
  
   if (isPC(attacker)) {
+
  attacker.minAttackValuePolymorph = 0;
     attackValuePercent = attacker.attackValuePercent;
+
  attacker.maxAttackValuePolymorph = 0;
     attackMeleeMagic = attacker.attackMeleeMagic;
+
 
 +
   if (isPC(attacker) && isPolymorph(attacker)) {
 +
     var polymorphPowerPct =
 +
      getPolymorphPower(attacker.polymorphPoint, polymorphPowerTable) / 100;
 +
     var polymorphMonster = createMonster(attacker.polymorphMonster);
  
     var weaponType = attackerWeapon[1];
+
     var polymorphStr = floorMultiplication(
 +
      polymorphPowerPct,
 +
      polymorphMonster.str
 +
    );
  
     var weaponDefenseName = mapping.defenseWeapon[weaponType];
+
     attacker.polymorphDex += floorMultiplication(
     var weaponDefenseBreakName = mapping.breakWeapon[weaponType];
+
      polymorphPowerPct,
 +
      polymorphMonster.dex
 +
     );
  
     if (victim.hasOwnProperty(weaponDefenseName)) {
+
     attacker.minAttackValuePolymorph = floorMultiplication(
       weaponDefense = victim[weaponDefenseName];
+
      polymorphPowerPct,
     }
+
      polymorphMonster.minAttackValue
 +
    );
 +
    attacker.maxAttackValuePolymorph = floorMultiplication(
 +
       polymorphPowerPct,
 +
      polymorphMonster.maxAttackValue
 +
     );
  
     if (attacker.whiteDragonElixir === "on") {
+
     if (!attacker.weapon) {
       whiteDragonElixir = 10;
+
       attacker.maxAttackValuePolymorph += 1;
 
     }
 
     }
  
     if (isPC(victim)) {
+
     attacker.attackValue = 0;
      if (weaponType === 2 && !isPolymorph(attacker)) {
 
        missPercentage = victim.arrowBlock;
 
      } else {
 
        missPercentage = victim.meleeBlock;
 
      }
 
  
       missPercentage +=
+
    if (isMagicClass(attacker)) {
        victim.meleeArrowBlock -
+
       attacker.statAttackValue = 2 * (polymorphStr + attacker.int);
        (missPercentage * victim.meleeArrowBlock) / 100;
+
    } else {
 
+
       attacker.statAttackValue = 2 * (polymorphStr + attacker.str);
       typeBonus = Math.max(1, attacker.humanBonus - victim.humanResistance);
+
    }
      raceBonus = attacker[mapping.raceBonus[victim.race]];
+
  } else {
      raceResistance = victim[mapping.raceResistance[attacker.race]];
+
    attacker.statAttackValue = calcStatAttackValue(attacker);
 +
  }
 +
}
  
      calcElementCoeffPvP(elementBonus, mapping, attacker, victim);
+
function computeHorse(attacker) {
 +
  attacker.horseAttackValue = 0;
  
      if (weaponType !== 2 && attacker.hasOwnProperty(weaponDefenseBreakName)) {
+
  if (isPC(attacker) && isRiding(attacker)) {
        weaponDefense -= attacker[weaponDefenseBreakName];
+
    var horseConstant = 30;
      }
 
  
      criticalHitPercentage = 0;
+
     if (attacker.class === "weaponary") {
      blessingBonus = calcBlessingBonus(skillPowerTable, victim);
+
      horseConstant = 60;
      averageDamageResistance = victim.averageDamageResistance;
+
    }
     } else {
 
      if (attacker.isMarried === "on") {
 
        if (attacker.loveNecklace === "on") {
 
          attackValueMarriage = getMarriageBonusValue(
 
            attacker,
 
            marriageTable,
 
            "loveNecklace"
 
          );
 
        }
 
  
        if (attacker.loveEarrings === "on") {
+
    attacker.horseAttackValue = floorMultiplication(
          criticalHitPercentageMarriage = getMarriageBonusValue(
+
      2 * attacker.level + attacker.statAttackValue,
            attacker,
+
      attacker.horsePoint / horseConstant
            marriageTable,
+
    );
            "loveEarrings"
+
  }
          );
+
}
        }
 
  
        if (attacker.harmonyEarrings === "on") {
+
function getRankBonus(attacker) {
          piercingHitPercentageMarriage = getMarriageBonusValue(
+
  if (attacker.lowRank !== "on") {
            attacker,
+
    return 0;
            marriageTable,
+
  }
            "harmonyEarrings"
 
          );
 
        }
 
      }
 
  
      if (attacker.tigerStrength === "on") {
+
  switch (attacker.playerRank) {
        tigerStrength = 40;
+
    case "aggressive":
       }
+
      return 1;
 +
    case "fraudulent":
 +
      return 2;
 +
    case "malicious":
 +
      return 3;
 +
    case "cruel":
 +
       return 5;
 +
  }
  
      for (var index = 0; index < elementBonus.length; index++) {
+
  return 0;
        var elementBonusName = mapping.elementBonus[index];
+
}
        var elementResistanceName = mapping.elementResistance[index];
 
  
        if (attacker[elementBonusName] && victim[elementBonusName]) {
+
function calcElementCoeffPvP(elementBonus, mapping, attacker, victim) {
          elementBonus[index] =
+
  var minElementMalus = 0;
            (attacker[elementBonusName] - victim[elementResistanceName]) / 200;
+
  var maxDifference = 0;
        } else {
+
  var savedElementDifferences = [];
          elementBonus[index] = attacker[elementBonusName] / 2000;
+
  var elementBonusIndex = 0;
        }
 
      }
 
  
      var victimType = victim.type;
+
  for (var index = 0; index < elementBonus.length; index++) {
 +
    if (!attacker[mapping.elementBonus[index]]) {
 +
      continue;
 +
    }
  
      if (victimType !== -1) {
+
    var elementDifference =
        typeBonus = attacker[mapping.typeFlag[victimType]];
+
      attacker[mapping.elementBonus[index]] -
       }
+
       victim[mapping.elementResistance[index]];
  
       monsterBonus = attacker.monsterBonus;
+
    if (elementDifference >= 0) {
 +
      elementBonus[elementBonusIndex] = 10 * elementDifference;
 +
      minElementMalus -= elementDifference;
 +
       maxDifference = Math.max(maxDifference, elementDifference);
 +
      elementBonusIndex++;
 +
    } else {
 +
      savedElementDifferences.push(elementDifference);
 +
    }
 +
  }
  
      if (isStone(victim)) {
+
  if (!savedElementDifferences.length) {
        stoneBonus = attacker.stoneBonus;
+
    return;
      }
+
  }
  
      if (isBoss(victim)) {
+
  minElementMalus += maxDifference;
        averageDamage += attacker.bossDamage;
+
  savedElementDifferences.sort(compareNumbers);
      }
 
  
      if (attacker.onYohara === "on") {
+
  for (var index = 0; index < savedElementDifferences.length; index++) {
        var sungmaStrDifference = attacker.sungmaStr - attacker.sungmaStrMalus;
+
    var elementDifference = savedElementDifferences[index];
  
        if (sungmaStrDifference >= 0) {
+
    elementBonus[elementBonusIndex + index] =
          sungMaStrBonus = sungmaStrDifference;
+
      10 * Math.max(minElementMalus, elementDifference);
        } else {
 
          sungmaStrMalus = 0.5;
 
        }
 
      }
 
    }
 
  
     averageDamage += attacker.averageDamage;
+
     minElementMalus = Math.min(
    rankBonus = getRankBonus(attacker);
+
      0,
     damageBonus = attacker.damageBonus;
+
      Math.max(minElementMalus, minElementMalus - elementDifference)
 +
     );
 +
  }
 +
}
  
    if (attacker.empireMalus === "on") {
+
function skillChanceReduction(value) {
      empireMalus = 10;
+
   if (value <= 9) {
    }
+
    return Math.floor(value / 2);
   } else {
+
  }
    if (isPC(victim)) {
+
  return 5 + Math.floor((value - 10) / 4);
      if (victim.isMarried === "on") {
+
}
        if (victim.harmonyBracelet === "on") {
 
          monsterResistanceMarriage = getMarriageBonusValue(
 
            victim,
 
            marriageTable,
 
            "harmonyBracelet"
 
          );
 
        }
 
  
        if (victim.harmonyNecklace === "on") {
+
function magicResistanceToCoeff(magicResistance) {
          defenseMarriage = getMarriageBonusValue(
+
  if (magicResistance) {
            victim,
+
    return 2000 / (6 * magicResistance + 1000) - 1;
            marriageTable,
+
  }
            "harmonyNecklace"
+
  return 1;
          );
+
}
        }
 
      }
 
  
      monsterResistance = victim.monsterResistance;
+
function createBattleValues(attacker, victim, battle, skillType) {
 +
  var { mapping, constants } = battle;
 +
  var calcAttackValues;
  
      for (var index = 0; index < elementBonus.length; index++) {
+
  var missPercentage = 0;
        var elementBonusName = mapping.elementBonus[index];
+
  var attackValueMeleeMagic = 0;
        var elementResistanceName = mapping.elementResistance[index];
+
  var attackValueMarriage = 0;
 
+
  var monsterResistanceMarriage = 0;
        if (attacker[elementBonusName]) {
+
  var monsterResistance = 0;
          elementBonus[index] =
+
  var typeBonus = 0;
            (attacker[elementBonusName] - victim[elementResistanceName]) / 125;
+
  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;
  
      if (attacker.attack == 0) {
+
  computePolymorphPoint(attacker, victim, constants.polymorphPowerTable);
        missPercentage = victim.meleeBlock;
+
  computeHorse(attacker);
        averageDamageResistance = victim.averageDamageResistance;
 
        blessingBonus = calcBlessingBonus(skillPowerTable, victim);
 
      } else if (attacker.attack == 1) {
 
        missPercentage = victim.arrowBlock;
 
        weaponDefense = victim.arrowDefense;
 
        averageDamageResistance = victim.averageDamageResistance;
 
        blessingBonus = calcBlessingBonus(skillPowerTable, victim);
 
      } else {
 
        missPercentage = victim.arrowBlock;
 
        skillDamageResistance = victim.skillDamageResistance;
 
        magicResistance = victim.magicResistance;
 
      }
 
  
       missPercentage +=
+
  if (isPC(attacker)) {
        victim.meleeArrowBlock -
+
    if (weaponData.hasOwnProperty(attacker.weapon)) {
        (missPercentage * victim.meleeArrowBlock) / 100;
+
       attacker.weapon = createWeapon(attacker.weapon);
 +
    } else {
 +
      attacker.weapon = createWeapon(0);
 
     }
 
     }
  
     typeBonus = 1;
+
     attackValueMeleeMagic =
     damageMultiplier = attacker.damageMultiplier;
+
      attacker.attackValuePercent + Math.min(100, attacker.attackMeleeMagic);
  }
+
 
 +
     var weaponType = attacker.weapon.type;
  
  if (isPC(victim)) {
+
    if (skillType && attacker.class === "archery") {
    if (victim.biologist70 === "on") {
+
      if (weaponType !== 2) {
       victim.defense = floorMultiplication(victim.defense, 1.1);
+
        useDamages = 0;
 +
        weaponType = 2;
 +
      }
 +
       defense = 0;
 
     }
 
     }
    criticalHitPercentage = Math.max(
 
      0,
 
      criticalHitPercentage - victim.criticalHitResistance
 
    );
 
    piercingHitPercentage = Math.max(
 
      0,
 
      piercingHitPercentage - victim.piercingHitResistance
 
    );
 
  
     if (isMagicClass(victim)) {
+
     var weaponDefenseName = mapping.defenseWeapon[weaponType];
      defensePercent = (-2 * victim.magicDefense * victim.defensePercent) / 100;
+
    var weaponDefenseBreakName = mapping.breakWeapon[weaponType];
    } else {
+
 
       defensePercent = (-2 * victim.defense * victim.defensePercent) / 100;
+
    if (victim.hasOwnProperty(weaponDefenseName)) {
 +
       weaponDefense = victim[weaponDefenseName];
 
     }
 
     }
  
     if (victim.steelDragonElixir === "on") {
+
     if (isChecked(attacker.whiteDragonElixir)) {
       steelDragonElixir = 10;
+
       whiteDragonElixir = 10;
 
     }
 
     }
  }
 
  
  missPercentage = Math.min(100, missPercentage);
+
    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;
 +
      }
  
  var battleValues = {
+
      typeBonus = Math.max(1, attacker.humanBonus - victim.humanResistance);
    missPercentage: missPercentage,
+
      raceBonus = attacker[mapping.raceBonus[victim.race]];
    adjustCoeff: 0,
+
      raceResistance = victim[mapping.raceResistance[attacker.race]];
    attackValueCoeff:
+
 
      1 + (attackValuePercent + Math.min(100, attackMeleeMagic)) / 100,
+
      calcElementCoeffPvP(elementBonus, mapping, attacker, victim);
    attackValueMarriage: attackValueMarriage,
+
 
    monsterResistanceMarriageCoeff: 1 - monsterResistanceMarriage / 100,
+
       if (weaponType !== 2 && attacker.hasOwnProperty(weaponDefenseBreakName)) {
    monsterResistanceCoeff: 1 - monsterResistance / 100,
+
        weaponDefense -= attacker[weaponDefenseBreakName];
    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,
 
    tigerStrengthCoeff: 1 + tigerStrength / 100,
 
    blessingBonusCoeff: 1 - blessingBonus / 100,
 
    extraPiercingHitCoeff: 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: Math.floor(defensePercent),
 
    damageBonusCoeff: damageBonus / 100,
 
    empireMalusCoeff: 1 - empireMalus / 100,
 
    sungMaStrBonusCoeff: 1 + sungMaStrBonus / 10000,
 
    sungmaStrMalusCoeff: sungmaStrMalus,
 
    whiteDragonElixirCoeff: 1 + whiteDragonElixir / 100,
 
    steelDragonElixirCoeff: 1 - steelDragonElixir / 100,
 
  };
 
  
  criticalHitPercentage = Math.min(
+
      criticalHitPercentage = 0;
     criticalHitPercentage + criticalHitPercentageMarriage,
+
     } else {
    100
+
      if (isChecked(attacker.isMarried)) {
  );
+
        if (isChecked(attacker.loveNecklace)) {
  piercingHitPercentage = Math.min(
+
          attackValueMarriage = getMarriageBonusValue(
    piercingHitPercentage + piercingHitPercentageMarriage,
+
            attacker,
    100
+
            constants.marriageTable,
  );
+
            "loveNecklace"
 +
          );
 +
        }
  
  battleValues.damagesTypeCombinaison = [
+
         if (isChecked(attacker.loveEarrings)) {
    {
+
          criticalHitPercentage += getMarriageBonusValue(
      criticalHit: false,
+
            attacker,
      piercingHit: false,
+
            constants.marriageTable,
      weight:
+
            "loveEarrings"
         (100 - criticalHitPercentage) *
+
          );
        (100 - piercingHitPercentage) *
+
         }
        (100 - missPercentage),
+
 
      name: "Coup classique",
+
         if (isChecked(attacker.harmonyEarrings)) {
    },
+
          piercingHitPercentage += getMarriageBonusValue(
    {
+
            attacker,
      criticalHit: true,
+
            constants.marriageTable,
      piercingHit: false,
+
            "harmonyEarrings"
      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 perçant",
 
    },
 
  ];
 
  
  return battleValues;
+
      if (isChecked(attacker.tigerStrength)) {
}
+
        tigerStrength = 40;
 +
      }
  
function createSkillBattleValues(
+
      for (var index = 0; index < elementBonus.length; index++) {
  attacker,
+
        var elementBonusName = mapping.elementBonus[index];
  attackerWeapon,
+
        var elementResistanceName = mapping.elementResistance[index];
  victim,
 
  mapping,
 
  marriageTable,
 
  magicSkill
 
) {
 
  var adjustCoeff = 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 damageMultiplier = 1;
 
  var useDamages = 1;
 
  var defense = victim.defense;
 
  var magicResistance = 0;
 
  var weaponDefense = 0;
 
  var tigerStrength = 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;
 
  var sungMaStrBonus = 0;
 
  var sungmaStrMalus = 0;
 
  var whiteDragonElixir = 0;
 
  var steelDragonElixir = 0;
 
  
  computePolymorphPoint(attacker, victim);
+
        if (attacker[elementBonusName] && victim[elementBonusName]) {
  computeHorse(attacker);
+
          elementBonus[index] =
 +
            50 * (attacker[elementBonusName] - victim[elementResistanceName]);
 +
        } else {
 +
          elementBonus[index] = 5 * attacker[elementBonusName];
 +
        }
 +
      }
  
  if (isPC(attacker)) {
+
      var victimType = victim.type;
    attackValuePercent = attacker.attackValuePercent;
 
    attackMeleeMagic = attacker.attackMeleeMagic;
 
  
    var weaponType = attackerWeapon[1];
+
      if (victimType !== -1) {
 +
        typeBonus = attacker[mapping.typeFlag[victimType]];
 +
      }
  
    if (attacker.class === "archery") {
+
      monsterBonus = attacker.monsterBonus;
      if (weaponType !== 2) {
+
 
        useDamages = 0;
+
      if (isStone(victim)) {
         weaponType = 2;
+
        stoneBonus = attacker.stoneBonus;
 +
      }
 +
 
 +
      if (isBoss(victim)) {
 +
        if (skillType) {
 +
          skillDamage += attacker.skillBossDamage;
 +
         } else {
 +
          averageDamage += attacker.bossDamage;
 +
        }
 
       }
 
       }
      defense = 0;
 
    }
 
  
    var weaponDefenseName = mapping.defenseWeapon[weaponType];
+
      if (isChecked(attacker.onYohara)) {
    var weaponDefenseBreakName = mapping.breakWeapon[weaponType];
+
        var sungmaStrDifference = attacker.sungmaStr - attacker.sungmaStrMalus;
  
    if (victim.hasOwnProperty(weaponDefenseName)) {
+
        if (sungmaStrDifference >= 0) {
      weaponDefense = victim[weaponDefenseName];
+
          sungMaStrBonus = sungmaStrDifference;
 +
        } else {
 +
          sungmaStrMalus = 0.5;
 +
        }
 +
      }
 
     }
 
     }
  
     if (attacker.whiteDragonElixir === "on") {
+
     if (skillType) {
       whiteDragonElixir = 10;
+
      skillDamage += attacker.skillDamage;
 +
    } else {
 +
       averageDamage += attacker.averageDamage;
 
     }
 
     }
  
 +
    rankBonus = getRankBonus(attacker);
 +
    damageBonus = attacker.damageBonus;
 +
 +
    if (isChecked(attacker.empireMalus)) {
 +
      empireMalus = 1;
 +
    }
 +
  } else {
 
     if (isPC(victim)) {
 
     if (isPC(victim)) {
       typeBonus = Math.max(1, attacker.humanBonus - victim.humanResistance);
+
       if (isChecked(victim.isMarried)) {
      raceBonus = attacker[mapping.raceBonus[victim.race]];
+
        if (isChecked(victim.harmonyBracelet)) {
      raceResistance = victim[mapping.raceResistance[attacker.race]];
+
          monsterResistanceMarriage = getMarriageBonusValue(
 +
            victim,
 +
            constants.marriageTable,
 +
            "harmonyBracelet"
 +
          );
 +
        }
  
      calcElementCoeffPvP(elementBonus, mapping, attacker, victim);
+
         if (isChecked(victim.harmonyNecklace) && !skillType) {
 
+
           defenseMarriage = getMarriageBonusValue(
      if (weaponType !== 2 && attacker.hasOwnProperty(weaponDefenseBreakName)) {
+
             victim,
         weaponDefense -= attacker[weaponDefenseBreakName];
+
             constants.marriageTable,
      }
+
             "harmonyNecklace"
 
 
      criticalHitPercentage = 0;
 
    } else {
 
      if (attacker.isMarried === "on") {
 
        if (attacker.loveNecklace === "on") {
 
          attackValueMarriage = getMarriageBonusValue(
 
            attacker,
 
            marriageTable,
 
            "loveNecklace"
 
          );
 
        }
 
 
 
        if (attacker.loveEarrings === "on") {
 
           criticalHitPercentage += getMarriageBonusValue(
 
             attacker,
 
            marriageTable,
 
             "loveEarrings"
 
          );
 
        }
 
 
 
        if (attacker.harmonyEarrings === "on") {
 
          piercingHitPercentage += getMarriageBonusValue(
 
            attacker,
 
            marriageTable,
 
             "harmonyEarrings"
 
 
           );
 
           );
 
         }
 
         }
 
       }
 
       }
  
       if (attacker.tigerStrength === "on") {
+
       monsterResistance = victim.monsterResistance;
        tigerStrength = 40;
 
      }
 
  
 
       for (var index = 0; index < elementBonus.length; index++) {
 
       for (var index = 0; index < elementBonus.length; index++) {
Ligne 2 314 : Ligne 2 439 :
 
         var elementResistanceName = mapping.elementResistance[index];
 
         var elementResistanceName = mapping.elementResistance[index];
  
         if (attacker[elementBonusName] && victim[elementBonusName]) {
+
         if (attacker[elementBonusName]) {
 
           elementBonus[index] =
 
           elementBonus[index] =
             (attacker[elementBonusName] - victim[elementResistanceName]) / 200;
+
             80 * (attacker[elementBonusName] - victim[elementResistanceName]);
        } else {
 
          elementBonus[index] = attacker[elementBonusName] / 2000;
 
 
         }
 
         }
 
       }
 
       }
  
       var victimType = victim.type;
+
       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;
 +
        }
  
      if (victimType !== -1) {
+
        missPercentage +=
        typeBonus = attacker[mapping.typeFlag[victimType]];
+
          victim.meleeArrowBlock -
 +
          (missPercentage * victim.meleeArrowBlock) / 100;
 
       }
 
       }
 +
    }
  
      monsterBonus = attacker.monsterBonus;
+
    typeBonus = 1;
 +
    damageMultiplier = attacker.damageMultiplier;
 +
  }
  
      if (isStone(victim)) {
+
  if (skillType) {
        stoneBonus = attacker.stoneBonus;
+
    criticalHitPercentage = skillChanceReduction(criticalHitPercentage);
      }
+
    piercingHitPercentage = skillChanceReduction(piercingHitPercentage);
 +
  }
  
      if (isBoss(victim)) {
+
  if (isPC(victim)) {
        skillDamage += attacker.skillBossDamage;
+
    if (!skillType && isChecked(victim.biologist70)) {
      }
+
      defenseBoost = Math.floor((defenseBoost * 110) / 100);
 +
    }
  
       if (attacker.onYohara === "on") {
+
    criticalHitPercentage = Math.max(
        var sungmaStrDifference = attacker.sungmaStr - attacker.sungmaStrMalus;
+
      0,
 +
       criticalHitPercentage - victim.criticalHitResistance
 +
    );
 +
    piercingHitPercentage = Math.max(
 +
      0,
 +
      piercingHitPercentage - victim.piercingHitResistance
 +
    );
  
        if (sungmaStrDifference >= 0) {
+
    if (skillType) {
          sungMaStrBonus = sungmaStrDifference;
+
      skillDamageResistance = victim.skillDamageResistance;
        } else {
 
          sungmaStrMalus = 0.5;
 
        }
 
      }
 
 
     }
 
     }
  
     skillDamage += attacker.skillDamage;
+
     if (isMagicClass(victim)) {
     rankBonus = getRankBonus(attacker);
+
      defensePercent = (-2 * victim.magicDefense * victim.defensePercent) / 100;
     damageBonus = attacker.damageBonus;
+
     } else {
 +
      defensePercent = (-2 * defenseBoost * victim.defensePercent) / 100;
 +
     }
  
     if (attacker.empireMalus === "on") {
+
     if (isChecked(victim.steelDragonElixir)) {
       empireMalus = 10;
+
       steelDragonElixir = 10;
 
     }
 
     }
   } else {
+
   }
    if (isPC(victim)) {
 
      if (victim.isMarried === "on" && victim.harmonyBracelet === "on") {
 
        monsterResistanceMarriage = getMarriageBonusValue(
 
          victim,
 
          marriageTable,
 
          "harmonyBracelet"
 
        );
 
      }
 
  
      monsterResistance = victim.monsterResistance;
+
  if (skillType === "magic") {
 
+
     attackValueMeleeMagic = 0;
      for (var index = 0; index < elementBonus.length; index++) {
+
     magicAttackValueMeleeMagic =
        var elementBonusName = mapping.elementBonus[index];
+
       attacker.attackMagic + Math.min(100, attacker.attackMeleeMagic);
        var elementResistanceName = mapping.elementResistance[index];
+
     attackValueMarriage = 0;
 
+
     defense = 0;
        if (attacker[elementBonusName]) {
 
          elementBonus[index] =
 
            (attacker[elementBonusName] - victim[elementResistanceName]) / 125;
 
        }
 
      }
 
    }
 
 
 
    typeBonus = 1;
 
    damageMultiplier = attacker.damageMultiplier;
 
  }
 
 
 
  criticalHitPercentage = skillChanceReduction(criticalHitPercentage);
 
  piercingHitPercentage = skillChanceReduction(piercingHitPercentage);
 
 
 
  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 (victim.steelDragonElixir === "on") {
 
      steelDragonElixir = 10;
 
    }
 
  }
 
 
 
  if (magicSkill) {
 
    adjustCoeff = 0.5;
 
    attackValuePercent = attacker.attackMagic;
 
     attackValueMarriage = 0;
 
     defense = 0;
 
 
     if (!isDispell(attacker, 6)) {
 
     if (!isDispell(attacker, 6)) {
 
       magicResistance = victim.magicResistance;
 
       magicResistance = victim.magicResistance;
 
     }
 
     }
 
     weaponDefense = 0;
 
     weaponDefense = 0;
 +
    calcAttackValues = calcMagicAttackValue;
 +
  } else {
 +
    calcAttackValues = calcSecondaryAttackValue;
 
   }
 
   }
  
   var battleValues = {
+
  missPercentage = Math.min(100, missPercentage);
 +
 
 +
   var bonusValues = {
 +
    missPercentage: missPercentage,
 
     weaponBonusCoeff: 1,
 
     weaponBonusCoeff: 1,
    adjustCoeff: adjustCoeff,
+
     attackValueCoeff: 100 + attackValueMeleeMagic,
     attackValueCoeff:
 
      1 + (attackValuePercent + Math.min(100, attackMeleeMagic)) / 100,
 
 
     attackValueMarriage: attackValueMarriage,
 
     attackValueMarriage: attackValueMarriage,
     monsterResistanceMarriageCoeff: 1 - monsterResistanceMarriage / 100,
+
     monsterResistanceMarriageCoeff: 100 - monsterResistanceMarriage,
     monsterResistanceCoeff: 1 - monsterResistance / 100,
+
     monsterResistanceCoeff: 100 - monsterResistance,
     typeBonusCoeff: 1 + typeBonus / 100,
+
     typeBonusCoeff: typeBonus,
     raceBonusCoeff: raceBonus / 100,
+
     raceBonusCoeff: raceBonus,
     raceResistanceCoeff: raceResistance / 100,
+
     raceResistanceCoeff: raceResistance,
     monsterBonusCoeff: 1 + monsterBonus / 100,
+
     stoneBonusCoeff: stoneBonus,
     stoneBonusCoeff: 1 + stoneBonus / 100,
+
     monsterBonusCoeff: monsterBonus,
 
     elementBonusCoeff: elementBonus,
 
     elementBonusCoeff: elementBonus,
 
     damageMultiplier: damageMultiplier,
 
     damageMultiplier: damageMultiplier,
 
     useDamages: useDamages,
 
     useDamages: useDamages,
 
     defense: defense,
 
     defense: defense,
     tigerStrengthCoeff: 1 + tigerStrength / 100,
+
     defenseBoost: defenseBoost,
     piercingHitDefense: victim.defense,
+
    defenseMarriage: defenseMarriage,
 +
     tigerStrengthCoeff: 100 + tigerStrength,
 
     magicResistanceCoeff: magicResistanceToCoeff(magicResistance),
 
     magicResistanceCoeff: magicResistanceToCoeff(magicResistance),
     weaponDefenseCoeff: 1 - weaponDefense / 100,
+
     weaponDefenseCoeff: 100 - weaponDefense,
     skillDamageCoeff: 1 + skillDamage / 100,
+
    blessingBonusCoeff: 100 - blessingBonus,
     skillDamageResistanceCoeff: 1 - Math.min(99, skillDamageResistance) / 100,
+
    magicAttackValueCoeff: 100 + magicAttackValueMeleeMagic,
     rankBonusCoeff: 1 + rankBonus / 100,
+
    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),
 
     defensePercent: Math.floor(defensePercent),
     damageBonusCoeff: damageBonus / 100,
+
     damageBonusCoeff: damageBonus,
     empireMalusCoeff: 1 - empireMalus / 100,
+
     empireMalusCoeff: 10 - empireMalus,
     sungMaStrBonusCoeff: 1 + sungMaStrBonus / 10000,
+
     sungMaStrBonusCoeff: 10000 + sungMaStrBonus,
 
     sungmaStrMalusCoeff: sungmaStrMalus,
 
     sungmaStrMalusCoeff: sungmaStrMalus,
     whiteDragonElixirCoeff: 1 + whiteDragonElixir / 100,
+
     whiteDragonElixirCoeff: 100 + whiteDragonElixir,
     steelDragonElixirCoeff: 1 - steelDragonElixir / 100,
+
     steelDragonElixirCoeff: 100 - steelDragonElixir,
 
   };
 
   };
  
Ligne 2 455 : Ligne 2 563 :
 
   piercingHitPercentage = Math.min(piercingHitPercentage, 100);
 
   piercingHitPercentage = Math.min(piercingHitPercentage, 100);
  
   battleValues.damagesTypeCombinaison = [
+
   var damagesTypeCombinaison = [
 
     {
 
     {
 
       criticalHit: false,
 
       criticalHit: false,
 
       piercingHit: false,
 
       piercingHit: false,
       weight: (100 - criticalHitPercentage) * (100 - piercingHitPercentage),
+
       weight:
       name: "Coup classique",
+
        (100 - criticalHitPercentage) *
 +
        (100 - piercingHitPercentage) *
 +
        (100 - missPercentage),
 +
       name: "normalHit",
 
     },
 
     },
 
     {
 
     {
 
       criticalHit: true,
 
       criticalHit: true,
 
       piercingHit: false,
 
       piercingHit: false,
       weight: criticalHitPercentage * (100 - piercingHitPercentage),
+
       weight:
       name: "Coup critique",
+
        criticalHitPercentage *
 +
        (100 - piercingHitPercentage) *
 +
        (100 - missPercentage),
 +
       name: "criticalHit",
 
     },
 
     },
 
     {
 
     {
 
       criticalHit: false,
 
       criticalHit: false,
 
       piercingHit: true,
 
       piercingHit: true,
       weight: (100 - criticalHitPercentage) * piercingHitPercentage,
+
       weight:
       name: "Coup perçant",
+
        (100 - criticalHitPercentage) *
 +
        piercingHitPercentage *
 +
        (100 - missPercentage),
 +
       name: "piercingHit",
 
     },
 
     },
 
     {
 
     {
 
       criticalHit: true,
 
       criticalHit: true,
 
       piercingHit: true,
 
       piercingHit: true,
       weight: criticalHitPercentage * piercingHitPercentage,
+
       weight:
       name: "Coup critique perçant",
+
        criticalHitPercentage * piercingHitPercentage * (100 - missPercentage),
 +
       name: "criticalPiercingHit",
 
     },
 
     },
 
   ];
 
   ];
  
   return battleValues;
+
   return {
 +
    attacker: attacker,
 +
    victim: victim,
 +
    attackFactor: calcAttackFactor(attacker, victim),
 +
    mainAttackValue: calcMainAttackValue(attacker),
 +
    attackValues: calcAttackValues(attacker),
 +
    bonusValues: bonusValues,
 +
    damagesTypeCombinaison: damagesTypeCombinaison,
 +
  };
 
}
 
}
  
function updateBattleValues(battleValues, skillInfo, attackerWeapon) {
+
function updateBattleValues(battleValues, skillFormula, skillInfo) {
 
   var weaponBonus = 0;
 
   var weaponBonus = 0;
 
   var skillWard = 0;
 
   var skillWard = 0;
 
   var skillBonus = 0;
 
   var skillBonus = 0;
 
   var skillBonusByBonus = 0;
 
   var skillBonusByBonus = 0;
 +
  var { attacker: attacker, bonusValues: bonusValues } = battleValues;
 +
  var {
 +
    range: [minVariation, maxVariation],
 +
  } = skillInfo;
 +
  var variationLength = maxVariation - minVariation + 1;
  
 
   if (skillInfo.hasOwnProperty("weaponBonus")) {
 
   if (skillInfo.hasOwnProperty("weaponBonus")) {
 
     var [weaponType, weaponBonusValue] = skillInfo.weaponBonus;
 
     var [weaponType, weaponBonusValue] = skillInfo.weaponBonus;
  
     if (weaponType === attackerWeapon[1]) {
+
     if (weaponType === attacker.weapon.type) {
 
       weaponBonus = weaponBonusValue;
 
       weaponBonus = weaponBonusValue;
 
     }
 
     }
Ligne 2 512 : Ligne 2 643 :
  
 
   if (skillInfo.removeWeaponReduction) {
 
   if (skillInfo.removeWeaponReduction) {
     battleValues.weaponDefenseCoeff = 1;
+
     bonusValues.weaponDefenseCoeff = 100;
 
   }
 
   }
  
   battleValues.weaponBonusCoeff = 1 + weaponBonus / 100;
+
   bonusValues.weaponBonusCoeff = 100 + weaponBonus;
   battleValues.skillWardCoeff = 1 - skillWard / 100;
+
   bonusValues.skillWardCoeff = 1 - skillWard / 100;
   battleValues.skillBonusCoeff = 1 + skillBonus / 100;
+
   bonusValues.skillBonusCoeff = 1 + skillBonus / 100;
   battleValues.skillBonusByBonusCoeff = 1 + skillBonusByBonus / 100;
+
   bonusValues.skillBonusByBonusCoeff = 100 + skillBonusByBonus;
 +
 
 +
  battleValues.skillFormula = skillFormula;
 +
  battleValues.skillRange = skillInfo.range;
 +
  battleValues.attackValues.totalCardinal *= variationLength;
 +
  battleValues.attackValues.possibleDamagesCount *= variationLength;
 
}
 
}
  
function calcPhysicalDamages(
+
function calcWeights(minValue, maxValue, minInterval) {
  attacker,
+
   var firstWeightLimit = minValue + minInterval - 1;
  attackerWeapon,
+
  var lastWeightsLimit = maxValue - minInterval + 1;
  victim,
+
   var weights = [];
  tableResult,
 
  mapping,
 
  constants,
 
  damagesChart,
 
  numberFormat
 
) {
 
   var battleValues = createPhysicalBattleValues(
 
    attacker,
 
    attackerWeapon,
 
    victim,
 
    mapping,
 
    constants.polymorphPowerTable,
 
    constants.marriageTable,
 
    constants.skillPowerTable
 
   );
 
  
   var sumDamages = 0;
+
   for (var value = minValue; value < firstWeightLimit; value++) {
   var minMaxDamages = { min: Infinity, max: 0 };
+
    weights.push(value - minValue + 1);
 +
   }
  
   var attackFactor = calcAttackFactor(attacker, victim);
+
   for (var value = firstWeightLimit; value <= lastWeightsLimit; value++) {
  var mainAttackValue = calcMainAttackValue(attacker, attackerWeapon);
+
     weights.push(minInterval);
  var [
+
   }
    minAttackValue,
 
    maxAttackValue,
 
    attackValueOther,
 
     minInterval,
 
    totalCardinal,
 
   ] = calcSecondaryAttackValue(attacker, attackerWeapon);
 
  
   totalCardinal *= 100;
+
   for (var value = lastWeightsLimit + 1; value <= maxValue; value++) {
 
+
     weights.push(maxValue - value + 1);
  if (battleValues.missPercentage) {
 
     addRowToTableResult(tableResult, "Miss");
 
    addToTableResult(
 
      tableResult,
 
      { 0: battleValues.missPercentage / 100 },
 
      numberFormat
 
    );
 
 
   }
 
   }
  
   var lastWeightsLimit = maxAttackValue - minInterval + 1;
+
   return weights;
  var firstWeightLimit = minAttackValue + minInterval - 1;
+
}
  
   for (var damagesType of battleValues.damagesTypeCombinaison) {
+
function calcBlessingBonus(skillPowerTable, victim) {
     if (!damagesType.weight) {
+
   if (victim.isBlessed !== "on") {
      continue;
+
     return 0;
    }
+
  }
 +
 
 +
  var int = victim.intBlessing;
 +
  var dex = victim.dexBlessing;
 +
  var skillPower = getSkillPower(victim["skillBlessing"], skillPowerTable);
 +
 
 +
  if (!skillPower) {
 +
    return 0;
 +
  }
  
    var damagesWeighted = {};
+
  var blessingBonus = floorMultiplication(
     addRowToTableResult(tableResult, damagesType.name);
+
     ((int * 0.3 + 5) * (2 * skillPower + 0.5) + 0.3 * dex) / (skillPower + 2.3),
 +
    1
 +
  );
  
    for (
+
  if (victim.class === "dragon" && isChecked(ictim.blessingOnself)) {
      var attackValue = minAttackValue;
+
     blessingBonus = floorMultiplication(blessingBonus, 1.1);
      attackValue <= maxAttackValue;
+
  }
      attackValue++
 
     ) {
 
      var weight;
 
  
      if (attackValue > lastWeightsLimit) {
+
  return blessingBonus;
        weight = maxAttackValue - attackValue + 1;
+
}
      } else if (attackValue < firstWeightLimit) {
 
        weight = attackValue - minAttackValue + 1;
 
      } else {
 
        weight = minInterval;
 
      }
 
  
      var secondaryAttackValue = 2 * attackValue + attackValueOther;
+
function getSkillFormula(battle, skillId, battleValues, removeSkillVariation) {
      var rawDamages =
+
  var { attacker, victim, attackFactor } = battleValues;
        mainAttackValue +
+
  var skillPowerTable = battle.constants.skillPowerTable;
        floorMultiplication(attackFactor, secondaryAttackValue);
 
      var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
 
        rawDamages,
 
        battleValues
 
      );
 
  
      var minPiercingDamages =
+
  var skillFormula;
        damagesWithPrimaryBonuses -
+
  var skillInfo = { range: [0, 0] };
        battleValues.defense +
 
        battleValues.defenseMarriage;
 
  
      if (minPiercingDamages <= 2) {
+
  var { class: attackerClass, level: lv, vit, str, int, dex } = attacker;
        for (var damages = 1; damages <= 5; damages++) {
 
          var finalDamages = calcDamageWithSecondaryBonuses(
 
            damages,
 
            battleValues,
 
            damagesType,
 
            minPiercingDamages,
 
            damagesWithPrimaryBonuses
 
          );
 
  
          addKeyValue(
+
  if (skillId <= 9) {
            damagesWeighted,
+
     var skillPower = getSkillPower(
            finalDamages,
+
       attacker["attackSkill" + skillId],
            (weight * damagesType.weight) / (5 * totalCardinal)
+
       skillPowerTable
          );
 
          sumDamages += (finalDamages * weight * damagesType.weight) / 5;
 
        }
 
      } else {
 
        var finalDamages = calcDamageWithSecondaryBonuses(
 
          minPiercingDamages,
 
          battleValues,
 
          damagesType,
 
          minPiercingDamages,
 
          damagesWithPrimaryBonuses
 
        );
 
 
 
        addKeyValue(
 
          damagesWeighted,
 
          finalDamages,
 
          (weight * damagesType.weight) / totalCardinal
 
        );
 
        sumDamages += finalDamages * weight * damagesType.weight;
 
      }
 
    }
 
 
 
     var scatterData = addToTableResult(
 
       tableResult,
 
      damagesWeighted,
 
      numberFormat,
 
       minMaxDamages
 
 
     );
 
     );
    updateDamagesChart(scatterData, damagesChart, damagesType.name);
 
  }
 
  
  if (minMaxDamages.min === Infinity) {
+
    var improvedBySkillBonus = false;
     minMaxDamages.min = 0;
+
     var improvedByBonus = false;
  }
 
  
  return [sumDamages / totalCardinal, minMaxDamages];
+
    if (attackerClass === "body") {
}
+
      switch (skillId) {
 
+
        // Triple lacération
function calcBlessingBonus(skillPowerTable, victim) {
+
        case 1:
  if (victim.isBlessed !== "on") {
+
          skillFormula = function (atk) {
    return 0;
+
            return floorMultiplication(
  }
+
              1.1 * atk + (0.5 * atk + 1.5 * str) * skillPower,
 
+
              1
  var int = victim.intBlessing;
+
            );
  var dex = victim.dexBlessing;
+
          };
  var skillPower = getSkillPower(victim["skillBlessing"], skillPowerTable);
+
          improvedByBonus = true;
 
+
          break;
  if (!skillPower) {
+
        // Moulinet à l'épée
    return 0;
+
        case 2:
  }
+
          skillFormula = function (atk) {
 
+
            return floorMultiplication(
  var blessingBonus = floorMultiplication(
+
              3 * atk + (0.8 * atk + 5 * str + 3 * dex + vit) * skillPower,
    ((int * 0.3 + 5) * (2 * skillPower + 0.5) + 0.3 * dex) / (skillPower + 2.3),
+
              1
    1
+
            );
  );
+
          };
 
+
          improvedByBonus = true;
  if (victim.class === "dragon" && victim.blessingOnself === "on") {
+
          improvedBySkillBonus = true;
    blessingBonus = floorMultiplication(blessingBonus, 1.1);
+
          break;
  }
+
         // Accélération
 
+
         case 5:
  return blessingBonus;
 
}
 
 
 
function getSkillFormula(
 
  skillPowerTable,
 
  skillId,
 
  attacker,
 
  attackFactor,
 
  victim
 
) {
 
  var skillFormula;
 
  var skillInfo = {};
 
 
 
  var attackerClass = attacker.class;
 
  var lv = attacker.level;
 
  var vit = attacker.vit;
 
  var str = attacker.str;
 
  var int = attacker.int;
 
  var dex = attacker.dex;
 
 
 
  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) {
 
           skillFormula = function (atk) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               1.1 * atk + (0.5 * atk + 1.5 * str) * skillPower,
+
               2 * atk + (atk + dex * 3 + str * 7 + vit) * skillPower,
 
               1
 
               1
 
             );
 
             );
Ligne 2 719 : Ligne 2 753 :
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
         // Moulinet à l'épée
+
         // Volonté de vivre
         case 2:
+
         case 6:
 
           skillFormula = function (atk) {
 
           skillFormula = function (atk) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               3 * atk + (0.8 * atk + 5 * str + 3 * dex + vit) * skillPower,
+
               (3 * atk + (atk + 1.5 * str) * skillPower) * 1.07,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
          improvedByBonus = true;
 
          improvedBySkillBonus = true;
 
 
           break;
 
           break;
         // Accélération
+
         // Tremblement de terre
         case 5:
+
         case 9:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
              2 * atk + (atk + dex * 3 + str * 7 + vit) * skillPower,
+
               3 * atk +
              1
+
                 (0.9 * atk + variation + 5 * str + 3 * dex + lv) * skillPower,
            );
 
          };
 
          improvedByBonus = true;
 
          break;
 
        // Volonté de vivre
 
        case 6:
 
          skillFormula = function (atk) {
 
            return floorMultiplication(
 
              (3 * atk + (atk + 1.5 * str) * skillPower) * 1.07,
 
              1
 
            );
 
          };
 
          break;
 
        case 9:
 
          skillFormula = function (atk) {
 
            return floorMultiplication(
 
               3 * atk +
 
                 (0.9 * atk + 500.5 + 5 * str + 3 * dex + lv) * skillPower,
 
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [1, 1000];
 
           break;
 
           break;
 
       }
 
       }
Ligne 2 813 : Ligne 2 828 :
 
         // Tremblement de terre
 
         // Tremblement de terre
 
         case 9:
 
         case 9:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               3 * atk +
 
               3 * atk +
                 (0.9 * atk + 500.5 + 5 * str + 3 * dex + lv) * skillPower,
+
                 (0.9 * atk + variation + 5 * str + 3 * dex + lv) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [1, 1000];
 
           break;
 
           break;
 
       }
 
       }
Ligne 2 826 : Ligne 2 842 :
 
         // Embuscade
 
         // Embuscade
 
         case 1:
 
         case 1:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               atk + (1.2 * atk + 600 + 4 * dex + 4 * str) * skillPower,
+
               atk + (1.2 * atk + variation + 4 * dex + 4 * str) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 
           skillInfo.weaponBonus = [1, 50];
 
           skillInfo.weaponBonus = [1, 50];
 +
          skillInfo.range = [500, 700];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           improvedBySkillBonus = true;
 
           improvedBySkillBonus = true;
Ligne 2 838 : Ligne 2 855 :
 
         // Attaque rapide
 
         // Attaque rapide
 
         case 2:
 
         case 2:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               atk + (1.6 * atk + 250 + 7 * dex + 7 * str) * skillPower,
+
               atk + (1.6 * atk + variation + 7 * dex + 7 * str) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 
           skillInfo.weaponBonus = [1, 35];
 
           skillInfo.weaponBonus = [1, 35];
 +
          skillInfo.range = [200, 300];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
Ligne 2 878 : Ligne 2 896 :
 
         // Étoiles brillantes
 
         // Étoiles brillantes
 
         case 9:
 
         case 9:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               atk + (1.7 * atk + 500.5 + 6 * dex + 5 * lv) * skillPower,
+
               atk + (1.7 * atk + variation + 6 * dex + 5 * lv) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [1, 1000];
 
           break;
 
           break;
 
       }
 
       }
Ligne 2 910 : Ligne 2 929 :
 
         // Flèche de feu
 
         // Flèche de feu
 
         case 3:
 
         case 3:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               1.5 * atk + (2.6 * atk + 0.9 * int + 200) * skillPower,
+
               1.5 * atk + (2.6 * atk + 0.9 * int + variation) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [100, 300];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           improvedBySkillBonus = true;
 
           improvedBySkillBonus = true;
Ligne 2 931 : Ligne 2 951 :
 
         // Flèche empoisonnée
 
         // Flèche empoisonnée
 
         case 5:
 
         case 5:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               atk +
 
               atk +
                 (1.4 * atk + 150 + 7 * dex + 4 * str + 4 * int) * skillPower,
+
                 (1.4 * atk + variation + 7 * dex + 4 * str + 4 * int) *
 +
                  skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [100, 200];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
 
         // Coup étincelant
 
         // Coup étincelant
 
         case 6:
 
         case 6:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               (atk +
 
               (atk +
                 (1.2 * atk + 150 + 6 * dex + 3 * str + 3 * int) * skillPower) *
+
                 (1.2 * atk + variation + 6 * dex + 3 * str + 3 * int) *
 +
                  skillPower) *
 
                 1.2,
 
                 1.2,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [100, 200];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
 
         // Tir tempête
 
         // Tir tempête
 
         case 9:
 
         case 9:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               1.9 * atk + (2.6 * atk + 500.5) * skillPower,
+
               1.9 * atk + (2.6 * atk + variation) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [1, 1000];
 
           break;
 
           break;
 
       }
 
       }
Ligne 2 993 : Ligne 3 018 :
 
         // Contre-sort
 
         // Contre-sort
 
         case 6:
 
         case 6:
           skillFormula = function (mav) {
+
           skillFormula = function (mav, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               40 +
 
               40 +
 
                 5 * lv +
 
                 5 * lv +
 
                 2 * int +
 
                 2 * int +
                 (10 * int + 7 * mav + 75) * attackFactor * skillPower,
+
                 (10 * int + 7 * mav + variation) * attackFactor * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [50, 100];
 
           break;
 
           break;
 
         // Coup démoniaque
 
         // Coup démoniaque
 
         case 9:
 
         case 9:
           skillFormula = function (atk) {
+
           skillFormula = function (atk, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
               1.9 * atk + (2.6 * atk + 500.5) * skillPower,
+
               1.9 * atk + (2.6 * atk + variation) * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [1, 1000];
 
           break;
 
           break;
 
       }
 
       }
Ligne 3 017 : Ligne 3 044 :
 
         // Attaque des ténèbres
 
         // Attaque des ténèbres
 
         case 1:
 
         case 1:
           skillFormula = function (mav) {
+
           skillFormula = function (mav, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               40 +
 
               40 +
 
                 5 * lv +
 
                 5 * lv +
 
                 2 * int +
 
                 2 * int +
                 (13 * int + 6 * mav + 75) * attackFactor * skillPower,
+
                 (13 * int + 6 * mav + variation) * attackFactor * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [50, 100];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           improvedBySkillBonus = true;
 
           improvedBySkillBonus = true;
Ligne 3 031 : Ligne 3 059 :
 
         // Attaque de flammes
 
         // Attaque de flammes
 
         // case 2:
 
         // case 2:
         //  skillFormula = function (mav) {
+
         //  skillFormula = function (mav, variation) {
 
         //    return floorMultiplication(
 
         //    return floorMultiplication(
         //      5 * lv + 2 * int + (7 * int + 8 * mav + 4 * str + 2 * vit + 190) * skillPower,
+
         //      5 * lv + 2 * int + (7 * int + 8 * mav + 4 * str + 2 * vit + variation) * skillPower,
 
         //      1
 
         //      1
 
         //    );
 
         //    );
 
         //  };
 
         //  };
 +
        //  skillInfo.range = [180, 100];
 
         //  improvedByBonus = true;
 
         //  improvedByBonus = true;
 
         //  break;
 
         //  break;
 
         // Esprit de flammes
 
         // Esprit de flammes
 
         case 3:
 
         case 3:
           skillFormula = function (mav) {
+
           skillFormula = function (mav, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               30 +
 
               30 +
 
                 2 * lv +
 
                 2 * lv +
 
                 2 * int +
 
                 2 * int +
                 (7 * int + 6 * mav + 350) * attackFactor * skillPower,
+
                 (7 * int + 6 * mav + variation) * attackFactor * skillPower,
 
               1
 
               1
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [200, 500];
 
           break;
 
           break;
 
         // Frappe de l'esprit
 
         // Frappe de l'esprit
 
         // case 5:
 
         // case 5:
         //  skillFormula = function (mav) {
+
         //  skillFormula = function (mav, variation) {
 
         //    return floorMultiplication(
 
         //    return floorMultiplication(
         //      40 + 2 * lv + 2 * int + (2 * vit + 2 * dex + 13 * int + 6 * mav + 190) * attackFactor * skillPower,
+
         //      40 + 2 * lv + 2 * int + (2 * vit + 2 * dex + 13 * int + 6 * mav + variation) * attackFactor * skillPower,
 
         //      1
 
         //      1
 
         //    );
 
         //    );
 
         //  };
 
         //  };
 +
        //  skillInfo.range = [180, 200];
 
         //  break;
 
         //  break;
 
         // Orbe des ténèbres
 
         // Orbe des ténèbres
Ligne 3 074 : Ligne 3 105 :
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
      }
+
         // Vague mortelle
    } else if (attackerClass === "dragon") {
+
         case 9:
      switch (skillId) {
+
           skillFormula = function (mav, variation) {
         // Talisman volant
 
         case 1:
 
           skillFormula = function (mav) {
 
 
             return floorMultiplication(
 
             return floorMultiplication(
               70 +
+
              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 +
 
                 5 * lv +
 
                 (18 * int + 7 * str + 5 * mav + 50) * attackFactor * skillPower,
 
                 (18 * int + 7 * str + 5 * mav + 50) * attackFactor * skillPower,
Ligne 3 120 : Ligne 3 165 :
 
           skillInfo.weaponBonus = [4, 10];
 
           skillInfo.weaponBonus = [4, 10];
 
           improvedByBonus = true;
 
           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;
 
           break;
 
       }
 
       }
Ligne 3 126 : Ligne 3 185 :
 
         // Jet de foudre
 
         // Jet de foudre
 
         case 1:
 
         case 1:
           skillFormula = function (mav) {
+
           skillFormula = function (mav, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               60 +
 
               60 +
 
                 5 * lv +
 
                 5 * lv +
                 (8 * int + 2 * dex + 8 * mav + 10 * int) *
+
                 (8 * int + 2 * dex + 8 * mav + variation) *
 
                   attackFactor *
 
                   attackFactor *
 
                   skillPower,
 
                   skillPower,
Ligne 3 137 : Ligne 3 196 :
 
           };
 
           };
 
           skillInfo.weaponBonus = [6, 10];
 
           skillInfo.weaponBonus = [6, 10];
 +
          skillInfo.range = [5 * int, 15 * int];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
 
         // Invocation de foudre
 
         // Invocation de foudre
 
         case 2:
 
         case 2:
           skillFormula = function (mav) {
+
           skillFormula = function (mav, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               40 +
 
               40 +
 
                 4 * lv +
 
                 4 * lv +
                 (13 * int + 2 * str + 10 * mav + 10.5 * int) *
+
                 (13 * int + 2 * str + 10 * mav + variation) *
 
                   attackFactor *
 
                   attackFactor *
 
                   skillPower,
 
                   skillPower,
Ligne 3 152 : Ligne 3 212 :
 
           };
 
           };
 
           skillInfo.weaponBonus = [6, 10];
 
           skillInfo.weaponBonus = [6, 10];
 +
          skillInfo.range = [5 * int, 16 * int];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           improvedBySkillBonus = true;
 
           improvedBySkillBonus = true;
Ligne 3 157 : Ligne 3 218 :
 
         // Griffe de foudre
 
         // Griffe de foudre
 
         case 3:
 
         case 3:
           skillFormula = function (mav) {
+
           skillFormula = function (mav, variation) {
 
             return floorMultiplication(
 
             return floorMultiplication(
 
               50 +
 
               50 +
 
                 5 * lv +
 
                 5 * lv +
                 (8 * int + 2 * str + 8 * mav + 400.5) *
+
                 (8 * int + 2 * str + 8 * mav + variation) *
 
                   attackFactor *
 
                   attackFactor *
 
                   skillPower,
 
                   skillPower,
Ligne 3 167 : Ligne 3 228 :
 
             );
 
             );
 
           };
 
           };
 +
          skillInfo.range = [1, 800];
 
           improvedByBonus = true;
 
           improvedByBonus = true;
 
           break;
 
           break;
Ligne 3 215 : Ligne 3 277 :
 
           };
 
           };
 
           improvedByBonus = true;
 
           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;
 
           break;
 
       }
 
       }
Ligne 3 232 : Ligne 3 305 :
 
     if (improvedByBonus) {
 
     if (improvedByBonus) {
 
       skillInfo.skillBonusByBonus = attacker["skillBonus" + skillId];
 
       skillInfo.skillBonusByBonus = attacker["skillBonus" + skillId];
 +
    }
 +
 +
    if (removeSkillVariation) {
 +
      var averageVariation = (skillInfo.range[0] + skillInfo.range[0]) / 2;
 +
      skillInfo.range = [averageVariation, averageVariation];
 
     }
 
     }
 
   } else {
 
   } else {
Ligne 3 273 : Ligne 3 351 :
 
   }
 
   }
  
   return [skillFormula, skillInfo];
+
   updateBattleValues(battleValues, skillFormula, skillInfo);
 
}
 
}
  
function calcPhysicalSkillDamages(
+
function calcMagicAttackValueAugmentation(
   attacker,
+
   magicAttackValueWeapon,
   attackerWeapon,
+
   magicAttackValueBonus
  victim,
 
  tableResult,
 
  mapping,
 
  constants,
 
  damagesChart,
 
  numberFormat,
 
  skillId
 
 
) {
 
) {
   var battleValues = createSkillBattleValues(
+
   if (magicAttackValueBonus) {
     attacker,
+
     return Math.max(
    attackerWeapon,
+
      1,
    victim,
+
      0.0025056 *
     mapping,
+
        magicAttackValueBonus ** 0.602338 *
    constants.marriageTable
+
        magicAttackValueWeapon ** 1.20476
   );
+
     );
 +
  }
 +
   return 0;
 +
}
  
   var sumDamages = 0;
+
function getMagicAttackValueAugmentation(
   var minMaxDamages = { min: Infinity, max: 0 };
+
  minMagicAttackValue,
 +
   maxMagicAttackValue,
 +
  magicAttackValueBonus
 +
) {
 +
   var magicAttackValueAugmentation = [];
  
   var attackFactor = calcAttackFactor(attacker, victim);
+
   for (
  var mainAttackValue = calcMainAttackValue(attacker, attackerWeapon);
+
    var magicAttackValue = minMagicAttackValue;
  var [
+
    magicAttackValue <= maxMagicAttackValue;
     minAttackValue,
+
     magicAttackValue++
    maxAttackValue,
+
  ) {
     attackValueOther,
+
     magicAttackValueAugmentation.push(
    minInterval,
+
      calcMagicAttackValueAugmentation(magicAttackValue, magicAttackValueBonus)
     totalCardinal,
+
     );
   ] = calcSecondaryAttackValue(attacker, attackerWeapon);
+
   }
  
   var lastWeightsLimit = maxAttackValue - minInterval + 1;
+
   return magicAttackValueAugmentation;
  var firstWeightLimit = minAttackValue + minInterval - 1;
+
}
  
   var [skillFormula, skillInfo] = getSkillFormula(
+
function calcPhysicalDamages(battleValues) {
    constants.skillPowerTable,
+
   var {
    skillId,
 
    attacker,
 
 
     attackFactor,
 
     attackFactor,
     victim
+
     mainAttackValue,
   );
+
    attackValues: { minAttackValue, maxAttackValue, attackValueOther, weights },
 +
    bonusValues,
 +
    damagesTypeCombinaison,
 +
   } = battleValues;
  
   updateBattleValues(battleValues, skillInfo, attackerWeapon);
+
   var damagesWeightedByType = {};
  
   for (var damagesType of battleValues.damagesTypeCombinaison) {
+
  if (bonusValues.missPercentage) {
 +
    damagesWeightedByType.miss = bonusValues.missPercentage / 100;
 +
  }
 +
 
 +
   for (var damagesType of damagesTypeCombinaison) {
 
     if (!damagesType.weight) {
 
     if (!damagesType.weight) {
 
       continue;
 
       continue;
Ligne 3 327 : Ligne 3 410 :
  
 
     var damagesWeighted = {};
 
     var damagesWeighted = {};
     addRowToTableResult(tableResult, damagesType.name);
+
     damagesWeightedByType[damagesType.name] = damagesWeighted;
  
 
     for (
 
     for (
Ligne 3 334 : Ligne 3 417 :
 
       attackValue++
 
       attackValue++
 
     ) {
 
     ) {
       var weight;
+
       var weight = weights[attackValue - minAttackValue] * damagesType.weight;
 
 
      if (attackValue > lastWeightsLimit) {
 
        weight = maxAttackValue - attackValue + 1;
 
      } else if (attackValue < firstWeightLimit) {
 
        weight = attackValue - minAttackValue + 1;
 
      } else {
 
        weight = minInterval;
 
      }
 
  
 
       var secondaryAttackValue = 2 * attackValue + attackValueOther;
 
       var secondaryAttackValue = 2 * attackValue + attackValueOther;
Ligne 3 351 : Ligne 3 426 :
 
       var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
 
       var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
 
         rawDamages,
 
         rawDamages,
         battleValues
+
         bonusValues
 
       );
 
       );
  
       if (damagesWithPrimaryBonuses <= 2) {
+
      var minPiercingDamages =
 +
        damagesWithPrimaryBonuses -
 +
        bonusValues.defenseBoost +
 +
        bonusValues.defenseMarriage;
 +
 
 +
       if (minPiercingDamages <= 2) {
 
         for (var damages = 1; damages <= 5; damages++) {
 
         for (var damages = 1; damages <= 5; damages++) {
          damages *= battleValues.useDamages;
+
           var finalDamages = calcDamageWithSecondaryBonuses(
 
+
             damages,
          var damagesWithFormula = skillFormula(damages);
+
             bonusValues,
 
 
          damagesWithFormula = floorMultiplication(
 
            damagesWithFormula,
 
            battleValues.weaponBonusCoeff
 
          );
 
 
 
           var finalDamages = calcSkillDamageWithSecondaryBonuses(
 
             damagesWithFormula,
 
             battleValues,
 
 
             damagesType,
 
             damagesType,
 +
            minPiercingDamages,
 
             damagesWithPrimaryBonuses
 
             damagesWithPrimaryBonuses
 
           );
 
           );
  
           addKeyValue(
+
           addKeyValue(damagesWeighted, finalDamages, weight / 5);
            damagesWeighted,
 
            finalDamages,
 
            (weight * damagesType.weight) / (5 * totalCardinal)
 
          );
 
          sumDamages += (finalDamages * weight * damagesType.weight) / 5;
 
 
         }
 
         }
 
       } else {
 
       } else {
        damagesWithPrimaryBonuses *= battleValues.useDamages;
+
         var finalDamages = calcDamageWithSecondaryBonuses(
 
+
           minPiercingDamages,
        var damagesWithFormula = skillFormula(damagesWithPrimaryBonuses);
+
           bonusValues,
 
 
        damagesWithFormula = floorMultiplication(
 
          damagesWithFormula,
 
          battleValues.weaponBonusCoeff
 
        );
 
 
 
         var finalDamages = calcSkillDamageWithSecondaryBonuses(
 
           damagesWithFormula,
 
           battleValues,
 
 
           damagesType,
 
           damagesType,
 +
          minPiercingDamages,
 
           damagesWithPrimaryBonuses
 
           damagesWithPrimaryBonuses
 
         );
 
         );
  
         addKeyValue(
+
         addKeyValue(damagesWeighted, finalDamages, weight);
          damagesWeighted,
 
          finalDamages,
 
          (weight * damagesType.weight) / totalCardinal
 
        );
 
        sumDamages += finalDamages * weight * damagesType.weight;
 
 
       }
 
       }
 
     }
 
     }
 
    var scatterData = addToTableResult(
 
      tableResult,
 
      damagesWeighted,
 
      numberFormat,
 
      minMaxDamages
 
    );
 
    updateDamagesChart(scatterData, damagesChart, damagesType.name);
 
 
   }
 
   }
  
  if (minMaxDamages.min === Infinity) {
+
   return damagesWeightedByType;
    minMaxDamages.min = 0;
 
  }
 
 
 
   return [sumDamages / totalCardinal, minMaxDamages];
 
 
}
 
}
  
function calcMagicSkillDamages(
+
function calcPhysicalSkillDamages(battleValues) {
  attacker,
+
   var {
  attackerWeapon,
 
  victim,
 
  tableResult,
 
  mapping,
 
  constants,
 
  damagesChart,
 
  numberFormat,
 
  skillId
 
) {
 
   var battleValues = createSkillBattleValues(
 
    attacker,
 
    attackerWeapon,
 
    victim,
 
    mapping,
 
    constants.marriageTable,
 
    true
 
  );
 
 
 
  var sumDamages = 0;
 
  var minMaxDamages = { min: Infinity, max: 0 };
 
 
 
  var attackFactor = calcAttackFactor(attacker, victim);
 
  var [minMagicAttackValue, maxMagicAttackValue, minInterval, totalCardinal] =
 
    calcMagicAttackValue(attacker, attackerWeapon);
 
 
 
  var lastWeightsLimit = maxMagicAttackValue - minInterval + 1;
 
  var firstWeightLimit = minMagicAttackValue + minInterval - 1;
 
 
 
  var [skillFormula, skillInfo] = getSkillFormula(
 
    constants.skillPowerTable,
 
    skillId,
 
    attacker,
 
 
     attackFactor,
 
     attackFactor,
     victim
+
     mainAttackValue,
   );
+
    attackValues: { minAttackValue, maxAttackValue, attackValueOther, weights },
 +
    bonusValues,
 +
    damagesTypeCombinaison,
 +
    skillFormula,
 +
    skillRange: [minVariation, maxVariation],
 +
   } = battleValues;
  
   updateBattleValues(battleValues, skillInfo, attackerWeapon);
+
   var damagesWeightedByType = {};
  
   for (var damagesType of battleValues.damagesTypeCombinaison) {
+
   for (var damagesType of damagesTypeCombinaison) {
 
     if (!damagesType.weight) {
 
     if (!damagesType.weight) {
 
       continue;
 
       continue;
Ligne 3 467 : Ligne 3 482 :
  
 
     var damagesWeighted = {};
 
     var damagesWeighted = {};
     addRowToTableResult(tableResult, damagesType.name);
+
     var savedDamages = {};
 +
 
 +
    damagesWeightedByType[damagesType.name] = damagesWeighted;
  
 
     for (
 
     for (
       var magicAttackValue = minMagicAttackValue;
+
       var attackValue = minAttackValue;
       magicAttackValue <= maxMagicAttackValue;
+
       attackValue <= maxAttackValue;
       magicAttackValue++
+
       attackValue++
 
     ) {
 
     ) {
       var weight;
+
       var weight = weights[attackValue - minAttackValue] * damagesType.weight;
  
       if (magicAttackValue > lastWeightsLimit) {
+
       var secondaryAttackValue = 2 * attackValue + attackValueOther;
        weight = maxMagicAttackValue - magicAttackValue + 1;
+
       var rawDamages =
       } else if (magicAttackValue < firstWeightLimit) {
+
         mainAttackValue +
         weight = magicAttackValue - minMagicAttackValue + 1;
+
         floorMultiplication(attackFactor, secondaryAttackValue);
      } else {
 
         weight = minInterval;
 
      }
 
  
       var rawDamages = skillFormula(magicAttackValue);
+
       var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
 
 
      rawDamages = floorMultiplication(
 
 
         rawDamages,
 
         rawDamages,
         battleValues.weaponBonusCoeff
+
         bonusValues
 
       );
 
       );
  
       var damagesWithPrimaryBonuses = calcDamageWithPrimaryBonuses(
+
       for (
        rawDamages,
+
        var variation = minVariation;
         battleValues
+
        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;
  
      if (damagesWithPrimaryBonuses <= 2) {
+
           var damagesWithFormula = skillFormula(
        for (var damages = 1; damages <= 5; damages++) {
 
           var finalDamages = calcSkillDamageWithSecondaryBonuses(
 
            damages,
 
            battleValues,
 
            damagesType,
 
 
             damagesWithPrimaryBonuses,
 
             damagesWithPrimaryBonuses,
             skillFormula
+
             variation
 
           );
 
           );
  
           addKeyValue(
+
           if (savedDamages.hasOwnProperty(damagesWithFormula)) {
             damagesWeighted,
+
            var finalDamages = savedDamages[damagesWithFormula];
 +
             damagesWeighted[finalDamages] += weight;
 +
            continue;
 +
          }
 +
 
 +
          var finalDamages = Math.floor(
 +
            (damagesWithFormula * bonusValues.weaponBonusCoeff) / 100
 +
          );
 +
 
 +
          finalDamages = calcSkillDamageWithSecondaryBonuses(
 
             finalDamages,
 
             finalDamages,
             (weight * damagesType.weight) / (5 * totalCardinal)
+
             bonusValues,
 +
            damagesType,
 +
            damagesWithPrimaryBonuses
 
           );
 
           );
           sumDamages += (finalDamages * weight * damagesType.weight) / 5;
+
 
 +
           savedDamages[damagesWithFormula] = finalDamages;
 +
          addKeyValue(damagesWeighted, finalDamages, weight);
 
         }
 
         }
      } else {
 
        var finalDamages = calcSkillDamageWithSecondaryBonuses(
 
          damagesWithPrimaryBonuses,
 
          battleValues,
 
          damagesType,
 
          damagesWithPrimaryBonuses,
 
          skillFormula
 
        );
 
 
        addKeyValue(
 
          damagesWeighted,
 
          finalDamages,
 
          (weight * damagesType.weight) / totalCardinal
 
        );
 
        sumDamages += finalDamages * weight * damagesType.weight;
 
 
       }
 
       }
 
     }
 
     }
 +
  }
  
    var scatterData = addToTableResult(
+
  return damagesWeightedByType;
      tableResult,
+
}
      damagesWeighted,
 
      numberFormat,
 
      minMaxDamages
 
    );
 
    updateDamagesChart(scatterData, damagesChart, damagesType.name);
 
  }
 
  
  if (minMaxDamages.min === Infinity) {
+
function calcMagicSkillDamages(battleValues) {
     minMaxDamages.min = 0;
+
  var {
   }
+
     attackValues: {
 +
      minMagicAttackValue,
 +
      maxMagicAttackValue,
 +
      magicAttackValueAugmentation,
 +
      weights,
 +
    },
 +
    bonusValues,
 +
    damagesTypeCombinaison,
 +
    skillFormula,
 +
    skillRange: [minVariation, maxVariation],
 +
   } = battleValues;
  
   return [sumDamages / totalCardinal, minMaxDamages];
+
   var damagesWeightedByType = {};
}
 
  
function changeMonsterValues(monster, instance, attacker) {
+
  for (var damagesType of damagesTypeCombinaison) {
  switch (instance) {
+
    if (!damagesType.weight) {
    case "SungMahiTower":
+
       continue;
       var sungMahiFloor = 1;
+
    }
      var sungMahiStep = 1;
 
      var rawDefense = 120;
 
  
      if (isPC(attacker)) {
+
    var damagesWeighted = {};
        sungMahiFloor = attacker.sungMahiFloor;
+
    var savedDamages = {};
        sungMahiStep = attacker.sungMahiStep;
 
      }
 
  
      if (monster.rank === 5) {
+
    damagesWeightedByType[damagesType.name] = damagesWeighted;
        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 createMonster(monsterVnum, attacker) {
+
    for (
  var monsterAttributes = monsterData[monsterVnum];
+
      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
 +
        );
  
  var monster = {
+
        if (damagesWithPrimaryBonuses <= 2) {
    name: monsterAttributes[36],
+
          for (var damages = 1; damages <= 5; damages++) {
    rank: monsterAttributes[0],
+
            var finalDamages = calcSkillDamageWithSecondaryBonuses(
    race: monsterAttributes[1],
+
              damages,
    attack: monsterAttributes[2],
+
              bonusValues,
    level: monsterAttributes[3],
+
              damagesType,
    type: monsterAttributes[4],
+
              damagesWithPrimaryBonuses
    str: monsterAttributes[5],
+
            );
    dex: monsterAttributes[6],
+
            addKeyValue(damagesWeighted, finalDamages, weight / 5);
    vit: monsterAttributes[7],
+
          }
    int: monsterAttributes[8],
+
        } else {
    minAttackValue: monsterAttributes[9],
+
          var finalDamages = calcSkillDamageWithSecondaryBonuses(
    maxAttackValue: monsterAttributes[10],
+
            damagesWithPrimaryBonuses,
    rawDefense: monsterAttributes[11],
+
            bonusValues,
    criticalHit: monsterAttributes[12],
+
            damagesType,
    piercingHit: monsterAttributes[13],
+
            damagesWithPrimaryBonuses
    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;
+
          savedDamages[rawDamages] = finalDamages;
 +
          addKeyValue(damagesWeighted, finalDamages, weight);
 +
        }
 +
      }
 +
    }
 +
  }
  
  // if (attacker && monster.instance === 0) {
+
   return damagesWeightedByType;
  //  changeMonsterValues(monster, "SungMahiTower", attacker);
 
  // }
 
 
 
  monster.defense = monster.rawDefense + monster.level + monster.vit;
 
 
 
   return monster;
 
 
}
 
}
  
function addPotentialErrorInformation(
+
function calcDamages(
  errorInformation,
 
 
   attacker,
 
   attacker,
 
   victim,
 
   victim,
   characters
+
   attackType,
 +
  battle,
 +
  removeSkillVariation
 
) {
 
) {
   for (var error of Object.values(errorInformation)) {
+
   var damagesCalculator, skillId, skillType;
    hideElement(error);
 
  }
 
  
   if (isPC(attacker)) {
+
   if (attackType === "physical") {
    if (isRiding(attacker)) {
+
    damagesCalculator = calcPhysicalDamages;
      if (attacker.horsePoint === 0) {
+
  } else if (attackType.startsWith("attackSkill")) {
        showElement(errorInformation["horse-level"]);
+
    skillId = Number(attackType.split("attackSkill")[1]);
      }
 
      showElement(errorInformation["horse-stat"]);
 
    } else if (isPolymorph(attacker)) {
 
      if (attacker.polymorphPoint === 0) {
 
        showElement(errorInformation["polymorph-level"]);
 
      }
 
  
      if (
+
    if (isMagicClass(attacker) || isDispell(attacker, skillId)) {
        (attacker.polymorphPoint <= 39 && attacker.attackValuePercent <= 199) ||
+
      skillType = "magic";
        (attacker.polymorphPoint === 40 && attacker.attackValuePercent <= 299)
+
      damagesCalculator = calcMagicSkillDamages;
      ) {
+
    } else {
        showElement(errorInformation["polymorph-bonus"]);
+
      skillType = "physical";
       }
+
       damagesCalculator = calcPhysicalSkillDamages;
 
     }
 
     }
   } else {
+
   } else if (attackType.startsWith("horseSkill")) {
     showElement(errorInformation["monster-attacker"]);
+
     skillType = "physical";
 +
    skillId = Number(attackType.split("horseSkill")[1]);
 +
    damagesCalculator = calcPhysicalSkillDamages;
 
   }
 
   }
  
   if (isPC(victim)) {
+
   var battleValues = createBattleValues(attacker, victim, battle, skillType);
    if (isRiding(victim)) {
+
 
      showElement(errorInformation["horse-stat"]);
+
  if (skillId) {
    } else if (isPolymorph(victim)) {
+
    getSkillFormula(battle, skillId, battleValues, removeSkillVariation);
      if (attacker.polymorphPoint === 0) {
 
        showElement(errorInformation["polymorph-level"]);
 
      }
 
      showElement(errorInformation["polymorph-defense"]);
 
    }
 
 
   }
 
   }
  
   if (characters.unsavedChanges) {
+
   var {
     showElement(errorInformation["save"]);
+
    attackValues: { totalCardinal, possibleDamagesCount },
   }
+
  } = battleValues;
 +
 
 +
  return {
 +
     damagesWeightedByType: damagesCalculator(battleValues),
 +
    totalCardinal: totalCardinal,
 +
    possibleDamagesCount: possibleDamagesCount,
 +
    skillType: skillType,
 +
   };
 
}
 
}
  
function displayFightResults(
+
function damagesWithoutVariation(
 +
  attacker,
 +
  victim,
 +
  attackType,
 
   battle,
 
   battle,
   attackerName,
+
   characters
  victimName,
 
  meanDamages,
 
  minMaxDamages
 
 
) {
 
) {
   var tableResultHistory = battle.tableResultHistory;
+
   startDamagesTime = performance.now();
  var attackTypeSelection = battle.attackTypeSelection;
 
  var savedFights = battle.savedFights;
 
  
   showElement(tableResultHistory);
+
   var {
   hideElement(tableResultHistory.rows[1]);
+
    damagesWeightedByType,
 +
    totalCardinal,
 +
    possibleDamagesCount,
 +
    skillType,
 +
  } = calcDamages(attacker, victim, attackType, battle);
 +
 
 +
   endDamagesTime = performance.now();
  
   var valuesToDisplay = [
+
   possibleDamagesCount = displayResults(
     attackerName,
+
     possibleDamagesCount,
     victimName,
+
     totalCardinal,
     attackTypeSelection.options[attackTypeSelection.selectedIndex].textContent,
+
     damagesWeightedByType,
     meanDamages,
+
     battle,
     minMaxDamages.min,
+
     attacker.name,
     minMaxDamages.max,
+
     victim.name
   ];
+
   );
  
   savedFights.push(valuesToDisplay);
+
   endDisplayTime = performance.now();
  updateSavedFights(savedFights);
 
  
   addRowToTableResultHistory(
+
   displayFightInfo(
     tableResultHistory,
+
     possibleDamagesCount,
     valuesToDisplay,
+
     endDamagesTime - startDamagesTime,
     battle.deleteFightTemplate,
+
    endDisplayTime - endDamagesTime,
     battle.numberFormat
+
    battle
 +
  );
 +
  addPotentialErrorInformation(
 +
     battle.errorInformation,
 +
    attacker,
 +
    victim,
 +
     skillType,
 +
    characters
 
   );
 
   );
 +
 +
  hideElement(battle.bonusVariationResultContainer);
 +
  showElement(battle.fightResultContainer);
 
}
 
}
  
function createBattle(characters, battle) {
+
function damagesWithVariation(
   function isPseudoSaved(pseudo) {
+
  attacker,
     return characters.savedCharacters.hasOwnProperty(pseudo);
+
  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;
  
   battle.battleForm.addEventListener("submit", function (event) {
+
   for (
     event.preventDefault();
+
    var bonusValue = minVariation;
 +
    bonusValue <= maxVariation;
 +
    bonusValue += step
 +
  ) {
 +
     entity[entityVariation] = bonusValue;
  
     // auto save
+
     var { damagesWeightedByType, totalCardinal } = calcDamages(
    if (characters.unsavedChanges) {
+
      copyObject(attacker),
       characters.saveButton.click();
+
       copyObject(victim),
     }
+
      attackType,
 +
      battle,
 +
      true
 +
     );
  
     var battleInfo = new FormData(event.target);
+
     var meanDamages = calcMeanDamages(damagesWeightedByType, totalCardinal);
    var attackerName = battleInfo.get("attacker");
 
    var attackType = battleInfo.get("attackTypeSelection");
 
    var victimName = battleInfo.get("victim");
 
  
     if (!attackerName && !attackType && !victimName) {
+
     if (bonusValue === minVariation) {
       return;
+
       var firstDamages = Math.max(meanDamages, 1e-3);
 
     }
 
     }
  
     var attackerWeapon = null;
+
     damagesByBonus.push({ x: bonusValue, y: meanDamages });
 +
    augmentationByBonus.push({
 +
      x: bonusValue,
 +
      y: meanDamages / firstDamages - 1,
 +
    });
 +
    simulationCount++;
 +
  }
  
    if (isPseudoSaved(attackerName)) {
+
  endTime = performance.now();
      var attacker = copyObject(characters.savedCharacters[attackerName]);
 
  
      if (weaponData.hasOwnProperty(attacker.weapon)) {
+
  battle.damagesByBonus = damagesByBonus.concat(entityVariation);
        attackerWeapon = weaponData[attacker.weapon];
 
      } else {
 
        attackerWeapon = weaponData[0];
 
      }
 
    } else {
 
      var attacker = createMonster(attackerName);
 
    }
 
  
     if (isPseudoSaved(victimName)) {
+
  addToBonusVariationChart(
      var victim = copyObject(characters.savedCharacters[victimName]);
+
    damagesByBonus,
     } else {
+
     augmentationByBonus,
      var victim = createMonster(victimName, attacker);
+
    entity.bonusVariationDisplay,
    }
+
     battle.bonusVariationChart
 +
  );
  
    var meanDamages, minMaxDamages;
+
  simulationCount = battle.numberFormats.default.format(simulationCount);
     var calcDamages;
+
  simulationTime = battle.numberFormats.second.format(
    var skillId = 0;
+
     (endTime - startTime) / 1000
 +
  );
  
    if (attackType === "physical") {
+
  battle.simulationCounter.textContent = simulationCount;
      calcDamages = calcPhysicalDamages;
+
  battle.simulationTime.textContent = simulationTime;
    } else if (attackType.startsWith("attackSkill")) {
 
      skillId = Number(attackType.split("attackSkill")[1]);
 
  
      if (isMagicClass(attacker) || isDispell(attacker, skillId)) {
+
  hideElement(battle.fightResultContainer);
        calcDamages = calcMagicSkillDamages;
+
  showElement(battle.bonusVariationResultContainer);
      } else {
 
        calcDamages = calcPhysicalSkillDamages;
 
      }
 
    } else if (attackType.startsWith("horseSkill")) {
 
      skillId = Number(attackType.split("horseSkill")[1]);
 
      calcDamages = calcPhysicalSkillDamages;
 
    }
 
  
     clearTableResult(battle.tableResult);
+
  if (
     clearDamageChart(battle.damagesChart);
+
     isChecked(attacker.bonusVariationActivation) &&
 +
    isChecked(victim.bonusVariationActivation)
 +
  ) {
 +
    showElement(battle.errorInformation["attacker-victim-variation"]);
 +
  } else {
 +
     hideElement(battle.errorInformation["attacker-victim-variation"]);
 +
  }
 +
}
  
    [meanDamages, minMaxDamages] = calcDamages(
+
function changeMonsterValues(monster, instance, attacker) {
      attacker,
+
  switch (instance) {
      attackerWeapon,
+
    case "SungMahiTower":
      victim,
+
       var sungMahiFloor = 1;
      battle.tableResult,
+
       var sungMahiStep = 1;
       battle.mapping,
+
       var rawDefense = 120;
       battle.constants,
 
       battle.damagesChart,
 
      battle.numberFormat,
 
      skillId
 
    );
 
  
    displayDamagesChart(battle.damagesChart, battle.chartContainer);
+
      if (isPC(attacker)) {
    displayFightResults(
+
        sungMahiFloor = attacker.sungMahiFloor;
       battle,
+
        sungMahiStep = attacker.sungMahiStep;
       attacker.name,
+
      }
       victim.name,
+
 
       meanDamages,
+
      if (monster.rank === 5) {
       minMaxDamages
+
        monster.level = 121;
    );
+
        monster.dex = 75;
    addPotentialErrorInformation(
+
        rawDefense += 1;
       battle.errorInformation,
+
      } else if (monster.rank === 6) {
       attacker,
+
        monster.level = 123;
       victim,
+
        monster.dex = 75;
       characters
+
        rawDefense += 1;
    );
+
      } else {
    showElement(battle.fightResultContainer);
+
        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;
 +
   }
  
   battle.attackerSelection.addEventListener("change", function (event) {
+
   // Alastor
     var attackerName = event.target.value;
+
  if (monster.vnum === 6790) {
     var attackTypeSelection = battle.attackTypeSelection;
+
     monster.iceResistance = 0;
 +
    monster.iceBonus = 0,
 +
    monster.lightningResistance = -10;
 +
     monster.lightningBonus = 65;
 +
  }
 +
}
  
    if (isPseudoSaved(attackerName)) {
+
function createWeapon(weaponVnum) {
      var attacker = characters.savedCharacters[attackerName];
+
  var weapon = weaponData[weaponVnum];
      filterAttackTypeSelection(attacker, attackTypeSelection);
+
  var weaponName = weapon[0];
     } else {
+
 
      filterAttackTypeSelectionMonster(attackTypeSelection);
+
  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 createMapping() {
+
function createMonster(monsterVnum, attacker) {
   mapping = {
+
   var monsterAttributes = monsterData[monsterVnum];
     typeFlag: [
+
 
      "animalBonus", // 0
+
  var monster = {
      "humanBonus", // 1
+
     vnum: monsterVnum,
      "orcBonus", // 2
+
    name: monsterAttributes[36],
      "mysticBonus", // 3
+
    rank: monsterAttributes[0],
      "undeadBonus", // 4
+
    race: monsterAttributes[1],
      "insectBonus", // 5
+
    attack: monsterAttributes[2],
      "desertBonus", // 6
+
     level: monsterAttributes[3],
      "devilBonus", // 7
+
     type: monsterAttributes[4],
     ],
+
    str: monsterAttributes[5],
     raceBonus: {
+
    dex: monsterAttributes[6],
      warrior: "warriorBonus",
+
    vit: monsterAttributes[7],
      sura: "suraBonus",
+
    int: monsterAttributes[8],
      ninja: "ninjaBonus",
+
     minAttackValue: monsterAttributes[9],
      shaman: "shamanBonus",
+
     maxAttackValue: monsterAttributes[10],
      lycan: "lycanBonus",
+
    rawDefense: monsterAttributes[11],
     },
+
    criticalHit: monsterAttributes[12],
     raceResistance: {
+
    piercingHit: monsterAttributes[13],
      warrior: "warriorResistance",
+
    fistDefense: monsterAttributes[14],
      sura: "suraResistance",
+
     swordDefense: monsterAttributes[15],
      ninja: "ninjaResistance",
+
     twoHandedSwordDefense: monsterAttributes[16],
      shaman: "shamanResistance",
+
    daggerDefense: monsterAttributes[17],
      lycan: "lycanResistance",
+
    bellDefense: monsterAttributes[18],
     },
+
    fanDefense: monsterAttributes[19],
     defenseWeapon: [
+
    arrowDefense: monsterAttributes[20],
      "swordDefense", // 0
+
    clawDefense: monsterAttributes[21],
      "daggerDefense", // 1
+
     fireResistance: monsterAttributes[22],
      "arrowDefense", // 2
+
     lightningResistance: monsterAttributes[23],
      "twoHandedSwordDefense", // 3
+
    magicResistance: monsterAttributes[24],
      "bellDefense", // 4
+
    windResistance: monsterAttributes[25],
      "clawDefense", // 5
+
     lightningBonus: monsterAttributes[26],
      "fanDefense", // 6
+
     fireBonus: monsterAttributes[27],
      "swordDefense", // 7
+
    iceBonus: monsterAttributes[28],
      "fistDefense", // 8
+
    windBonus: monsterAttributes[29],
     ],
+
    earthBonus: monsterAttributes[30],
     breakWeapon: [
+
    darknessBonus: monsterAttributes[31],
      "breakSwordDefense", // 0
+
     darknessResistance: monsterAttributes[32],
      "breakDaggerDefense", // 1
+
     iceResistance: monsterAttributes[33],
      "breakArrowDefense", // 2
+
    earthResistance: monsterAttributes[34],
      "breakTwoHandedSwordDefense", // 3
+
     damageMultiplier: monsterAttributes[35],
      "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() {
+
   // monster.instance = 0;
   var constants = {
+
 
    polymorphPowerTable: [
+
  // if (attacker && monster.instance === 0) {
      10, 11, 11, 12, 13, 13, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 26, 27,
+
  //  changeMonsterValues(monster, "SungMahiTower", attacker);
      29, 31, 33, 35, 37, 39, 41, 44, 46, 49, 52, 55, 59, 62, 66, 70, 74, 79,
+
  // }
      84, 89, 94, 100, 0,
+
 
    ],
+
   changeMonsterValues(monster);
    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],
 
    },
 
   };
 
  return constants;
 
}
 
  
function initResultTableHistory(battle) {
+
   monster.defense = monster.rawDefense + monster.level + monster.vit;
   var tableResultHistory = battle.tableResultHistory;
 
  var savedFights = battle.savedFights;
 
  var startIndex = 3;
 
  
   if (savedFights.length) {
+
   return monster;
    hideElement(tableResultHistory.rows[1]);
+
}
  
    for (var savedFight of battle.savedFights) {
+
function addPotentialErrorInformation(
      addRowToTableResultHistory(
+
  errorInformation,
        tableResultHistory,
+
  attacker,
        savedFight,
+
  victim,
        battle.deleteFightTemplate,
+
  skillType,
        battle.numberFormat
+
  characters
      );
+
) {
    }
+
  for (var error of Object.values(errorInformation)) {
 +
    hideElement(error);
 
   }
 
   }
  
   tableResultHistory.addEventListener("click", function (event) {
+
   if (isPC(attacker)) {
     var deleteButton = event.target.closest(".svg-icon-delete");
+
     if (isRiding(attacker)) {
 
+
      if (attacker.horsePoint === 0) {
    if (deleteButton) {
+
        showElement(errorInformation["horse-level"]);
      var row = deleteButton.closest("tr");
+
      }
 
+
       showElement(errorInformation["horse-stat"]);
       if (row) {
+
    } else if (isPolymorph(attacker)) {
        savedFights.splice(row.rowIndex - startIndex, 1);
+
      if (attacker.polymorphPoint === 0) {
        updateSavedFights(savedFights);
+
        showElement(errorInformation["polymorph-level"]);
 
 
        row.remove();
 
 
 
        if (tableResultHistory.rows.length === startIndex) {
 
          showElement(tableResultHistory.rows[1]);
 
        }
 
 
       }
 
       }
    }
 
  });
 
}
 
  
function initChart(battle, chartSource) {
+
      if (
  function createChart() {
+
        (attacker.polymorphPoint <= 39 && attacker.attackValuePercent <= 199) ||
     var verticalLinePlugin = {
+
        (attacker.polymorphPoint === 40 && attacker.attackValuePercent <= 299)
       id: "verticalLine",
+
      ) {
       afterDatasetsDraw: function (chart, easing) {
+
        showElement(errorInformation["polymorph-bonus"]);
         if (chart.tooltip._active && chart.tooltip._active.length) {
+
      }
          var ctx = chart.ctx;
+
    }
          var activePoint = chart.tooltip._active[0];
+
     if (skillType === "magic") {
          var x = activePoint.element.x;
+
       if (attacker.magicAttackValue) {
          var topY = chart.scales.y.top;
+
        showElement(errorInformation["magic-attack-value-bonus"]);
          var bottomY = chart.scales.y.bottom;
+
       }
 +
      if (victim.magicResistance) {
 +
         showElement(errorInformation["magic-resistance"]);
 +
      }
 +
    }
 +
  } else {
 +
    showElement(errorInformation["monster-attacker"]);
 +
    if (isMagicAttacker(attacker) && victim.magicResistance) {
 +
      showElement(errorInformation["magic-resistance"]);
 +
    }
 +
  }
  
          ctx.save();
+
  if (isPC(victim)) {
          ctx.beginPath();
+
    if (isRiding(victim)) {
          ctx.setLineDash([3, 2]);
+
      showElement(errorInformation["horse-stat"]);
          ctx.moveTo(x, topY);
+
    } else if (isPolymorph(victim)) {
          ctx.lineTo(x, bottomY);
+
      if (attacker.polymorphPoint === 0) {
          ctx.lineWidth = 1;
+
        showElement(errorInformation["polymorph-level"]);
          ctx.strokeStyle = "lightgray";
+
      }
          ctx.stroke();
+
      showElement(errorInformation["polymorph-defense"]);
          ctx.restore();
+
    }
         }
+
  }
 +
 
 +
  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;
  
     Chart.register(verticalLinePlugin);
+
     for (var index = 0; index < datasets.length; index++) {
 +
      var dataset = datasets[index];
 +
      var scatterData = scatterDataByType[dataset.name];
  
    var ctx = battle.plotDamages.getContext("2d");
+
      if (dataset.canBeReduced && reduceChartPoints.checked) {
    var chart = new Chart(ctx, {
+
        dataset.data = aggregateDamages(scatterData, maxPoints);
       type: "scatter",
+
        addAnimations = true;
      data: {
+
       } else {
        datasets: [],
+
        dataset.data = scatterData;
      },
+
      }
      options: {
+
    }
        responsive: true,
+
 
        maintainAspectRatio: false,
+
    handleChartAnimations(chart, addAnimations);
        plugins: {
+
    chart.update();
          legend: {
+
 
            display: true,
+
    displayTime.textContent = numberFormat.format(
            onClick: (e, legendItem, legend) => {
+
      (performance.now() - startDisplayTime) / 1000
              var index = legendItem.datasetIndex;
+
    );
              var chart = legend.chart;
+
  });
              var meta = chart.getDatasetMeta(index);
+
 
              meta.hidden =
+
  reduceChartPointsContainer.addEventListener("pointerup", function (event) {
                meta.hidden === null
+
    if (event.pointerType === "mouse") {
                  ? !chart.data.datasets[index].hidden
+
      reduceChartPoints.click();
                  : null;
+
    }
              chart.update();
+
  });
            },
+
}
          },
+
 
          tooltip: {
+
function downloadRawDataListener(battle) {
            mode: "index",
+
  var { downLoadRawData, downLoadRawDataVariation } = battle;
            intersect: false,
+
  var fileType = "text/csv;charset=utf-8;";
          },
+
 
        },
+
  downLoadRawData.addEventListener("click", function () {
        hover: {
+
    var damagesWeightedByType = battle.damagesWeightedByType;
          mode: "index",
+
    var filename = "raw_damages.csv";
          intersect: false,
+
    var csvContent = "damage,probabilities,damageType\n";
        },
+
 
        scales: {
+
    for (var damagesType in damagesWeightedByType) {
          x: {
+
      var damagesWeighted = damagesWeightedByType[damagesType];
            type: "linear",
+
 
            position: "bottom",
+
      for (var damages in damagesWeighted) {
            title: {
+
        csvContent +=
              display: true,
+
          damages + "," + damagesWeighted[damages] + "," + damagesType + "\n";
              text: "Dégâts",
+
      }
            },
+
    }
          },
+
 
          y: {
+
    downloadData(csvContent, fileType, filename);
            title: {
+
  });
              display: true,
+
 
              text: "Pourcentage",
+
  downLoadRawDataVariation.addEventListener("click", function () {
            },
+
    var damagesByBonus = battle.damagesByBonus;
            ticks: {
+
    var damagesByBonusLength = damagesByBonus.length;
              format: {
+
    var filename = "damages_variation.csv";
                style: "percent",
+
 
              },
+
    if (!damagesByBonusLength) {
            },
+
      return;
          },
+
    }
        },
+
 
       },
+
    var csvContent =
    });
+
       damagesByBonus[damagesByBonusLength - 1] + ",averageDamage\n";
 
+
 
     var dataset = {
+
     for (var index = 0; index < damagesByBonusLength - 1; index++) {
       "Coup classique": {
+
       var row = damagesByBonus[index];
        label: "Coup classique",
+
 
        showLine: false,
+
      csvContent += row.x + "," + row.y + "\n";
        backgroundColor: "rgba(75, 192, 192, 0.2)",
+
    }
        borderColor: "rgba(75, 192, 192, 1)",
+
 
        borderWidth: 1,
+
    downloadData(csvContent, fileType, filename);
        pointRadius: 3,
+
  });
      },
+
}
      "Coup perçant": {
+
 
        label: "Coup perçant",
+
function displayResults(
        showLine: false,
+
  possibleDamagesCount,
        backgroundColor: "rgba(192, 192, 75, 0.2)",
+
  totalCardinal,
        borderColor: "rgba(192, 192, 75, 1)",
+
  damagesWeightedByType,
        borderWidth: 1,
+
  battle,
        pointRadius: 3,
+
  attackerName,
        hidden: true,
+
  victimName
      },
+
) {
      "Coup critique": {
+
  var [
        label: "Coup critique",
+
    meanDamages,
        showLine: false,
+
    minDamages,
        backgroundColor: "rgba(192, 75, 192, 0.2)",
+
    maxDamages,
        borderColor: "rgba(192, 75, 192, 1)",
+
    scatterDataByType,
        borderWidth: 1,
+
    possibleDamagesCount,
        pointRadius: 3,
+
    uniqueDamagesCount,
        hidden: true,
+
  ] = prepareDamagesData(
      },
+
    damagesWeightedByType,
      "Coup critique perçant": {
+
    possibleDamagesCount,
        label: "Coup critique perçant",
+
    totalCardinal
        showLine: false,
+
  );
        backgroundColor: "rgba(75, 75, 192, 0.2)",
+
 
        borderColor: "rgba(75, 75, 192, 1)",
+
  addToDamagesChart(
        borderWidth: 1,
+
    scatterDataByType,
        pointRadius: 3,
+
    battle.damagesChart,
        hidden: true,
+
    battle.reduceChartPoints.checked
      },
+
  );
     };
+
  updateDamagesChartDescription(
    battle.damagesChart = {
+
    battle.uniqueDamagesCounters,
      chart: chart,
+
    uniqueDamagesCount,
      dataset: dataset,
+
    battle.numberFormats.default
     };
+
  );
  }
+
  displayFightResults(
 
+
    battle,
   loadScript(chartSource, createChart);
+
    attackerName,
}
+
    victimName,
 
+
    meanDamages,
function createDamageCalculatorInformation(chartSource) {
+
    minDamages,
   var characters = {
+
    maxDamages
     unsavedChanges: false,
+
  );
     savedCharacters: {},
+
  battle.damagesWeightedByType = damagesWeightedByType;
     currentCharacter: null,
+
  battle.scatterDataByType = scatterDataByType;
     savedMonsters: getSavedMonsters(),
+
 
    characterCreation: document.getElementById("character-creation"),
+
  return possibleDamagesCount;
    addNewCharacterButton: document.getElementById("add-new-character"),
+
}
    dropZone: document.getElementById("character-drop-zone"),
+
 
    characterInput: document.getElementById("character-input"),
+
function displayFightResults(
     newCharacterTemplate: document.getElementById("new-character-template")
+
  battle,
      .children[0],
+
  attackerName,
     charactersContainer: document.getElementById("characters-container"),
+
  victimName,
     newMonsterTemplate: document.getElementById("new-monster-template")
+
  meanDamages,
      .children[0],
+
  minDamages,
    monstersContainer: document.getElementById("monsters-container"),
+
  maxDamages
    monsterListForm: document.getElementById("monster-list-form"),
+
) {
    searchMonster: document.getElementById("search-monster"),
+
  var {
    monsterList: document.getElementById("monster-list"),
+
    tableResultFight,
    saveButton: document.getElementById("save-character"),
+
    tableResultHistory,
    weaponCategory: document.getElementById("weapon-category"),
+
    attackTypeSelection,
     weaponDisplay: document.getElementById("weapon-display"),
+
    savedFights,
     randomAttackValue: document.getElementById("random-attack-value"),
+
    numberFormats: { default: numberFormat },
     randomMagicAttackValue: document.getElementById(
+
     deleteFightTemplate,
      "random-magic-attack-value"
+
  } = battle;
     ),
+
 
     yoharaCreation: document.getElementById("yohara-creation"),
+
  hideElement(tableResultHistory.rows[1]);
     blessingCreation: document.getElementById("blessing-creation"),
+
 
     marriageCreation: document.getElementById("marriage-creation"),
+
  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"),
 +
    },
 
   };
 
   };
  
   delete characters.newCharacterTemplate.dataset.click;
+
   characters.bonusVariation.inputDisplay.setAttribute("readonly", "");
  
 
   for (var [pseudo, character] of Object.entries(getSavedCharacters())) {
 
   for (var [pseudo, character] of Object.entries(getSavedCharacters())) {
Ligne 4 144 : Ligne 4 947 :
 
     attackTypeSelection: document.getElementById("attack-type-selection"),
 
     attackTypeSelection: document.getElementById("attack-type-selection"),
 
     victimSelection: document.getElementById("victim-selection"),
 
     victimSelection: document.getElementById("victim-selection"),
 +
    damagesWeightedByType: {},
 +
    scatterDataByType: {},
 +
    damagesByBonus: [],
 +
    tableResultFight: document.getElementById("result-table-fight"),
 
     tableResultHistory: document.getElementById("result-table-history"),
 
     tableResultHistory: document.getElementById("result-table-history"),
 
     deleteFightTemplate: document.getElementById("delete-fight-template")
 
     deleteFightTemplate: document.getElementById("delete-fight-template")
Ligne 4 149 : Ligne 4 956 :
 
     errorInformation: {},
 
     errorInformation: {},
 
     fightResultContainer: document.getElementById("fight-result-container"),
 
     fightResultContainer: document.getElementById("fight-result-container"),
     tableResult: document.getElementById("result-table"),
+
     downLoadRawData: document.getElementById("download-raw-data"),
     chartContainer: document.getElementById("chart-container"),
+
    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"),
 
     plotDamages: document.getElementById("plot-damages"),
     numberFormat: {
+
     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, {
 
       default: new Intl.NumberFormat(undefined, {
 
         minimumFractionDigits: 0,
 
         minimumFractionDigits: 0,
Ligne 4 159 : Ligne 4 982 :
 
       percent: new Intl.NumberFormat(undefined, {
 
       percent: new Intl.NumberFormat(undefined, {
 
         style: "percent",
 
         style: "percent",
 +
        maximumFractionDigits: 3,
 +
      }),
 +
      second: new Intl.NumberFormat(undefined, {
 +
        style: "unit",
 +
        unit: "second",
 +
        unitDisplay: "long",
 
         maximumFractionDigits: 3,
 
         maximumFractionDigits: 3,
 
       }),
 
       }),
Ligne 4 164 : Ligne 4 993 :
 
     mapping: mapping,
 
     mapping: mapping,
 
     constants: constants,
 
     constants: constants,
 +
    translation: getTranslation(constants.translation),
 
   };
 
   };
  
 +
  attackSelectonListener(
 +
    characters,
 +
    battle.attackerSelection,
 +
    battle.attackTypeSelection
 +
  );
 
   initResultTableHistory(battle);
 
   initResultTableHistory(battle);
   initChart(battle, chartSource);
+
   loadScript(chartSource, function () {
 +
    initDamagesChart(battle);
 +
    initBonusVariationChart(battle);
 +
  });
 +
  reduceChartPointsListener(battle);
 +
  downloadRawDataListener(battle);
  
   var errorElements = document
+
   var errorElements = document.querySelectorAll("[data-error]");
    .getElementById("error-information")
 
    .querySelectorAll("li[data-error]");
 
  
 
   for (var index = 0; index < errorElements.length; index++) {
 
   for (var index = 0; index < errorElements.length; index++) {

Version actuelle datée du 27 novembre 2024 à 21:18

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;
  }

  // Alastor
  if (monster.vnum === 6790) {
    monster.iceResistance = 0;
    monster.iceBonus = 0,
    monster.lightningResistance = -10;
    monster.lightningBonus = 65;
  }
}

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 = {
    vnum: monsterVnum,
    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);
  // }

  changeMonsterValues(monster);

  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);
})();