Adding up a current variable with the previous one - javascript

I have a problem here, basically I want my Dice game to display 3 lines.
The first line says what number of the die I got
The second line adds the number I got from the first die with the second die i rolled and so on.. (basically everytime i click the button).
The third line would just count how many times I rolled the dice.
My problem is that on my second line, im not sure how I can add up my current die roll with my previous one everytime I click the button.
var count=0;
function swap_pic()
{
var x = Math.floor(Math.random()*6)+1;
var pic = document.getElementById("dice");
var xx = x+x;
count++;
document.getElementById("result").innerHTML = "You got " + x;
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
document.getElementById("result").innerHTML += "<br>Number of tries = " + count;
if (count==5)
{
document.getElementById("result").innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style","visibility:hidden");
}
if (x==1)
{
pic.src = "images/die1.png";
}
else if (x==2)
{
pic.src = "images/die2.png";
}
else if (x==3)
{
pic.src = "images/die3.png";
}
else if (x==4)
{
pic.src = "images/die4.png";
}
else if (x==5)
{
pic.src = "images/die5.png";
}
else if (x==6)
{
pic.src = "images/die6.png";
}
}
Problem is this line
document.getElementById("result").innerHTML += "<br>Your score is: " + xx;
Thank you for the help guys!

Several concatenation of innerHTML should be avoided, as well as repeated else if when possible. Try this:
var count = 0;
var sum = 0;
function swap_pic() {
var x = Math.floor(Math.random() * 6) + 1;
var pic = document.getElementById("dice");
sum += x;
count++;
var html = "You got " + x;
html += "<br>Your score is: " + sum;
html += "<br>Number of tries = " + count;
if (count == 5) {
html += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>";
count = 0;
document.getElementById('button').setAttribute("style", "visibility:hidden");
}
document.getElementById("result").innerHTML = html;
pic.src = "images/die" + x +".png";
}

Try this on for size
//create these as global variables
var totalScore;
var rollCount;
var lastRoll;
var image;
var text;
var button;
function reload(){
totalScore = 0;
rollCount = 0;
lastRoll = 0;
image = document.getElementById('dice'); //store image element
text = document.getElementById('result'); //store result element
button = document.getElementById('button'); //store button element
button.style.visibility = visible; //restore button visibility
}
function roll(){
lastRoll = Math.floor(Math.random()*6)+1; //generate random number
rollCount++; //increase our roll counter
totalScore+= lastRoll; //add new roll to score
image.src = "images/die" +lastRoll+ ".png"; //update dice image
text.innerHTML = "You got " // generate result string
+ lastRoll
+ "<br>Your score is: "
+ totalScore
+ "<br>Number of tries = "
+ rollCount;
if(rollCount >= 5){ //end game parameter!!
text.innerHTML += "<br><span style='color:red;font-weight:bold;font-size:14px;'>Game Over!</span>"; //add game over text
button.style.visibility = 'hidden';//hide button
//reload(); //uncomment to reset game now?
}
}
window.onload = reload; //set up on page load

Related

showing total scores with localStorage - Javascript

I'd like to display scores and total scores in a basic clicking game. Every time the user clicks, the scores add 1 , and totalscores adds the total and the 1 generated in scores.
Every time the user starts the game the total score is showing and then it just keeps adding the numbers showed in scores
I think this works in the first round -> the scores are the same as total scores in the board and when i click start the totalScores are showing instead of going back to 0.
But when i start clicking the element the total scores don't add what I have stored they just follow along the number of scores.
How can I store the total and just add the score ?
the click function
score++;
scoreBoard.textContent = score;
localStorage.setItem("totalscore", score);
total.textContent = "total " + localStorage.getItem("totalscore");
the start function
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.getItem("totalscore");
If I am right in assuiming that this is your Javascript code:
click = () => {
score++;
scoreBoard.textContent = score;
localStorage.setItem("totalscore", score);
total.textContent = "total " + localStorage.getItem("totalscore");
}
start = () => {
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.getItem("totalscore");
}
Then you should do the following:
click = () => {
score++;
scoreBoard.textContent = score;
localStorage.totalscore = score;
total.textContent = "total " + localStorage.totalscore;
}
start = () => {
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.totalscore;
}
localStorage set the items as string
Use Number(localStorage.getItem('totalScore')) to convert string to number
the click function
score++;
scoreBoard.textContent = score;
var currentTotalScore = new Number(localStorage.getItem("totalScore") || 0);
localStorage.setItem("totalscore", currentTotalScore + score);
total.textContent = "total " + localStorage.getItem("totalscore");
the start function
score = 0;
scoreBoard.textContent = "0";
total.textContent = "total " + localStorage.getItem("totalscore");

vars not holding proper value after localStorage.getItem('key')

My code works fine up until I try to save my data, exit out, then reopen then load saved data. I save using localStorage.setItem('key', value) then I load using localStorage.getItem('key'), but after I load my vars are not holding the right values. Is localStorage.getItem('key') returning a string, because 1 +1 = 2, not 11 like it's displaying. please help.
The page itself is stored on my PC not online, I'm opening it up with Google Chrome. I run Windows Edge. When I try opening this with Internet Explorer, forget about localStorage.set/getItem all together. I've tried just running my code with the variables then try to save and load. (note:All my code works flawlessly until I try to save the variables, then reload them). I'm working on a video game so I need to be able to save my variables. And since I'm not sure where the problem in my code lies, I'm sorry but I see no other option than to post about 180 lines of code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="black" >
<font color="white" >
<progress id="myProgress" value="10" max="10"></progress><br>
<p id='demo5' ;></p>
<button id="enemy" type="button" onclick="dealDamage(), imageSwap()"><img
id="enemy1" src="Game_Images/smiley_1.png"></button>
<button id="spriteTest" type="button" onclick="imageSwap2()"><img
id="enemy2" src="Game_Images/smiley_1.png"></button><br>
<button id="upgrade" type="button" onclick="upgradeClickDamage()">
</button>
<button type="button" onclick="moreGold()">More Gold</button><br>
<button type="button" onclick="saveGame()">Save Game</button>
<button type="button" onclick="loadGame()">Load Game</button>
<p id='demo' ;></p>
<p id='demo2' ;></p>
<p id='demo3' ;></p>
<p id='demo4' ;></p>
<script>
var clickDamage = 1;
var gold = 0;
var stage = 1;
var enemyNum = 1;
var enemiesTotal = 10;
var enemiesKilled = 0;
var cost = 100;
var enemyHPTotal = 10;
var enemyHPCurrent = 10;
document.getElementById("upgrade").innerHTML = "Upgrade click damage for:"
+ cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:"
+ enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:" +
enemyHPCurrent + "/" + enemyHPTotal;
function imageSwap() {
var image = document.getElementById("enemy1");
if (image.src.match("Game_Images/smiley_1")){
image.src="Game_Images/smiley_2.png"
}
else if (image.src.match("Game_Images/smiley_2")){
image.src="Game_Images/smiley_3.png"
}
else {
image.src="Game_Images/smiley_1.png"
}
}
function imageSwap2(){
var image2 = document.getElementById("enemy2");
if(image2.src.match("Game_Images/smiley_1")){
setTimeout(image2.src="Game_Images/smiley_2.png", 300);
}
else if(image2.src.match("Game_Images/smiley_2")){
setTimeout(image2.src="Game_Images/smiley_3.png", 300);
}
else {
setTimeout(image2.src="Game_Images/smiley_1.png", 300);
}
}
function dealDamage() {
document.getElementById("myProgress").value -= clickDamage;
//If enemy is hit but does not die
if(document.getElementById("myProgress").value >= 1){
enemyHPCurrent = document.getElementById("myProgress").value
enemyHPTotal = document.getElementById("myProgress").max
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If enemy is killed and there are remaining enemies in the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum < 10) {
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyHPTotal = document.getElementById("myProgress").value;
enemyNum += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled += 1;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If the enemy is killed and it is the last enemy of the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum == 10) {
document.getElementById("myProgress").max += 1;
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyNum = 1;
stage += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled = 0;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPTotal = document.getElementById("myProgress").max;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
}
function upgradeClickDamage() {
if (gold >= cost) {
gold -= cost;
clickDamage += 1;
cost += 100;
document.getElementById("messageBox").innerHTML =
"Congratulations!!! You just upgraded your click damage."
document.getElementById("upgrade").innerHTML = "Upgrade click damage
for:" + cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
}
else if (gold < cost) {
document.getElementById("messageBox").innerHTML = "You don't have
enough gold for this upgrade."
}
}
function moreGold() {
gold += 100;
document.getElementById("demo").innerHTML = "Gold: " + gold;
}
function saveGame(){
//save all vars
localStorage.setItem('CLICKDAMAGE', clickDamage);
localStorage.setItem('GOLD', gold);
localStorage.setItem('STAGE', stage);
localStorage.setItem('ENEMYNUM', enemyNum);
localStorage.setItem('ENEMIESTOTAL', enemiesTotal);
localStorage.setItem('ENEMIESKILLED', enemiesKilled);
localStorage.setItem('COST', cost);
localStorage.setItem('ENEMYHPTOTAL', enemyHPTotal);
localStorage.setItem('ENEMYHPCURRENT', enemyHPCurrent);
}
function loadGame(){
//load all vars
clickDamage = localStorage.getItem('CLICKDAMAGE');
gold = localStorage.getItem('GOLD');
stage = localStorage.getItem('STAGE');
enemyNum = localStorage.getItem('ENEMYNUM');
enemiesTotal = localStorage.getItem('ENEMIESTOTAL');
enemiesKilled = localStorage.getItem('ENEMIESKILLED');
cost = localStorage.getItem('COST');
enemyHPTotal = localStorage.getItem('ENEMYHPTOTAL');
enemyHPCurrent = localStorage.getItem('ENEMYHPCURRENT');
}
</script>
<div id="messageBox"></div>
</font>
</body>
</html>
I expected all variables to function properly after loading.
gold, cost, and enemiesKilled are all affected by this same problem. If gold = 1, and I save that variable then load that variable later, then add 1 again, I get 11, not 2. With cost, if cost = 100, then I save, then I load later, then I add 100 to cost, cost = 100100 not 200.
(This will restate a bit of what you hypothesized in your question for the sake of completeness)
If you look at the documentation for Storage.getItem(), it says:
Return value
A DOMString containing the value of the key. If the key does not exist, null is returned.
This means that no matter what data type you give in setItem, the output of getItem will always be a string. This is easy to test in the console:
localStorage.setItem("test", 1);
> undefined
localStorage.getItem("test");
> "1"
When you add a string to a number, it just concatenates the two together. In your case, you're adding "1" + 1 which becomes "11" instead of adding 1 + 1 which would be 2. The solution is to convert the number string into a number, which can be done several ways, but is easiest to do (in my opinion) by simply prefixing the expression with a +.
+localStorage.getItem("test");
> 1
The localStorage.setItem converts all passed values to string. Once you call localStorage.getItem you are getting back string value.
So you are trying to concatenate string and number "1" + 1 === "11".
To prevent this behavior you need to manually convert values to stringified JSON:
localStorage.setItem('CLICKDAMAGE', JSON.stringify(clickDamage));
And then parse it back:
clickDamage = JSON.parse(localStorage.getItem('CLICKDAMAGE'));

reset var to blank after running loop in javascript

HELP! I have been banging my head against the wall for hours and hour trying to find a way that once my "game" has ended either by winning or losing my lettersGuessed var resets and no longer displays my userGuesses. I can get through the first loop/ round by setting lettersGuessed = ""; but when a new userGuess is entered, I get an uncaught type error that lettersGuessed is not a function.
// array of letters for the computer to chose from
var letterBank = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
var lettersGuessed = []
// variables starting value for tally counter
var wins = 0;
var losses = 0;
var guessesLeft = 6;
var compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
for (var i = 0; i <= guessesLeft; i++) {
document.onkeyup = function(event) {
// var for use of collecting key answers for both user and computer.
var userGuess = event.key;
lettersGuessed.push(userGuess);
// if statements to get a win or loss
if (userGuess === compGuess) {
guessesLeft = 7;
alert("You won!")
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
userGuess = "";
lettersGuessed = "";
wins++;
}
if (userGuess != compGuess) {
guessesLeft--;
}
if (guessesLeft === 0) {
alert("GAME OVER");
guessesLeft = 6;
losses++;
userGuess = "";
compGuess = letterBank[Math.floor(Math.random() * letterBank.length)];
}
// variables to display a win/loss tally and the computer/user guesses
var html =
"<p> your choice: " + userGuess + "</p>" +
"<p> losses: " + losses + "</p>" +
"<p> wins: " + wins + "</p>" +
"<p> Guesses left: " + guessesLeft + "</p>" +
"<p> Your Guesses so far:" + lettersGuessed + "</p>";
// sends info collected from html var to the game div
document.querySelector("#game").innerHTML = html;
};
};
<div id="game">Type a letter</div>
lettersGuessed is an array when declared and not a string. To reset, you need to use the same code as the first initialization. So in your first if statement, replace
lettersGuessed = "";
with
lettersGuessed = [];

.innerHTML is showing up as undefined

ok so I understand this is a very basic JS logic but I am trying to replace any document.write() with .innerHTML and I tried it with the code below
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
document.write(writeString);
}
}
function newTable() {
for(let i = 1; i <= 10; i++ ) {
let para = document.getElementById("paragraph");
para.innerHTML = writeTimesTable(i)
}
}
I have a div element with the ID of paragraph already. I keep getting undefined when I look at the div#paragraph and the rest of my code outputs under my script tag but not in the div element. What am I doing wrong?
Your function writeTimesTable() needs to return a value. Your writeString string, needs to be concatenated as well, you can do that with += like seen below:
function writeTimesTable(num) {
let writeString = "";
for(let i = 1; i < 10; i++ ) {
writeString += i + " * " + num + " = ";
writeString += writeString + (i * num);
writeString += writeString + "<br />";
}
return writeString
}
Using para.innerHTML = writeTimesTable(i) probably isn't intended, as it will just display the last loop, so you might also want to use += here as well:
para.innerHTML += writeTimesTable(i)
You normally want to avoid document.write because it literally writes out to the document.
I have also taken the liberty of doing the DOM creation off-page during the loop, and just add it to the actual DOM at the end. This means you aren't constantly re-drawing the page while you loop.
This is better than changing your innerHTML = to innerHTML +=, which you would need to do if you wanted to avoid overwriting each previous iteration of the loop.
function writeTimesTable(num) {
for(let i = 1; i < 10; i++ ) {
let writeString = i + " * " + num + " = ";
writeString = writeString + (i * num);
writeString = writeString + "<br />";
return writeString;
}
}
function newTable() {
const inner = document.createElement('div');
for(let i = 1; i <= 10; i++ ) {
const item = document.createElement('div');
item.innerHTML = writeTimesTable(i);
inner.appendChild(item);
}
let para = document.getElementById("paragraph");
para.appendChild(inner);
}
newTable();
<div id="paragraph"></div>
Your newTable() function with the 10 loops is useless. You're doing 10 times the same stuff over a single DOM element.
Don't use document.write...
I'd do it like:
function newTable( num ) {
var HTML = "";
for (var i=1; i <= num; i++) {
HTML += i +" * "+ num +" = "+ (i*num) +"<br>";
}
return HTML; // Return the concatenated HTML
}
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>
Or in a super uselessly cryptic ES6 way:
const newTable = n =>
Array(n).fill().map((_,i) =>
`${i+=1} * ${n} = ${i*n}<br>`
).join('');
document.getElementById("paragraph").innerHTML = newTable(10);
<p id="paragraph">asdasdasd</p>

Replace , with <br>

Been browsing SO for some time since I picked up a programming course, and have found it to be an awesome community and great place for knowledge.
Currently I'm stuck with a JavaScript function that I'm trying to clean up.
I need to have names input into an array, and then when I run a 'start' function, it would display the amount of names as a number, and then show each name on a new line.
I've managed to get it working, however there is a ',' character at the start of each line. I've tried various ways to get around it (using replace and split + join) but had no luck so far.
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
The reason is most likely because you are trying to display arrName which is an Array with this code: document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
Here's what I'd suggest:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
Since there is no need for the WHILE Loop, You can skip it like so:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
An array when console logged or inserted to DOM directly will be represented as item1,item2,item3,item4
So simply, arrName.join("<br />")
Also, your while loop can be simply replaced by
totalName = arrName.length;
count = arrName.length

Categories

Resources