I've only been working with javascript for the past 3 days and I have an assignment to do. (Don't ask me why they're making me create a game on my first js assignment) I've made this game you can view it here http://nwdevelopment.host56.com/game.html
How it should work: Click the start button, then the start button goes away and the animation starts on the character. Timer will still go until 30 seconds are up. (1 second currently for testing purposes) Game ends and displays amounts of clicks in pop up ( + 50 to win). Start button comes back up and you can play again.
The problem i'm having is:
1: I need to make the button go away when clicked, but still continue to count down until the end of the game but come back up when the game ends. Where can I learn to do this? Direct me to a site or show me please.
2: During all of this, when you press start game, i need Ganon to move around slowly while you click on him and the score goes up. I got the score to go up but I can't get him to move and I'm not even sure where to start. Also, when you click on him I need it to move 10 pixels randomly on the screen.
I need this in the simplest form you can give me with javascript. Can you point me in the right direction for tutorials or something? Here is the code so far, sorry the CSS and scripts are in one file currently. (leaving out the CSS as i don't think you need it.)
<div id="textWrapper">
<h1>Try to Defeat<br /> Ganon!</h1>
<p class="description">Click on Ganon and watch your score rise! If you hit Ganon enough times before the time runs out, you win!</p>
<ul>
<li>Home</li>
<li>UNIT3A</li>
<li>UNIT3B</li>
<li>Game</li>
</ul>
<br />
<!-- Counter -->
<div id="numberCounter">
<p>0</p>
</div>
</div>
<div id="backgroundImageWrapper">
<div id="ganonWrapper">
<img src="ganon.png" alt="ganon" onclick="myFunction()"/>
</div>
<div id="buttonWrapper">
<button id="button" onclick="myTimer()">Start Game</button>
</div>
</div>
<!-- START JAVASCRIPT -->
<script>
var counter = 0;
function add() {
return counter += 1;
}
function myFunction(){
document.getElementById("numberCounter").innerHTML = add();
}
function myTimer() {
setTimeout(function(){ alert("Game over!"); }, 1000);
}
</script>
Maybe this little fiddle can help you get the timer things to work.
http://jsfiddle.net/2zfdLf0q/2/
// lets put everything in our game object
var game = {
//this is the init function (we call this function on page load (see last line))
init: function(){
//we attach a click event on the button
document.getElementById('start').addEventListener('click', function(){
//we hide the button
document.getElementById('start').style.display = "none";
//on click we start the timer
game.timer.start();
});
},
//this is the timer object
timer: {
startTime: 5, //the time we start with (used to reset)
currentTime: 5, //the counter used to remember where the counter is
interval: null, //the interval object is stored here so we can stop it later
start: function(){
//when we start the timer we set an interval to execute every 1000 miliseconds
game.timer.interval = setInterval(function(){
game.timer.currentTime -= 1; //we minus 1 every second to the timer current time
//update the textbox to show the user what the time is
document.getElementById('counter').value = game.timer.currentTime + ' seconds';
//if timer hits 0 we show the game is over and reset the game, we also clear the timer
//so it wouldn't count below zero
if(game.timer.currentTime == 0){
alert('game over');
game.reset();
clearTimeout(game.timer.interval);
}
},1000);
}
},
//this is the reset function
reset: function(){
document.getElementById('start').style.display = 'inline-block';
game.timer.currentTime = game.timer.startTime;
document.getElementById('counter').value = game.timer.currentTime + ' seconds';
}
}
//we start the game on page load
//you should wrap this in
//window.onload = function(){}
//but jsFiddle does this automaticly
game.init();
Related
I would like to have the second button ( "free five") to keep checking the condition that it would reappear when the number reached 5 again after I clicked it. However, it never showed up again after I pressed it, unless I press the first button.
Game instruction is in the p section.
let birdNum = document.getElementById("birdNum")
let catchBtn = document.getElementById("catch")
let freeBtn = document.getElementById("free")
function catchBird() {
birdNum.innerHTML++;
if (birdNum.innerHTML > 4) {
freeBtn.classList.add("fadeIn");
freeBtn.disabled = false;
}
}
document.getElementById("catch").addEventListener("click", catchBird);
function freeBird() {
birdNum.innerHTML -= 5;
setInterval(() => {
birdNum.innerHTML++;
}, 1000);
if (birdNum.innerHTML <= 4) {
freeBtn.classList.remove("fadeIn");
freeBtn.disabled = true;
}
}
document.getElementById("free").addEventListener("click", freeBird);
#free {
opacity: 0;
}
#free.fadeIn {
opacity: 1;
}
<P>
press "catch one" to catch one bird. <br> press "free five" to free five bird. <br>
<br> Once you free five birds, they will come back with their kids, one bird per second.
</P>
<span id="birdNum">0</span>
<button id="catch">
catch one
</button>
<button id="free" disabled=t rue>
free five
</button>
Try the following code, see if it works for you:
Edit: I realised your issue, I edited to work now.
So in your code, you were only checking whether or not to make the 'free' button visible once. And you only checked when it was pressed. For example, we are playing your game and get to 6. We press the 'free birds' button and we go down to one and the 'free birds' button disappears. Now the setInterval keeps making the number of birds go up. We get to 5 and the button does not reappear because we are not running any code to make it reappear. In the setInterval, as well as incrementing the counter, we need to check whether or not we can make the 'free birds' button visible again. See the resetInterval() function. In the setInterval's callback, we are now checking whether of not the birds counter is above 5. If the condition returns true, we will show the 'free birds' button.
With the below JS, it should work nicely.
const birdNum = document.getElementById("birdNum");
const catchBtn = document.getElementById("catch");
const freeBtn = document.getElementById("free");
const initialTimeout = 1000;
let timesBirdsFreed = 0;
let intervalId;
function resetInterval(delay) {
if (delay < 10) delay = 10;
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(() => {
birdNum.innerHTML++;
// if statement from catch bird function is needed here too
if (birdNum.innerHTML >= 5) {
freeBtn.classList.add("fadeIn");
freeBtn.disabled = false;
}
}, delay);
}
function catchBird() {
birdNum.innerHTML++;
if (birdNum.innerHTML >= 5) {
freeBtn.classList.add("fadeIn");
freeBtn.disabled = false;
}
}
catchBtn.addEventListener("click", catchBird);
function freeBird() {
timesBirdsFreed++;
birdNum.innerHTML -= 5;
resetInterval(initialTimeout/timesBirdsFreed);
if (birdNum.innerHTML <= 4) {
freeBtn.classList.remove("fadeIn");
freeBtn.disabled = true;
}
}
freeBtn.addEventListener("click", freeBird);
#free {
opacity: 0;
}
#free.fadeIn {
opacity: 1;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Bird Game</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<p>press "catch one" to catch one bird. <br> press "free five" to free five bird. <br><br> Once you free five birds, they will come back with their kids, one bird per second.</p>
<span id="birdNum">0</span>
<button id="catch">catch one</button>
<button id="free" disabled=true>free five</button>
<script src="script.js"></script>
</body>
</html>
Edit 2: Further explanation and added links to setInterval() method and clearInterval() method.
function resetInterval(delay) {
// if delay is too small (less than 10 ms) make delay 10 ms
if (delay < 10) delay = 10;
// in beginning of the program, intervalId is undefined
// so we will only use clearInterval if intervalId is not undefined (if we've used setInterval already)
if (intervalId) clearInterval(intervalId);
// use setInterval method with a delay which was passed to the function as an argument
intervalId = setInterval(() => {
// make birds go up by one
birdNum.innerHTML++;
// if statement from catch bird function is needed here too
// (if birds counter is 5 or more, show 'free birds' button)
if (birdNum.innerHTML >= 5) {
freeBtn.classList.add("fadeIn");
freeBtn.disabled = false;
}
}, delay);
// all of this resets the interval but at a smaller delay so birds go up faster each time
}
The resetInterval() function just stops an existing setInterval() from executing code by using clearInterval(intervalId) which uses the ID returned when setInterval() when it was called. An ID can be, for example, 239 or maybe 146. After the existing setInterval() was cleared, another setInterval() is called and its ID is stored in the variable (intervalId) to be used to clear the new setInterval() the next time resetInterval() is called (the next time you free five birds). The difference though is with each call of the resetInterval() function, the setInterval's delay which was passed into the function is smaller, making the number of birds go up faster.
The way this is done is when the resetInterval function is called, a delay is passed into the function as a parameter like so resetInterval(initialTimeout/timesBirdsFreed). initialTimeout is set to always be 1000 (milliseconds). timesBirdsFreed is a number which tells you how many times you clicked the 'free birds' button. If you clicked 'free birds' once, initialTimeout/timesBirdsFreed will be 1000/1 which is 1000 (ms). So the first time you clicked 'free birds', the number of birds will go up by one bird every second. The second time you click 'free birds', initialTimeout/timesBirdsFreed will be 1000/2 which is 500 (ms), meaning now birds will go up by one every half a second.
Because of this, the more you click 'free birds', the faster they will go up (up to a limit - smallest delay possible is 10ms, so it won't go any faster than that).
References
MDN Web Docs
setInterval() method
W3Schools
setInterval() method
clearInterval() method
If you need to stop the setInterval you should keep its instance and then call clearInterval(instance)
I'm not sure what you want to achieve but you may get the idea from the this code:
let intervalInstance;
function freeBird() {
birdNum.innerHTML -= 5;
if (intervalInstance) {
clearInterval(intervalInstance);
}
intervalInstance = setInterval(() => {
birdNum.innerHTML++;
}, 1000);
if (birdNum.innerHTML <= 4) {
freeBtn.classList.remove("fadeIn");
freeBtn.disabled = true;
}
}
I'm doing an easy slider with buttons, it works fine, but I'd like to add TimeOut() function to current code, to allow slides to change automatically.
I tried to do that with jQuery but it didn't work.
$('.reviews-slider-button').click(function() {
var i = $(this).index();
$('.reviews-slider-person').hide();
$('.reviews-slider-person-' + (i + 1)).show();
});
I'd like to change automatically slider every 10 seconds, and when I would click on .reviews-slider-button it would reset the timer ( to avoid situation I click to change slide, and timer automatically change to the next one).
I'd be grateful for your advice's.
You can use setInterval to click your button every 10 seconds:
var timer = ''; // Make global variable
function ScrollAuto() {
temp = setInterval(function() {
$('.nextButton').click();
}, 10000)
return timer;
}
And to reset your timer, inside your reset button add:
clearInterval(timer);
Similarly to the answer from Shree, but make it cleaner, but use timeout, not interval, you want the system to change slide every 10 seconds unless you click, in which case you reset the timeout, go to the next slide, and set up the next timeout
Something like this:
var slideMaxDuration = 10000; // in ms
var slideTimer = void 0;
function nextSlide() {
clearInterval(slideTimer);
// ... go to next slide ...
}
function autoContinue() {
nextSlide();
setTimeout(autoContinue, slideMaxDuration);
}
$('.reviews-slider-button').click(autoContinue);
You also need to set up the initial autoContinue when you want the whole thing to start.
I'm making a whack a mole game for a school project and I've gotten the actual game to work, however I'm having an issue resetting the game once the 30 second timer runs out. The game is made with javascript and p5.js and as of right now when you load the page, the game div display is set to hidden, but when you click "begin" the display changes to block and the timer starts (the game is on github for reference https://abm96testgithub.github.io/whackamole/). When the 30 seconds are up, the "begin" button changes to "reset" and the game display goes back to "none" (both done using document.getElementByID).
Is there a way to make it so that when the player hits "reset" the entire page will reload or so that the button will read "begin" again and the score will reset?
I know I can make a separate reset button with a function for this, but I feel like it would mess up the aesthetic of the page to have two buttons.
The html for the button when the page first loads is
<button id="startButton" onclick="startGame();startTimer()">Begin!</button>
and the javascript for it is
function startGame() {
document.getElementById('sketch-holder').style.display = "block";
}
function countdown () {
var startCountdown = setInterval(function() {
document.getElementById('timerVar').innerHTML = counter + "s";
counter--;
if (counter < 0) {
clearInterval(startCountdown);
document.getElementById('sketch-holder').style.display = "none";
document.getElementById('startButton').innerHTML = "Reset";
}
}, 1000)
}
function startTimer() {
if (timerOn === false) {
timerOn = true;
countdown();
}
}
It's a little strange to use setInterval() when you're using P5.js. P5.js has its own internal timing mechanisms, which we talked about in your last question.
Instead of using setInterval(), I'd use the millis() function or the frameCount variable to perform timing logic. See my code in my answer to your last question:
function setup() {
createCanvas(200,200);
background(32);
}
function draw(){
// 60 frames is 1 second
if(frameCount % 60 == 0){
ellipse(random(width), random(height), 25, 25);
}
}
This code draws a circle once per second. This is just an example, but you could do something very similar to reset your game after 30 seconds.
Then to reset your game, all you really need to do is set any variables you're using back to their default values. Try writing a reset() function that does exactly that.
If I understood right, Instead of Button You can go witha a tag with void href then on click you can add href="javascript:window.location.href=window.location.href" which will reload the page.
function startGame() {
document.getElementById('sketch-holder').style.display = "block";
}
function countdown () {
var startCountdown = setInterval(function(){
document.getElementById('timerVar').innerHTML = counter + "s";
counter--;
if (counter < 0) {
clearInterval(startCountdown);
document.getElementById('sketch-holder').style.display = "none";
document.getElementById('startButton').innerHTML = "Reset";
document.getElementById('startButton').setAttribute("href", 'javascript:window.location.href=window.location.href"');
}
}, 1000)
}
function startTimer() {
if (timerOn === false) {
timerOn = true;
countdown();
}
}
Begin!
Is there any way that I could be able to make a progress bar go backwards? I have seen an example that told me to turn the progress bar 180 degrees, but that seems like a very dirty way to do it. What I'm looking for is so the progress bar can be time controlled, and so that a by pressing a button, I would add three seconds to the timer, thus pulling back the bar a bit (Say the timer is at 7 seconds, pressing the button would add a second, bringing it to 8 seconds thus pulling back the timer a little bit). If I could incorporate this with a countdown timer as well, it would be cool, but not 100% needed. Here is what I have so far. Changes that need to be made is so that the timer goes backwards instead of forwards, and so I could be able to add time on to it by pressing a button.
HTML:
Javascript:
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
}
setTimeout(animator, updatesPerSecond);
});
JSFiddle
1st: - We will create a new function for reverse
2nd: - Add min="0" attribute to the progress bar
3rd: - change progress value to 200 progress.val('200'); before running the setTimeout()
Finally: - change + to - on progress.val() - interval
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
},
reverse = function(){
progress.val(progress.val() - interval);
$('#val').text(progress.val());
if ( progress.val() - interval > progress.attr('min')){
setTimeout(reverse, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('min'));
}
}
progress.val('200');
setTimeout(reverse, updatesPerSecond);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<progress max="200" min="0" value="1"></progress>
<div id="val"></div>
Simply start with progress.val at its maximum, and decrement it. When it gets to 0, you're done.
I am trying to adapt the countdown timer from http://www.jqueryscript.net/time-clock/Simple-jQuery-Html5-Based-360-Degree-Countdown-Timer-countdown360.html to add buttons which determine the time to count down.
I am a little confused (no, really a lot confused) about
a) how to link the buttons to the countdown display,
b) how to stop the display starting until I have clicked the desired button, and
c) how to reset the process without reloading the page.
Currently it takes the initial seconds value of 10 (put there just to test to see what it is doing) but does not respond to the buttons.
Here is the html:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="../src/jquery.countdown360.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="container">
<div id="countdown"></div>
<script type="text/javascript" charset="utf-8">
$("#countdown").countdown360({
radius : 50,
seconds : 10,
fontColor : '#FFFFFF',
autostart : false,
onComplete : function () {//will ring bell
}
}).start()
</script>
<script>
window.onload = init;
function init(){
document.getElementById('btnStart1').onclick = start1;
document.getElementById('btnStart2').onclick = start2;
document.getElementById('btnReset').onclick = cdreset;
start.countdown360();
}
function start1(){ // starts 1 min countdown
seconds = 60;
countdown360();
}
function start2(){ // starts 2 min countdown
seconds = 120;
countdown360();
}
function reset() { // resets countdown
seconds=0;
//???
}
</script>
</div>
<div id="container">
<div id="countdown"></div>
<input type="button" value="1 min" id="btnStart1"/>
<input type="button" value="2 min" id="btnStart2"/>
<br>
<input type="button" value="Reset" id="btnReset"/>
</body>
</html>
Any help would be most welcome!
Answer & Demo
So it turns out there isn't a legit way of doing this, truth be told there isn't a lot of documentation about the subject and the plugin itself doesn't provide such functionability, or at least not in a user friendly way.
But I went down to the guts of the code and managed to make it work.
Here is a JSFiddle where I demonstrate what I understood you wanted.
HTML
<div id="countdown"></div>
<button id="start">Start</button>
<button id="set60">Set 60s</button>
<button id="set120">Set 120s</button>
<button id="reset">Reset</button>
JavaScript
start = document.querySelector("#start");
set60 = document.querySelector("#set60");
set120 = document.querySelector("#set120");
reset = document.querySelector("#reset");
div = $("#countdown");
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
pingSound.preload = "auto"; //<- Optional but recommended
countdown = div.countdown360({
radius: 50,
seconds: 30,
fontColor: '#FFFFFF',
autostart: false,
onComplete: function () {
pingSound.play();
}
});
countdown.start(); //This right here is for showing the clock on load.
countdown.stop();
start.onclick = function () {
startCountdown(countdown);
}
set60.onclick = function () {
setSeconds(countdown, 60);
}
set120.onclick = function () {
setSeconds(countdown, 120);
}
reset.onclick = function () {
setSeconds(countdown, 0);
}
function startCountdown(countdown) {
countdown.start();
}
function setSeconds(countdown, seconds) {
countdown.stop();
countdown.settings.seconds = seconds;
countdown.start();
}
Explanation
Variables
start, set60, set120, reset : Link to their respective button elements.
div : Link to the countdown div element.
pingSound : Audio element that contains the "ping" sound.
countdown : The countdown object itself, you need to declare it like this, passing the initial properties and saving it in a variable.
Functions
startCountdown(countdown) : Takes any countdown object and start's it's execution, this will get the countdown running.
setSeconds(countdown,seconds) : Takes any countdown object and set's it second (it can be used in mid-excecution). It works by first stopping the countdown, then updating the Countdown.settings.seconds property, which is the actual seconds the countdown will run.
Development
With those variables & methods, how I did it is pretty straight forward.
If you want the clock hidden until you play it:
We first create the countdown object and hide the div.
div = $("#countdown");
div.css( "display" , "none" );
countdown = div.countdown360({..});
Why? Well because of how the plugin works. As soon as you create the countdown your div is made bigger by the plugin, and you need to create the countdown there because that's the only way it works, so if you don't want a blank square of nothing (since we haven't started the countdown) you have to hide the div itself.
So, we add an onclick event to each button:
for start -> startCountdown(countdown) , div.css( "display" , "block" ); -> Starts the countdown and shows the div.
for set60 -> setSeconds(countdown,60) -> Sets the countdown to 60s.
for set120 -> setSeconds(countdown,120) -> Sets the countdown to 120s.
for set0 -> setSeconds(countdown,0) -> Sets the countdown to 0s.
And that's it, it took me a while to figure out, hopefully I didn't just bore you to death, and may I suggest getting a better plugin next time? Good luck :)
If you want the clock displayed on load:
Okey, so this is an update upon your request, if we part from my original code, to make the div appear on load is quite simple (JSFiddle & code here have been updated)
We first create the countdown object, then start it and inmeadiatly stop it (freezing it until you start it again).
countdown = div.countdown360({..});
countdown.start();
countdown.stop();
Now, we add the same onclick events to the buttons except for the start button, which will no longer have to display the div as block as it isn't hidden.
for start -> startCountdown(countdown) -> Starts the countdown.
(..)
If you want to play a sound at the end of the countdown:
For the ping sound to play in the end, you just need to create a new Audio object with the mp3/ogg src as a parameter:
pingSound = new Audio("http://www.sounddogs.com/previews/2220/mp3/402763_SOUNDDOGS__mu.mp3");
Then, preload the audio so it's ready to play (otherwise when you call play it will first have to load). This is optional but recommended.
pingSound.preload = "auto";
And then call the Audio.play() function in the countdown's onComplete event.
countdown = div.countdown360({
(..)
onComplete:function(){
pingSound.play();
}
});
That's it, happy coding :)
Updates
Updated code to display the clock on load (1:43p.m 31/12/14)
Updated code to play sound in the end of countdown(6:10p.m 02/01/14)
First you don't have jquery.js and you are using $('#countdown')
You don't have any function called cdreset .
Well I wrote a similar code for you :
<script>
var m = setInterval(start, 1000), // init the interval , every 1 sec will call start function
s = 60;
function start(){
s = s -1;
document.getElementById("count").innerHTML = s;
}
function stop(){
clearInterval(m);
}
</script>
<p id="count">60</p>
<input type="submit" onclick="stop()" value="stop" />
it will count down starting from 60 to -XXX
You should add a condition so as to stop the timer at 0 :)