Javascript Page Reset - javascript

Im trying to get my page to reset to its original layout once the popup goes away after 5 seconds. I've tried setTimeOut(fullReset(true), messageHIde, 5000) but that stops the pop up from working.I know how to get it back to its original layout if it was the case of using a button. Any tips about how to get it working? My java script is below for the popup and the fullReset.
if ((playerChoice == "higher") && (playerCard > computerCard))
{
document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
/* increase the score by 5 because the user won */
total = total + 5;
}
else if ((playerChoice == "higher") && (computerCard > playerCard))
{
document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;
}
else if ((playerChoice == "equal") && (playerCard > computerCard))
{ document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total +5 ; }
else if ((playerChoice == "equal") && (computerCard > playerCard))
{ document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;}
else if ((playerChoice == "lower") && (playerCard > computerCard))
{
document.getElementById("popup").innerHTML ="You win!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total + 5;}
else if ((playerChoice =="lower") && (computerCard > playerCard))
{document.getElementById("popup").innerHTML ="You lose!";
document.getElementById("popup").style.display = "block";
setTimeout(messageHide, 5000);
total = total - 10;}
/* display the new total */
alert(total + " " + playerChoice + " " + playerCard + " " +computerCard);
document.getElementById('score').innerHTML = total;
}
function messageHide(){
document.getElementById('popup').style.display = "none";
}
function fullReset(){
document.getElementById('img1').src = 'back.gif';
document.getElementById('img2').src = 'back.gif';
document.getElementById('higherButton').style.backgroundColor = "white";
document.getElementById('lowerButton').style.backgroundColor = "white";
document.getElementById('equalButton').style.backgroundColor = "white";
document.getElementById('drawButton').style.backgroundColor = "white";
document.getElementById('score').innerHTML = "0" +total;
startButton.disabled = false;
higherButton.disabled = true;
lowerButton.disabled = true;
equalButton.disabled = true;
drawButton.disabled = true;
}

Use
setTimeOut(function(){
messageHide();
fullReset();
}, 5000);

Related

How can I use a CE key in a calculator?

I'm making a calculator like the Windows calculator, and have completed it, the only thing I cannot do is make the CE button usable. I want the CE button to delete the last equation you entered, eg. if you enter like 78-89*90, it will delete the *90 only.
Here is the javascript code I have:
var display = document.getElementById("screen");
var buttons = document.getElementsByClassName("button");
Array.prototype.forEach.call(buttons, function(button) {
button.addEventListener("click", function() {
if (button.textContent != "=" &&
button.textContent != "C" &&
button.textContent != "x" &&
button.textContent != "÷" &&
button.textContent != "√" &&
button.textContent != "x ²" &&
button.textContent != "%" &&
button.textContent != "⌫" &&
button.textContent != "1/x" &&
button.textContent != "CE" &&
button.textContent != "±") {
display.value += button.textContent;
} else if (button.textContent === "=") {
equals();
} else if (button.textContent === "C") {
clear();
} else if (button.textContent === "x") {
multiply();
} else if (button.textContent === "÷") {
divide();
} else if (button.textContent === "±") {
plusMinus();
} else if (button.textContent === "⌫") {
backspace();
} else if (button.textContent === "%") {
percent();
} else if (button.textContent === "x ²") {
square();
} else if (button.textContent === "√") {
squareRoot();
} else if (button.textContent === "1/x") {
divide1();
} else if (button.textContent === "CE") {
clearone();
}
});
});
function syntaxError() {
if (eval(display.value) == SyntaxError || eval(display.value) == ReferenceError || eval(display.value) == TypeError) {
display.value == "Syntax Error";
}
}
function equals() {
if ((display.value).indexOf("^") > -1) {
var base = (display.value).slice(0, (display.value).indexOf("^"));
var exponent = (display.value).slice((display.value).indexOf("^") + 1);
display.value = eval("Math.pow(" + base + "," + exponent + ")");
} else {
display.value = eval(display.value)
checkLength()
syntaxError()
}
}
function clear() {
display.value = "";
}
function backspace() {
display.value = display.value.substring(0, display.value.length - 1);
}
function multiply() {
display.value += "*";
}
function divide() {
display.value += "/";
}
function plusMinus() {
if (display.value.charAt(0) === "-") {
display.value = display.value.slice(1);
} else {
display.value = "-" + display.value;
}
}
function square() {
display.value = eval(display.value * display.value);
}
function squareRoot() {
display.value = Math.sqrt(display.value);
}
function percent() {
display.value = display.value / 100;
}
function divide1() {
display.value = 1 / display.value;
}
I need to make a function called clearone that as said before, cleans the last equation you entered.
Thanks in advance.
Just split the values and check one by one and remove the value if it's a number and break the loop when is not a number.
function clearone(){
let v = '78-89*90'.split('');
let ar = [0,1,2,3,4,5,6,7,8,9];
for(a of v){
let index = ar.indexOf(parseInt(a));
if(index == -1){
v.pop();
v= v.join("");
console.log(v);
break;
}else{
v.pop();
}
}
}
clearone();

Calculate the score for Memory Game based on number of turns , time and matches

I'm developing a memory game and i need to calculate the fair score for the game, based on:
number of tries,
time and
number of matches
So, i tried using a function to calculate the score, but when i tried to display the score in the winning screen, the score do not appear. Help me out with this
the variables are
var matches = 0;
var moves = 0;
var counter = document.querySelector(".moves");
To check for the matches:
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function (e) {
var turnable = e.target.dataset.turnable;
//first click
if (!wait && lastKnownButtonId == undefined && lastKnownButtonNumber == undefined && turnable == 'true') {
e.target.dataset.turnable = 'false';
e.target.innerHTML = getgImage(event.target.dataset.number);
e.target.style.backgroundColor = 'yellow';
lastKnownButtonId = e.target.id;
lastKnownButtonNumber = e.target.dataset.number;
}
//second click
else if (!wait && lastKnownButtonId != undefined && lastKnownButtonNumber != undefined && turnable == 'true' && e.target.id != lastKnownButtonId) {
e.target.dataset.turnable = 'false';
e.target.innerHTML = getgImage(event.target.dataset.number);
//match
if (e.target.dataset.number == lastKnownButtonNumber) {
e.target.style.backgroundColor = '#00FF7F';
document.getElementById(lastKnownButtonId).style.backgroundColor = '#00FF7F';
lastKnownButtonId = undefined;
lastKnownButtonNumber = undefined;
matches++;
if (matches == 8) {
document.getElementById("finalMove").innerHTML = moves;
showWinScreen();
//clearTimeout(timeoutHandle);
}
}
//no match
else {
document.getElementById(lastKnownButtonId).style.backgroundColor = 'red';
e.target.style.backgroundColor = 'red';
wait = true;
setTimeout(() => {
e.target.dataset.turnable = 'true';
e.target.style.backgroundColor = 'white'
e.target.innerHTML = getgImage(0);
var tempLastClickedButton = document.getElementById(lastKnownButtonId);
tempLastClickedButton.dataset.turnable = 'true';
tempLastClickedButton.style.backgroundColor = 'white';
tempLastClickedButton.innerHTML = getgImage(0);
lastKnownButtonId = undefined;
lastKnownButtonNumber = undefined;
wait = false;
}, 1000);
}
moveCounter();
}
});
}
i have inserted a function to calculate the score
function calcScore(){
var tilesbonus = (16 - matches) * 20; // 20 points for each successful tile
var timebonus = (60 - finaltime) * 8; // 8 points for each second
var triesbonus = (48 - moves) * 10; // (deduct) 10 points for each try
if (tilesbonus <0) { tilesbonus = 0; }
if (timebonus <0) { timebonus = 0; }
if (triesbonus <0) { triesbonus = 0; }
var totalscore= tilesbonus + timebonus + triesbonus;
return totalscore;
}
The function for timer:
window.onload = function() {
var timeoutHandle;
function countdown(minutes, seconds) {
function tick() {
var timecounter = document.getElementById("timer");
timecounter.innerHTML = minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
seconds--;
if (seconds >= 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (minutes >= 1) {
setTimeout(function () {
countdown(minutes - 1, 59);
}, 1000);
}
}
if (seconds==0 && minutes ==0){
alert("Game over");
//reset();
}
if (matches==8){
var totalscore = calcScore();
clearTimeout(timeoutHandle);
var finaltime= timecounter.innerHTML;
document.getElementById("seconds").innerHTML= finaltime;
document.getElementById("score").innerHTML=totalscore;
}
}
tick();
}
countdown(1, 00); }
the Move counter:
function moveCounter(){
moves++;
counter.innerHTML = moves;
}
the calscore() function is called when the game ends
if (matches==8){
calcScore();
clearTimeout(timeoutHandle);
var finaltime= timecounter.innerHTML;
document.getElementById("seconds").innerHTML= finaltime;
document.getElementById("score").innerHTML=totalscore;
document.getElementById("finalMove").innerHTML = moves;
}
The html code where the score should appear is :
<p><font size= "5">Your score: <span id=score> </span></font></p>
It's because you try to use a variables defined in a fonction from the global scope
here's an explanation of javascript scopes
basically if you declare a variable inside a fonction you can't use it outside of it
corrected and commented your code about this specific problem
var matches = 8
var finaltime = 42
var moves = 13
function calcScore(){
var tilesbonus = (16 - matches) * 20; // 20 points for each successful tile
var timebonus = (60 - finaltime) * 8; // 8 points for each second
var triesbonus = (48 - moves) * 10; // (deduct) 10 points for each try
if (tilesbonus <0) { tilesbonus = 0; }
if (timebonus <0) { timebonus = 0; }
if (triesbonus <0) { triesbonus = 0; }
var totalscore= tilesbonus + timebonus + triesbonus; // you defined the variable here
return totalscore;
} // totalscore is destroyed after the end of the function
if (matches==8){
var totalscore = calcScore(); // I modified this line and now it works
// I declare a new variable which contains the value returned by calcScore
clearTimeout(null); // i don't have the timeout var so I can't clear it
var finaltime= timecounter.innerHTML;
document.getElementById("seconds").innerHTML= finaltime;
document.getElementById("score").innerHTML=totalscore; // finally use the variable
}
<p><font size= "5">Your score: <span id=score> </span></font></p>
<p><font size= "5">finalTime: <span id=seconds> </span></font></p>
<span id=timecounter>42</span>

Button Array seems to not be working

I have an exercise that I had to do for my class and was not sure why my button array does not work. The number of times I click the button does not equal to the exact number of times being clicked if that makes sense.
function changeDisplay(buttonClicked) {
if (currentButton == buttonClicked) {
return;
}
if (buttonClicked == "linear") {
buttonArray[0] = buttonArray[0] + 1;
document.getElementById('linear').innerHTML = " Linear = " + buttonArray[0];
document.getElementById('section1').style.float = 'none';
document.getElementById('section1').style.width = "100%";
document.getElementById('sidebar').style.float = 'none';
document.getElementById('section2').style.float = 'none';
currentButton = buttonClicked;
console.log("linear " + buttonArray[0]);
} else if (buttonClicked == "right") {
buttonArray[0] += 1;
document.getElementById('right').innerHTML = " Right Sidebar = " + buttonArray[0];
document.getElementById('section1').style.float = 'none';
document.getElementById('section1').style.width = "100%";
document.getElementById('sidebar').style.float = 'right';
document.getElementById('sidebar').style.width = "25%";
document.getElementById('section2').style.float = 'none';
currentButton = buttonClicked;
console.log("right " + buttonArray[1]);
} else if (buttonClicked == "center") {
buttonArray[0] += 1;
document.getElementById('center').innerHTML = " Center Sidebar = " + buttonArray[0];
document.getElementById('section1').style.float = 'left';
document.getElementById('section1').style.width = "30%";
document.getElementById('section1').style.marginRight = "25px";
document.getElementById('sidebar').style.float = 'left';
document.getElementById('sidebar').style.width = "25%";
document.getElementById('section2').style.float = 'none';
document.getElementById('section2').style.width = "100%";
currentButton = buttonClicked;
console.log("center " + buttonArray[2]);
} else if (buttonClicked == "left") {
buttonArray[0] += 1;
document.getElementById('left').innerHTML = " Left Sidebar = " + buttonArray[0];
document.getElementById('section1').style.float = 'none';
document.getElementById('section1').style.width = "100%";
document.getElementById('sidebar').style.float = 'left';
document.getElementById('sidebar').style.width = "25%";
document.getElementById('section2').style.float = 'none';
document.getElementById('section2').style.width = "100%";
currentButton = buttonClicked;
console.log("left " + buttonArray[3]);
}
}
</script>

showing variable value in <p> paragraph using getElementById.innerHTML in Javascript

I'm trying to write a Blackjack code using Javascript, and showing the result in an HTML page. I have written the logic already, but I can't get to show the results in paragraph by ID, using getElementById.innerHTML. I don't know how to make it right. Could you please help me with this? I'm running out of time :(. here's the code:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
</body>
</html>
As #nnnnnn has mentioned that your html tags are not even loaded when your JS has executed and hence the issue. Try something like below to correct the issue:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
<script>
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</body>
</html>
your script is loading before the document that has the elements in it. Enclose your script in:
window.onload=function() {
//all of your JavaScript code
}

Simple Guessing Game Program in Javascript

Trying to create a very simple number guessing game as a first project. I want the player to have 5 guesses before they lose.
I'm having difficulty troubleshooting the bugs or coding mistakes.
var num = Math.floor((Math.random(1,10) * 10) +1);
console.log(num); //To check
var counter = 5;
while(counter > 0){
function guess(){
counter = counter-1
var guess = prompt("You've got " + counter + " tries to guess the number.");
if (num == guess){
alert("That's the number!");
}else if (guess != (int){
alert("That's not a number...");
}else{
alert("Nice try");
}
}
}
alert("You lost.");
Working fiddle: http://jsfiddle.net/0skh4t4r/
var num = Math.floor((Math.random(1, 10) * 10) + 1);
console.log(num); //To check
var counter = 5;
function guess() {
var x = prompt("You've got " + counter + " tries to guess the number.");
if (!x) return; // cancel the game
counter--;
if (num === parseInt(x)) {
alert("That's the number!");
return;
} else if (isNaN(x)) {
alert("That's not a number...");
} else {
alert("Nice try");
}
if(counter === 0) {
alert("You lost");
} else {
guess(); // next try
}
}
guess();

Categories

Resources