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!
Related
I am second semester, taking a class in Javascript. Basically, we were given the HTML and CSS for a website, and it is supposed to do the following:
It's a number game. The computer generates a number, and you have ten tries to guess this number. If you get to zero, the computer wins, and there is a reset button which should reset all the variables and start again. Only problem is, I cannot for the life of me figure out how to reset the countDown variable after the score reaches 0. Please help. Also we are using only pure Javascript for this course for now. I don't want to cheat, I am more trying to figure out what the issue is that's holding me back.
var countDown = 10;
var computerNumber = Math.floor((Math.random() * 501) + 1);
function generate() {
playerNumber = document.getElementById("guess").value;
if (computerNumber == playerNumber && countDown > 0) {
alert("Congratulations! You've won!");
} else if (playerNumber < computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too Low";
} else if (playerNumber > computerNumber && countDown > 0) {
countDown--;
document.getElementById("guesses").value = countDown;
document.getElementById("result").value = "Too High";
} else if (countDown == 0) {
alert("Game Over. The Number Was " + computerNumber);
}
}
function reset() {
countDown = 10;
computerNumber = Math.floor((Math.random() * 501) + 1);
}
In the reset function, you would need to update the element that displays the countDown in the HTML
Here you need to add the reset button in the html:
<input type="button" class="reset-button" value="Reset Count">
Then grab that button in your JS below the reset function and attach an eventListener that fires the reset function when clicked:
const resetBtn = document.querySelector('.reset-button')
resetBtn.addEventListener('click', reset )
And that's it.
You would probably want the count displayed on the page, too. You could add a line in the reset function that pushes the new value of countDown into the html (with element.textContent = countDown.toString(), for example)
If you take a JS class in 2021 you should definitely use const and let instead of var, and let your teacher know why. Using var works, though, but will show a future employer that you're out of touch with what's going on in the JS world.
I am busy making a memory game, where an image is to be displayed to the user, and after some 10 seconds of the image flashing, it should hide and four options are to be shown for the user to choose either the correct or incorrect answer.
So far, all I have accomplished is to load the images and cycle through all the puzzles that my code can find.
What I'm trying to do now is to make the image flash and hide after some time, while also just refreshing that section of the page, and not the entire page.
I am using C# and a user control on my page.
What I have tried so far is only
<script>
var x;
function BlinkImage() {
x = 1;
setInterval(change, 2000);
}
function change() {
if (x === 1) {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = false;
x = 2;
}
else {
var image = document.getElementById('<%=imgMain.ClientID %>');
image.visible = true;
x = 1;
}
}
</script>
And on loading my puzzle for that instance (in code behind)
Page.ClientScript.RegisterStartupScript(typeof(game), "Start", "<script language=javascript> BlinkImage(); </script>");
Which does fire, as I can step through the code in debugging on Firefox. But my image does not flash or blink. I understand I am just using visiblity as my "blinker". I don't know what else to use exactly.
What can I do to make the image flash or blink for, say 20 seconds, then hide the image after that time has passed? Then repeat the process once the user has made a choice.
You can try the following (comments in code):
var blinkInterval = setInterval(change, 2000), // set the interval into a variable
image = document.getElementById('test'), // replace test with your client id: <%=imgMain.ClientID %>
x = 1;
function change() {
if (x % 2 === 1) { // see if it is odd or even by modding by 2 and getting remainder
image.style.display = 'none';
} else {
image.style.display = 'block';
}
x++; // increment x
if (x === 10) { // should have happened 10 times (which is 20 seconds with your intervals being at 2 seconds)
clearInterval(blinkInterval); // clear the interval (should end hidden as odd is display none and we clear beforethe 20th is run)
}
}
<div id="test">test</div>
After the code has finished, wherever the user is making their selection, you just need to reset the blinkInterval variable:
blinkInterval = setInterval(change, 2000); // notice no need for the var declaration when you reset this
Use style attribute and change if visible/hidden
function change() {
var image = document.getElementById('<%=imgMain.ClientID %>');
//check if visible
if (image.style.visibility=="visible") {
image.style.visibility="hidden";
}
else {
image.style.visibility="visible";
}
}
;
Try this:
function flashAndHide(img_id){
var img = $("#"+img_id);
var x = 0;
var inter = setInterval(function(){
if(x % 2 == 0){
img.hide();
}else{
img.show();
}
x += 1;
}
},1000);
if(x === 20){
img.hide();
clearInterval(inter);
}
}
Haven't tested this, but it should work,
I have 9 links in my header and 10 divs in the body. The first div is the main page, the other 9 divs have diffrent content in them. What i want to do is when people mouseover the 9 links it shows the 1 of the 9 divs. But if the user stops using the mouse it needs to return to the first div after 5 minutes.
I hope somebody can help me to set this up.
How about something like this?
// call showPage('something') to switch to a different section
var currPage = 'main';
function showPage(id) {
if (currPage !== null) {
document.getElementById(currPage).style.display = 'none';
}
currPage = id;
document.getElementById(currPage).style.display = 'block';
}
var lastMove = new Date().getTime();
document.onmousemove = function() {
lastMove = new Date().getTime();
}
setInterval(function() {
var now = new Date().getTime();
if (now - lastMove > 300000) {
showPage('main');
}
}, 5000);
We keep a global lastMove variable that gets updated with the current timestamp every time the mouse moves.
Then we have a function that's called every 5 seconds that can do something if it's been 5 minutes since the last time the mouse moved.
This is an alternate solution that involves setting up a new timer every time the mouse moves.
function goToMain() {
// todo: switch back to Main
}
var timer = null;
document.onmousemove = function {
if (timer !== null) clearTimeout(timer);
timer = setTimeout(goToMain, 300000);
}
This is slightly cleaner code than my first solution, but it's doing more processing on every mouse move, so it may not be as efficient.
You can make all the divs with absolute position and just play with style.visibility switching it from "hidden" to "visible". As for 5 minutes and back to div 1 - you can make timer function and onMouseMove just reset counter.
<header>
<script type='text/javascript'>
var maxTime = 300;//sec=5min
var offTime = 0;
document.documentElement.onmousemove = function(){offTime=0};
function isTimeToReturn(){
offTime++;
if(offTime<=maxTime){
setTimeout('isTimeToReturn',1000);
}else{
//change your present div to hidden and first to visible
}
}
setTomeout('isTimeToReturn',1000);
</script>
</header>
In my game I have set the timer to 30000ms (30 secs). When the timer ends the game ends. I want to show the user the timer to give them some idea of how long they have left. How would I do this, I have tried to do it like this:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
}, 500);
});
}, 30000).show('#timer'); //here I am trying to display the time in the "#timer"
}
I think I am approaching this all wrong can someone give me a point in the right direction?
Fiddle: http://jsfiddle.net/cFKHq/8/
Have a gander at this jsFiddle. You just need to change your timeout to an interval and keep a count of the seconds.
Instead of running the timer by all 30000 at once, run the timer in 1000ms increments. Each time it hits, subtract one from the counter, refresh the page, and if the counter is 0, end the game.
I changed the jsfiddle you posted to show a counter after pushing play button. See http://jsfiddle.net/cFKHq/10/
Inside your function startplay() I added a variable ttime with an initial value of 30 and I added the line $("#timer").text(--ttime); to the setInterval argument function that is called every second.
Look into using delta times. I have found this to be a great way to handle things that need to measure changes in time.
prevTime = curTime;
curTime += new Date();
deltaTime = curTime - prevTime;
This will also allow you to have a "x seconds remaining" counter if you fire off an event every 1 second, or even every 100ms. All depends on how fast you want it to go.
You need to seperate your timer logic from your "game over" logic, as the timer should tick regardless:
var secondsLeft = 30;
var timerElement = $('#timer');
(function timer() {
timerElement.text(secondsLeft);
secondsLeft--;
if (secondsLeft !== 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
http://jsfiddle.net/cFKHq/14/
Note that in this solution the 30 * 1 second timer countdown and 30 seconds of gameplay are not related or reliant on one another, which may cause some synchronicity issues if the user is on a slow machine.
You can use a global window.duration variable were you set the seconds the game will last, then decrement from that in the "one second" interval:
See working demo
At start of script:
var hit = 0;
var attempted = 0;
var target = $("#target");
window.cont = true;
window.duration = 30; //set your desired game duration in seconds
then on the "one second interval" we decrement the timer and print the timer text:
play = setInterval(function() {
if (window.cont) {
window.cont = false;
scramble();
}
window.duration--;
$('#timer').html(window.duration + ' seconds to go');
}, 1000);
Also display a "finished" text when the game ends, the relevant part follows:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
$('#timer').html('Finished');
}, 500);
Here is an example: http://jsfiddle.net/RPSMJ/4/
JavaScript
var counter = 30,
timerOutput = document.getElementById('timerOutput');
(function timer() {
timerOutput.innerHTML = counter;
counter -= 1;
if (counter >= 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
HTML
<div id='timerOutput'></div>
I have a gaming website and I want to put a advertisement before the game. So can someone tell me how to show the advertisement div for 15 seconds which says below it. "The game will start in [time left] seconds". Then one the time is up then it will show the div which holds the game. In javascript please.
Thank you
I would recommend taking a looking at setTimeout. It allows you do something after a certain time. If you need more help let us know.
EDIT: I'm sorry I misread your question. A more appropriate method you should use is setInterval so every second during the 15 seconds, you can show the time. Speransky's answer has the right idea.
Demo: http://jsfiddle.net/myDTK/1
var secondsLeft = 15;
var delay = 1000; // 1 second
var interval = setInterval(function () {
if (secondsLeft > 0) {
document.getElementById('timer').innerHTML = 'The game will start in ' + secondsLeft + ' seconds...';
secondsLeft -= 1;
} else {
document.getElementById('timer').style.display = 'none';
clearInterval(interval);
document.getElementById('game').style.display = 'block';
}
}, delay);
function doSome() {
//do some
}
setTimeout(function(){
doSome();
}, 15000);
Have a look at the setTimeout function
eg.
setTimeout(function(){
//code to hide the div and how game div
}, 15000);
Here's a live example using jQuery.
Basically just make a function that adds the div, call that function whenever you need to, and then in that function do setTimeout(removeFunction, 15000) to call the remove function 15 secs later.
In order to do the countdown timer, you can call a function updateTimer once per second (again, setTimeout(updateTimer, 1000)) and have that function simply search for the timer and decrement the counter.