How do I have a button appear after a certain function is executed?
I'm trying to create a simple game and it has 2 buttons which lead to function 2 and 3 when the program first runs.
After pressing one of the two buttons and executing one of the functions, the button disappears. I then want to create another button on the second and third function that will allow player to replay the game and exit the game. The problem is that I don't know how to make the button only appear on the second function or third functions.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE="JavaScript">
var score;
score = 0
function mainmenu() {
var start
name = prompt("What is your name?")
document.write("Welcome " + name + " for playing game" + "<BR>")
}
function game() {
var ask
var repeat
var again
again = "yes"
while (again == "yes") {
document.write("Hello " + name + " Welcome to the game, you will decide on what action you will take depending on the situation. You will either gain or loose score depending on your decision made. GLHF!" + "<br>" + "<BR>")
document.write(" You enter the dungeon and its pitch black, you can barely see your hand infront of your face. You have a pair of flint inside your pocket and you can attempt to make a torch by ripping a piece of your cloth. What do you do?" + "<BR>")
decision1 = (" Option 1) You brave the darkness" + "<br>")
document.write(decision1)
/* dont need to use all these's variables for decision 1-16*/
decision2 = ("Option 2) You attempt to make a torch" + "<BR>")
document.write(decision2)
decision3 = ("Option 3) You attempt to find a wall and let it guide you" + "<BR>")
document.write(decision3)
decision4 = ("Option 4) You run like an animal, screaming like an animal" + "<BR>")
document.write(decision3)
ask = prompt("Which decision do you choose? Choose from 1,2,3 and 4" + "<BR>")
if (ask == "1") {
document.write("You walk for a few minute without any event but you suddenly step onto a pot-hole and loose your grip. You injured your right knee. You'll live but its gonna hurt for a while" + "<BR>")
score = score + 20
}
if (ask == "2") {
document.write("You tore off a piece of cloth from your sholder and you write it around a stick you found nearby but ask you reach into your pocket to grab your flint, you dropped it. As you attempt to find it, you accidentally felt something sharp and you started to bleed from your left hand. Tought luck m8" + "<BR>")
score = score - 30
}
if (ask == "3") {
document.write("You glide your hand agaist the wall, after half and hour of nothing happening. You finally found a ray of light at the end of the tunnel" + "<BR>")
score = score + 50
}
if (ask == "4") {
document.write("You started running and you scream your lungs out. You took 3 steps and you fell down face first. What the hell were you thinking?" + "<BR>")
score = score - 50
}
document.write("Your current score is " + score + "<BR>")
document.write(" As you finally walk past the darkness, you stumble upon a bright litted room. In the middle of the room, filled a chest. You took a survey around the room and you notice there's nothing in the room except the chest. What to do you?" + "<BR>" + "<BR>")
decision5 = ("Option 1) You rush towards the treasure chest and open it. Gotta get dat bootie!" + "<br>")
document.write(decision5)
/* dont need to use all these's variables for decision 1-16*/
decision6 = ("Option 2) You take a more carefull look around the room." + "<BR>")
document.write(decision6)
decision7 = ("Option 3) You leave the chest alone and walk straight past it and into the next room" + "<BR>")
document.write(decision7)
decision8 = ("Option 4) You kick the chest" + "<BR>")
document.write(decision8)
ask = prompt("Which decision do you choose? Choose from 5,6,7 and 8" + "<BR>")
if (ask == "1") {
document.write("You rush towards the chest with full speed and suddenly, half a dozen arrow wizzez past you. Unfortunatly, you've been hit around the sholder. You decided its too dangerous and you cut your losses and enter the next room" + "<BR>")
score = score - 50
}
if (ask == "2") {
document.write("As you walk to the side of the room, you notice there are dozens of small holes placed infront of the the treasure chest. You also notice there are pressure plates suinfront of the chest. You walk behind the chest and opened it and you fond that its completely empty!. So much for bootie." + "<BR>")
score = score + 50
}
if (ask == "3") {
document.write("You decided to play it safe and walk past the treasure chest. Nothing happens" + "<BR>")
score = score + 0
}
if (ask == "4") {
document.write("You decided to kick the chest for whatever reason. You hurt your foot during the process. Why would you do that?" + "<BR>")
score = score - 20
}
document.write("Your current score is " + score + "<BR>")
document.write(" As you continue along your journey, you stumble upon an injured adventurer! You rush to his side and he claims that his right leg is broken. He's seems to be carrying a rather heavy rucksack. You cant carry him with you because he's simply too heavy. " + "<BR>" + "<BR>")
decision9 = (" Option 1) You perform some medical treatment on him. Though you dont have much experience on medicine." + "<br>")
document.write(decision9)
/* dont need to use all these's variables for decision 1-16*/
decision10 = ("Option 2) You ignore him." + "<BR>")
document.write(decision10)
decision11 = ("Option 3) You search for his bag and see if there is anything useful to help him" + "<BR>")
document.write(decision11)
decision12 = ("Option 4) You end his misery. He's not gonna last long here anyway." + "<BR>")
document.write(decision12)
ask = prompt("Which decision do you choose? Choose from 9,10,11 and 12" + "<BR>")
if (ask == "1") {
document.write("you attempt to fix the adventurer's leg by applying some ointment onto his leg. It wont help much but at least it's something" + "<BR>")
score = score + 10
}
if (ask == "2") {
document.write("You walk past him and ignore his plea of him. There's nothing you can do to help him" + "<BR>")
score = score + 0
}
if (ask == "3") {
document.write("As you run through his bad you found a stick! Looks like he's in a sticky situation :D, you tied the stick to the adventurer's leg. It seems to be sturdy enough to hold him. He thanks you and he goes to his merry ways." + "<BR>")
score = score + 40
}
if (ask == "4") {
document.write("You decide to end his misery by knocking him in the back. He falls dead on the ground the moment your hand make contact. How this work i will nover know. Just roll with it" + "<BR>")
score = score - 20
}
document.write(" At the end of the room a giant lion statue gazes upon you. He ask you a quiz. What walks on 4 legs, then 2 and finally 3. " + "<BR>" + "<BR>")
decision13 = (" Option 1) AN ANIMAL!" + "<br>")
document.write(decision13)
/* dont need to use all these's variables for decision 1-16*/
decision14 = ("Option 2) A CHAIR!" + "<BR>")
document.write(decision14)
decision15 = ("Option 3) A MAN!" + "<BR>")
document.write(decision15)
decision16 = ("Option 4) I dunno" + "<BR>")
document.write(decision16)
ask = prompt("Which decision do you choose? Choose from 13,14,15 and 16" + "<BR>")
if (ask == "1") {
document.write("NOPE, the lion statue slowly disapears and behind it leads to the outside world" + "<BR>")
score = score - 10
}
if (ask == "2") {
document.write("NOPE, the lion statue slowly disapears and behind it leads to the outside world" + "<BR>")
score = score - 10
}
if (ask == "3") {
document.write("Correct!, the lion statue slowly disapears and behind it leads to the outside world." + "<BR>")
score = score + 10
}
if (ask == "4") {
document.write("Your not even gonna try? The lion's head shook in disapointment and slowly disapears. Behind it leads to the outside world" + "<BR>")
score = score - 20
}
document.write("Your current score is " + score)
again = prompt("would you like to play again?")
}
leaderboard()
}
function leaderboard() {
var n, temp;
ok = false;
var leaderboardarray = new Array(5);
leaderboardarray[0] = 50;
leaderboardarray[1] = 60;
leaderboardarray[2] = 130;
leaderboardarray[3] = 120;
leaderboardarray[4] = score;
leaderboardarray.sort(function (a, b) {
return b - a
});
var myContent = '';
for (var n = 0; n < 5; n++)
myContent += "score: " + leaderboardarray[n] + "<br>";
document.getElementById("leaderBoard").innerHTML = myContent;
document.write("Your current score is " + score)
}
leaderboard()
</SCRIPT>
</HEAD>
<BODY style="background-color:#cccccc;">
<INPUT NAME="dobutton" TYPE="button" value="Start game" onclick=game()>
<INPUT NAME="dobutton" TYPE="button" value="Leaderboard" onclick=leaderboard()>
<H2>The Foundation Page </H2>
<HR>
<div id="leaderBoard">
<script type="text/javascript">mainmenu();</script>
</div>
<BR>
</BODY>
</HTML>
You may assign ad ID to both buttons, and hide the second one:
<INPUT ID="btn1" NAME="dobutton" TYPE="button" value="Start game" onclick="game()">
<INPUT ID="btn2" NAME="dobutton" TYPE="button" value="Leaderboard" onclick="leaderboard()" style="display:none;">
Then you can show or hide them in this way:
document.getElementById("btn1").style.display = "none"; /// first button disappear
document.getElementById("btn2").style.display = "inline"; /// second button appear
Related
I need to make those "If's" below work together ("If" inputs's value less than 1900, I need message display "Please enter a valid year" and "If" Dog's age higher than 14, I need message display as "Your dog completed its life span" message at third sentance. However only one them works and sometimes other one. But not working together. Can someone show me where I do wrong here? thank you.
function calc() {
let x = document.getElementById("year").value
let current = new Date().getFullYear()
let age = current - Number(x)
let trans = age * 7
let remain = 15 - age
let msg ="Your dog is " + age + " years old. Your dog's human race is " + trans + ". Your dog has " + remain + " years to complete its life span."
document.getElementById("result").innerHTML= msg
if (x < 1900) {
document.getElementById("result").innerHTML="Please enter a valid year."
}
if (remain <= 0) {
document.getElementById("result").innerHTML= "Your dog is " + age + " years old. Your dog's human race is " + trans + ". Your dog completed its life span."
}
}
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Page</title>
</head>
<body>
<h1>Dog Age Calculate</h1>
<b>Please enter your dog's birth of year:</b><br><br>
<input type="number" id="year" required min="1900" max="2022"><br><br>
<button onclick="calc()">Calculate</button><br>
<p id="result"></p>
<script src="Chasm.js"></script>
</body>
</html>
You are not leaving your function when your if case is triggered. Therefore it is possible that after the first if the second ifis triggered as well.
You have a few options here.
Option 1:
return from the function if any if case is triggered.
if (x < 1900) {
return document.getElementById("result").innerHTML="Please enter a valid year."
}
if (remain <= 0) {
return document.getElementById("result").innerHTML= "Your dog is " + age + " years old. Your dog's human race is " + trans + ". Your dog completed its life span."
}
//set the msg at the end of the function so you are checking your if statements before
document.getElementById("result").innerHTML= msg
Option 2:
use if / else
if (x < 1900) {
document.getElementById("result").innerHTML="Please enter a valid year."
} else if (remain <= 0) {
document.getElementById("result").innerHTML= "Your dog is " + age + " years old. Your dog's human race is " + trans + ". Your dog completed its life span."
} else {
document.getElementById("result").innerHTML= msg
}
You could also improve performance when setting the first if directly under your assigned variable. If that case matches, you don't need the further calculations.
let x = document.getElementById("year").value
if (x < 1900) {
return document.getElementById("result").innerHTML="Please enter a valid year."
}
....
The stock number decreases by one every time a user chooses and buys a soda.
However, if the user keeps on buying on the same code ("A1" in this case) but there are no stocks left, money still subtracts by a certain amount.
How do I warn the user that there are no more stocks left for "A1" and how do I let the user know their money will be refunded?
//Soda Choice with If-Then Statements
sodaChoice.addEventListener("click", function() {
var sodaChoice = window.prompt("Select your code.");
console.log(sodaChoice);
if (sodaChoice == "A1") {
window.alert("You selected Coca-Cola.");
window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
window.alert(sodaPrice[0] <= $money ? "You have enough. Have a nice day." : "You don't have enough. Try again.");
$money -= sodaPrice[0].toFixed(2);
console.log("You now have " + $money.toFixed(2));
while (stockCocaCola !== 0) {
stockCocaCola--;
break; //The break function stops this while loop from rapidly subtracting stockCocaCola by 1 until stockCocaCola reaches 0.
}
console.log("Stock left for Coca-Cola: " + stockCocaCola);
}
Instead of refunding, I would deduct money only if the stock is available, else give alert message. (Removed while loop too as it's not required)
//Soda Choice with If-Then Statements
sodaChoice.addEventListener("click", function() {
var sodaChoice = window.prompt("Select your code.");
console.log(sodaChoice);
if (sodaChoice == "A1") {
window.alert("You selected Coca-Cola.");
window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
window.alert(sodaPrice[0] <= $money ? "You have enough. Have a nice day." : "You don't have enough. Try again.");
if(stockCocaCola > 0) {
$money -= sodaPrice[0].toFixed(2);
console.log("You now have " + $money.toFixed(2));
stockCocaCola--;
}
else{
window.alert("No Stock available for " + sodaChoice );
}
console.log("Stock left for Coca-Cola: " + stockCocaCola);
}
I have did my fair share of research and can't find much on the topic. Basically, I am trying to replicate a custom turn based battle system. The problem I am facing, is it when the while loop finishes, it just spits out all the results. I would like to see each iteration while the condition has not been met yet.
The loop: javascript
const battle = (enemy) => {
while(xPlayerBattleRound(enemy) != true && enemyBattleRound() != true) {
}
if(xPlayer.health <= 0 && enemy.health > 0) {
return false
} else {
return true
}
}
the functions associated:
const selectEnemy = () => {
enemyNum = Math.round(Math.random())
enemy = enemies[enemyNum]
selectedEnemy = enemy
return selectedEnemy.name
}
xPlayerBattleRound = (enemy) => {
playerDmg = xPlayerStrike()
enemy.health = enemy.health - playerDmg
content += "<br>" + selectAttackStyle() + "" + selectAttackMultiplier() + " towards a " + enemy.name + " and strike it for <span class='bold'>" + playerDmg + " </span>damage."
document.getElementById('content-creation').innerHTML = content
if(enemy.health <= 0) {
content += "<br>You KILLED a " + enemy.name + "! You gained " + enemyExp + " experience."
document.getElementById('content-creation').innerHTML = content
enemy.reset()
return true
}
}
enemyBattleRound = () => {
enemyDmg = enemyStrike(enemy)
xPlayer.health = xPlayer.health - enemyDmg
content += "<br>A " + enemy.name + " " + selectAttackMultiplier() + " bites you for <span class='bold'>" + enemyDmg + " </span>damage!"
if(xPlayer.health <= 0) {
content += "<br>You were MORTALLY wounded by " + enemy.name + "!"
document.getElementById('content-creation').innerHTML = content
enemy.reset()
return true
}
}
Things I have tried, include attempting to setTimeout on the individual functions. I have made several other changes as well. Not sure how to approach this. I also tried different ways as to format it.
Output:
You punch incompetently towards a wild dog and strike it for 14
damage. A wild dog competently bites you for 20 damage! You attack
ordinarily towards a wild dog and strike it for 11 damage. A wild dog
clumsily bites you for 26 damage! You swing extraordinarily towards a
wild dog and strike it for 19 damage. A wild dog clumsily bites you
for 15 damage! You swing incompetently towards a wild dog and strike
it for 11 damage. A wild dog incompetently bites you for 19 damage!
You swing incompetently towards a wild dog and strike it for 21
damage. You KILLED a wild dog! You gained 10 experience.
Rather than the dump, I want to see each line for like 2000ms or something.
This question already has an answer here:
Why is my window.setInterval function overlapping itself in the DOM when called multiple times?
(1 answer)
Closed 1 year ago.
I'm new to JS, and decided to start of learning by a making a small game. I am using a setInterval to automate the enemy's attack. For their first attack the interval is correct, but after the second attack it speeds up to attacking almost three times, or more, a second. I'm also having trouble stopping the interval once either the player's or the enemy's health reaches 0.
here is pretty much all the code pertaining my problem. The whole code can be found here
function deadFunct(){
if(yourHealth <= 0){
window.alert("You dead");
clearInterval(fightAuto);
clearInterval(deadAuto);
}
if(enemyHealth <= 0){
window.alert("The enemy is dead");
clearInterval(fightAuto);
clearInterval(deadAuto);
}
}
function nextFunct(){
document.getElementById("nextBtn").disabled=true;
document.getElementById("swordBtn").disabled=false;
document.getElementById("bowBtn").disabled=false;
document.getElementById("hamBtn").disabled=false;
var a=Math.random();
if(a>0.66){
enemy="Knight";
eAcc=.75;
eDmg=5;
eAttackSpeed=2000;
y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
document.getElementById("attack").innerHTML=y;
}else if(a>0.33){
enemy="Archer";
eAcc=.80;
eDmg=3;
eAttackSpeed=1750;
y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
document.getElementById("attack").innerHTML=y;
}else{
enemy="Berserker";
eAcc=.66;
eDmg=7;
eAttackSpeed=2500;
y= "Your health = " + yourHealth + " || "+ enemy +" = " + enemyHealth + "<br>";
document.getElementById("attack").innerHTML=y;
}
}
function enemyAttackFunct(){
for(var i=0; i<1;i++){
if(enemy == "Archer"){
fightAuto = setInterval(function(){aAttackFunct()},eAttackSpeed);
document.getElementById("test").innerHTML=eAttackSpeed;
}else if(enemy == "Knight"){
fightAuto = setInterval(function(){kAttackFunct()},eAttackSpeed);
document.getElementById("test").innerHTML=eAttackSpeed;
}else{
fightAuto = setInterval(function(){bAttackFunct()},eAttackSpeed);
document.getElementById("test").innerHTML=eAttackSpeed;
}
}
}
You keep calling 'setInterval' again again. Each call is running in parallel.
If you have more than one warrior peer type (archer, knight, etc), create an array that will have a separate set interval for each.
If, as seems the case, you only have one and they play at random each turn, add clearInterval before every setInterval
you should never use setInterval for animations!
Just use requestAnimationFrame instead!
https://developer.mozilla.org/en/docs/Web/API/window.requestAnimationFrame
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
http://css-tricks.com/using-requestanimationframe/
This code is supposed prompt for two player names and generate a random number between 1 and 6 for each player. It is then supposed to compare those two numbers and provide the output of which player has the higher number or display tie if there is a tie. Sometimes this works and sometimes it does the opposite other times it says both numbers match when they don't.
Anyone have any ideas for me?
var playerOne = " "
var playerTwo = " "
var rollWinner = " "
var p1number = 0;
var p2number = 0;
var end = " "
main()
function main()
{
do {
getNames()
rollDice()
displayResults()
endProgram()
}
while (end == "yes")
}
function getNames()
{
playerOne = prompt("Please enter the name of Player One: ")
playerTwo = prompt("Please enter the name of Player Two: ")
}
function rollDice()
{
p1Number = Math.floor((Math.random()*6)+1)
p2Number = Math.floor((Math.random()*6)+1)
if (p1Number > p2Number)
{
return playerOne
}
else if (p1Number < p2Number)
{
return playerTwo
}
else
{
return "Sorry no winner, there was a tie"
}
}
function displayResults()
{
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
window.alert("The winner is! " + rollDice())
}
function endProgram()
{
end = prompt("Do you want to play again? Enter yes or no")
if (end == "no")
window.alert("Thank you for playing");
else if (end == "yes")
return end;
}
window.alert("The winner is! " + rollDice())
This line calls rollDice again for a 2nd time. You display the results of the first call then you re-roll and display the return value of the 2nd call (which may be different).
// display p1Number and p2Number from first roll
window.alert(playerOne + " rolled a " + p1Number)
window.alert(playerTwo + " rolled a " + p2Number)
// recall rollDice
window.alert("The winner is! " + rollDice())
In displayResults(), you are showing the values of p1Number and p2Number before assigning values to them (since that happens within rollDice()).
So your program is working, but your diagnostic output is misleading you.