I am working on a game to learn JavaScript and I have some problems:
1.I want to remove 1 point from the player score when the player had missed the zombie. I tried something with a score function which is called after the settimeout () but it doesn't work.
2.I want to add a sound effect when the player click. This sound effect will change (as the weapon's image) when the score reaches 7 and then 3. I can't manage to achieve both, and now the game is broken (can't start it).
3.With the zombie popup function. I want that a zombie can't appear in the same frame as the former one (because when it happens the player is not really aware it is a new zombie). I also want to prevent that more than one zombie is on screen (which is happening after several seconds).
A little diagram to help you understand
window.onload = build;
var zombie;
var timer;
var invasion;
var score = 10;
var sound1 = new Audio("sound/magnum.mp3");
var sound2 = new Audio("sound/crossbow.mp3");
var sound3 = new Audio("sound/baseball-bat.mp3");
document.querySelector('.score__counter__number').innerHTML = 10;
var kill = true;
function build() {
zombie = document.querySelectorAll('.gameboard__zombie');
for (var x = 0; x < zombie.length; x++) {
zombie[x].addEventListener('click', hitzombie, false);
}
}
function start() {
popup();
}
function popup() {
kill = true;
invasion = zombie[Math.floor(Math.random() * zombie.length)];
invasion.classList.add('zombie--popup');
var zTime = 2000;
timer = setTimeout(hidezombie, zTime);
}
function hidezombie() {
if (score >= 1) {
invasion.classList.remove('zombie--popup');
popup();
score();
weapon();
} else {
end();
}
}
function score() {
score--;
document.querySelector('.score__counter__number').innerHTML = score;
}
function hitzombie() {
if (score > 7) {
sound1.play();
event.target.classList.remove('zombie--popup');
if (kill) {
kill = false;
score = score;
}
} else if (score <= 7) {
sound2.play();
event.target.classList.remove('zombie--popup');
if (kill) {
kill = false;
score = score;
}
} else if (score >= 3 || score >= 1) {
sound3.play();
event.target.classList.remove('zombie--popup');
if (kill) {
kill = false;
score = score;
}
popup();
} else {
end();
}
function weapon() {
if (score == 7) {
document.getElementsById('weapon__image').src = "images/DarylCrossbow.png";
}
if (score == 3) {
document.getElementsById('weapon__image').src = "images/NeganBat.png";
}
}
function end() {
invasion.classList.remove('zombie--popup');
timeSurvived = document.querySelector('.score__survive');
timeSurvived.style.fontSize = "5rem";
var blinkSpeed = 3000;
var blinkInterval = setInterval(function () {
var ele = document.querySelector('.score__start');
ele.style.visibility = (ele.style.visibility == 'hidden' ? '' : 'hidden');
}, blinkSpeed);
}
Thank you for your help ;)
What I have tried:
I tried for some hours to find a solution and really need some hints to find a solution by myself.