Javascript Score Counter not increasing - javascript

I'm creating a simple card game that when a player wins the score should increase per win. But whenever I run this code it keeps resetting the score back to 0.
How can I make it so the scores keep increasing +1 if the corresponding player wins?
I've tried the below and it's unfortunately not working with what I have
$(document).ready(function(){
//storing our images, separating them out by suit. Orderimg from lowest to highest cards.
arrClubs=['2_of_clubs.png','3_of_clubs.png', '4_of_clubs.png', '5_of_clubs.png', '6_of_clubs.png', '7_of_clubs.png', '8_of_clubs.png', '9_of_clubs.png', '10_of_clubs.png', 'jack_of_clubs.png','queen_of_clubs.png', 'king_of_clubs.png', 'ace_of_clubs.png']
arrDiamonds=['2_of_diamonds.png','3_of_diamonds.png', '4_of_diamonds.png', '5_of_diamonds.png', '6_of_diamonds.png', '7_of_diamonds.png', '8_of_diamonds.png', '9_of_diamonds.png', '10_of_diamonds.png', 'jack_of_diamonds.png','queen_of_diamonds.png', 'king_of_diamonds.png', 'ace_of_diamonds.png']
arrHearts=['2_of_hearts.png','3_of_hearts.png', '4_of_hearts.png', '5_of_hearts.png', '6_of_hearts.png', '7_of_hearts.png', '8_of_hearts.png', '9_of_hearts.png', '10_of_hearts.png', 'jack_of_hearts.png','queen_of_hearts.png', 'king_of_hearts.png', 'ace_of_hearts.png']
arrSpades=['2_of_spades.png','3_of_spades.png', '4_of_spades.png', '5_of_spades.png', '6_of_spades.png', '7_of_spades.png', '8_of_spades.png', '9_of_spades.png', '10_of_spades.png', 'jack_of_spades.png','queen_of_spades.png', 'king_of_spades.png', 'ace_of_spades.png']
//console.log(arrClubs);
var player1Score = 0;
var player2Score = 0;
//get random suit. 1 = Clubs, 2 = Diamonds, 3 = Hearts, 4 = Spades.
var suitType = Math.ceil(Math.random() * 4)
var card = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
console.log(arrClubs[card])
selectedCard = arrClubs[card]
} else if(suitType == "2"){
console.log(arrDiamonds[card])
selectedCard = arrDiamonds[card]
} else if (suitType == "3"){
console.log(arrHearts[card])
selectedCard = arrHearts[card]
} else {
console.log(arrSpades[card])
selectedCard = arrSpades[card]
}
document.getElementById('p1Card').src = "./images/cards/" + selectedCard
//Player 2 Randomly Selected Card:
var suitType = Math.ceil(Math.random() * 4)
var card2 = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
// console.log(arrClubs[card2])
selectedCard = arrClubs[card2]
} else if(suitType == "2"){
// console.log(arrDiamonds[card2])
selectedCard = arrDiamonds[card2]
} else if (suitType == "3"){
//console.log(arrHearts[card2])
selectedCard = arrHearts[card2]
} else {
//console.log(arrSpades[card2])
selectedCard = arrSpades[card2]
}
document.getElementById('p2Card').src = "./images/cards/" + selectedCard;
if (card < card2){
player2Score++;
document.getElementById('player2Results').value = player2Score;
// alert("Player 2 Wins")
} else if (card > card2){
player1Score++;
document.getElementById('player1Results').value = player1Score;
// alert("Player 1 wins")
} else {
// alert("TIE!")
console.log('Tie!');
}
})
<!DOCTYPE html>
<html lang="en">
<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>War</title>
</head>
<body>
<div> Game</div>
<img src="./images/cards/black_joker.png" id="p1Card">
<img src="./images/cards/red_joker.png" id="p2Card">
<input type="text" readonly id="player1Results"/>
<input type="text" readonly id="player2Results"/>
<button id="play">Play</button>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="./js/index.js"></script>
</body>
</html>

Most likely you are setting player1Score and player2Score back to 0 each time you run it. Here's a working example:
const runGame = (() => {
var player1Score = 0;
var player2Score = 0;
return () => {
const card = Math.random();
const card2 = Math.random();
if (card < card2){
player2Score++;
console.log('Player 2 Wins! Score: ' + player2Score);
document.getElementById('p2').value = player2Score;
} else if (card > card2){
player1Score++;
console.log('Player 1 Wins! Score: ' + player1Score);
document.getElementById('p1').value = player1Score;
} else {
console.log('Tie!');
}
}
})();
document.getElementById('play').addEventListener('click', runGame);
<div id="player1Results"></div>
<div id="player2Results"></div>
<input type="text" readonly id="p1"/>
<input type="text" readonly id="p2"/>
<button id="play">Play</button>

Related

running a setInterval function before previous instance is done on diffrent event.target

Im trying shuffle the words on mouseover, but to shuffle a new word the previous word have be finished shuffling. This is because otherwise i will get an event.target.innerHTML of a word made up of random letters, if i mouseover the word while the alogorithm is shuffling.
How can i get over this problem, and shuffle any word on mouseover unless that specific word is allready shuffling?
var interv = 'undefined'
var canChange = false
var globalCount = 0
var count = 0
var isGoing = false
document.querySelectorAll("span").forEach((button) => button.addEventListener("mouseover", shuffleWord));
let texxt = document.querySelector('p');
console.log(texxt);
function shuffleWord(event){
let INITIAL_WORD = event.target.innerHTML;
if(isGoing) return;
var randomWord = getRandomWord(INITIAL_WORD);
event.target.innerHTML = randomWord;
isGoing = true;
interv = setInterval(function() {
var finalWord = ''
for(var x=0;x<INITIAL_WORD.length;x++) {
if(x <= count && canChange) {
finalWord += INITIAL_WORD[x]
} else {
finalWord += getRandomLetter()
}
}
event.target.innerHTML = finalWord
if(canChange) {
count++
}
if(globalCount >= 20) {
canChange = true
}
if(count>=INITIAL_WORD.length) {
clearInterval(interv)
count = 0
canChange = false
globalCount = 0
isGoing = false
}
globalCount++
},40)
function getRandomLetter() {
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
return alphabet[rand(0,alphabet.length - 1)]
}
function getRandomWord(word) {
var text = word;
console.log(text);
INITIAL_WORD = event.target.innerText;
var finalWord = ''
for(var i=0;i<text.length;i++) {
finalWord += text[i] == ' ' ? ' ' : getRandomLetter()
}
return finalWord
}
function rand(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
}
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<span>SOME RANDOM TEXT</span>
<br>
<br>
<span>MORE TEXT</span>
<br>
<br>
<span>EVEN MORE TEXT</span>
<script src="script.js"></script>
</body>
</html>

Increment number of attempts and decrement number of guesses remaining

I am new to JS, I want to the code to display number of attempts made, number of guesses remaining in this simple game. I have gotten lost in the code and I don't know what I am not doing right. The const remainingAttempts returns undefined yet I want to subtract number of attempts made from maxNumberOfAttempts.
const guessInput = document.getElementById("guess");
const submitButton = document.getElementById("submit");
const resetButton = document.getElementById("reset");
const messages = document.getElementsByClassName("message");
const tooHighMessage = document.getElementById("too-high");
const tooLowMessage = document.getElementById("too-low");
const maxGuessesMessage = document.getElementById("max-guesses");
const numberOfGuessesMessage = document.getElementById("number-of-guesses");
const correctMessage = document.getElementById("correct");
let targetNumber;
let attempts = 0;
let maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = "";
} else {
tooHighMessage.style.display = ""; //replaced else condition statement
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts === maxNumberOfAttempts) {
maxGuessesMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = "";
resetButton.style.display = "";
}
function hideAllMessages() {
/*replaced elementIndex <= messages.length to elementIndex < messages.length*/
for (let elementIndex = 0; elementIndex < messages.length; elementIndex++) {
messages[elementIndex].style.display = "none"; //removed [elementIndex]
}
// for (let message in messages.value) {
// //used for..in to iterate through the HTML collection
// message.style.display = "none";
// }
}
function setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabled = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = "none";
}
submitButton.addEventListener("click", checkGuess);
resetButton.addEventListener("click", setup);
setup();
main {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin: auto;
}
#guess {
width: 5em;
}
#reset {
margin: 20px;
}
<!DOCTYPE html>
<html lang="en">
<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" />
<link href="guess.css" rel="stylesheet" />
<title>Number Guesser</title>
</head>
<body>
<main>
<h1>Guessing Game</h1>
<p>
I'm thinking of a number from 1 to 99! Can you guess it in 5 tries or
less?
</p>
<div>
<input type="number" id="guess" min="1" max="99" />
<button id="submit">Submit Guess</button>
</div>
<div>
<p class="message" id="number-of-guesses"></p>
<p class="message" id="too-high">You guessed too high. Try again.</p>
<p class="message" id="too-low">You guessed too low. Try again.</p>
<p class="message" id="max-guesses">
You reached the max number of guesses
</p>
<p class="message" id="correct">
Congratulations, You guessed correctly! <br />
Would you like to play again?
</p>
</div>
<button id="reset">Reset</button>
</main>
<script src="guess.js"></script>
</body>
</html
just increment attempts as attempts++; below const remainingAttempts = maxNumberOfAttempts - attempts;. this should solve the no. of attempts part.
In setup(), when you reset the number of attempts, you should be setting it to 5: maxNumberOfAttempts = 5;
Additionally, in checkGuess(), you should:
Make sure to decrease the number of attempts with each guess. Add maxNumberOfAttempts-- at the top of the function.
At the bottom of if (guess !== targetNumber), you can replace the variable in the message from ${remainingAttempts} to ${maxNumberOfAttempts}
, since maxNumberOfAttempts is now keeping track of the amount of attempts remaining.
Lastly, the next if statement can check if the user is out of attempts with if (maxNumberOfAttempts === 0) {...}
This eliminates the need to use 3 different 'attempt' variables since you're resetting back to '5' at each instance of setup() anyway.

Javascript textcontent is not displaying anything

I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.

Images not showing up in Javascript

This is supposed to be a dice game where 2 people click to roll dice and they add what they get until they reach the goal. Their score resets if they roll over 9 though. Images of dice are supposed to pop up and show what they rolled. I know the images are not on here but it still shows that there should an image there with the error symbol. I am having trouble with the second image not showing up which should come from the SetPic2 function. Any help would be appreciated. Also, the PASS buttons are supposed the pass the person's turn to the other player but the main problem is the images.
//console.log("file loaded");
//var p1Button = document.getElementById("p1");
var p1Button = document.querySelector("#p1");
var p2Button = document.querySelector("#p2");
var P1Pass = document.querySelector("P1Pass");
var P2Pass = document.querySelector("P2Pass");
var setButton = document.querySelector("#set");
var resetButton = document.querySelector("#reset");
var diceImage = document.querySelector("img");
var diceImage2 = document.querySelector("img2");
var p1Total = document.querySelector("#p1score");
var p2Total = document.querySelector("#p2score");
var targetScore = document.querySelector("#tscore");
var newScore = document.querySelector("#newtarget");
var num = 0,
num2 = 0,
p1val = 0,
p2val = 0,
target;
var playgame = true;
target = Number(targetScore.textContent); //convert the string to num
p1Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p1val = p1val + num + num2;
p1Total.textContent = p1val;
setButton.disabled = true;
p1Button.disabled = true;
p2Button.disabled = false;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p1val = 0;
}
if (p1val >= target) {
playgame = false;
p1Total.classList.add("winner");
stopGame();
}
}
});
p2Button.addEventListener("click", function() {
if (playgame) {
//Math.random() --> return a value between 0 & 1
num = Math.floor((Math.random() * 6) + 1);
num2 = Math.floor((Math.random() * 6) + 1);
p2val = p2val + num + num2;
p2Total.textContent = p2val;
setButton.disabled = true;
p1Button.disabled = false;
p2Button.disabled = true;
setPic(num);
setPic2(num2);
if (num + num2 > 9) {
p2val = 0;
}
if (p2val >= target) {
playgame = false;
p2Total.classList.add("winner");
stopGame();
}
}
});
/*P1Pass.addEventListener("click", function(){
p1Button.disabled= true;
p2Button.disabled = false;
});
P2Pass.addEventListener("click", function(){
p1Button.disabled = false;
p2Button.disabled = true;
});*/
setButton.addEventListener("click", function() {
targetScore.textContent = newScore.value;
target = Number(targetScore.textContent);
setButton.disabled = true;
newScore.disabled = true;
});
resetButton.addEventListener("click", function() {
p1Button.disabled = false;
p2Button.disabled = true;
p1Total.textContent = "0";
p2Total.textContent = "0";
targetScore.textContent = "25";
setButton.disabled = false;
newScore.disabled = false;
p1Total.classList.remove("winner");
p2Total.classList.remove("winner");
playgame = true;
p1val = 0;
p2val = 0;
target = 25;
});
function stopGame() {
p1Button.disabled = true;
p2Button.disabled = true;
setButton.disabled = true;
newScore.disabled = true;
}
function setPic(val) {
if (val == 1) {
diceImage.src = "1.png";
} else if (val == 2) {
diceImage.src = "2.png";
} else if (val == 3) {
diceImage.src = "3.png";
} else if (val == 4) {
diceImage.src = "4.png";
} else if (val == 5) {
diceImage.src = "5.png";
} else if (val == 6) {
diceImage.src = "6.png";
}
}
function setPic2(val2) {
if (val2 == 1) {
diceImage2.src = "1.png";
} else if (val2 == 2) {
diceImage2.src = "2.png";
} else if (val2 == 3) {
diceImage2.src = "3.png";
} else if (val2 == 4) {
diceImage2.src = "4.png";
} else if (val2 == 5) {
diceImage2.src = "5.png";
} else if (val2 == 6) {
diceImage2.src = "6.png";
}
}
.winner {
color: green;
background-color: yellow;
}
;
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initialscale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap
.min.css" integrity="sha384-
Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="gamestyle.css">
<title>Dice Game</title>
</head>
<body>
<div class="container">
<br>
<h1> <span id="p1score">0</span> vs. <span id="p2score">0</span> </h1>
<br>
<p>Target-Score: <span id="tscore">25</span></p>
<br>
<button class="btn btn-success" id="p1"> Player One </button>
<button class="btn btn-warning" id="p2"> Player Two </button>
<br><br>
<button class="btn btn-secondary" id="P1Pass">PASS</button>
<button class="btn btn-secondary" id="P2Pass">PASS</button>
<br><br> New Target: <input type="number" id="newtarget">
<br><br>
<button class="btn btn-primary" id="set"> Set </button>
<button class="btn btn-danger" id="reset"> Reset </button>
<br><br>
<img src="">
<img src="">
</div>
<script src="gamefunction.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-
J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min
.js" integrity="sha384-
Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.m
in.js" integrity="sha384-
wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
Your selector will not finding your second image element.
var diceImage2 = document.querySelector("img2");
You could give your images IDs and reference them directly:
HTML
<img id="die1" src="" />
<img id="die2" src="" />
JS
var diceImage1 = document.getElementById('die1');
var diceImage2 = document.getElementById('die2');

Reset Function for dice rolling game

I have worked for a while on this code for learning purposes. I finally got the program to work, however when you "roll the dice", it only allows the dice to be rolled 1 time; If you wish to roll the dice a second time you must refresh the screen.
I am trying to build a reset function for this program so that I can roll the dice as many times as I wish without a screen-refresh.
I have built the reset function, but It is not working... It clear's the DIV's, but doesn't allow the program to be executed again.
Can someone please help me out?
*I am a semi-noobie at Javascript, I am making programs like this to practice my skills.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dice Rolling</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header>
<h1>Roll the Dice!</h1>
<h2>By: Jeff Ward</h2>
</header>
<h3>Setup your Dice!</h3>
<div id="left">
<form id="numberOfDiceSelection">
Number Of Dice Used:
<br>
<input id="numberOfDice" type="text" name="numberOfDice">
</form>
</div>
<div id="right">
<form id="diceSidesSelection">
Number of sides on each dice:
<br>
<input id="diceSides" type="text" name="diceSides">
</form>
</div>
<button type="button" onclick="roll()">Roll the Dice!</button>
<button type="button" onclick="reset()">Reset Roll</button>
<div id="output">
</div>
<div id="output1">
</div>
<script src="js/script.js"></script>
</body>
</html>
JavaScript:
function roll() {
var text = "";
var sides = +document.getElementById("diceSides").value;
var dice = +document.getElementById("numberOfDice").value;
var rolls = [];
// --------Ensures both Numbers are Intergers-----------
if (isNaN(sides) || isNaN(dice)) {
alert("Both arguments must be numbers.");
}
// --------Loop to Print out Rolls-----------
var counter = 1;
do {
roll = Math.floor(Math.random() * sides) + 1;
text += "<h4>You rolled a " + roll + "! ----- with dice number " + counter + "</h4>";
counter++;
rolls.push(roll);
}
while (counter <= dice)
document.getElementById("output").innerHTML = text;
// --------Double Determination-----------
var cache = {};
var results = [];
for (var i = 0, len = rolls.length; i < len; i++) {
if (cache[rolls[i]] === true) {
results.push(rolls[i]);
} else {
cache[rolls[i]] = true;
}
// --------Print amount of Doubles to Document-----------
}
if (results.length === 0) {} else {
document.getElementById("output1").innerHTML = "<h5> You rolled " + results.length + " doubles</h5>";
}
}
// --------RESET FUNCTION-----------
function reset() {
document.getElementById("output1").innerHTML = "";
document.getElementById("output").innerHTML = "";
document.getElementById("diceSides").value = "";
document.getElementById("numberOfDice").value = "";
text = "";
rolls = [];
}
Thank you!!
JSFiddle Link = https://jsfiddle.net/kkc6tpxs/
I rewrote and did what you were trying to do:
https://jsfiddle.net/n8oesvoo/
var log = logger('output'),
rollBtn = getById('roll'),
resetBtn = getById('reset'),
nDices = getById('numofdices'),
nSides = getById('numofsides'),
dices = null,
sides = null,
rolls = [],
doubles=0;
rollBtn.addEventListener('click',rollHandler);
resetBtn.addEventListener('click', resetHandler);
function rollHandler() {
resetView();
sides = nSides.value;
dices = nDices.value;
doubles=0;
rolls=[];
if(validateInput()) {
log('invalid input');
return;
}
//rolling simulation
var rolled;
while (dices--) {
rolled = Math.ceil(Math.random()*sides);
log('For Dice #'+(dices+1)+' Your Rolled: '+ rolled +'!');
rolls.push(rolled);
}
//finding doubles
//first sort: you can use any way to sort doesnt matter
rolls.sort(function(a,b){
return (a>b?1:(a<b)?0:-1);
});
for (var i =0; i < rolls.length; i++) {
if (rolls[i] == rolls[i+1]) {
doubles++;
i++;
}
}
if (doubles>0) log("You rolled " + doubles + " doubles");
}
function resetHandler(){
resetView();
nDices.value = nSides.value = '';
}
function resetView() {
getById('output').innerText = '';
}
function validateInput(){
return (isNaN(sides) || sides == '' || isNaN(dices) || dices == '');
}
function logger(x) { var output = getById(x);
return function(text){
output.innerText += text + '\n';
};}
function getById(x){ return document.getElementById(x); }

Categories