Iam trying to give 2 different colors on my timer countdown apps..
on workout timer will be green.
on rest timer will be red. (and the color will be red until end)
my question is how to make the timer back to green after rest timer(red) and back to red after green(workout timer)
document.getElementById('start').addEventListener('click', startCountdown);
function startCountdown() {
let counter = 3,
mode = "Workout",
rounds = 1;
const interval = setInterval(function() {
counter--;
if (mode == "Workout" && counter >= 0) {
id = document.getElementById("count");
id.innerHTML = "ROUND " + rounds + " <br> " + counter;
id.classList.add('green') <<<THE FRIST COLOR RUNNING WELL
} else {
id = document.getElementById("count");
id.innerHTML = "REST " + " <br> " + counter;
id.classList.add('red') <<< SECOND COLOR RUNNING WELL
}
if (counter === 0) {
if (mode == "Workout") {
mode = "Rest";
} else {
mode = "Workout";
rounds++;
}
id.innerHTML = "DONE";
counter = 3;
if (rounds == 21) {
clearInterval(interval);
}
}
}, 1000);
add this near line 9
(mode == "Workout" && counter >= 0) ? clsnm="green" : clsnm="red";
and pass this variable near id.classList.add(clsnm)
alternatively you can also try to add id.classList.remove('class_name') before id.classList.add('class_name')
Related
My game has two players that get random numbers, and the person who has the bigger number gets 1 "win". My while loop is for the "auto-roll" button, and instead of clicking "roll dice" each time, auto-roll will do it for you until one player has wins == game limit # (bestof.value). No matter where I put my setInterval it increases by a bunch at a time. If bestof.value = 10 then each interval displays at least 10 wins for one player at a time.
checkBox.checked = input checkmark that enables auto-roll feature. So this setInterval will only be active while the auto-roll loop is active.
Anyways, what am I doing wrong?
button.addEventListener("click", myFunction);
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
screenID.innerHTML = random;
screenIDD.innerHTML = random2;
if (random > random2){
winNumber.innerHTML = ++a;
} else if(random2 > random){
winNumba1.innerHTML = ++b;
} else {
console.log("Draw");
}
if (a > b){
winNumber.style.color = 'white';
winNumba1.style.color = 'black';
} else if(b > a){
winNumba1.style.color = 'white';
winNumber.style.color = 'black';
} else {
winNumber.style.color = 'black';
winNumba1.style.color = 'black';
}
if (checkBox.checked){
setInterval(myFunction, 2000)
while(a < bestof.value && b < bestof.value){
myFunction();
}};
if (winNumba1.innerHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumba1 wins!');
} else if (winNumber.innterHTML == bestof.value){
winAlert.style.display = "flex";
console.log('winNumber wins!');
} else {}
};
I wrote a simplified js only version of your game here since I don't have html at hand, but I am sure you can adjust it to your environment.
Main difference: I check if someone won and use return to stop the function
If no one won and autoplay is activated I autoplay after 500ms again.
let playerA = 0
let playerB = 0
let autoPlay = true
let bestOf = 3
function myFunction() {
let random = Math.floor((Math.random() * 6) + 1);
let random2 = Math.floor((Math.random() * 6) + 1);
console.log("New Round " + random + " vs " + random2)
if (random > random2) {
playerA++
} else if (random2 > random) {
playerB++
} else {
console.log("Draw");
}
if (playerA > playerB) {
console.log("a is winning")
} else if (playerB > playerA) {
console.log("b is winning")
} else {
console.log("There has been a draw")
}
if (playerA == bestOf) {
console.log('A won');
return
} else if (playerB == bestOf) {
console.log('B won');
return
}
if (autoPlay) {
setTimeout(myFunction, 500)
};
};
myFunction()
all the code was given by the teacher and you just had to place it in the right spot. even working with the teacher we couldn't get it to update the "value" attribute in between turns. it updates at the finish of the game but not during? what are we not seeing? any help appreciated.. if you need to see html i can add as comment
"use strict";
var $ = function(id) { return document.getElementById(id); };
var getRandomNumber = function(max) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
return random;
};
var playGame = function() {
var odd = 0;
var even = 0;
var player, computer, total;
resetFields(); // clear any previous entries
while (odd < 50 && even < 50) {
//get computers fingers
computer = getRandomNumber(5);
// get player's fingers
player = parseInt(prompt("Enter a number between 1 and 5, or 999 to quit", 999));
if (!isNaN(player) && player <= 5) {
// show current round
$("player").value = player;
$("computer").value = computer;
// update totals
total = player + computer;
if (total % 2 === 0) {
even = even + total;
$("even").value = even;
} else {
odd = odd + total;
$("odd").value = odd;
}
}
//if loop for player quitting
if (player === 999) {
resetFields();
break;
}
}
//after loop ends, determine winner
if (odd >= 50) { $("message").firstChild.nodeValue = "You WIN!"; }
else if (even >= 50) { $("message").firstChild.nodeValue = "You lose :("; }
else { $("message").firstChild.nodeValue = "You quit"; }
// set focus on button so you can play again
$("play").focus();
};
var resetFields = function() {
$("player").value = "0";
$("computer").value = "0";
$("odd").value = "0";
$("even").value = "0";
$("message").firstChild.nodeValue = "";
};
window.onload = function() {
$("play").onclick = playGame;
$("play").focus();
};
I'm making a JavaScript/jQuery version of a dice game my buddies and I play. Here's a 3 player version of the game:
http://codepen.io/jwnardini/pen/jmygqd
I'm trying to make a version of the game where the user can select how many players are playing, and have the game function in the same way:
http://codepen.io/jwnardini/pen/ZKLVqW
Every time the "Go" button is pressed, it's supposed to move on to the next person's turn, and I use a modular operator if condition in a for loop to check whose turn it is, so i can perform a specific action on their turn.
var turn = 0;
$(".goButton").click(function() {
turn = turn + 1;
var playerCount = $('#input-number').val();
for (i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
});
This works great for every player I've created, except the last one (player# playerCount). This is because playerCount % playerCount = 0, and i is never 0, so the last player is always skipped.
I tried to work around this with an else statement for when turn % playerCount = 0 :
var turn = 0;
$(".goButton").click(function() {
turn = turn + 1;
var playerCount = $('#input-number').val();
for (i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
} else if (turn % playerCount == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
}
});
However, when I reach player# playerCount's turn, I get playerCount times "hi!" appended. For example, for 5 players, this is the output in browser:
Player 1
$3Hi!
Player 2
$3Hi!
Player 3
$3Hi!
Player 4
$3Hi!
Player 5
$3Hi!Hi!Hi!Hi!Hi!
Is this a classic "off by 1" error on my part? Or is my else statement flawed in some way?
The problem is your loop, when you iterate over playerCount and try to get the class name to append to.
Instead of the entire loop, try to do the following:
var m = turn % playerCount;
if (m==0) {m = playerCount};
$(".player" + m + "dollars").append("Hi!");
take out the 4th player condition outside the loop. the problem is when turn ==playercount, u dont have to enter the loop because that condiiotn is independant of i and will always be true hence hgetting executed times.
for (var i=1;i <= playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
if (turn % playerCount == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
here is the code working code snippet :
var turn = 0;
var pot = 0;
$("form").submit(function(event){
var i = 0
var playerCount = $('#input-number').val();
var dollarCounts = [];
$(".players").empty();
for (var i=1; i <= playerCount; i++) {
var player= "player";
player = player + i.toString();
$(".players").append(
'<div class="player-wrap"><div class="player' + i.toString() + ' clearable">Player '
+ i +
'</div>$<span class="' + player + 'dollars clearable"></span><br><br><br></div>');
dollarCounts[i] = 3;
$("." + player + "dollars").empty().append(dollarCounts[i]);
}
event.preventDefault();
});
//TURN
$(".goButton").click(function() {
turn = turn + 1;
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
var dice3 = Math.floor(Math.random() * 6) + 1;
$(".turn").empty().append(turn);
//Print "Left", "Right", "Center"
if (dice1 == 1) {
$(".d1").empty().append("LEFT");
}
if (dice2 == 1) {
$(".d2").empty().append("LEFT");
}
if (dice3 == 1) {
$(".d3").empty().append("LEFT");
}
if (dice1 == 2) {
$(".d1").empty().append("RIGHT");
}
if (dice2 == 2) {
$(".d2").empty().append("RIGHT");
}
if (dice3 == 2) {
$(".d3").empty().append("RIGHT");
}
if (dice1 == 3) {
$(".d1").empty().append("CENTER");
}
if (dice2 == 3) {
$(".d2").empty().append("CENTER");
}
if (dice3 == 3) {
$(".d3").empty().append("CENTER");
}
if (dice1 == 4 || dice1 == 5 || dice1 == 6) {
$(".d1").empty().append("SAFE");
}
if (dice2 == 4 || dice2 == 5 || dice2 == 6) {
$(".d2").empty().append("SAFE");
}
if (dice3 == 4 || dice3 == 5 || dice3 == 6) {
$(".d3").empty().append("SAFE");
}
var playerCount = $('#input-number').val();
for (var i=1;i < playerCount;i++){
if (turn % playerCount == i) {
$(".player" + i + "dollars").append("Hi!");
}
}
if (turn % i == 0) {
$(".player" + playerCount + "dollars").append("Hi!");
}
});
//RESET
$(".resetButton").click(function() {
turn = 0;
pot = 0;
$(".players").empty();
var playerCount = 0;
var dollarCounts = [];
$(".turn").empty().append(turn);
$(".pot").empty().append(pot);
$(".d1").empty();
$(".d2").empty();
$(".d3").empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="start-form">
<label for="input-number">Number of players:</label>
<input id="input-number" type="number">
<button type="submit" class="btn">Set Player Count</button>
</form>
<button class="goButton" type="submit">Go</button>
<button class="resetButton" type="submit">Reset</button>
<br><br>
<div class="players"></div>
<h1>Turn count: <span class="turn"></span></h1>
<h2>Rolls:
<span class="d1"></span>
<span class="d2"></span>
<span class="d3"></span>
</h2>
<br>
<br>
<br>
<br>
<br>
<h1>POT</h1>
<div class="pot"></div>
So I want something like this:
As you can see, there's a + and - button, to which if clicked, they show respective values appended at No. of Units.
All in all, what I want is:
for example, if I clicked the + four times, it will show 12+4 (the +4 part with green color)
and if I clicked the - six times, it will then show 12-2 (the -2 part with red color),
and if I clicked the - another ten times, it will stop at the value 12-12 and prompt/alert Do you really want to delete this load? (same function as the x button at the rightmost).
The problem you see is, the adding of increment values works (if I click the + many times), but if I decrement it, it would only stop at 0 and alternates between 0 and 1 (the operationg used is still + and not - though), and not to the maximum default value (which in the picture above, is 12).
Also, if I clicked a decrement button first, it will only stop at 0 and the same case, it alternates between 0 and 1.
Why is this? Sorry, I was not able to commit the previous two iterations of this code but both have issues too (the first one works but it appends a -n value, thus 12--1 would appear, the second one would bypass the def value limit, it would reach 12-14 and so on). I am at a loss here already, so I would like some help. This is my jQuery code below.
PS. I'm constructing the rows through a jQuery DataTables, so I can't show the code that adds the rows because it is not too relevant.
PS(2). Here's the JSFiddle implementation of the above.
PS(3). It would be very appreciated if you modify the code below to your liking, as log as it FOLLOWS SUIT the THREE USE CASES STATED ABOVE. Thank you so much.
jQuery
// For increment and decrement no. of units
var def = $('#costcenter_data tr').find('td:nth-child(2)').html(); // default value or the "12" in the example
var out = def;
// Increment button
$('.btn.btn-xs.btn-primary.add-unit').click(function(e){
var count = $('#costcenter_data tr').find('td:nth-child(2)');
var value = parseInt(count.data('change_value'));
var clicked;
if (isNaN(value) && isNaN(prev)) {
value = 1;
count.data('clicked', "+")
} else {
value++;
}
var prev = count.data('clicked');
if (prev != "+") {
clicked = "-";
} else {
clicked = prev;
}
$('#costcenter_data tr').find('td:nth-child(2)').html(out+clicked+value);
count.data('change_value', value);
count.data('clicked', "+");
});
// Decrement button
$('.btn.btn-xs.btn-warning.remove-unit').click(function(e){
var count = $('#costcenter_data tr').find('td:nth-child(2)');
var value = parseInt(count.data('change_value'));
var clicked;
if (isNaN(value) && isNaN(prev)) {
value = 1;
count.data('clicked', "-")
} else if ((value-1) < 0) {
value--;
value = Math.abs(value);
if (value == parseInt(def)) {
alert("Delete prompt here");
return false;
}
} else {
value--;
clicked = count.data('clicked');
}
var prev = count.data('clicked');
if (prev != "-") {
clicked = "+";
} else {
clicked = prev;
}
$('#costcenter_data tr').find('td:nth-child(2)').html(out+clicked+value);
count.data('change_value', value);
});
I've looked at your fiddle, make some changes in if statements, seems like its working now - https://jsfiddle.net/oscsz4wt/.
I've add default clicked value so it could be accessible from the beginning and changed if logic. Also clicked may be renamed to scope or something like this, so it would be more clear I think.
// For increment and decrement no. of units
var def = $('#costcenter_data tr').find('td:nth-child(2)').html();
var out = def;
$('.btn.btn-xs.btn-primary.add-unit').click(function(e) {
var count = $('#costcenter_data tr').find('td:nth-child(2)');
var value = parseInt(count.data('change_value'));
var clicked = count.data('clicked') || '+';
// If no value
if (isNaN(value) && isNaN(prev)) {
value = 1;
count.data('clicked', "+")
// If value is positive - increase number
} else if (value > 0 && clicked == '+') {
value++;
// If value is negative - decrease number
} else if (value > 0 && clicked == '-') {
value--;
// If value is 0 - increase number and change scope to '+'
} else if (value == 0) {
value++;
count.data('clicked', '+');
}
var prev = count.data('clicked');
if (prev != "+") {
clicked = "-";
} else {
clicked = prev;
}
$('#costcenter_data tr').find('td:nth-child(2)').html(out + clicked + value);
count.data('change_value', value);
});
$('.btn.btn-xs.btn-warning.remove-unit').click(function(e) {
var count = $('#costcenter_data tr').find('td:nth-child(2)');
var value = parseInt(count.data('change_value'));
var clicked = count.data('clicked') || '-';
// If no value
if (isNaN(value) && isNaN(prev)) {
value = 1;
count.data('clicked', "-")
// If value is positive and we are in '+' scope decrease number
} else if (value > 0 && clicked == '+') {
value--;
// If value is positive and we are in '-' scope increase number
} else if (value > 0 && clicked == '-') {
value++;
// If value is 0 - increase number and change scope to '-'
} else if (value == 0) {
value++;
count.data('clicked', '-');
}
if (value == parseInt(def) && clicked == '-') {
alert("Delete prompt here");
return false;
}
var prev = count.data('clicked');
if (prev != "-") {
clicked = "+";
} else {
clicked = prev;
}
$('#costcenter_data tr').find('td:nth-child(2)').html(out + clicked + value);
count.data('change_value', value);
});
I'm a new programmer learning HTML/CSS/Javascript, and was fiddling around with it until I came across a bug. I was making the computer guess my number (0-5), but then realized if I put in a number higher than 5, the website just crashes. Is there any way I can make it so that if the user puts in a number higher than 5 it will just delete it automatically? Or is that not Javascript. Thanks in advance :)
document.getElementById("guess").onclick=function() {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Try this :
document.getElementById("guess").onclick=function() {
if(document.getElementById("myNumber").value > 5) {
document.getElementById("myNumber").value = "";
alert("Please provide a number that is with in 0 to 5");
} else {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Than define a onchange function to check length:
document.getElementById("myNumber").onchange = function (ev){
try{
var target = document.getElementById("myNumber");
if(parseInt(target.value) > x) { // can throw exception, when given a non number
target.value="";
}
} catch(ex) {
alert('Not a number');
}
};
IMPORTANT:
You have a greater problem here: You are generating a random number, and then comparing it to input( that does not change). This is an infinite loop. Because this is a random operation, and you can hit same number more than once.
You need to generate your number first (before click event on 'guess' button), before clicking on quess button. Like so:
var luckyNumber = x;
var guesses=1;
document.getElementById("start").onclick=function(){ //init counters once
guesses=0;
x=Math.floor(Math.random()*6);
gotit = false;
}
document.getElementById("guess").onclick=function() { // guess as many times as you want
if(document.getElementById("myNumber").value==x) {
gotit=true;
}
guesses++;
if(gotit){
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
}
But if you want to computer to quess your number, than you need to limit number of guesses (add a counter), or it will hang eventualy.
I took this as a little challenge and just went ahead and re-did your little game. Hope this helps.
Demo here
(function (guess, tryy, message) {
var comp = function () {
return Math.floor(Math.random() * 6)
};
var number = comp();
var count = 0;
var test = function () {
var val = guess.value;
if (!Number.isNaN(val) && val >= 0 && val <= 5) {
switch (true) {
case val > number:
message.innerHTML = 'Your guess was too high!';
count++;
break;
case val < number:
message.innerHTML = 'Your guess was too low!';
count++;
break;
case val == number:
count++;
message.innerHTML = 'Congratulations you found the number! It took you ' + count + ' guesses';
//Reseting game here
setTimeout(function(){
count = 0;
number = comp();
guess.value = '';
message.innerHTML = 'Your game has been reset';
}, 2000);
break;
};
}
};
tryy.onclick = test;
guess.onkeyup = function (e) {
if (e.keyCode == 13) {
test();
}
}
})(document.getElementById('guess'), document.getElementById('tryy'), document.getElementById('message'));