function he() {
var x = Math.floor((Math.random() * 100) + 1);
document.getElementById("res1").innerHTML = "Heroes have dealt " + x + " damage on villains.";
var vhp = villains - x;
document.getElementById("res2").innerHTML = "<br/>Villains have " + vhp + " hp left.";
vok();
}
function vok() {
var y = Math.floor((Math.random() * 100) + 1);
document.getElementById("res3").innerHTML = "<br/>Villains have dealt " + y + " damage on Heroes.";
var hhp = hero - y;
document.getElementById("res4").innerHTML = "<br/>Heroes have " + hhp + " hp left.";
he();
}
Here is the above code I made function he() is called when a button is clicked and vok function is called after execution of he() function but it's not going good currently i want to overwrite the innerHTML every time the function is runned how am I supposed to do so?
Related
I made a CGPA-SGPA calculator and I cannot get the value with refresh.
When I refresh and check the value it get feed
but not getting value without refresh.
var credit_1001 = document.querySelector('#credit_1001')
var grade_1001 = document.querySelector('#grade_1001')
var credit_1002 = document.querySelector('#credit_1002')
var grade_1002 = document.querySelector('#grade_1002')
var credit_1003 = document.querySelector('#credit_1003')
var grade_1003 = document.querySelector('#grade_1003')
var credit_1004 = document.querySelector('#credit_1004')
var grade_1004 = document.querySelector('#grade_1004')
var credit_1008 = document.querySelector('#credit_1008')
var grade_1008 = document.querySelector('#grade_1008')
var credit_1009 = document.querySelector('#credit_1009')
var grade_1009 = document.querySelector('#grade_1009')
//btn and result S1
var btn_check = document.querySelector('#check_s1')
var result_s1 = document.querySelector('#result_s1')
//btn click S1
var total_s1_credit = parseInt(credit_1001.value) + parseInt(credit_1002.value) + parseInt(credit_1003.value) + parseInt(credit_1004.value) + parseInt(credit_1008.value) + parseInt(credit_1009.value)
var got_s1_marks = parseInt(credit_1001.value) * parseInt(grade_1001.value) + parseInt(credit_1002.value) * parseInt(grade_1002.value) + parseInt(credit_1003.value) * parseInt(grade_1003.value) + parseInt(credit_1004.value) * parseInt(grade_1004.value) + parseInt(credit_1008.value) * parseInt(grade_1008.value) + parseInt(credit_1009.value) * parseInt(grade_1009.value)
btn_check.addEventListener('click', () => {
result_s1.innerText = " S1 SGPA " + got_s1_marks / total_s1_credit
console.log("S1 Total Credit = " + total_s1_credit)
console.log("S1 Got Marks = " + got_s1_marks)
console.log("S1 SGPA = " + result_s1.innerText)
})
You need to get the values for your calculation inside of the click handler, right now you get them before the click, and then use (the old values) when the click happens
btn_check.addEventListener('click', () => {
//btn click S1
var total_s1_credit = parseInt(credit_1001.value) + parseInt(credit_1002.value) + parseInt(credit_1003.value) + parseInt(credit_1004.value) + parseInt(credit_1008.value) + parseInt(credit_1009.value)
var got_s1_marks = parseInt(credit_1001.value) * parseInt(grade_1001.value) + parseInt(credit_1002.value) * parseInt(grade_1002.value) + parseInt(credit_1003.value) * parseInt(grade_1003.value) + parseInt(credit_1004.value) * parseInt(grade_1004.value) + parseInt(credit_1008.value) * parseInt(grade_1008.value) + parseInt(credit_1009.value) * parseInt(grade_1009.value)
result_s1.innerText = " S1 SGPA " + got_s1_marks / total_s1_credit
console.log("S1 Total Credit = " + total_s1_credit)
console.log("S1 Got Marks = " + got_s1_marks)
console.log("S1 SGPA = " + result_s1.innerText)
})
I am working on creating a small 5 question addition quiz that asks the user a new random addition question every time they answer the previous one. I would like to be able to have my script ask a new question every time the user clicks on the "check answer" button without having to refresh the page. Then, once the user has completed the 5 questions, I would like to be able to have a popup state they have completed the quiz and can refresh the page to start a new quiz. With my current code, the script asks a random addition question, and then once the user clicks on the "check answer" button, the user must refresh the page to get a new question. I am stuck on figuring out how to modify my current code to fit what I am trying to do. I am thinking that a while loop may be they way to go, but I don't really know how to implement it. The code that I have so far is: `
<h1>Addition Quiz!</h1>
<p>This short 5 question quiz will test your addition skills! Answer the question as the computer asks it and pat yourself on the back for each correct answer!</p>
<h3 id="mathquestion"></h3>
<input type="text" name="answerbox" id="answerbox">
<button onclick="addition()">Check Answer</button>
<script>
var minimum = 1;
var maximum = 9;
var intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
var questionanswer = intiger1 + intiger2;
function addition() {
var useranswer = document.getElementById('answerbox').value;
if (useranswer == questionanswer) {
alert("Correct! Congrats!");
} else {
alert("Sorry, your answer is incorrect. Better luck with the next question!")
}
}
</script>`
So what you want is the part that setups your question into a new function. And run that function when the answer is right. An example:
<script>
var minimum = 1;
var maximum = 9;
var questionanswer = 0;
setupQuestion();
function setupQuestion(){
var intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
questionanswer = intiger1 + intiger2;
}
function addition() {
var useranswer = document.getElementById('answerbox').value;
if (useranswer == questionanswer) {
alert("Correct! Congrats!");
setupQuestion();
} else {
alert("Sorry, your answer is incorrect. Better luck with the next question!")
}
}
</script>`
Just update the variable
<script>
var minimum = 1;
var maximum = 9;
var intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
var intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
var questionanswer = intiger1 + intiger2;
function addition() {
var useranswer = document.getElementById('answerbox').value;
if (useranswer == questionanswer) {
alert("Correct! Congrats!");
} else {
alert("Sorry, your answer is incorrect. Better luck with the next question!")
}
// Updating question
intiger1 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
intiger2 = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
document.getElementById("mathquestion").innerHTML = intiger1 + " " + "+" + " " + intiger2;
}
</script>
https://jsfiddle.net/kelliwilli/6bgrt7bL/128/
var percent = function() {
var totalGames = (scores.draw + scores.p1 + scores.Ali);
var drawPercent = ((scores.draw / totalGames) * 100);
var AliPercent = ((scores.Ali / totalGames) * 100);
var p1Percent = ((scores.p1 / totalGames) * 100;
alert ("There has been " + drawPercent + "% of draws. I won " + AliPercent + "%, and" +p1 +" won" + p1Percent "%!");
}
Seems to just be a simple syntax error, which is not what I thought you were getting at with the question or lack of...
Anyways alert ("There has been " + drawPercent + "% of draws. I won " + AliPercent + "%, and" +p1 +" won" + p1Percent + "%!"); should fix it. You simply forgot to concat the last variable.
Look into template literals, they're super handy for throwing together strings with many variables, along with the fact I find them to be awesome syntax wise.
Template literal form:
alert(`There has been ${drawPercent}% of draws. I won ${AliPercent}%, and ${p1} won ${p1Percent}%!});
https://jsfiddle.net/kelliwilli/6bgrt7bL/224/
//percent funtion
var percent = function() {
var totalGames = (scores.draw + scores.p1 + scores.Ali);
var drawPercent = ((scores.draw / totalGames) * 100);
var AliPercent = ((scores.Ali / totalGames) * 100);
var p1Percent = ((scores.p1 / totalGames) * 100);
alert("There has been " + drawPercent + "% of draws. Ali won " + AliPercent + "%, and " + p1 + " won " + p1Percent + "% of the games! Thanks for playing!!!");
}
There was some code out of sequence, calling a function before it was defined, and an "if" loop that should have been a "while".
Simple fixes. :)
This fiddle link works!
I am trying to make so when the looping of 100 hits on the character exits the loop when the life dice rolls to 0. How it currently is is all gets looped 100 times. I am not quite sure how I need to go about solving this, any tips would be helpful. My code is below.
function addChar(fname, lname, speed, agility, wep, outfit, mood) {
this.fname = fname;
this.lname = lname;
this.speed = speed;
this.agility = agility;
this.wep = wep;
this.outfit = outfit;
this.mood = mood;
this.special = function(specialMove) {
specialMove();
}
this.jumpKick = function() {
var jmpkckTimes = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write("He jumpkicks " + jmpkckTimes + " times. ");
if (jmpkckTimes > 70) {
document.write("He enters rage mode! ");
} else {
document.write("He does not have enough kicks for rage mode. ");
}
}
this.hits = function() {
var allHits = Math.floor(Math.random() * (100 - 33 + 1)) + 33;
document.write(" He gets attacked for " + allHits + " HP.");
}
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
if (life > 0) {
document.write(" The life dice rolls a " + life + ". You have survived! For now...");
} else {
document.write(" The life dice rolls a " + life + ". You have died!");
}
}
}
var myChar = new addChar('Johhny', 'Kicker', 10, 7, 'Ancient Greataxe', 'Barrows', 'angry');
document.write(myChar.fname + " " + myChar.lname + "'s speed is " + myChar.speed + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s agility is " + myChar.agility + "<br>");
document.write(myChar.fname + " " + myChar.lname + "'s weapon of choice is: " + myChar.wep + "<br>");
document.write(myChar.fname + " " + myChar.lname + " feels " + myChar.mood + "<br>");
document.write(myChar.fname + " " + myChar.lname + " attempts his special: ");
myChar.special(myChar.jumpKick)
for (i = 1; i < 101; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
function myOutfit() {
document.getElementById("demo").innerHTML = ("He is wearing " + myChar.outfit)
}
var start = Date.now();
var response = prompt("Do you think my character has what it takes?", "");
var end = Date.now();
var elapsed = (end - start) / 1000;
console.log("You took " + elapsed + " seconds" + " to type: " + response);
You need to have a way to communicate outside of the object, of what is happening inside the object.
For example, when something happens in a function, like lifes() or hits(), you should assign a value to a variable on the object to retain state. That way you can access the state from the for loop.
Example:
this.isAlive = true; // starting condition
this.lifes = function() {
var life = Math.floor(Math.random() * (3 - 0 + 1)) + 0;
this.isAlive = (life > 0);
if (this.alive) {
document.write('you survived');
} else {
document.write('you died');
}
Now in your for loop, you can access isAlive:
// loop until 100 attempts or you die, which ever comes first
for (i = 1; i < 101 && myChar.isAlive; i++) {
myChar.hits(myChar.allHits)
myChar.lifes(myChar.lifes)
}
well in general you can break out of foor loops aswell as prevent further execution of a foor loop and continue the next iteration:
for (var i = 0; i < 10; i++) {
if (i == 4) continue;
if (i == 8) break;
console.log(i);
}
this will basically print: 0, 1, 2, 3, 5, 6, 7
(as you can see it kind of skipped 4)
(it will also work in while / do while loops)
so in your case you could check if the return value of one of your functions is true or false or do some other kind of conditional checking in order to break out of the loop.
or similar to how Rob Brander wrote in his answer:
var maxTurns = 100;
var turns = 0;
while (myChar.isAlive && ++turns <= maxTurns) {
myChar.hits();
myChar.lifes();
}
console.log("character is: " + myChar.isAlive ? "alive" : "dead");
console.log("after: " + turns + " turns.");
I am making a basic game with popup boxes.
My problem is that if you look at the goblinAttack function it will repeat till the goblin is dead but the damage is random.
For example, I hit the goblin 6 damage every time until it dies instead of it being a random number between 1 and 25 and the goblin does 4 damage on me every time it hits. Its boring. I wanted it to be random each hit but repeating the function seems to not give a random number each time.
//VARIABLES
var dmgMultiply = Math.floor(Math.random() * 10 + 1);
var dmg = 10;
var armour = 0;
var hp = 100;
//ENEMY VARIABLES
var dmgGoblin = Math.floor(Math.random() * 10 + 1);
var goblinHP = 100;
//ARRAYS
var choiceArray = ["Type 'sword' equip your sword.",
"Type 'run' if you're scared.",
"Type 'stats' to see your stats."];
var answerArray = ["sword", "run", "stats"];
var outcomeArrayOne = ["You equip your sword.",
"You run away. Game Over."];
var outcomeArrayTwo = ["Sword Equipped."]
//GAME CHOICE
function choice(a, b, c, x, y, z, aa, bb)
{
var answer = prompt(a + "\n" + b + "\n" + c);
if(answer == x)
{
alert(aa);
swordEquipped(outcomeArrayTwo[0]);
}
if(answer == y)
{
alert(bb);
}
if(answer == z)
{
displayStats();
}
}
//EQUIPPED SWORD
function swordEquipped(a)
{
dmg = 25;
dmgMultiply = Math.floor(Math.random() * 25 + 1);
alert(a + "\n" + "DMG : " + dmg);
goblinCombatStart("goblin");
}
//GOBLIN COMBAT START
function goblinCombatStart(g)
{
alert("A wild " + g + " appears!" + "\n" + "The " + g + " has 100 HP!");
goblinAttack("goblin")
}
function goblinAttack(g)
{
alert("The " + g + " swings his axe at you!" + "\n" + "The " + g + " does " + dmgGoblin + " damage to you!");
hp -= dmgGoblin;
var attack = prompt("Type 'attack' to swing your sword at the " + g + "\n" + "HP : " + hp);
if(attack == "attack")
{
alert("You swing your sword at the " + g + "\n" + "You did " + dmgMultiply + " to the " + g);
goblinHP -= dmgMultiply;
alert("The " + g + " is on " + goblinHP + "HP");
if(goblinHP < 0)
{
goblinDead();
}
if(goblinHP > 0)
{
goblinAttack("goblin");
}
}
else
{
alert("You dropped your sword an shouted " + "'" + attack + "'" + " in the goblins face. It wasn't very effective and the goblin choppped your head off");
}
}
function goblinDead()
{
alert("You have slain the puny goblin with only a few scratches!");
}
//GAME START
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
//STATISTICS
function displayStats()
{
var statCheck = confirm("HP : " + hp + "\n" +
"ARMOUR : " + armour + "\n" +
"DMG : " + dmg + "\n" +
"Press OK to continue");
if(statCheck == true)
{
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
}
}
Instead of computing the random damage value only once at the beginning of your script, compute them whenever you need them. That would probably be in your attack function.
Maybe you are misunderstand something here: Math.random doesn't return some special magical value which changes every time it's read. It returns a number and that number doesn't change.
If you want multiple random values, you have to call Math.random multiple times. If you want a different random value whenever the goblin attacks, you have to call Math.random when it attacks.
The problem here is that you're initializing your variables at the beginning as random.
That means that, on every move, it will use the same random number that was generated at the beginning.
If you want it to be random for each time, you have to call Math.random() on every move.
As it stands, dmgMultiply and dmgGoblin are computed randomly once and use the same value on each turn, so you end up getting the same amount of damage taken and dealt each time.
Declare your variables at the beginning:
var dmgMultiply;
var dmgGoblin;
Then, set them to a random number within your attack function so that it computes a random number each turn:
function goblinAttack(g)
{
dmgMultiply = Math.floor(Math.random() * 10 + 1);
dmgGoblin = Math.floor(Math.random() * 10 + 1);
...
}
Demo