I'm trying to code a game and part of it has a combat system. I want the player to click a button as many times as they want to find an opponent, then to click the attack button when they find one they like and a timed event happens to slowly reveal the result.
The problems I'm coming against are:
- If the VAR are outside the functions, then you can only infiltrate once, but if it's inside the first function then the other ones can't use those values for the battle.
- The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Thank you very much for looking and I appreciate the help!
Javascript:
var titles = ["Peasant", "Knight"];
var first = ["Ada", "Adro", "Ama"];
var last = ["nija", "har", "nake"];
var random_name1 = titles[Math.floor(Math.random() * titles.length)] + ' ' + first[Math.floor(Math.random() * first.length)] + last[Math.floor(Math.random() * last.length)];
var random_acres1 = (max_acres * (Math.floor(Math.random() * (140 - 75)) + 75) / 100).toFixed(0);
var random_troops1 = (random_acres1 * (Math.floor(Math.random() * (1500 - 600)) + 600) / 100).toFixed(0);
var random_off1 = (random_troops1 * (Math.floor(Math.random() * (1200 - 400)) + 400) / 100).toFixed(0);
var combat_victory_acres1 = (random_acres1 * (((Math.random() * (35 - 11)) + 11) / 100)).toFixed(0);
var combat_defeat_acres1 = (random_acres1 * (Math.floor(Math.random() * (20 - 11)) + 11) / 100).toFixed(0);
var text_victory = 'You have been awarded with ';
var text_defeat = 'You have lost control of ';
var text_acres = ' acres.';
function infiltrate(){
var x = document.getElementById("Combat_table");
if (x.style.display === "none") {
x.style.display = "block";
}
document.getElementById('combat_army_strength').innerHTML = army_strength;
document.getElementById('combat_max_acres').innerHTML = max_acres;
document.getElementById('random_name1').innerHTML = random_name1;
document.getElementById('random_acres1').innerHTML = random_acres1;
document.getElementById('random_troops1').innerHTML = random_troops1;
document.getElementById('random_off1').innerHTML = random_off1;
};
function attack_random1(){
document.getElementById("attack_button1").style.display="none";
document.getElementById("infiltration").style.display="none";
var y = document.getElementById("Combat_Results");
if (y.style.display === "none") {
y.style.display = "block";
}
setTimeout(Combat_Text4, 5000)
var final_outcome1 = army_strength - random_off1;
if (final_outcome1 >= 0) {
setTimeout(Combat_Text_Victory1, 6000);
} else {
setTimeout(Combat_Text_Defeat1, 6000);
}
};
function Combat_Text4() {
document.getElementById("Combat_Results4").innerHTML = "The battle is over, a scout is dispatched to you with the results.";
}
function Combat_Text_Victory1() {
max_acres = max_acres + combat_victory_acres1;
var text_victory_1 = text_victory + combat_victory_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You achieved <b>Victory!</b>";
document.getElementById("Combat_Results6").innerHTML = text_victory_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
function Combat_Text_Defeat1() {
max_acres = max_acres - combat_defeat_acres1;
var text_defeat_1 = text_defeat + combat_defeat_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You have been <b>Defeated!</b>";
document.getElementById("Combat_Results6").innerHTML = text_defeat_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
HTML:
<div id="Combat" class="tabcontent">
Total Land: <span id="combat_max_acres">10</span><br>
Total Offense: <span id="combat_army_strength">0</span><p>
<button id="infiltration" onclick="infiltrate()">Infiltrate Kingdoms</button>
<div id="Combat_table" style="display: none">
<center><table>
<tr valign="center">
<th>Kingdom Name</th>
<th>Acres</th>
<th>Troop <br>Numbers</th>
<th>Total <br>Offense</th>
<th></th>
</tr>
<tr id="combat_row1">
<td><span id="random_name1"></span></td>
<td><span id="random_acres1"></span></td>
<td><span id="random_troops1"></span></td>
<td><span id="random_off1"></span></td>
<td><button onclick="attack_random1()" id="attack_button1">Attack!</button></td>
</tr>
</table>
</div>
<br>
<div id="Combat_Results" style="display: none">
<center><table><tr>
<td><center><span id="Combat_Results4"></span></td>
</tr><tr>
<td><center><span id="Combat_Results5"></span></td>
</tr><tr>
<td><center><span id="Combat_Results6"></span></td>
</tr>
</table>
</div>
The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Use Math.round instead of Number#toFixed, because for addition numerical values, you need both operands as number, not a string.
Use toFixed only for displaying a number.
For the other parts, I suggest to use an object with arrays for same items, like
{
name: [],
acres: [],
troops: [],
off: [],
victory_acres: [],
combat_defeat_acres: [],
// etc.
}
Related
$(".submitNum").click(function() {
var $tr = $(this).closest('tr');
var $remaining = $tr.find(".remaining");
var $qty = $tr.find(".stockQuantity");
var $numToSubmit = $tr.find(".customInput");
//Get current values
var batchSize = $remaining.attr("data-maxNumber");
var currentRemaining = $remaining.text();
var currentQty = $qty.text();
var currentInputValue = $numToSubmit.val();
var difference = Number(currentRemaining) - Number(currentInputValue);
var divisible = Number(currentInputValue) / Number(batchSize);
var usesFromQuantity = Number(currentQty) * Number(batchSize);
var totalUses = Number(usesFromQuantity) + Number(currentRemaining);
var decimalPart = divisible - Math.round(divisible);
var finalRemaining = Number(decimalPart) * Number(batchSize);
//Subtract values
if (currentInputValue < 0) {
alert('Please insert a valid quantity to withdraw');
} else if (currentInputValue > totalUses) {
alert("Cannot withdraw this amount");
} else if (currentInputValue > Number(batchSize) + Number(currentRemaining) &&
Number(currentInputValue) < Number(totalUses)) {
currentQty = Number(currentQty) - Math.round(divisible);
currentRemaining = Math.round(finalRemaining);
} else if (difference == 0) {
currentRemaining = batchSize;
currentQty = currentQty - 1;
} else if (difference < 0) {
currentRemaining = Number(difference) + Number(batchSize);
currentQty = Number(currentQty) - 1;
} else if (difference > 0) {
currentRemaining = difference;
} else if (currentInputValue == totalUses) {
currentRemaining = 0;
currentQty = 0;
}
//Update text
$remaining.text(currentRemaining);
$qty.text(currentQty);
$tr.find(".collapseX").hide();
$tr.find(".inputBtn").show();
$tr.find('.customInput').val('');
});
ul li {
display: inline;
}
body {
text-align: center;
}
input {
max-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Stock Quantity</th>
<th scope="col">Remaining Uses</th>
<th scope="col">Withdraw Item</th>
</tr>
</thead>
<tbody>
<tr>
<td>#Item1</td>
<td class="stockQuantity">3</td>
<td data-maxNumber="30" class="remaining">15</td>
<td>
<ul>
<li class="list-inline-item">
<input placeholder="Set uses qty" class="customInput" type="number" min="1">
</li>
<li class="list-inline-item"><button href="#" class=" submitNum">Sumit</button></li>
</ul>
</td>
</tr>
</tbody>
</table>
Okay so:
1 unit of stock quantity has 30 x remaining uses
What I am confused in is creating an algorithm that calculates how much is left in the stock quantity and the remaining uses if the value of the input field is an amount that exceeds the current remaining uses + 30 which is the amount per 1 unit of stock quantityso I can know how many units should I withdraw from stock quantity and how many units should be remaining in remaining uses.
The jquery function I have here is a bit big and cluttered, but its functional when I want to withdraw an amount that is less than or equal remaining uses + 30.
of course there can be smarter ways to do this feel free to change the whole thing
to understand what I mean better try withdrawing (45 units) or less it'll work and then try to withdraw (70 units) here you'll notice the bug.
You can use the modulus operator (%) to quickly figure out how many come out of remaining.
Say you have:
var qty = 3;
var remaining = 20;
var batchSize = 30;
var withdrawAttempt = 45;
Then:
var totalLeft = remaining + batchSize * qty;
if (withdrawAttempt > totalLeft) {
// invalid
} else {
// calculate how many to take from remaining
var wr = withdrawAttempt % batchSize;
// update qty and remaining
qty -= (withdrawAttempt - wr) / batchSize;
remaining -= wr;
if (remaining < 0) {
remaining += batchSize;
qty -= 1;
}
}
Lately i want to make a converter formula with javascript. but i got a stack at this function
javascript
function UconverterDP(){
var inputD = document.getElementById('inputD').value;
var inputP = document.getElementById('inputP').value;
jikaP = inputD * 0.4;
bagianatasU1 = 0.8 * inputP * inputD;
bagianbawahU1 = P + (0.4 * inputD);
hasilU1 = bagianatasU1 / bagianbawahU1;
bagaianatasU2 = 0.8 * inputD;
bagaianatasU2a = 1 - bagaianatasU2 ;
bagaianatasU2h = inputP - bagaianatasU2a;
bagianbawahU2 = 0.0114 * inputP;
bagianbawahU2a = Math.pow(bagianbawahU2, 1.7);
bagianbawahU2b = 0.92 * bagianbawahU2a;
bagianbawahU2h = bagianbawahU1 * bagianbawahU2b;
hasilU2 = bagaianatasU2h / bagianbawahU2h;
if (inputP <= jikaP) {
document.getElementById("outputU").innerHTML = Hasil U1;
} else {
document.getElementById("outputU").innerHTML = hasilU2;
}
}
this my input
<tr>
<td>
<label>D : </label>
<input id="inputD" type="number" onchange="UconverterDP()">
</td>
<td>
<label>P : </label>
<input id="inputP" type="number" onchange="UconverterDP()" >
</td>
</tr>
and this output
<label> BUI (U): </label>
<span id="outputU"></span>
And this is the formula:
i really don t know if this is what are you searching, if it isn't tell me what is missing (and explain me a little bit more your idea):
<script>
function UconverterDP(){
var inputD = document.getElementById('inputD').value;
var inputP = document.getElementById('inputP').value;
jikaP = inputD * 0.4;
if (inputP <= jikaP) { // here your program choose what formula will use
var u =(0.8*inputP*inputD)/(inputP+0.4*inputD)// here is the first formula
document.getElementById("outputU").innerHTML = u;// and then here you return the value that you want
}
else {
var u = inputP-((1-0.8*inputD)/(inputP+0.4*inputD))/(0.92*0.0114*(inputP**1.7))// and here is the second formula
document.getElementById("outputU").innerHTML = u;// here is the same you return the value
}
}
// maybe you can do more short this code putting together the two "document.getElementById("outputU").innerHTML = u;" here, but work in this way also
</script>
From the input on the HTML, the user inputs the employee name and a number of hours they worked. From here on the submit button it takes the information and stores it in the variables so that I can calculate how much their pay was. Now with this also comes the overtime pay. I thought this was on the right track but whenever I go back to my HTML it displays "undefined". Any suggestions?
//Global Variables
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
function paySalary() {
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("results").innerHTML = "Employee Name: " + employeeName + " | Employee Gross Pay: " + salary;
}
//Event Listener to Submit
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", paySalary, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", paySalary);
}
Screenshot of output
Look at the scope of your salary variable, it's defined inside the if-else block. Make your salary variable accessible to document.getElementById() by declaring it in your function like this:
<html>
<script>
function paySalary() {
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("name").innerHTML = "Employee Name: " + employeeName;
document.getElementById("pay").innerHTML = "Employee Gross Pay: " + salary;
}
</script>
<body>
<input id="name" value="Kamesh Dashora"></input>
<input id="hours" value=40></input>
<br>
<span id="pay">0</span>
<br>
<button id="submit" onclick="paySalary()">Submit</button>
<body>
</html>
I'm doing a math game. I have this HTML/JavaScript code. It generates a random number but when I input the correct answer, it still displays 'wrong'. I'm not sure what went wrong.
Here is HTML code:
<table width="400" border="1" align="center">
<tr>
<td><div id="number1">1</div></td>
<td><div>+</div></td>
<td><div id="number2">2</div></td>
<td><div>=</div></td>
<td><input type="text"></input></td>
<td><input type="button" value="Check"></input></td>
</tr>
</table>
Here is my JavaScript code:
//random number appear when start game
var number1;
var number2;
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
document.getElementById("number1").innerHTML=number1;
document.getElementById("number2").innerHTML=number2;
//Answer
var answer = number1 + number2;
//add click handler with check answer
var checkAnswer = document.querySelector('input[type=text]');
var value = checkAnswer.value;
var btn = document.querySelector('input[type=button][value=Check]');
btn.onclick = function()
{
if (value == answer)
{
alert('You are correct');
}
else{
alert('You are incorrect, the answer was ' + answer);
}
document.querySelector('input[type=text]').value = "";
document.getElementById('number1').innerHTML = "";
document.getElementById('number2').innerHTML = "";
number1 = Math.floor((Math.random() * 10) + 1);
number2 = Math.floor((Math.random() * 10) + 1);
document.getElementById('number1').innerHTML = number1;
document.getElementById('number2').innerHTML = number2;
answer = number1 + number2
};
Move following lines in .onclick method.
var checkAnswer = document.querySelector('input[type=text]'); //needn't be moved in method
var value = checkAnswer.value;
You can verify the result from JSFiddle.
The problem was the variable value is initialize with empty string when you load the page, as when page is loaded the value is empty.
Compare answer to value in checkAnswer:
if (checkAnswer.value == answer) {
//correct
}else{
//incorrect
}
You don't update the value.
In the button click event update the value. JSFiddle.
btn.onclick = function()
{
value = checkAnswer.value;
...
I have a funny bug in my calculation about interest days. I go through each day and check which day it is (1 to 31). Now I found a problem: In October the count doesn't work properly. That means the 27th is the 26th, or the 29th is the 28th. Is this a well know problem?
Maybe the problem is in my code, but, because it works over another period, it seems to be fine.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function berecheZinstage() {
//eingabe von den Feldern holen
var strVon = txtVonDatum.value;
var strBis = txtBisDatum.value;
//label um das Resultat anzuzeigen
var resultatTage = document.getElementById("lblTage");
var resultatZinsTage = document.getElementById("lblZinstage");
//tag als Milisekunden
var tagMs = 86400000;
var monatCount;
//Eingabeformat umwandeln für die Berechung
strVon = strVon.replace(/-/g, "/");
strBis = strBis.replace(/-/g, "/");
var vonDatum = new Date(strVon);
var bisDatum = new Date(strBis);
var zinsTage = 0;
if (bisDatum > vonDatum) {
var totTage = bisDatum - vonDatum;
var nDays = Math.round(totTage / (1000 * 60 * 60 * 24));
var pruefMS = vonDatum.getTime();
var startMS = vonDatum.getTime();
var endeMS = bisDatum.getTime();
var febCount = 0;
var langCount = 0;
var tage = 0;
for (var i = 0; i < nDays; i++) {
pruefMS = pruefMS + tagMs;
var pruefDatum = new Date(pruefMS);
var pruefMonat = pruefDatum.getMonth();
var pruefJahr = pruefDatum.getFullYear();
var pruefTag = pruefDatum.getDate();
if (pruefTag == 1 && pruefDatum != startMS) {
if (pruefMonat == 2) {
var istSchaltjahr = new Date(pruefJahr, 1, 29).getMonth() == 1;
if (istSchaltjahr) {
tage++;
}
else {
tage = tage + 2;
}
}
}
if (pruefTag != 31) {
tage++;
}
}
resultatZinsTage.innerText = tage.toString();
resultatTage.innerText = pruefTag;//nDays.toString();
}
else {
resultatTage.innerText = "Bis Datum muss grösser sein als von Datum";
}
}
</script>
<title>Zinstage berechen</title>
</head>
<body>
<table style="width:100%;">
<tr>
<td style="width:100px;"><input id="txtVonDatum" type="text" /></td>
<td style="width:100px;"><input id="txtBisDatum" type="text" /></td>
<td style="width:100px;"><button id="btnCalcDays" type="button" onclick="berecheZinstage();">Berechnen</button></td>
<td> </td>
</tr>
<tr>
<td>Tage:</td>
<td><label id="lblTage"></label></td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>Zinstage:</td>
<td><label id="lblZinstage"></label></td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Thanks, Marlowe
I don't understand what this code is trying to achieve, but the problem is DST (Daylight Saving Time).
Adding 86400000 millis for each day should work ok. But in locales that use DST (default in Germany), the result of date "2013/10/01 00:00:00" + 31*86400000 would be "2013/10/31 23:00:00".
Actually if we include the timezone, it would be "2013/10/01 00:00:00 GMT+0200" + 31*86400000 would be "2013/10/31 23:00:00 GMT+0100", so the addition is correct in UTC terms.
Likewise in March, the resulting date would be "2013/04/01 01:00:00", but we don't see the error since we're only counting the days.
When performing operations like this, always use UTC to avoid headaches :)
Here is now the working code. With the hint given by foibs I've built a little hack to calculate the interest days.
<script type="text/javascript">
function calcInterestDays() {
//get the values from the input fields
var strFrom = document.getElementById("txtFromDate").value;
var strTill = document.getElementById("txtTillDate").value;
//format strings
strFrom = strFrom.replace(/-/g, "/");
strTill = strTill.replace(/-/g, "/");
var fromDate = new Date(strFrom);
var tillDate = new Date(strTill);
var msDay = 86400000;
var startMS = fromDate.getTime();
var totDays = Math.round((tillDate - fromDate) / (1000 * 60 * 60 * 24));
var totMs = startMS;
var outputStr = "";
var days = 0;
for (var i = 0; i < totDays; i++) {
totMs = totMs + msDay;
var checkDate = new Date(totMs);
var splitDate = checkDate.toString().split(" ");
if (splitDate[6] == "0200") {
var calcDay = new Date(totMs);
}
else {
var calcDay = new Date(totMs + 3600000);
}
if (calcDay.getDate() == 1 && totMs != startMS) {
if (calcDay.getMonth() == 2) {
var istSchaltjahr = new Date(calcDay.getFullYear(), 1, 29).getMonth() == 1;
if (istSchaltjahr) {
days++;
}
else {
days = days + 2;
}
}
}
if (calcDay.getDate() != 31) {
days++;
}
outputStr = outputStr + "<br>" + calcDay;
}
document.getElementById("lblTotDays").innerHTML = totDays;
document.getElementById("lblInterestDays").innerHTML = days;
document.getElementById("output").innerHTML = outputStr;
}
</script>
Thanks for all the help.