\n', //TODO: add data-damage-* attributes with initial damage levels
'
\n',
'
\n',
'
D+
\n',
'
\n',
'
\n',
'\n',
'\n',
'
\n',
'\n',
'
\n',
'
\n',
'
\n',
'
'].join("");
const DAMAGE_MONITOR_HTML = [
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
\n',
'
'].join("");
const MAX_INI_CLASS = "table-primary";
const ZERO_INI_CLASS = "table-secondary";
const REGULAR_INI_CLASS = "table-success";
/*
* helper functions
*/
// roll for initiative with the given reaction and number of ini dice
function rollForInitiative(dice, rea) {
let diceRolls = Array.from({length: parseInt(dice)}, () => Math.ceil(Math.random() * 6));
console.log(diceRolls);
return diceRolls.reduce((a, b) => a + b, 0) + parseInt(rea);
}
// figure out whose action comes first out of two combatants a and b
function whoGoesFirst(a, b) {
// check for K.O./death
let tmpA = $(a).hasClass("out-of-commission") ? -1 : parseInt($(a).find(".combatantIni").text()) || 0;
let tmpB = $(b).hasClass("out-of-commission") ? -1 : parseInt($(b).find(".combatantIni").text()) || 0;
// compare ini
let comparer = tmpB - tmpA;
if (comparer != 0) {
return comparer;
} else
// tie; compare reaction
{
tmpA = parseInt($(a).find(".combatantRea").text()) || 0;
tmpB = parseInt($(b).find(".combatantRea").text()) || 0
return tmpB - tmpA;
}
}
// add contextual classes and sort combatants by ini value
function sortTable() {
// remove previous classes from rows, disable act buttons
$(".combatantRow").removeClass(MAX_INI_CLASS + " " + ZERO_INI_CLASS + " " + REGULAR_INI_CLASS).find(".act-button").prop("disabled", true).attr("aria-disabled", "true");
// get ini value for every combatant; set to 0 if K.O./dead
let iniValues = $.map( $(".combatantRow"), function(tr, i) {
//TODO: don't rely on class out-of-commission being set, check and set it here instead
return $(tr).hasClass("out-of-commission") ? 0 : parseInt($(tr).find(".combatantIni").text());
});
//TODO: maxIni wid nicht vergeben wenn damage > 0
// compute highest ini
let iniMax = Math.max.apply(null, iniValues);
// add contextual classes
//TODO: I should probably add badges here as well, maybe even effectiveIni
$(".combatantRow").each( function() {
// K.O./dead -> don't add anything
if ( $(this).hasClass("out-of-commission") ) {
return true;
}
// ini = zero
if ( parseInt($(this).find(".combatantIni").text()) == 0 ) {
$(this).addClass(ZERO_INI_CLASS);
return true;
}
// ini = max and non-zero
if ( parseInt($(this).find(".combatantIni").text()) == iniMax && iniMax > 0 ) {
$(this).addClass(MAX_INI_CLASS).find(".act-button").prop("disabled", false).removeAttr("aria-disabled");
return true;
}
// everything else
$(this).addClass(REGULAR_INI_CLASS);
})
// sort rows and append them in new order
let $rows = $(".combatantRow").toArray().sort(whoGoesFirst);
for ( var i = 0; i < $rows.length; i++ ) {
$("#combatantsTable").append($rows[i]);
}
return;
}
// returns a combatant's effective ini value (modified by wound penalties)
function getEffectiveIni(value, damageLevel1, damageLevel2) {
let effectiveIni;
// was function called with 1 argument (tr jQuery object)?
if ( arguments.length == 1 && $(value).is("tr.combatantRow") ) {
let trueIni = parseInt($(value).attr("data-true-ini"));
let damageStun = parseInt($(value).attr("data-damage-stun")) || 0;
let damagePhysical = parseInt($(value).attr("data-damage-physical")) || 0;
effectiveIni = trueIni - DAMAGE_PENALTY[damageStun] - DAMAGE_PENALTY[damagePhysical];
}
// or with 3 arguments (ini and damage levels)?
else if ( arguments.length == 3 ) {
effectiveIni = parseInt(value) - DAMAGE_PENALTY[parseInt(damageLevel1)] - DAMAGE_PENALTY[parseInt(damageLevel2)];
}
//
else {
return NaN;
}
//TODO: maybe check here for out-of-commission and return 'dead' or something instead of int
return effectiveIni < 0 ? 0 : effectiveIni;
}
/*
* Event handler functions
*/
// click handler for act buttons
function handleActButtonClick (e) {
// find current table row
let $tr = $(e.target).parents(".combatantRow");
let ini = $tr.attr("data-true-ini");
// reduce ini by 10 but not lower than 0
ini = Math.max(parseInt(ini) - 10, 0);
// set new ini value
// can't use text() here because that would delete wound badges
$tr.attr("data-true-ini", ini);
$tr.find(".combatantIni").contents()[0].data = getEffectiveIni($tr);
// resort table
sortTable();
}
// click handler for add buttons
function handleAddButtonClick (e) {
// restyle modal
$("#combatantModal .modal-title").text("Add Combatant");
$("#combatantModalAddOkButton").show();
$("#combatantModalEditOkButton").hide();
// add handler for enter key
$("#combatantModal input[id*='combatantModal']").off("keydown");
$("#combatantModal input[id*='combatantModal']").on("keydown", function (e) {
if ( e.which == 13 || e.which == 10 ) {
addCombatant(e);
}
});
// show modal
$("#combatantModal").modal("show");
}
// click handler for damage buttons; basically toggles visibility of table.damage-monitor
function handleDamageButtonClick (e) {
// get visibility status at click time
let visAtClick = $(e.target).parents(".damage-dropdown").find(".damage-monitor").css("display");
// hide all damage monitors
$(".damage-monitor:visible").css("display", "none");
// if targeted dm was hidden before, show it now
if ( visAtClick == "none" ) {
$(e.target).parents(".damage-dropdown").find(".damage-monitor").css("display", "block");
}
return false;
}
// click handler for damage monitor fields
function handleDamageMonitorClick (e) {
let $btn = $(e.target);
let $tr = $btn.parents("tr.combatantRow");
let damageType;
let otherDamageLevel
// calculate new damage level and type
let damageLevel = $btn.parent().parent().index();
console.log("damage level is", damageLevel);
if ( $btn.hasClass("damage-stun") ) {
damageType = "stun";
otherDamageLevel = $tr.attr("data-damage-physical") ? parseInt($tr.attr("data-damage-physical")) : 0;
} else if ( $btn.hasClass("damage-physical") ) {
damageType = "physical";
otherDamageLevel = $tr.attr("data-damage-stun") ? parseInt($tr.attr("data-damage-stun")) : 0;
} else {
return false;
}
// add damage level to table row as as data attribute
$tr.attr("data-damage-" + damageType, damageLevel);
//TODO: class out-of-commission should be set in sortTable() with the other contextual classes
if ( damageLevel == 10 || otherDamageLevel == 10 ) {
$tr.addClass("out-of-commission");
} else {
$tr.removeClass("out-of-commission");
}
// select/unselect damage boxes
$btn.addClass("active");
$btn.parent().parent().nextAll().find("button.damage-" + damageType).removeClass("active");
$btn.parent().parent().prevAll().find("button.damage-" + damageType).addClass("active");
// recalculate effective ini
$tr.find(".combatantIni").text(getEffectiveIni($tr));
// add damage level badges
if ( $tr.attr("data-damage-stun") && $tr.attr("data-damage-stun") != "0" ) {
$tr.find(".combatantIni").append('' + DAMAGE_NIVEAU[DAMAGE_PENALTY[$tr.attr("data-damage-stun")]] + '');
}
if ( $tr.attr("data-damage-physical") && $tr.attr("data-damage-physical") != "0" ) {
$tr.find(".combatantIni").append('' + DAMAGE_NIVEAU[DAMAGE_PENALTY[$tr.attr("data-damage-physical")]] + '');
}
// resort
sortTable();
// return false;
}
// click handler for edit buttons
function handleEditButtonClick (e) {
// find current table row
let $tr = $(e.target).parents(".combatantRow");
// restyle modal
$("#combatantModal .modal-title").text("Edit Combatant");
$("#combatantModalAddOkButton").hide();
$("#combatantModalEditOkButton").show();
// populate modal with values from row
$("#combatantModalName").val($tr.find(".combatantName").text());
$("#combatantModalDice").val($tr.find(".combatantDice").text());
$("#combatantModalRea").val($tr.find(".combatantRea").text());
$("#combatantModalIni").val($tr.attr("data-true-ini"));
//TODO: show effective ini in modal
// mark which row is being edited
$("#combatantModal").attr("data-row", $(".combatantRow").index($tr));
// add handler for enter key
$("#combatantModal input[id*='combatantModal']").off("keydown");
$("#combatantModal input[id*='combatantModal']").on("keydown", function (e) {
if ( e.which == 13 || e.which == 10 ) {
editCombatant(e);
}
});
// show modal
$("#combatantModal").modal("show");
}
function handleNewRoundButton (e) {
// restyle modal
$("#confirmModal .modal-title").text("Start new Round");
$("#confirmModalNewRoundOkButton").show();
$("#confirmModalRemoveCombatantOkButton").hide();
// show modal
$("#comfirmModal").modal("show");
}
// click handler for remove buttons
function handleRemoveButtonClick (e) {
// restyle modal
$("#confirmModal .modal-title").text("Remove Combatant");
$("#confirmModalRemoveCombatantOkButton").show();
$("#confirmModalNewRoundOkButton").hide();
// mark which row is being removed
$("#confirmModal").attr("data-row", $(".combatantRow").index($(e.target).parents(".combatantRow")));
// show modal
$("#comfirmModal").modal("show");
}
/*
* Validation functions
*/
// validate a combatant row form by checking for all conditions, including regular HTML5 validation
function validateCombatant() {
// get input elements
let inputElements = {
name: $("#combatantModalName").get(0),
ini: $("#combatantModalIni").get(0),
dice: $("#combatantModalDice").get(0),
rea: $("#combatantModalRea").get(0)
};
// do standard HTML5 form validation first
// (makes sure that name is not empty and that all other values are numbers within their individual ranges)
let valid = true;
Object.values(inputElements).forEach(function(input) {
if ( ! input.reportValidity() ) {
valid = false;
}
})
if ( ! valid ) {
return false;
}
// now for some custom validation; first we need to get the input values
let ini = inputElements["ini"].value.trim();
let dice = inputElements["dice"].value.trim();
let rea = inputElements["rea"].value.trim();
// invalidate if ini, dice and rea are all empty
if ( ini == "" && ( dice == "" || rea == "" ) ) {
inputElements["ini"].setCustomValidity("Requiring values for ini dice and reaction, or initiative, or all three");
inputElements["ini"].reportValidity();
inputElements["ini"].setCustomValidity("");
return false;
}
// invalidate if dice or rea is empty but not both
if ( ( dice == "" ) != ( rea == "" ) ) {
inputElements["dice"].setCustomValidity("Values required for both dice and reaction, or none (in which case ini is required)");
inputElements["dice"].reportValidity();
inputElements["dice"].setCustomValidity("");
return false;
}
// ok then
return true;
}
/*
* Main functions
*/
// add new combatant
function addCombatant (e) {
e.preventDefault();
// validate form
if ( ! validateCombatant() ) {
return false;
}
// hide modal
$("#combatantModal").modal("hide");
// roll for initiative if necessary
let ini = $("#combatantModalIni").val().trim();
ini = (ini != "") ? ini : rollForInitiative($("#combatantModalDice").val(), $("#combatantModalRea").val());
// construct jQuery object for table row
let $tr = $($.parseHTML(COMBATANT_TABLE_ROW));
$tr.find(".damage-dropdown").append($.parseHTML(DAMAGE_MONITOR_HTML));
// populate table row with values from modal
$tr.attr("data-true-ini", ini);
$tr.find(".combatantName").text($("#combatantModalName").val().trim());
$tr.find(".combatantIni").text(getEffectiveIni(ini, 0, 0)); // don't need to use contents()[0].data here b/c wound badges are added later
$tr.find(".combatantDice").text($("#combatantModalDice").val().trim());
$tr.find(".combatantRea").text($("#combatantModalRea").val().trim());
//TODO: retrieve initial damage levels
// construct jQuery object for table row
/* let $tr = $($.parseHTML( [
'
\n', //TODO: add data-damage-* attributes with initial damage levels
'
', name, '
\n',
'
', effectiveIni, '
\n',
'
', dice, 'D+', rea, '
\n',
'
\n',
'
\n',
'\n',
'\n',
'
\n',
'\n',
DAMAGE_MONITOR_HTML + "\n",
'
\n',
'
\n',
'
\n',
'
'].join("")
));*/
//TODO: mark initial damage levels with active class -> what? don't know what this means
// add handler to table cells (click to edit)
$tr.find(".combatantName, .combatantIni, .combatantDiceAndRea").on("click", handleEditButtonClick);
// add handlers to action buttons
$tr.find("button.edit-button").on("click", handleEditButtonClick);
$tr.find("button.act-button").on("click", handleActButtonClick);
$tr.find("button.damage-button").on("click", handleDamageButtonClick);
$tr.find("button.remove-button").on("click", handleRemoveButtonClick);
// add handler to damage monitor
$tr.find(".damage-stun, .damage-physical").on("click", handleDamageMonitorClick);
// add row to table and sort
$("#combatantsTable").append($tr);
sortTable();
}
// edit combatant
function editCombatant (e) {
e.preventDefault();
// validate form
if ( ! validateCombatant() ) {
return false;
}
// hide modal
$("#combatantModal").modal("hide");
// get values
let name = $("#combatantModalName").val().trim();
let ini = $("#combatantModalIni").val().trim();
let dice = $("#combatantModalDice").val().trim();
let rea = $("#combatantModalRea").val().trim();
// roll for initiative if ini is empty
ini = (ini != "") ? ini : rollForInitiative(dice, rea);
// get correct row
let index = parseInt($("#combatantModal").attr("data-row"));
$tr = $("tr.combatantRow").eq(index);
// set new values
$tr.find(".combatantName").text(name);
$tr.find(".combatantDice").text(dice);
$tr.find(".combatantRea").text(rea);
$tr.attr("data-true-ini", ini);
$tr.find(".combatantIni").text(getEffectiveIni($tr));
//TODO: add badges
// sort table
sortTable();
// clean up
$("#combatantModal").removeAttr("data-row");
}
// remove combatant
function removeCombatant (e) {
e.preventDefault();
// hide modal
$("#confirmModal").modal("hide");
// remove correct row
let index = parseInt($("#confirmModal").attr("data-row"));
$(".combatantRow").eq(index).remove();
// clean up
$("#confirmModal").removeAttr("data-row");
}
// start a new combat round
function startNewRound (e) {
e.preventDefault();
// hide modal
$("#confirmModal").modal("hide");
// are there rows at all?
if ( $(".combatantRow").length == 0 ) {
return;
}
// reset ini values
$(".combatantRow").each( function() {
let dice = $(this).find(".combatantDice").text();
if ( dice == "" ) {
$(this).attr("data-true-ini", "1");
} else {
$(this).attr("data-true-ini", rollForInitiative(dice, $(this).find(".combatantRea").text()));
}
$(this).find(".combatantIni").contents()[0].data = getEffectiveIni($(this));
});
// resort table
sortTable();
}
// add test combatant for testing purposes (duh)
function addTestCombatant() {
$("#addCombatantButton").click();
$("#combatantModalName").val("Goon1");
$("#combatantModalDice").val(2);
$("#combatantModalRea").val(6);
$("#combatantModalIni").val(12);
setTimeout(function(){
$("#combatantModalAddOkButton").click();
},500);
}
/*
* Initialize document
*/
$(document).ready(function(){
// add event handlers to navbar buttons
$("#addCombatantButton").on("click", handleAddButtonClick);
$("#newRoundButton").on("click", handleNewRoundButton);
// add event handlers to modal buttons
$("#combatantModalAddOkButton").on("click", addCombatant);
$("#combatantModalEditOkButton").on("click", editCombatant);
$("#confirmModalNewRoundOkButton").on("click", startNewRound);
$("#confirmModalRemoveCombatantOkButton").on("click", removeCombatant);
// always focus name input field when combatant modal appears
$('#combatantModal').on('shown.bs.modal', function() {
$('#combatantModalName').focus();
});
// always empty input fields when combatant modal disappears
$("#combatantModal").on('hidden.bs.modal', function (e) {
$("#combatantModal input[id*='combatantModal']").val("");
});
// Hide damage monitors after click somewhere else
$("html").on("click", function (e) {
if ( $(e.target).parents(".damage-monitor").length == 0 ) {
$(".damage-monitor:visible").css("display", "none");
}
});
addTestCombatant();
});