I am making a dice game where you roll dice. When you roll a number that number adds to your total score. But when you roll a 1 you lose your total score and it switches to the other player. You can also hold to switch player.
As it is right now it become 0 after getting a 1 the first time. My problem is that when you switch back to the original starter player the score that was there before comes back. Like it does not stay the value of 0 but only looks like it.
var swithcing = false;
var current1 = 0;
var total1 = 0;
var current2 = 0;
var total2 = 0;
function roll() {
var randomnumber = Math.floor(Math.random() * 6) + 1;
var player1score = document.querySelector('.player1total');
var player1curent = document.querySelector('.player1');
var player2score = document.querySelector('.player2total')
var player2curent = document.querySelector('.player2')
if (randomnumber == 1) {
swithcing = !swithcing;
player1score.innerHTML = 0;
player1curent.innerHTML = 0;
player2curent.innerHTML = 0;
}
if (randomnumber == 1 && swithcing == false) {
player2score.innerHTML = 0;
}
if (swithcing == true) {
current2 += randomnumber;
player2score.innerHTML = current2;
player2curent.innerHTML = randomnumber;
}
if (swithcing == false) {
current1 += randomnumber;
player1score.innerHTML = current1;
player1curent.innerHTML = randomnumber;
}
}
function hold() {
swithcing = !swithcing;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I think your code should look something like this
let switching = false;
let current1 = 0;
let total1 = 0;
let current2 = 0;
let total2 = 0;
let randomnumber = 0
const player1score = document.querySelector('.player1total');
const player1current = document.querySelector('.player1');
const player2score = document.querySelector('.player2total');
const player2current = document.querySelector('.player2');
function roll() {
randomnumber = Math.floor(Math.random() * 6) + 1;
//console.log(randomnumber);
//logic for normal rolls
if(randomnumber > 1){
if(switching==true){
current2=randomnumber;//set to number rolled
total2+=randomnumber;//sum to total score
} else {
current1=randomnumber;//set to number rolled
total1+=randomnumber;//sum to total score
}
}
//logic if player loses
if (randomnumber == 1) {
//switch
switching = !switching;
//if switches to player 2
current1=0;//reset
current2=0;//reset
if(switching==true){
//console.log("Player 2 selected");
total2+=total1//total becomes player 1 previous total
total1=0;//player 1 total resets
} else {
//console.log("Player 1 selected");
total1+=total2//total becomes player 2 previous total
total2=0;//player 2 total resets
}
}
player1score.textContent = total1;
player1current.textContent = current1;
player2current.textContent = current2;
player2score.textContent = total2;
}
function hold() {
switching = !switching;
player1score.textContent = total1;
player1current.textContent = 0;
player2current.textContent = 0;
player2score.textContent = total2;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
Building a countdown Timer with rounds, working and resting for training.
Issue: My timer seems to start fine (with the user inputted values) after the first round, once rest is done, my working timer doesn't start at the inputted value like it should. It's always one number short.
E.g If you input 5: 10: 10. When it comes back around, it will appear one number shorter than it should 4: 09: 00
From the left the Timer is rounds, working, rest.
Please help.
let rnd = '00';
let wrk = 00; // this will act as my seconds
let rst = '00';
let prepare =3;
let interval;
let rstInterval;
let startTimer = '00';
// store the working set in an array
let prepIn = document.getElementById('prep');
prepIn.innerHTML = prepare;
// buttons
document.getElementById('start').addEventListener('click', initTimer);
document.getElementById('pause').addEventListener('click', pauseTimer);
document.getElementById('reset').addEventListener('click', finishTimer);
let span= document.getElementById('app').getElementsByTagName('span');
function initTimer(){
clearInterval(interval)
let rounds = document.querySelector('.rounds').value;
rnd = rounds;
span[0].innerHTML = rnd
let work = document.querySelector('.work').value;
wrk = work;
startTimer = work;
span[1].innerHTML =wrk
let rest = document.querySelector('.rest').value;
rst = rest;
span[2].innerHTML = rst
console.log(startTimer)
interval= setInterval(countDown, 1000);
}
// Pause the timer
function pauseTimer(){
clearInterval(interval);
console.log("pauseTimer")
}
// reset timer
function finishTimer(){
clearInterval(interval);
span[0].innerHTML = '00'
span[1].innerHTML = '00'
span[2].innerHTML = '00'
rnd = '00';
wrk = '00';
rst = '00';
document.querySelector('.timeNum').style.display = "flex"
}
function countDown(){
prepare--
if(prepare < 10){
prepIn.innerHTML = '0' + prepare;
}
if(prepare >=9){
prepIn.innerHTML = prepare;
}
if(prepare <= 3){
prepIn.style.color = 'green';
}
if(prepare < 1){
clearInterval(interval)
prepare = 00
prepIn.style.display = 'none'
clearInterval(startTimer)
startTimer= setInterval(timerActive, 1000);
let work = document.querySelector('.work').value;
wrk = work;
console.log(wrk)
}
document.querySelector('.timeNum').style.display = "none";
}
function timerActive(){
wrk--
if(wrk <=9){
span[1].innerHTML = '0' + wrk;
}
if(wrk >=10){
span[1].innerHTML = wrk;
}
if(wrk <= 0){
clearInterval(startTimer)
let rest = document.querySelector('.rest').value;
rst = rest
let rstInterval = setInterval(() => {
rst--
if(rst<=9){
span[2].innerHTML = '0' + rst;
}
if(rst >=10){
span[2].innerHTML = rst;
}
if(rst < 1){
clearInterval(rstInterval)
rstcount();
}
},1000)
rnd--
if(rnd <10){
span[0].innerHTML = '0'+ rnd;
}
else{
span[0].innerHTML = rnd;
}
}
};
function rstcount(){
clearInterval(rstInterval);
countDown();
}
<div class="timer">
<div class="numb">
<h2 id="prep"></h2>
<h2 id="app"><span>00</span>:<span>00</span>:<span>00</span></h2>
<h1 class="timeNum"><input type='number' min="00" max="99" class="rounds" value='00'>:<input type='number' min="00" max="99" class="work" value="00">:<input type='number' min="00" max="99" class="rest" value="00"></h1>
<div class="buttons">
<input type="button" id="start" value="Start">
<input type="button" id="pause" value="Pause">
<input type="button" id="reset" value="Reset">
</div>
</div>
</div>
So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Your if statement is absolutely fine, the reason you never see the message "Please enter a Number between ${min} and ${max}" is because you let the code continue, and almost immediately that message is overwritten by a different one. Simply adding a return statement within your if block will solve this problem.
Note I also fixed this line guessInput = ''; which should be guessInput.value = '';
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
return; // here
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput.value = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Try changing the const to let. You're editing all these later in your code:
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>
I am trying to perform calculation using JavaScript. When user enter less than 10 pages in input (#page) the cost is 1. if he adds more than 10, each page costs .10. there are 2 options for checkbox, if he clicks first checkbox 10 is added and second checkbox 15 is added.
This is working when it is done in sequential steps. (input then clicking checkbox).
Ex: Input is : 9 (total: 1)
click checkbox1 - duplicates (total : 11)
click checkbox1 - laser (total: 26)
Now if i change the Input to 11, then the total becomes 1.10 - even if both the checkboxes are checked.. (expected result should be - 26.10)
I am not sure how to do this...can anyone help me out
<html>
<head>
<title>Calculation</title>
<script>
function calculate() {
var pages=document.getElementById("page").value;
if(pages <=10) {
total.value=1;
}
if(pages >= 11) {
var extra_pages= pages - 10;
var new_total= extra_pages * .10;
var new_total1= 1 + new_total;
total.value= new_total1;
}
}
function checkbox1() {
if(document.getElementById("ckbox1").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 10;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox1").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 10;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
function checkbox2() {
if(document.getElementById("ckbox2").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 15;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox2").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 15;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
</script>
<body>
Enter a Number: <input type="text" id="page" value="1" oninput="calculate()">
<br>
<br><br><br><br>
duplicates <input type="checkbox" id="ckbox1" onclick="checkbox1()">
laser print: <input type="checkbox" id="ckbox2" onclick="checkbox2()"> <br><br>
Total: <input type="text" id="total">
</body>
</html>
You can use calculate for all changes instead of creating each one for each input, which makes the calculation complex.
// Get reference to inputs.
var page = document.getElementById("page");
var total = document.getElementById("total");
var dup = document.getElementById("ckbox1");
var laser = document.getElementById("ckbox2");
function calculate() {
// To Number
var pages = parseInt(page.value, 10);
var value = 0;
if (pages <= 10) {
value = 1;
} else {
var extra_pages = pages - 10;
var new_total = extra_pages * .10;
var new_total1 = 1 + new_total;
value = new_total1;
}
// Add 10 if dup is checked.
if (dup.checked) {
value += 10;
}
// Add 15 if laser is checked.
// These can be moved out like
// const laserVal = 15;
// value += laserVal if you don't want magic number here.
if (laser.checked) {
value += 15;
}
// Truncate float.
total.value = value.toFixed(1);
}
Enter a Number:
<input type="text" id="page" value="1" oninput="calculate()">
<br>
<br>
<br>
<br>
<br>
duplicates:<input type="checkbox" id="ckbox1" onclick="calculate()">
laser print:<input type="checkbox" id="ckbox2" onclick="calculate()">
<br>
<br>Total:
<input type="text" id="total">