Changing sound effect on a function when variable changes - javascript

I'm writing a homework assignment for a JS class, and the teacher wants us to have a weapon sound when firing, but stop making sound when out of ammo.
I have the sound effect working for when the gun fires, but it continues making the sound when clicked with 0 ammo.
I tried doing an else{} function, but this breaks the "ammo display" in my browser, and the sound would continue playing anyway.
HTML:
<input type="button" value="Heal" class="shoot" onclick="shoot();">
<audio id="heal" src="sound/heal.mp3">
JS: Displays ammo starting at a maximum of 6 shots, with 6 shots in reserve, and counts down each time it is fired.
function shoot() {
if (currentAmmo > 0) {
currentAmmo--;
}
var shoot = document.getElementById("shoot");
shoot.play();
updatescreen();
function updatescreen() {
document.getElementById("total-ammo").innerHTML = "Bullets in Gun:</br>" + totalAmmo;
document.getElementById("current-ammo").innerHTML = "Reload Ammo:</br>" + currentAmmo;
}

You just need to move the play command inside the if-condition.
if (currentAmmo > 0) {
currentAmmo--;
var shoot = document.getElementById("shoot");
shoot.play();
}
updatescreen();

Place the play call inside your if statement, so it plays only if the statement is true:
function shoot() {
if (currentAmmo > 0) {
currentAmmo--;
document.getElementById("shoot").play();
}
}

Related

The video loop is multipling itself more than one time every time it ends

This question is using Aframe .
I have the videosphere on loop manually with addEventListener on ("end").
Code works fine until I look at the console. It gives me strange logs.
myvideo = document.querySelector("#videoSphere");
var aEntranceScene1 = document.querySelectorAll("#playButton1");
for (var i = 0; i < aEntranceScene1.length; i++) {
aEntranceScene1[i].addEventListener("click", function () {
Scene1();
});
};
function Scene1(){
myvideo.setAttribute("src", "video/AEntranceScene1.mp4");
myvideo.currentTime = 0;
myvideo.play();
console.log("playing AEntranceScene1");
Hotspots();
myvideo.addEventListener("ended", function () {
console.log("AEntranceScene1 ended");
Scene1();
});
};
function Hotspots() {
sceneIndex = 1;
document.querySelector("#DButton").emit("disappear");
setTimeout(function () {
if (sceneIndex == 1 && !myvideo.paused) {
document.querySelector("#DButton").emit("move-start");
}
}, 3000);
};
When the video plays first time. It displays the log "playing
AEntranceScene1 and when it ended, log displays "AEntranceScene1 ended" 1 time as expected.this (Attached the photo0) played 1 time
But then when the video play again. It displays the log "playing
AEntranceScene1" several times, not only add one. When it ended, log also displays several times of "AEntranceScene1 ended" this (Attached the photo1) played 2 time
This would get worst as more loop completed.This (Attached the photo2) played 3 times only
[
Can you explain to me whats happening here? and any fix to my code?
Thank you
I have found the answer myself.
Its caused by putting autoplay in the <a-assets>,
once i deleted autoplay, it works fine

How to reset game score and button text

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!

javascript, timeout, button, movement.

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();

Onended switch to Next track

I'm trying to build an MP3 player. Here I want to perform a switch to the next song once the current tack ends.
Here is a part of my code:
function clicki(ID, norrnd) {
if (norrnd == 'nor') {
$('.liActive').removeClass('liActive');
$('#' + ID).next().addClass('liActive');
// Set track Data
$('audio').attr('id', 'audioNor');
$('audio').attr('src', $('.liActive').attr('rel'));
// Play
var player = $('.tbd').get(0);
player.play();
$('#pause').removeClass('hi');
$(player).bind('ended', clicki(ID++, 'nor')); //as well as .onfinish result in TOO MUCH RECURSION error.
}
}
<audio controls id="" class="tbd" type="audio/mpeg" src="Ella Fitzgerald - It Don't Mean a Thing.mp3"></audio>
So when I just initiate clicki() first time the page instantly freezes:
Too Much Recursion.
How do I make the track be automatically switched with no Recursion flood?
You're calling the function immediately -- you need to create a function around it:
function clicki(ID, norrnd) {
if (norrnd === 'nor') {
$('.liActive').removeClass('liActive');
$('#' + ID).next().addClass('liActive');
// Set track Data
$('audio').attr('id', 'audioNor');
$('audio').attr('src', $('.liActive').attr('rel'));
// Play
var $player = $('.tbd');;
$player.get(0).play();
$('#pause').removeClass('hi');
// if you call it now, it's going to keep calling itself
$player.bind('ended', function () {
clicki(ID++, 'nor');
});
}
}

player plays two times on first click

I am having a tough time I have a code where you click on a image and if it possible to move it to next cell the it should move
function changecell(a){
var moved=false;
if(a%3 !=0) {
if(ij[a-1]==0) {
moved=true;
if(moved==true) {
no=firstmove++;
move.innerHTML = no;
playTick();
}
swap(a-1,a);
}
}
if((a+1)%3 !=0 && moved==false) {
if(ij[a+1]==0) {
moved=true;
if(moved==true) {
no=firstmove++;
move.innerHTML = no;
playTick();
}
swap(a+1,a);
}
}
}
function playTick() {
document.getElementById('tickSound').play();
}
function swap(x1,x2) {
var temp=ij[x1];
ij[x1]=ij[x2];
ij[x2]=temp;
var p = eval("document.images.i"+x1);
p.src="images1/"+ij[x1]+".png";
p = eval("document.images.i"+x2);
p.src="images1/"+ij[x2]+".png";
}
my problem is for first click the sound plays for two times and then after that it plays once as it is supposed to play.
Does anybody have any idea about this?
EDIT:
I did put an alert() in the if(moved==true) loop the alert shows only for once but sound plays twice. Suppose the if(moved==true) was getting executed again wouldn't I get another alert()?
I'm thinking that both the if conditions are being satisfied on the first run so the playTick() method is being called twice. Without knowing the value of a, i cannot be sure.

Categories