How to make a history of my var (Math.random) - javascript

I have a problem with my code, i wanna see my passed 4 generated number (Math.random), on a history box, but these numbers show out the same. Is there a way to delay a var?
I have tried putting var in order, but this makes no delay.
my html:
<div class="text-position-history">
<div class="text-style-history">
<p id="historyT"></p>
</div>
</div>
</body>
</html>
My javascript:
var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var history1 = result;
var history2 = history1;
var history3 = history2;
document.getElementById('historyT').innerHTML = "Guessed number: " + " " + result + " " + history1 + " " + history2 + " " + history3;
}
Is there a way to do this?

Why don't you just create an array and then append the new values of result to the array after you call Math.random()?
var resultHistory = new Array();
var result = Math.random();
resultHistory.push(result);
Then print out the array later on.

Why not just use array of numbers?
var _history = [];
function toHTMLElement(historyNode)
{
var node = document.createElement("div");
node.innerHTML = historyNode.text;
node.style.background = historyNode.win?'green':'red';
return node;
}
function renderHistory()
{
var result = document.getElementById("result");
result.innerHTML = "";
_history.forEach(function(e){
result.appendChild(toHTMLElement(e));
});
}
document.getElementById("form").addEventListener("submit", function(e){
e.preventDefault();
_history.push((Math.random()>0.5)?{win: true, text: 'You win'}:{win: false, text: 'You lose'});
if (_history.length > 3) _history.shift();
renderHistory();
});
<form id="form">
<input type="submit">
</form>
<div id="result"></div>

var green = 0;
var red = 0;
function odds(){
var result = Math.random();
if (result < 0.5)
{
document.body.style.backgroundColor = "green";
green++;
document.getElementById('greenT').innerHTML = "Times you survived: " + " " + green;
}
else{
document.body.style.backgroundColor = "red";
red++;
document.getElementById('redT').innerHTML = "Times you died: " + " " + red;
}
document.getElementById('resultT').innerHTML = "Guessed number: " + " " + result;
var myList = [result, result, result];
var history1 = myList.shift();
var history2 = myList.shift();
var history3 = myList.shift();
document.getElementById('historyT').innerHTML = "Guessed numbesr: " + " " + history1 + " " + history2 + " " + history3;
}
This still gives the same result?

I think actually changing the order of your history vars should fix it.
Change them to
var history3 = history2;
var history2 = history1;
var history1 = result;
Right now you are overwritung everything to results because:
var history1 = result
var history2 = history1 (history1 is already referring to result by now)

Related

how to create a element to load the json data in a loop using only javascript

i want to display the theaters like a child node element of the demo node and after i want to trigger the onclick event for other function using only JavaScript
how to use foreach for creating html dom for each array in json data
i want it display like this
<div id="demo">
<div>theater in vizag</div>
<div>sangam : 4K,DolbyAtmos</div>
<div>sarat : 4K,DolbyAtmos</div>
<div>melody : 4K,DolbyAtmos</div>
</div>
let VizagData = '{"theater":[' +
'{"TheaterName":"sangam","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"sarat","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"melody","Quality":"4K","sound":"DolbyAtmos"}]}';
let VZMData = '{"theater":[' +
'{"TheaterName":"Srikanya","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"kameswari","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"IMAX","Quality":"4K","sound":"DolbyAtmos"}]}';
function search() {
document.getElementById('th').innerHTML = myfunction();
function myfunction() {
var value = document.getElementById('ct').value;
var th1 = document.createElement('div');
document.getElementById('th').appendChild(th1);
th1.innerHTML = "theaters in " + value;
return th1.innerHTML;
}
}
function data() {
var index = document.getElementById('ct');
var demo = document.getElementById("demo");
if(index.value === "vizag"){
const obj = JSON.parse(VizagData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
else {
const obj = JSON.parse(VZMData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
}
var go = document.getElementById('go');
addEventListener('click', search);
addEventListener('click', data);
<select id="ct">
<option value="vizianagaram">vizianagaram</option>
<option value="vizag">vizag</option>
</select>
<button id="go">GO</button>
<div class="th" id="th"></div>
<div id="demo"></div>
Iterate over the data and build the innerHTML. Something like:
let VizagData = '{"theater":[' +
'{"TheaterName":"sangam","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"sarat","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"melody","Quality":"4K","sound":"DolbyAtmos"}]}';
let VZMData = '{"theater":[' +
'{"TheaterName":"Srikanya","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"kameswari","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"IMAX","Quality":"4K","sound":"DolbyAtmos"}]}';
function search() {
document.getElementById('th').innerHTML = myfunction();
function myfunction() {
var value = document.getElementById('ct').value;
var th1 = document.createElement('div');
document.getElementById('th').appendChild(th1);
th1.innerHTML = "theaters in " + value;
return th1.innerHTML;
}
}
function data() {
var index = document.getElementById('ct');
var demo = document.getElementById("demo");
var theatres = JSON.parse(VZMData);
if(index.value === "vizag"){
theatres = JSON.parse(VizagData);
}
var innerHTML = "";
for (var obj of theatres.theater) {
innerHTML += "<div>" + obj.TheaterName + " : " + obj.Quality + "," + obj.sound + "</div>";
}
demo.innerHTML = innerHTML;
}
var go = document.getElementById('go');
addEventListener('click', search);
addEventListener('click', data);
<select id="ct">
<option value="vizianagaram">vizianagaram</option>
<option value="vizag">vizag</option>
</select>
<button id="go">GO</button>
<div class="th" id="th"></div>
<div id="demo"></div>

Set the input to be able to read integer value

The page I created is to take Latitude & Longitude value input.
<div class="container ">
<form class="entry">
<div class="aligncenter">
<h5 style="color:MediumTurquoise; font-weight:100; font-family:'Oswald', sans-serif; letter-spacing: 0.1em;">Please enter the coordinate</h5>
<div>
<input type="number" min="0.0000000" max="999.9999999" id="lat" placeholder="Latitude">
<input type="number" min="0.0000000" max="999.9999999" id="long" placeholder="Longitude">
<button class="btn-rounded btn-normal btn-medium btn-primary" id="search" value="get Info">Submit</button>
</div>
</div>
</form>
</div>
Based on the input, i run a script using Jquery to display information from a REST API.
<script>
var data;
$(document).ready(function () {
$("#search").click(function () {
let lat = $("#lat").val();
let long =$("#long").val();
if (lat == "" || long == "") {
alert("please enter lat and long to get info");
return;
}
else {
document.getElementById('message').style.visibility = 'hidden';
document.getElementById('note').style.visibility = 'visible';
$('#note').show();
$('.show-onclick').show();
$.ajax({
type: "GET",
url: `https://rest.soilgrids.org/query?lon=${long}&lat=${lat}&attributes=ORCDRC,PHIHOX,PHIKCL,BLDFIE,CLYPPT,SLTPPT,SNDPPT,WWP`,
dataType: "json",
success: function (response) {
console.log(response);
var phihoxsl1 = response.properties.PHIHOX.M.sl1;
var phihoxsl2 = response.properties.PHIHOX.M.sl2;
var phihoxsl3 = response.properties.PHIHOX.M.sl3;
var phihoxsl4 = response.properties.PHIHOX.M.sl4;
var phihoxsl5 = response.properties.PHIHOX.M.sl5;
var phihoxsl6 = response.properties.PHIHOX.M.sl6;
var phihoxsl7 = response.properties.PHIHOX.M.sl7;
document.getElementById('phihoxsl1').innerHTML = "SL1 = " + phihoxsl1;
document.getElementById('phihoxsl2').innerHTML = "SL2 = " + phihoxsl2;
document.getElementById('phihoxsl3').innerHTML = "SL3 = " + phihoxsl3;
document.getElementById('phihoxsl4').innerHTML = "SL4 = " + phihoxsl4;
document.getElementById('phihoxsl5').innerHTML = "SL5 = " + phihoxsl5;
document.getElementById('phihoxsl6').innerHTML = "SL6 = " + phihoxsl6;
document.getElementById('phihoxsl7').innerHTML = "SL7 = " + phihoxsl7;
var phikclsl1 = response.properties.PHIKCL.M.sl1;
var phikclsl2 = response.properties.PHIKCL.M.sl2;
var phikclsl3 = response.properties.PHIKCL.M.sl3;
var phikclsl4 = response.properties.PHIKCL.M.sl4;
var phikclsl5 = response.properties.PHIKCL.M.sl5;
var phikclsl6 = response.properties.PHIKCL.M.sl6;
var phikclsl7 = response.properties.PHIKCL.M.sl7;
document.getElementById('phikclsl1').innerHTML = "SL1 = " + phikclsl1;
document.getElementById('phikclsl2').innerHTML = "SL2 = " + phikclsl2;
document.getElementById('phikclsl3').innerHTML = "SL3 = " + phikclsl3;
document.getElementById('phikclsl4').innerHTML = "SL4 = " + phikclsl4;
document.getElementById('phikclsl5').innerHTML = "SL5 = " + phikclsl5;
document.getElementById('phikclsl6').innerHTML = "SL6 = " + phikclsl6;
document.getElementById('phikclsl7').innerHTML = "SL7 = " + phikclsl7;
var orcdrcsl1 = response.properties.ORCDRC.M.sl1;
var orcdrcsl2 = response.properties.ORCDRC.M.sl2;
var orcdrcsl3 = response.properties.ORCDRC.M.sl3;
var orcdrcsl4 = response.properties.ORCDRC.M.sl4;
var orcdrcsl5 = response.properties.ORCDRC.M.sl5;
var orcdrcsl6 = response.properties.ORCDRC.M.sl6;
var orcdrcsl7 = response.properties.ORCDRC.M.sl7;
document.getElementById('orcdrcsl1').innerHTML = "SL1 = " + orcdrcsl1;
document.getElementById('orcdrcsl2').innerHTML = "SL2 = " + orcdrcsl2;
document.getElementById('orcdrcsl3').innerHTML = "SL3 = " + orcdrcsl3;
document.getElementById('orcdrcsl4').innerHTML = "SL4 = " + orcdrcsl4;
document.getElementById('orcdrcsl5').innerHTML = "SL5 = " + orcdrcsl5;
document.getElementById('orcdrcsl6').innerHTML = "SL6 = " + orcdrcsl6;
document.getElementById('orcdrcsl7').innerHTML = "SL7 = " + orcdrcsl7;
var wwpsl1 = response.properties.WWP.M.sl1;
var wwpsl2 = response.properties.WWP.M.sl2;
var wwpsl3 = response.properties.WWP.M.sl3;
var wwpsl4 = response.properties.WWP.M.sl4;
var wwpsl5 = response.properties.WWP.M.sl5;
var wwpsl6 = response.properties.WWP.M.sl6;
var wwpsl7 = response.properties.WWP.M.sl7;
document.getElementById('wwpsl1').innerHTML = "SL1 = " + wwpsl1;
document.getElementById('wwpsl2').innerHTML = "SL2 = " + wwpsl2;
document.getElementById('wwpsl3').innerHTML = "SL3 = " + wwpsl3;
document.getElementById('wwpsl4').innerHTML = "SL4 = " + wwpsl4;
document.getElementById('wwpsl5').innerHTML = "SL5 = " + wwpsl5;
document.getElementById('wwpsl6').innerHTML = "SL6 = " + wwpsl6;
document.getElementById('wwpsl7').innerHTML = "SL7 = " + wwpsl7;
var bldfiesl1 = response.properties.BLDFIE.M.sl1;
var bldfiesl2 = response.properties.BLDFIE.M.sl2;
var bldfiesl3 = response.properties.BLDFIE.M.sl3;
var bldfiesl4 = response.properties.BLDFIE.M.sl4;
var bldfiesl5 = response.properties.BLDFIE.M.sl5;
var bldfiesl6 = response.properties.BLDFIE.M.sl6;
var bldfiesl7 = response.properties.BLDFIE.M.sl7;
document.getElementById('bldfiesl1').innerHTML = "SL1 = " + bldfiesl1;
document.getElementById('bldfiesl2').innerHTML = "SL2 = " + bldfiesl2;
document.getElementById('bldfiesl3').innerHTML = "SL3 = " + bldfiesl3;
document.getElementById('bldfiesl4').innerHTML = "SL4 = " + bldfiesl4;
document.getElementById('bldfiesl5').innerHTML = "SL5 = " + bldfiesl5;
document.getElementById('bldfiesl6').innerHTML = "SL6 = " + bldfiesl6;
document.getElementById('bldfiesl7').innerHTML = "SL7 = " + bldfiesl7;
var clypptsl1 = response.properties.CLYPPT.M.sl1;
var clypptsl2 = response.properties.CLYPPT.M.sl2;
var clypptsl3 = response.properties.CLYPPT.M.sl3;
var clypptsl4 = response.properties.CLYPPT.M.sl4;
var clypptsl5 = response.properties.CLYPPT.M.sl5;
var clypptsl6 = response.properties.CLYPPT.M.sl6;
var clypptsl7 = response.properties.CLYPPT.M.sl7;
document.getElementById('clypptsl1').innerHTML = "SL1 = " + clypptsl1;
document.getElementById('clypptsl2').innerHTML = "SL2 = " + clypptsl2;
document.getElementById('clypptsl3').innerHTML = "SL3 = " + clypptsl3;
document.getElementById('clypptsl4').innerHTML = "SL4 = " + clypptsl4;
document.getElementById('clypptsl5').innerHTML = "SL5 = " + clypptsl5;
document.getElementById('clypptsl6').innerHTML = "SL6 = " + clypptsl6;
document.getElementById('clypptsl7').innerHTML = "SL7 = " + clypptsl7;
var sltpptsl1 = response.properties.SLTPPT.M.sl1;
var sltpptsl2 = response.properties.SLTPPT.M.sl2;
var sltpptsl3 = response.properties.SLTPPT.M.sl3;
var sltpptsl4 = response.properties.SLTPPT.M.sl4;
var sltpptsl5 = response.properties.SLTPPT.M.sl5;
var sltpptsl6 = response.properties.SLTPPT.M.sl6;
var sltpptsl7 = response.properties.SLTPPT.M.sl7;
document.getElementById('sltpptsl1').innerHTML = "SL1 = " + sltpptsl1;
document.getElementById('sltpptsl2').innerHTML = "SL2 = " + sltpptsl2;
document.getElementById('sltpptsl3').innerHTML = "SL3 = " + sltpptsl3;
document.getElementById('sltpptsl4').innerHTML = "SL4 = " + sltpptsl4;
document.getElementById('sltpptsl5').innerHTML = "SL5 = " + sltpptsl5;
document.getElementById('sltpptsl6').innerHTML = "SL6 = " + sltpptsl6;
document.getElementById('sltpptsl7').innerHTML = "SL7 = " + sltpptsl7;
var sndpptsl1 = response.properties.SNDPPT.M.sl1;
var sndpptsl2 = response.properties.SNDPPT.M.sl2;
var sndpptsl3 = response.properties.SNDPPT.M.sl3;
var sndpptsl4 = response.properties.SNDPPT.M.sl4;
var sndpptsl5 = response.properties.SNDPPT.M.sl5;
var sndpptsl6 = response.properties.SNDPPT.M.sl6;
var sndpptsl7 = response.properties.SNDPPT.M.sl7;
document.getElementById('sndpptsl1').innerHTML = "SL1 = " + sndpptsl1;
document.getElementById('sndpptsl2').innerHTML = "SL2 = " + sndpptsl2;
document.getElementById('sndpptsl3').innerHTML = "SL3 = " + sndpptsl3;
document.getElementById('sndpptsl4').innerHTML = "SL4 = " + sndpptsl4;
document.getElementById('sndpptsl5').innerHTML = "SL5 = " + sndpptsl5;
document.getElementById('sndpptsl6').innerHTML = "SL6 = " + sndpptsl6;
document.getElementById('sndpptsl7').innerHTML = "SL7 = " + sndpptsl7;
},
error: function (error) {
console.log(error);
alert("No data found");
}
})
}
})
})
</script>
However, I am only able to display the information on the first search only. The page won't refresh and display new data after I enter new input. I thought it was because of the input type, but seems can't to be solved. The information does appeared in console though.
Try adding type="button" to your submit button.
A button element is typed button by default if it is not inside a form.
Inside a form, a button is typed submit which has the same behavior has <input type="submit" /> which validates the form and refresh the page.
So you can :
use your button outside any form without specifying any type attribute
use it inside a form specifying type="button"
$("#btn").click((evt) => {
console.log("lat="+$("#lat").val()+" long="+$("#long").val());
});
<input id="lat" type="text" />
<input id="long" type="text" />
<button id="btn">Submit</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Removing random element from an array /Javascript

I googled my question but found no answer, thank you in advance for help. The thing is, I have some code that works ok, but I would like to improve it:
function go(times) {
function pick(n) {
return n[Math.floor(Math.random() * n.length)];
}
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
When the random word is picked, it should be removed from an array so there won't be any repeation. I can handle it with splice function if I know exact index of element, but when it's random it doesn't work how I want it to.
You can easily add a function to all arrays to return a random value and/or remove one randomly.
// After this, you can call.getRandomValue() on any array!
Array.prototype.getRandomValue = function(removeItem) {
if (this.length < 1) throw "Cannot get random value from zero-length array";
var randomIndex = Math.floor(Math.random() * this.length);
var randomValue = this[randomIndex];
if (removeItem)
this.splice(randomIndex, 1);
return randomValue;
};
function constructDescription(sentenceCount) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var description = "";
for(var i = 0; i < sentenceCount; i++) {
if (body.length > 0 && adj.length > 0 && word.length > 0) {
description += (description.length > 0) ? " And your " : "Your ";
description += body.getRandomValue(true) + " looks " + adj.getRandomValue(true) + " and " + word.getRandomValue(true) + "!"
}
}
return description;
}
Try it out with a Fiddle here.
Use a different function instead of calling go() recursively in the loop. By calling go() for each phrase you initialize the original arrays each time. Then do the splicing in pick()
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
var str = ''
function pick(n) {
var idx = Math.floor(Math.random() * n.length);
var str = n[idx];
n.splice(idx, 1)
return str;
}
function getPhrase(i) {
var phrase = pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
return i == 0 ? "Your " + phrase : " And your " + phrase;
}
for (var i = 0; i < times; i++) {
str += getPhrase(i);
}
return str;
}
document.body.innerHTML = go(4);
You just need to combine your splice and your randomizer. example:
function go(times) {
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function pick(n) {
return n.splice(Math.floor(Math.random() * n.length), 1);
}
var str = "";
for (var i = 0; i < times; i++) {
str += (i > 0 ? " And your ":"Your ") + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
}
return str;
}
#lucounu solution is absolutely spot on.
In case if you just wanted to improve upon your initial solution , you could have done the following :
var body = ["face", "nose", "hair", "smile"];
var adj = ["amazing", "nice", "beautiful", "perfect"];
var word = ["great", "innocent", "glowing", "adorable"];
function go(times) {
function pick(n) {
var index = Math.floor(Math.random() * n.length)
var randomString = n[index];
n.splice(index,1);
return randomString;
}
var str = "Your " + pick(body) + " looks " + pick(adj) + " and " + pick(word) + "!";
if (times > 0) {
for (i = 0; i < times; i++) {
str = str + " And " + go().toLowerCase();
}
}
return str;
}
console.log(go(2));
Give it a try
var data = ["brain", "mitochondria", "microsope", "beaker", "beaker-2", "scientist", "cell", "atom"];
while (data.length) {
document.write(data.splice(data.length * Math.random() | 0, 1)[0] + '<br>');
}

Calling the same function twice with different parameters

Supose I have a function that calls the same function twice, with differents parameter each time, some like this:
function one(){
two(a,b);
two(c,d);
}
When I call function one, only the first function two is executed, but not the second one. Is there a way to do this in Javascript only? (not Jquery)
Here's the code in cuestion (is a little text-based RPG)
window.onload = init;
function init(){
document.onmousedown = function disableselect(e) {return false;};
/*ELEMENTS*/
var monsterPicture = document.createElement('div');
monsterPicture.setAttribute('class', 'monsterPicture');
monsterPicture.style.position = 'absolute';
monsterPicture.style.top = '0';
monsterPicture.style.right = '0';
monsterPicture.style.bottom = '0';
monsterPicture.style.left = '0';
monsterPicture.style.height = '350px';
monsterPicture.style.width = '350px';
monsterPicture.style.margin = 'auto';
monsterPicture.style.backgroundColor = 'grey';
document.body.appendChild(monsterPicture);
var textInfo = document.createElement('textarea');
textInfo.setAttribute('class', 'textInfo');
textInfo.style.position = 'absolute';
textInfo.style.top = '0';
textInfo.style.bottom = '0';
textInfo.style.right = '0';
textInfo.style.height = '350px';
textInfo.style.width = '250px';
textInfo.style.margin = 'auto 50px auto auto';
textInfo.style.backgroundColor = 'white';
textInfo.style.overflowY = 'hidden';
textInfo.style.resize = 'none';
textInfo.readOnly = 'true';
textInfo.disabled = 'true';
textInfo.style.cursor = "default";
document.body.appendChild(textInfo);
var statsArea = document.createElement('div');
statsArea.setAttribute('class', 'statsArea');
statsArea.style.position = 'absolute';
statsArea.style.top = '0';
statsArea.style.top = '0';
statsArea.style.bottom = '0';
statsArea.style.right = '0';
statsArea.style.height = '350px';
statsArea.style.width = '200px';
statsArea.style.margin = 'auto 700px auto auto';
document.body.appendChild(statsArea);
var heroInfo = document.createElement('textarea');
heroInfo.setAttribute('class', 'heroInfo');
heroInfo.style.height = '160px';
heroInfo.style.width = '200px';
heroInfo.style.marginTop = '10px';
heroInfo.style.backgroundColor = 'white';
heroInfo.style.overflowY = 'hidden';
heroInfo.style.resize = 'none';
heroInfo.readOnly = 'true';
heroInfo.disabled = 'true';
heroInfo.style.cursor = "default";
document.body.appendChild(heroInfo);
var monsterInfo = document.createElement('textarea');
monsterInfo.setAttribute('class', 'monsterInfo');
monsterInfo.style.height = '160px';
monsterInfo.style.width = '200px';
monsterInfo.style.backgroundColor = 'white';
monsterInfo.style.overflowY = 'hidden';
monsterInfo.style.resize = 'none';
monsterInfo.readOnly = 'true';
monsterInfo.disabled = 'true';
monsterInfo.style.cursor = "default";
document.body.appendChild(monsterInfo);
statsArea.appendChild(monsterInfo);
statsArea.appendChild(heroInfo);
/*CONSTRUCTOR FUNCTIONS*/
function character (name, hitpoints, armorclass, attackbonus, weapondamage) {
this.name = name;
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
this.stats = function(){
return this.name + "\n" +
"Hit Points: " + this.hitPoints + "\n" +
"Armor Class: " + this.armorClass + "\n" +
"Attack Bonus: " + this.attackBonus + "\n" +
"Weapon Damage: " + this.weaponDamage;
};
this.alive = true;
this.reset = function (){
this.hitPoints = hitpoints;
this.armorClass = armorclass;
this.attackBonus = attackbonus;
this.weaponDamage = weapondamage;
};
}
var Arquer = new character("Arquer", 15, 6, 5, 8);
function selectMonster () {
var werewolf = new character("Werewolf", 15, 4, 4, 3);
var goblin = new character("Goblin", 15, 4, 4, 3);
switch(Math.floor(Math.random()*2)+1){
case 1: return werewolf;
case 2: return goblin;
}
}
var buttonAttack= document.createElement('input');
buttonAttack.setAttribute('type','button');
buttonAttack.setAttribute('value','Attack');
document.body.appendChild(buttonAttack);
var current_monster = selectMonster();
heroInfo.value = Arquer.stats() + "\n" + "Alive: " + Arquer.alive;
monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;
buttonAttack.onclick = function(){
if (current_monster.hitPoints <= 0){current_monster = selectMonster();monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;}
else{battle(Arquer, current_monster);}
};
function battle (hero, monster){
if(hero.alive===true && monster.alive===true){
var heroIniciative = Math.floor(Math.random()*20)+1;
var monsterIniciative = Math.floor(Math.random()*20)+1;
var attacker;
var defender;
var attackerInfo;
var defenderInfo;
/*INICIATIVE ROLL*/
if (heroIniciative >= monsterIniciative){
attacker = hero;
defender = monster;
attackerInfo = heroInfo;
defenderInfo = monsterInfo;
textInfo.value += attacker.name + " attacks first!: " + heroIniciative + " vs " + monsterIniciative + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
else {
attacker = monster;
defender = hero;
attackerInfo = monsterInfo;
defenderInfo = heroInfo;
textInfo.value += attacker.name + " attacks first!: " + monsterIniciative + " vs " + heroIniciative + "\n",
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
check_defeat(attacker, defender, attackerInfo, defenderInfo);
}
else {reset (hero, monster);
}
}
function attack (attacker, defender, attackerInfo, defenderInfo){
var d20 = Math.floor(Math.random()*20)+1;
var d_wp = Math.floor(Math.random()*attacker.weaponDamage)+1;
/*ROUND ONE*/
if (d20+attacker.attackBonus>defender.armorClass){
textInfo.value += attacker.name +" d20+" + attacker.attackBonus+": " + (d20+attacker.attackBonus)+ " vs AC " + defender.armorClass + "\n" + attacker.name +" hits! d" + attacker.weaponDamage + ": " + d_wp + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
defender.hitPoints = defender.hitPoints - d_wp;
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
}
else {
textInfo.value += attacker.name + " misses! d20+" + attacker.attackBonus+": " + (d20+attacker.attackBonus)+ " vs AC " + defender.armorClass;
textInfo.scrollTop = textInfo.scrollHeight;
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
}}
function check_defeat (attacker, defender, attackerInfo, defenderInfo) {
if (attacker.hitPoints <= 0){
attacker.hitPoints = 0;
attacker.alive = false,
attackerInfo.value = attacker.stats();
attackerInfo.append("\n" + "Alive: " + attacker.alive);
textInfo.value += "\n" +defender.name + " killed " + attacker.name + "!";
textInfo.scrollTop = textInfo.scrollHeight;
}
if (defender.hitPoints <= 0){
defender.hitPoints = 0;
defender.alive = false,
defenderInfo.value = defender.stats();
defenderInfo.append("\n" + "Alive: " + defender.alive);
textInfo.value += "\n" + attacker.name + " killed " + defender.name + "!";
}
}
function reset (hero, monster) {
if (hero.alive===false){
hero.reset();
hero.alive = true;
heroInfo.value = hero.stats();
heroInfo.append("\n" + "Alive: " + hero.alive);
}
if (monster.alive===false){
monster.reset();
monster.alive = true;
monsterInfo.value = monster.stats();
monsterInfo.append("\n" + "Alive: " + monster.alive);
}
}
}
(For some reason it doesn't work in jsfiddle). The problem is in the function battle.
function battle (hero, monster){
if(hero.alive===true && monster.alive===true){
var heroIniciative = Math.floor(Math.random()*20)+1;
var monsterIniciative = Math.floor(Math.random()*20)+1;
var attacker;
var defender;
var attackerInfo;
var defenderInfo;
/*INICIATIVE ROLL*/
if (heroIniciative >= monsterIniciative){
attacker = hero;
defender = monster;
attackerInfo = heroInfo;
defenderInfo = monsterInfo;
textInfo.value += attacker.name + " attacks first!: " + heroIniciative + " vs " + monsterIniciative + "\n";
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
else {
attacker = monster;
defender = hero;
attackerInfo = monsterInfo;
defenderInfo = heroInfo;
textInfo.value += attacker.name + " attacks first!: " + monsterIniciative + " vs " + heroIniciative + "\n",
textInfo.scrollTop = textInfo.scrollHeight;
attack(attacker, defender, attackerInfo, defenderInfo);
attack(defender, attacker, defenderInfo, attackerInfo);
}
check_defeat(attacker, defender, attackerInfo, defenderInfo);
}
else {reset (hero, monster);
}
}
When I call it, it just execute the first function attack, but not the second one.
buttonAttack.onclick = function(){
if (current_monster.hitPoints <= 0){current_monster = selectMonster();monsterInfo.value = current_monster.stats() + "\n" + "Alive: " + current_monster.alive;}
else{battle(Arquer, current_monster);}
};
When executing a function you don't have to write function up front.
try
function one(){
two(a,b);
two(c,d);
}
It should work -
function two(a,b){
console.log(a+b);
}
function one(){
two(1,2);
two(3,4);
}
one();
output:
2
7
the first function two is executed
This is highly unlikely; why do you believe it was executed? Before you call anything, or anything is executed, there is a syntax error, probably something like "Unexpected token ;", because the syntax
function two(a, b);
is invalid; function definitions must have a body in curly braces. You would see the error if you looked at the console; did you? It must be:
function two(a, b) { }
But apparently you just want to call the function, in which case you should use the basic function call syntax of two(a, b). function is for defining functions, not calling them.
Best and easiest solution is to use Promist.all() with nodejs
Example
let _ = require('underscore')
let response = ['some data','other data']
return Promise.all(_.map(response, function (data) { return
functionName(data) }))
.then((response)=>{
console.log(response)
})
Result
['response1','response2']
you can simply call a function twice or any time you want just remember its arguments and its data types since you are not forced to put data type on function call but if there is wrong data type it can create serious mess.
//currently in a mess

getting statistics from a textarea

Getting text statistics from a textarea.
which would be better?
this one?
function getStats() {
var text = textarea.value,
stats = {};
stats.chars = text.length;
stats.words = text.split(/\S+/g).length - 1;
stats.lines = text.replace(/[^\n]/g, "").length + 1;
return stats.lines + " lines, " + stats.words + " words, " + stats.chars + " chars";
}
or this one?
function getStats() {
var text = textarea.value,
chars = text.length,
words = text.split(/\S+/g).length - 1,
lines = text.replace(/[^\n]/g, "").length + 1;
return lines + " lines, " + words + " words, " + chars + " chars";
}
The second one.
Not for any performance reasons, but you are just declaring a Javascript object when there is no need for one.
Creating an object to store your variables would only make sense if you were using it like:
function getStats() {
var text = textarea.value,
stats = {};
stats.chars = text.length;
stats.words = text.split(/\S+/g).length - 1;
stats.lines = text.replace(/[^\n]/g, "").length + 1;
return stats;
}

Categories