Make all div.obstacles have the same function - javascript

I am making a simple game that if the characters touch the "obstacle" which is another div the character that touches it will slow down while they are collided.
I already have a code for this, but it is only working for my .obstacle1 div even if I tried using jquery.each or I'm just missing something.
Here is the code which is working only for .obstacle1
HTML
<div class="field">
<div id="char1" class="characters character1">char1</div>
<div id="char2" class="characters character2">char2</div>
<div id="char3" class="characters character3">char3</div>
<div class="obstacles obstacle1">1</div>
<div class="obstacles obstacle2">2</div>
</div>
CSS
* {
padding: 0;
margin: 0;
}
.field-container {
overflow: scroll;
}
.field {
width: 1550px;
height: 700px;
border: 1px solid red;
position: relative;
}
.characters {
position: absolute;
width: 50px;
height: 50px;
transition: .1s ease-in-out;
}
.character1 {
background-color: blue;
top: 100px;
left: 0;
}
.character2 {
background-color: green;
top: 175px;
left: 0;
}
.character3 {
background-color: red;
top: 250px;
left: 0;
}
.obstacle1 {
height: 50px;
width: 50px;
background-color: lightblue;
position: absolute;
top: 200px;
left: 500px;
}
.obstacle2 {
height: 50px;
width: 50px;
background-color: lightblue;
position: absolute;
top: 120px;
left: 750px;
}
jQuery
$(document).ready(function(){
intervalCharacters = setInterval(function(){
moveChar();
},100);
function moveChar() {
$(".characters").each(function(){
move($(this));
});
}
/*--------------
OBSTACLES
---------------*/
var obstacle1 = $(".obstacles");
var obstacle1CurrentPosX = obstacle1.offset().left;
var obstacle1CurrentPosY = obstacle1.offset().top;
var obstacle1Height = obstacle1.outerHeight();
var obstacle1Width = obstacle1.outerWidth();
var totalY = obstacle1CurrentPosY + obstacle1Height;
var totalX = obstacle1CurrentPosX + obstacle1Width;
function checkIfCollidesChar(thisChar) {
var thisCharPosX = thisChar.offset().left;
var thisCharPosY = thisChar.offset().top;
var thisCharWidth = thisChar.outerWidth();
var thisCharHeight = thisChar.outerHeight();
var totalCharY = thisCharPosY + thisCharHeight;
var totalCharX = thisCharPosX + thisCharWidth;
if (totalY < thisCharPosY || obstacle1CurrentPosY > totalCharY || totalX < thisCharPosX || obstacle1CurrentPosX > totalCharX) {
return false;
console.log("FALSE");
} else {
return true
console.log("TRUE");
}
}
/* -----
move the characters
---- */
var moveFromLeft = 0;
var maxPosition = 1500;
function move(thisChar) {
var _this = thisChar;
var currentPosition = _this.offset().left;
var charSpeed = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
if(checkIfCollidesChar(_this)) {
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + (charSpeed*.25);
}
}else{
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + charSpeed;
}
}
_this.css({
"left" : moveFromLeft,
});
if(moveFromLeft > maxPosition) {
checkIfFinish(_this);
_this.css({
"left" : maxPosition+"px",
});
}
_this.html(moveFromLeft);
}
});
Here is my fiddle.

Here's a fiddle with my suggested fix:
https://jsfiddle.net/40evn8pr/
The problem is that you're 'flattening' the obstacles jquery selection to a single value when you're directly asking for its offset/width/height. You should ask every element from the jquery selection what its offset is with an '$.each' loop to have every obstacle work.
$(document).ready(function(){
intervalCharacters = setInterval(function(){
moveChar();
},100);
function moveChar() {
$(".characters").each(function(){
move($(this));
});
}
var position = ["first","second","third"];
var counter = 0;
function checkIfFinish(thisChar) {
var position2 = position[counter];
counter++;
$(".result").append("<br>Position"+position2+ " counter" + counter + " : " + thisChar.attr("id"));
if(counter >= 3) {
clearInterval(interval);
}
}
/*--------------
OBSTACLES
---------------*/
var obstacle1 = $(".obstacles");
function checkIfCollidesChar(thisChar) {
var thisCharPosX = thisChar.offset().left;
var thisCharPosY = thisChar.offset().top;
var thisCharWidth = thisChar.outerWidth();
var thisCharHeight = thisChar.outerHeight();
var totalCharY = thisCharPosY + thisCharHeight;
var totalCharX = thisCharPosX + thisCharWidth;
var isCollision = false;
$.each(obstacle1, function(i, ob) {
var obstacle1CurrentPosX = $(ob).offset().left;
var obstacle1CurrentPosY = $(ob).offset().top;
var obstacle1Height = obstacle1.outerHeight();
var obstacle1Width = obstacle1.outerWidth();
var totalY = obstacle1CurrentPosY + obstacle1Height;
var totalX = obstacle1CurrentPosX + obstacle1Width;
if (!(totalY < thisCharPosY || obstacle1CurrentPosY > totalCharY || totalX < thisCharPosX || obstacle1CurrentPosX > totalCharX)) {
isCollision = true;
}
});
return isCollision;
}
/* -----
move the characters
---- */
var moveFromLeft = 0;
var maxPosition = 1500;
function move(thisChar) {
var _this = thisChar;
var currentPosition = _this.offset().left;
var charSpeed = Math.floor(Math.random() * (10 - 0 + 1)) + 0;
if(checkIfCollidesChar(_this)) {
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + (charSpeed*.25);
}
}else{
if(_this.offset().left > maxPosition) {
moveFromLeft = maxPosition;
}else{
moveFromLeft = currentPosition + charSpeed;
}
}
_this.css({
"left" : moveFromLeft,
});
if(moveFromLeft > maxPosition) {
checkIfFinish(_this);
_this.css({
"left" : maxPosition+"px",
});
}
_this.html(moveFromLeft);
}
});

I think you are almost good. For your loop, you can use as model the
$(".characters").each(function(){
move($(this));
});
In your case, this would give :
$(".obstacles").each(function(){
var obstacle1 = $(this)
var obstacle1CurrentPosX = obstacle1.offset().left;
var obstacle1CurrentPosY = obstacle1.offset().top;
var obstacle1Height = obstacle1.outerHeight();
var obstacle1Width = obstacle1.outerWidth();
var totalY = obstacle1CurrentPosY + obstacle1Height;
var totalX = obstacle1CurrentPosX + obstacle1Width;
...
});

Related

I want draw line between elements with JQuery and JavaScript only

Question:
I have many "divs" in first and second row, I can create a Rectangle with "pageY" and "pageX" and position, but I'd like to create a Line.
Does anyone know how can I do that?
Details : when the user clicks on two points for the first time, a line is created and one class is added to the points for better visibility.
The second time the user clicks, classes are removed and, then, if no class are appended for two point, a new line is created again.
If the user clicks on a line, the line will be removed.
When I talk about "lines" I mean "rectangles" that I would like to replace with lines.
Here is my view
Below is my JS code :
let pTop = '', pLeft = '', pBottom = '', pRight = '';
$('.row-rope-1 .pin').off('click').on('click', function (topLeft) {
if ($(this).hasClass('rope-loop')) {
$(this).removeClass('rope-loop');
pTop = '';
pLeft = '';
} else {
$(this).addClass('rope-loop');
pTop = $(this).offset().top + 37;
pLeft = $(this).offset().left;
}
createElement();
});
$('.row-rope-2 button.pin').off('click').on('click', function(bottomRight) {
if ($(this).hasClass('rope-loop')) {
$(this).removeClass('rope-loop');
pBottom = '';
pRight = '';
} else {
$(this).addClass('rope-loop');
pBottom = $(this).offset().top + 37;
pRight = $(this).offset().left;
}
createElement();
});
function createElement() {
let FpTop,FpLeft,FpBottom,FpRight;
if (pTop !== '' && pLeft !== '' && pBottom !== '' && pRight !== '') {
let line = document.createElement("span");
line.setAttribute('class', 'rope-line');
FpTop = pTop;
FpLeft = pLeft;
FpBottom = pBottom;
FpRight = pRight;
if (pLeft > pRight){
FpLeft = pRight;
FpRight = pLeft;
}
if (pTop > pBottom){
FpTop = pBottom;
FpBottom = pTop;
}
line.setAttribute('style', 'top:' + FpTop + 'px;left:' + FpLeft + 'px;bottom:calc(100% - ' + FpBottom + 'px);right:calc(100% - ' + FpRight + 'px);');
$('body').append(line);
pTop = '';
pLeft = '';
pBottom = '';
pRight = '';
removeElement();
}
}
function removeElement() {
$('.rope-line').off('click').on('click', function () {
$(this).remove();
});
}
span.rope-line {
position: absolute;
background-color: yellow;
cursor: pointer;
z-index: 9;
}
let pTop = '', pLeft = '', pBottom = '', pRight = '';
$('.row-rope-1 .pin').off('click').on('click', function (topLeft) {
if ($(this).hasClass('rope-loop')) {
$(this).removeClass('rope-loop');
pTop = '';
pLeft = '';
} else {
$(this).addClass('rope-loop');
pTop = $(this).offset().top + 37;
pLeft = $(this).offset().left;
}
createElement();
});
$('.row-rope-2 button.pin').off('click').on('click', function (bottomRight) {
if ($(this).hasClass('rope-loop')) {
$(this).removeClass('rope-loop');
pBottom = '';
pRight = '';
} else {
$(this).addClass('rope-loop');
pBottom = $(this).offset().top + 37;
pRight = $(this).offset().left;
}
createElement();
});
function createElement() {
let FpTop,FpLeft,FpBottom,FpRight;
if (pTop !== '' && pLeft !== '' && pBottom !== '' && pRight !== '') {
let line = document.createElement("span");
line.setAttribute('class', 'rope-line');
FpTop = pTop;
FpLeft = pLeft;
FpBottom = pBottom;
FpRight = pRight;
if (pLeft > pRight){
FpLeft = pRight;
FpRight = pLeft;
}
if (pTop > pBottom){
FpTop = pBottom;
FpBottom = pTop;
}
line.setAttribute('style', 'top:' + FpTop + 'px;left:' + FpLeft + 'px;bottom:calc(100% - ' + FpBottom + 'px);right:calc(100% - ' + FpRight + 'px);');
$('body').append(line);
pTop = '';
pLeft = '';
pBottom = '';
pRight = '';
removeElement();
}
}
function removeElement() {
$('.rope-line').off('click').on('click', function () {
$(this).remove();
});
}
span.rope-line {
position: absolute;
background-color: yellow;
cursor: pointer;
z-index: 9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12 row-rope-1">
<button class="pin pin-up" style="margin-bottom:120px;">
point 1
</button>
</div>
<div class="col-12 row-rope-2">
<button class="pin pin-up" style="margin-left: 50px;">
point2
</button>
</div>
<div class="col-12 row-rope-1">
<button class="pin pin-up" style="margin-bottom:120px;margin-left: 150px;">
point3
</button>
</div>
<div class="col-12 row-rope-2">
<button class="pin pin-up" style="margin-top: 20px;">
point4
</button>
</div>
I would appreciate if you could help me with the easiest way :).
Thanks.
You can use CSS transform and transform-origin. Calculate distance, angle and you can connect two points in 2D space.
let selectedPin = null;
$('.pin').on('click', function () {
let pin = $(this);
if (selectedPin === null) {
selectedPin = pin;
return;
}
let selectedPinPos = {
x: selectedPin.offset().top,
y: selectedPin.offset().left
}
let pinPos = {
x: pin.offset().top,
y: pin.offset().left
}
let distance = calcDistance(selectedPinPos, pinPos);
let angle = 90-calcAngle(selectedPinPos, pinPos);
$('#rope').css({
transform: 'rotate('+angle+'deg)',
width: distance+'px',
top: selectedPinPos.x,
left: selectedPinPos.y
});
selectedPin = null;
});
function calcDistance(p1,p2)
{
var dx = p2.x-p1.x;
var dy = p2.y-p1.y;
return Math.sqrt(dx*dx + dy*dy);
}
function calcAngle(p1, p2)
{
return Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;
}
span.rope-line {
position: absolute;
background-color: yellow;
cursor: pointer;
z-index: 9;
}
#rope {
position: absolute;
top: 20px;
left: 20px;
background: #f00;
width: 0;
height: 2px;
transform: rotate(80deg);
transform-origin: 0% 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-12 row-rope-1">
<button class="pin pin-up" style="margin-bottom:120px;">
point 1
</button>
</div>
<div class="col-12 row-rope-2">
<button class="pin pin-up" style="margin-left: 50px;">
point2
</button>
</div>
<div class="col-12 row-rope-1">
<button class="pin pin-up" style="margin-bottom:120px;margin-left: 150px;">
point3
</button>
</div>
<div class="col-12 row-rope-2">
<button class="pin pin-up" style="margin-top: 20px;">
point4
</button>
</div>
<div id="rope"></div>
Fiddle: https://jsfiddle.net/dbz8of46/2/
Angle formula: https://gist.github.com/conorbuck/2606166
Distance formula: https://gist.github.com/aurbano/4693462
More info:
https://www.w3schools.com/css/css3_2dtransforms.asp
https://www.w3schools.com/cssref/css3_pr_transform-origin.asp

Make Fullpage-Scroll-Script less static

Heyo,
I got a little Fullpage-Scroll-Script and I want to make it a bit less static. So instead of calling every single Div by a different Class (.one, .two, .tree...) I want to make the script work if all Divs have only one Class (.page). I tried it myself with the .each() function from jQuery ... but I couldn't get it to work.
Here is the current Script:
// Fullpage Scroll Script
function ScrollHandler(pageClass) {
var page = $('.' + pageClass);
var pageStart = page.offset().top;
var pageJump = false;
function scrollToPage() {
pageJump = true;
$('html, body').animate({
scrollTop: pageStart
}, {
duration: 1000,
easing:'swing',
complete: function() {
pageJump = false;
}
});
}
window.addEventListener('wheel', function(event) {
var viewStart = $(window).scrollTop();
if (!pageJump) {
var pageHeight = page.height();
var pageStopPortion = pageHeight / 2;
var viewHeight = $(window).height();
var viewEnd = viewStart + viewHeight;
var pageStartPart = viewEnd - pageStart;
var pageEndPart = (pageStart + pageHeight) - viewStart;
var canJumpDown = pageStartPart >= 0;
var stopJumpDown = pageStartPart > pageStopPortion;
var canJumpUp = pageEndPart >= 0;
var stopJumpUp = pageEndPart > pageStopPortion;
var scrollingForward = event.deltaY > 0;
if ( ( scrollingForward && canJumpDown && !stopJumpDown) || (!scrollingForward && canJumpUp && !stopJumpUp)) {
event.preventDefault();
scrollToPage();
}
} else {
event.preventDefault();
}
});
}
new ScrollHandler('one');
new ScrollHandler('two');
new ScrollHandler('three');
* {
margin:0;
padding:0;
}
.page {
height: 100vh;
}
.one { background-color: blue; }
.two { background-color: green; }
.three { background-color: orange; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page one"></div>
<div class="page two"></div>
<div class="page three"></div>
So instead of using:
new ScrollHandler('one');
new ScrollHandler('two');
new ScrollHandler('three');
I tried to use this:
$('.page').each(function() {
new ScrollHandler('page');
}
But it only worked for the first Div.
You need to pass $(this) in each loop and change the page variable to get directly the parameter :
// Fullpage Scroll Script
function ScrollHandler(pageClass) {
var page = pageClass;
var pageStart = page.offset().top;
var pageJump = false;
function scrollToPage() {
pageJump = true;
$('html, body').animate({
scrollTop: pageStart
}, {
duration: 1000,
easing: 'swing',
complete: function() {
pageJump = false;
}
});
}
window.addEventListener('wheel', function(event) {
var viewStart = $(window).scrollTop();
if (!pageJump) {
var pageHeight = page.height();
var pageStopPortion = pageHeight / 2;
var viewHeight = $(window).height();
var viewEnd = viewStart + viewHeight;
var pageStartPart = viewEnd - pageStart;
var pageEndPart = (pageStart + pageHeight) - viewStart;
var canJumpDown = pageStartPart >= 0;
var stopJumpDown = pageStartPart > pageStopPortion;
var canJumpUp = pageEndPart >= 0;
var stopJumpUp = pageEndPart > pageStopPortion;
var scrollingForward = event.deltaY > 0;
if ((scrollingForward && canJumpDown && !stopJumpDown) || (!scrollingForward && canJumpUp && !stopJumpUp)) {
event.preventDefault();
scrollToPage();
}
} else {
event.preventDefault();
}
});
}
$('.page').each(function() {
new ScrollHandler($(this));
})
* {
margin: 0;
padding: 0;
}
.page {
height: 100vh;
}
.one {
background-color: blue;
}
.two {
background-color: green;
}
.three {
background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="page one"></div>
<div class="page two"></div>
<div class="page three"></div>
JSfiddle: https://jsfiddle.net/fw8h7v4q/

Javascript how to properly filter html divs

So I’ve been creating an html music player, and I’ve run into a problem. The problem is that when I click on an album, it filters out all the song that belong to any album, instead of filtering out the songs that only belong to the clicked album. Here is my .js files.
main.js
var btnv = 0;
var update = 0;
var NumberOfSongs = 37;
function Dropdown() {
var i = 0;
if (i == 0) {
i++;
document.getElementById("Dropbutton").classList.toggle("dropbtnclick");
document.getElementById("Dropbutton").classList.toggle("dropbtnpos");
document.getElementById("myDropdown").classList.toggle("show");
document.getElementById("PlaylistDropdown").classList.toggle("show");
document.getElementById("SearchBox").setAttribute("style", "height: 30px;");
} else {
i--;
document.getElementById("Dropbutton").classList.remove("dropbtnclick");
}}
window.onerror = function(error) {console.log(error);};
function startUI() {
var SB;
for (SB = 0; SB < NumberOfSongs;) {
SB++;
let NewSongBtn = document.createElement("a");
NewSongBtn.id = SB;
NewSongBtn.setAttribute("style", "color: white; padding: 10px 50px; text-decoration: none; text-align: left; display: block; border-top: 0.9px solid #9B9898;");
NewSongBtn.innerHTML = titles[SB] + " -- " + artists[SB];
NewSongBtn.onclick = function() {Playbutton(NewSongBtn.id);};
let LI = document.createElement("li");
LI.appendChild(NewSongBtn);
document.getElementById("SongBtns").appendChild(LI);
}
var n;
for (n = 0; n < NumberOfSongs; n++) {}
createAlbums();
}
function createAlbums() {
var AB;
for (AB = 0; AB < NumberOfSongs;) {
AB++;
if (AlbumName[AB] == "") {} else {
if (AlbumIMG[AB] == "") {} else {
let NewAlbumBtn = document.createElement("div");
NewAlbumBtn.classList.toggle("column");
NewAlbumBtn.id = AB;
NewAlbumBtn.setAttribute("style", "float: left; width: 25%; padding: 0 8px; text-align:center;align-items:center; display: inline-block; float: none; white-space: nowrap; overflow: hidden; text-overflow:ellipsis;");
//NewAlbumBtn.innerHTML = AlbumName[AB];
NewAlbumBtn.onclick = function() {PlayAlbum(NewAlbumBtn.id);};
let IMG = document.createElement("img");
IMG.src = AlbumIMG[AB];
IMG.style.width = "100%";
NewAlbumBtn.appendChild(IMG);
let text = document.createElement("p");
text.innerHTML = AlbumName[AB];
NewAlbumBtn.appendChild(text);
document.getElementById("albums").appendChild(NewAlbumBtn);
}}}}
function PlayAlbum(clicked_id) {
Id = clicked_id;
var AN;
for (AN = 0; AN < NumberOfSongs;) {
AN++;
let AB = document.getElementById(AN);
if (AlbumName[AB.id] == AlbumName[Id]) {
console.log("AlbumName " + AlbumName[Id]);
} else {
console.log("id: " + Id.id + " AB " + AB.id);
AB.remove();
}
}
}
function Update() {
let UpdateContainer = document.createElement("div");
UpdateContainer.id = "UC";
UpdateContainer.classList.toggle("NewUpdate");
document.body.appendChild(UpdateContainer);
let Updatetxt = document.createElement("div");
Updatetxt.id = "UTXT";
var wm = "Welcome to LanyxSoft Music!";
var wmr= wm.bold();
Updatetxt.innerHTML = wmr + " please note that this web player is still in beta testing mode meaning that there will most likely be issues. Thank you for you coaperation.";
Updatetxt.setAttribute("style", "z-index: 7; position: fixed; left: 50%; top: 15%; transform: translate(-50%, -50%); text-align: center; color: black; font-size: 20px; width: 430px;")
UpdateContainer.appendChild(Updatetxt);
let Updatebackground = document.createElement("div");
Updatebackground.id = "UB";
Updatebackground.classList.toggle("UpdateBackground");
document.body.appendChild(Updatebackground);
let UpdateScrollController = document.createElement("div");
UpdateScrollController.setAttribute("style", "z-index: 7; position: fixed; left: 50%; top: 40%; transform: translate(-50%, -50%); text-align: left; color: black; font-size: 20px; width: 430px; height: 120px;")
UpdateScrollController.id = "USC";
UpdateContainer.appendChild(UpdateScrollController);
let UpdateHead = document.createElement("div");
UpdateHead.id = "UH";
var u = "UPDATES";
var ur = u.bold();
UpdateHead.innerHTML = ur;
UpdateHead.setAttribute("style", "position: relative; text-align: center; color: black; font-size: 23px; width: 430px;")
UpdateScrollController.appendChild(UpdateHead);
let Updatetxt2 = document.createElement("div");
Updatetxt2.id = "UTXT2";
var UTXT2B = "Automatic button creation";
Updatetxt2.innerHTML = UTXT2B.bold() + " makes the player's ability to load faster.";
Updatetxt2.setAttribute("style", "position: relative; text-align: left; color: black; font-size: 20px; width: 430px;")
UpdateScrollController.appendChild(Updatetxt2);
let Updatetxt3 = document.createElement("div");
Updatetxt3.id = "UTXT3";
var UTXT3B = "Automatic Update notifications";
Updatetxt3.innerHTML = UTXT3B.bold() + " makes sure that when there's a new update, you will be notified.";
Updatetxt3.setAttribute("style", "position: relative; text-align: left; color: black; font-size: 20px; width: 430px;")
UpdateScrollController.appendChild(Updatetxt3);
let Updatetxt4 = document.createElement("div");
Updatetxt4.id = "UTXT4";
var UTXT4B = "More Album Art";
Updatetxt4.innerHTML = UTXT4B.bold() + " new and updated album art.";
Updatetxt4.setAttribute("style", "position: relative; text-align: left; color: black; font-size: 20px; width: 430px;")
UpdateScrollController.appendChild(Updatetxt4);
let Updatebutton = document.createElement("div");
Updatebutton.id = "UBTN";
Updatebutton.classList.toggle("UpdateCB");
Updatebutton.style.fontSize = "xx-large";
Updatebutton.innerHTML = "Continue";
Updatebutton.onclick = function() {document.getElementById("UTXT").style.visibility = "hidden"; document.getElementById("UTXT2").style.visibility = "hidden"; document.getElementById("UC").style.visibility = "hidden"; document.getElementById("UB").style.visibility = "hidden"; document.getElementById("UBTN").style.visibility = "hidden"; startUI();}
UpdateContainer.appendChild(Updatebutton);
}
var config = {apiKey:"", authDomain: "”, databaseURL: "", projectId: "", storageBucket: "", messagingSenderId: ""};
firebase.initializeApp(config);
function InitializeStartzup() {
let id = localStorage.getItem("LUDIN");
var ref = firebase.database().ref('LanyxSoft-Music-Update/' + id + '/updatestats');
ref.on('value', function(snapshot) {
startUI();
});
}
function BeginUpdate() {
var postData = {};
let id = (0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36);
var updates = {};
let L = localStorage.getItem("LUDIN");
Update();
firebase.database().ref('LanyxSoft-Music-Update/' + L).set({
updated : "true"
});
var ref = firebase.database().ref().child('/LanyxSoft-Music-Update/'+id);
ref.on("child_added", function(child) {
var IDofFriends = child.val();
if(IDofFriends == localStorage.getItem("LUDIN")) {
console.log("func: child_added result: User id matches to id in accepted LanyxSoft database");
} else {
console.log("func: child_added result: User id doesn't match to id in accepted LanyxSoft database");
}
});
//updates["/posts/" + "hihihihihi"] = postData;
return firebase.database().ref().update(updates);
}
//child_added
function SetID() {
let id = (0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36)+"-"+(0|Math.random()*9e6).toString(36);
localStorage.setItem("LUDIN", id);
BeginUpdate();
}
// Check browser support
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("LUDIN") == null) {
console.log("func: SetID() result:", true);
SetID();
} else {
console.log("func: InitializeStartzup() result:", true); //console.log("func: InitializeStartzup() result: func success= "+ true);
InitializeStartzup();
}
} else {
Update();
console.log("s means that some feature aren't available on this device");
}
function drop() {
}
window.onclick = function(event, clicked_id) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
//openDropdown.classList.remove('show');
}}}}
//labels
//buttons
var input = document.getElementById("button");
var input2 = document.getElementById("button2");
//text/labels/numbers
//number vals
var num = 1;
var a = new Date();
var mt = a.getMonth() + 1;
var dy = a.getDate();
var yr = a.getFullYear();
var tm = a.getHours()+":"+a.getMinutes();
var dateFormat = mt+"/"+dy+"/"+yr+"_"+tm;
//labels
var audiotitle = document.getElementById("audiotitle");
var audioartist = document.getElementById("artist");
var image = document.getElementById("AlbumArt");
var x = document.getElementById("myAudio");
var percent = document.getElementById("currentlbl");
audiotitle.innerHTML = x.title;
//inputslider
var slider = document.getElementById("myRange");
slider.oninput = function() {
percent.innerHTML = this.value + "%";
x.currentTime = slider.value;
}
//device orientation functions
function zoomOutMobile() {
var viewport = document.querySelector('meta[name="viewport"]');
if ( viewport ) {
viewport.content = "width=device-width, initial-scale=1.0";
}
}
function readDeviceOrientation() {
switch (window.orientation) {
case 0:
// Portrait
document.getElementById("PlaylistC").style.visibility = "hidden";
document.getElementById("PlaylistC").style.display = "none";
document.getElementById("container").setAttribute("style", "top: 5%; position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 20px auto; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
break;
case 180:
// Portrait (Upside-down)
document.getElementById("PlaylistC").style.visibility = "hidden";
document.getElementById("PlaylistC").style.display = "none";
document.getElementById("container").setAttribute("style", "top: 5%; position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 20px auto; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
break;
case -90:
// Landscape (Clockwise)
document.getElementById("PlaylistC").style.visibility = "visible";
document.getElementById("PlaylistC").style.display = "block";
document.getElementById("container").setAttribute("style", "position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 0px; left: 0; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
zoomOutMobile();
break;
case 90:
// Landscape (Counterclockwise)
document.getElementById("PlaylistC").style.visibility = "visible";
document.getElementById("PlaylistC").style.display = "block";
document.getElementById("container").setAttribute("style", "position: relative; width: 330px; min-height:480px; background: #333; overflow: auto; margin: 0px; left: 0; border-radius: 10px; box-shadow: 0 10px 8px -8px #333; align-items: center; text-align: center;");
zoomOutMobile();
break;
}
}
readDeviceOrientation();
window.onorientationchange = readDeviceOrientation;
//SEARCH
//document.getElementById("SearchBox").addEventListener("keyup",);
function search() {
var input, filter, ui, li, a, w;
input = document.getElementById("SearchBox");
filter = input.value.toUpperCase();
ui = document.getElementById("PlaylistDropdown");
li = ui.getElementsByTagName("li");
//function for dd
for (w = 0; w < li.length; w++) {
a = li[w].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[w].style.display = "";
} else {
li[w].style.display = "none";
}}
}
/*function searchAlbums() {
var input, filter, ui, li, a, w;
input = document.getElementById("SearchBox");
filter = input.value.toUpperCase();
ui = document.getElementById("albums");
li = ui.getElementsByTagName("div");
//function for dd
for (w = 0; w < li.length; w++) {
a = li[w].getElementsByTagName("p")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[w].style.display = "";
} else {
li[w].style.display = "none";
}}
}*/
function Shuffle() {
var s = Math.floor(Math.random() * NumberOfSongs) + 1;
x.title = titles[s];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[s];
if (albumart[s] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[s];
}
x.src = songs[s];
x.play();
num = 1;
playAudio();
}
var i = 1;
function keys() {
if (x.currentTime == x.duration) {
//x.src = sources.two;
i++;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}}
function next() {
i++;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}
function rewind() {
i--;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}
function Playbutton(clicked_id) {
i = clicked_id;
x.title = titles[i];
audiotitle.innerHTML = x.title;
audioartist.innerHTML = artists[i];
if (albumart[i] == "") {
image.src = "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p164.png";
} else {
image.src = albumart[i];
}
x.src = songs[i];
x.play();
num = 1;
playAudio();
}
function startup() {
input2.style.display="none";
}
startup()
function playAudio() {
x.play();
if (num == 1) {
x.play();
//text.innerHTML = "pause";
input.style.display="none";
input2.style="visibility:visible;";
input2.style.display="block";
num = 0;
d = dateFormat + "playing";
} else {
x.pause();
//text.innerHTML = "play";
input2.style="visibility:hidden;";
input2.style.display="none";
input.style="visibility:visable;";
num = 1;
d = dateFormat + "paused";
}}
window.addEventListener('load', function() {
var cur = document.querySelector('#perc'),
vid = document.querySelector('#myAudio')
dur = document.getElementById("durationlbl");
per = document.getElementById("currentlbl");
})
myAudio.addEventListener('timeupdate', function(e) {
//current time
per.textContent = sToTime(e.target.currentTime);
//duraion
dur.textContent = sToTime(e.target.duration);
slider.value = x.currentTime;
//percent.innerHTML = x.currentTime;
slider.max = x.duration;
keys();
})
function sToTime(t) {
return padZero(parseInt((t / (60 * 60)) % 24)) + ":" +
padZero(parseInt((t / (60)) % 60)) + ":" +
padZero(parseInt((t) % 60));
}
function padZero(v) {
return (v < 10) ? "0" + v : v;
}
So in main.js I have the “brains” i guess, of the entire player. The function PlayAlbum(clicked_id) is the problem. That’s the function that is supposed to filter all the songs so that the only songs left are the ones from the clicked album.
song-list.js
So in song-list.js i just have the list of songs and the album art for it. I also have the link to the file. For you guys’s Sake i really should organize this better, but that’ll happen in a little bit. I didn’t include the code in here because its not an important factor to my problem.
variables.js
var AlbumName = {
1 : "",
2 : "",
3 : "",
4 : "",
5 : "Mania",
6 : "",
7 : "",
8 : "",
9 : "American Beauty/American Psycho",
10 : "",
11 : "Vessel",
12 : "",
13 : "Vessel",
14 : "American Beauty/American Psycho",
15 : "",
16 : "",
17 : "",
18 : "",
19 : "",
20 : "",
21 : "",
22 : "",
23 : "Vessel",
24 : "",
25 : "",
26 : "",
27 : "",
28 : "",
29 : "",
30 : "",
31 : "",
32 : "",
33 : "Mania",
34 : "Watching the Sky",
35 : "",
36 : "",
37 : ""
}
var AlbumIMG = {
1 : "",
2 : "",
3 : "https://vignette.wikia.nocookie.net/monstercat/images/0/0c/Marshmello_-_Alone.jpg/revision/latest?cb=20160513204533",
4 : "",
5 : "https://images-na.ssl-images-amazon.com/images/I/41K3SuHNQpL._SS500.jpg",
6 : "",
7 : "",
8 : "",
9 : "https://upload.wikimedia.org/wikipedia/en/b/b6/American_Beauty_American_Psycho_cover.png",
10 : "",
11 : "https://images-na.ssl-images-amazon.com/images/I/41%2BCuqqyyvL.jpg",
12 : "",
13 : "https://images-na.ssl-images-amazon.com/images/I/41%2BCuqqyyvL.jpg",
14 : "https://upload.wikimedia.org/wikipedia/en/b/b6/American_Beauty_American_Psycho_cover.png",
15 : "",
16 : "",
17 : "",
18 : "",
19 : "",
20 : "",
21 : "",
22 : "",
23 : "https://images-na.ssl-images-amazon.com/images/I/41%2BCuqqyyvL.jpg",
24 : "",
25 : "",
26 : "",
27 : "",
28 : "",
29 : "",
30 : "",
31 : "",
32 : "",
33 : "https://images-na.ssl-images-amazon.com/images/I/41K3SuHNQpL._SS500.jpg",
34 : "https://iplock.weebly.com/uploads/9/5/7/3/95731436/p184.png",
35 : "",
36 : "",
37 : ""
}
So the variables.js file is just the list of the albums, like the first set of variables is the list of songs and what album they belong to. The second is the links to the album art for the specified album.
To see my full code go to https://github.com/lightning417techa/Music
EDIT 2
I was thinking about simplifying this a bit but i came to a point where if i did simplify the creation of the song buttons and the album buttons, it throws an error. I also noticed that i cant set the ids as a number.
I'm pretty sure let AB = document.getElementById(AN); is your issue. Throw a debugger in after that line and make sure it's populating the way you expect it to. I'm fairly certain that ids can't be numbers and you're expecting them to be (if I'm reading this all correctly).
So i went old school and actually grabbed a whiteboard and wrote my idea down. I came to realization that in the function StartUI() it sets The I’d of the button to a number, then i read the documentation on w3schools and i saw that i can remove part of a string for example if i did document.getElementById(“Text”).innerHTML = MyEditedText; would turn out to
let myText = "hello1";
document.getElementById(“Text”).innerHTML = myText;
function MyFunction() {
let MyEditedText = myText.replace("hello", "");
document.getElementById(“Text”).innerHTML = MyEditedText;
}
<p id=“Text”></p>
<button onclick=“MyFunction”>Click Me</button>

Javascript end game when click on image

Hey this is my first time on Stackoverflow!
I am building a small javascript html5 game where you click on objects kind of like whack-a-mole.. The goal is to kill as many "gem green" and " gem blue" as possible in 10 seconds, and when you click on the "gem red".. the game ends and plays a sound.
I got most things to work, except I can't find a way to make the game end when clicking on "gem red".. I have tried lots of functions and listeners.. but to no avail.. can anyone help me figure this out?
Here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Gem Game</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<style>
section#game {
width: 480px;
height: 800px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
background-image: url('img/Splash.png');
position: relative;
color: #ffffff;
font-size: 30px;
font-family: "arial,sans-serif";
}
section#game .score{
display: block;
position: absolute;
top: 10px;
left: 10px;
}
section#game .time{
display: block;
position: absolute;
top: 10px;
right: 10px;
}
section#game .start{
display: block;
padding-top: 40%;
margin: 0 auto 0 auto;
text-align: center;
width: 70%;
cursor: pointer;
}
section#game .start .high-scores{
text-align: left;
}
section#game .gem{
display: block;
position: absolute;
width: 40px;
height: 44px;
cursor: pointer;
}
section#game .gem.green{
background: url('img/Gem Green.png') no-repeat top left;
}
section#game .gem.blue{
background: url('img/Gem Blue.png') no-repeat top left;
}
section#game .gem.red{
background: url('img/Gem Red.png') no-repeat top left;
}
</style>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
function Game(){
var game = document.querySelector("section#game");
var score = game.querySelector("section#game span.score");
var high_scores = game.querySelector("section#game ol.high-scores");
var time = game.querySelector("section#game span.time");
var start = game.querySelector("section#game span.start");
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 1.2);
gems[1] = new Gem('blue', 20, 1);
gems[2] = new Gem('red', 50, 0.75);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
<!-- parse high score keeper -->
function HighScores() {
if(typeof(Storage)!=="undefined"){
var scores = false;
if(localStorage["high-scores"]) {
high_scores.style.display = "block";
high_scores.innerHTML = '';
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = scores[i];
var fragment = document.createElement('li');
fragment.innerHTML = (typeof(s) != "undefined" ? s : "" );
high_scores.appendChild(fragment);
}
}
} else {
high_scores.style.display = "none";
}
}
function UpdateScore() {
if(typeof(Storage)!=="undefined"){
var current = parseInt(score.innerHTML);
var scores = false;
if(localStorage["high-scores"]) {
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = parseInt(scores[i]);
var val = (!isNaN(s) ? s : 0 );
if(current > val)
{
val = current;
scores.splice(i, 0, parseInt(current));
break;
}
}
scores.length = 10;
localStorage["high-scores"] = JSON.stringify(scores);
} else {
var scores = new Array();
scores[0] = current;
localStorage["high-scores"] = JSON.stringify(scores);
}
HighScores();
}
}
function Stop(interval) {
clearInterval(interval);
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
var interval = setInterval(Spawn, 750);
var count = 10;
var counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
Stop(interval);
Stop(counter);
time.innerHTML = "Game Over!";
start.style.display = "block";
UpdateScore();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var game = new Game();
});
</script>
</head>
<body>
<div id="page">
<section id="game">
<span class="score">0</span>
<span class="time">0</span>
<span class="start">START!
<ol class="high-scores"></ol>
</span>
</section>
</div>
</body>
</html>
Alessio -
You only need a few minor changes to your code to make it work. The example below should help you get started in the right direction. Good luck.
Changes:
Add an endGame() function and move the stop game logic from the timer() function into it.
Add a line to the click() function to check for red gem clicks.
if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!");
Declare the count, counter, and interval variables at the top of your Game object.
The code below also has a few minor CSS changes used for debugging which you can remove.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>HTML 5 Gem Game</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1">
<style>
section#game {
width: 480px;
height: 800px;
max-width: 100%;
max-height: 100%;
overflow: hidden;
position: relative;
background-image: url('img/Splash.png');
border: 1px red dotted;
position: relative;
color: red;
font-size: 30px;
font-family: "arial,sans-serif";
}
section#game .score{
display: block;
position: absolute;
top: 10px;
left: 10px;
}
section#game .time{
display: block;
position: absolute;
top: 10px;
right: 10px;
}
section#game .start{
display: block;
padding-top: 40%;
margin: 0 auto 0 auto;
text-align: center;
width: 70%;
cursor: pointer;
}
section#game .start .high-scores{
text-align: left;
}
section#game .gem{
display: block;
position: absolute;
width: 40px;
height: 44px;
cursor: pointer;
}
section#game .gem.green{
background: url('img/Gem Green.png') no-repeat top left;
background-color: green;
}
section#game .gem.blue{
background: url('img/Gem Blue.png') no-repeat top left;
background-color: blue;
}
section#game .gem.red{
background: url('img/Gem Red.png') no-repeat top left;
background-color: red;
}
</style>
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
function Game(){
var game = document.querySelector("section#game");
var score = game.querySelector("section#game span.score");
var high_scores = game.querySelector("section#game ol.high-scores");
var time = game.querySelector("section#game span.time");
var start = game.querySelector("section#game span.start");
var interval, counter, count;
function Gem(Class, Value, MaxTTL) {
this.Class = Class;
this.Value = Value;
this.MaxTTL = MaxTTL;
};
var gems = new Array();
gems[0] = new Gem('green', 10, 1.2);
gems[1] = new Gem('blue', 20, 1);
gems[2] = new Gem('red', 50, 0.75);
function Click(event)
{
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var target = event.target || event.srcElement;
if(target.className.indexOf('gem') > -1){
var value = parseInt(target.getAttribute('data-value'));
var current = parseInt( score.innerHTML );
var audio = new Audio('music/blaster.mp3');
audio.play();
score.innerHTML = current + value;
target.parentNode.removeChild(target);
if (target.className.indexOf('red') > 0) endGame("Red Gem - You win!");
}
return false;
}
function Remove(id) {
var gem = game.querySelector("#" + id);
if(typeof(gem) != 'undefined')
gem.parentNode.removeChild(gem);
}
function Spawn() {
var index = Math.floor( ( Math.random() * 3 ) );
var gem = gems[index];
var id = Math.floor( ( Math.random() * 1000 ) + 1 );
var ttl = Math.floor( ( Math.random() * parseInt(gem.MaxTTL) * 1000 ) + 1000 ); //between 1s and MaxTTL
var x = Math.floor( ( Math.random() * ( game.offsetWidth - 40 ) ) );
var y = Math.floor( ( Math.random() * ( game.offsetHeight - 44 ) ) );
var fragment = document.createElement('span');
fragment.id = "gem-" + id;
fragment.setAttribute('class', "gem " + gem.Class);
fragment.setAttribute('data-value', gem.Value);
game.appendChild(fragment);
fragment.style.left = x + "px";
fragment.style.top = y + "px";
setTimeout( function(){
Remove(fragment.id);
}, ttl)
}
<!-- parse high score keeper -->
function HighScores() {
if(typeof(Storage)!=="undefined"){
var scores = false;
if(localStorage["high-scores"]) {
high_scores.style.display = "block";
high_scores.innerHTML = '';
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = scores[i];
var fragment = document.createElement('li');
fragment.innerHTML = (typeof(s) != "undefined" ? s : "" );
high_scores.appendChild(fragment);
}
}
} else {
high_scores.style.display = "none";
}
}
function UpdateScore() {
if(typeof(Storage)!=="undefined"){
var current = parseInt(score.innerHTML);
var scores = false;
if(localStorage["high-scores"]) {
scores = JSON.parse(localStorage["high-scores"]);
scores = scores.sort(function(a,b){return parseInt(b)-parseInt(a)});
for(var i = 0; i < 10; i++){
var s = parseInt(scores[i]);
var val = (!isNaN(s) ? s : 0 );
if(current > val)
{
val = current;
scores.splice(i, 0, parseInt(current));
break;
}
}
scores.length = 10;
localStorage["high-scores"] = JSON.stringify(scores);
} else {
var scores = new Array();
scores[0] = current;
localStorage["high-scores"] = JSON.stringify(scores);
}
HighScores();
}
}
function Stop(interval) {
clearInterval(interval);
}
function endGame( msg ) {
count = 0;
Stop(interval);
Stop(counter);
var left = document.querySelectorAll("section#game .gem");
for (var i = 0; i < left.length; i++) {
if(left[i] && left[i].parentNode) {
left[i].parentNode.removeChild(left[i]);
}
}
time.innerHTML = msg || "Game Over!";
start.style.display = "block";
UpdateScore();
}
this.Start = function() {
score.innerHTML = "0";
start.style.display = "none";
interval = setInterval(Spawn, 750);
count = 10;
counter = null;
function timer()
{
count = count-1;
if (count <= 0)
{
endGame();
return;
} else {
time.innerHTML = count + "s left";
}
}
counter = setInterval(timer, 1000);
setTimeout( function(){
Stop(interval);
}, count * 1000)
};
addEvent(game, 'click', Click);
addEvent(start, 'click', this.Start);
HighScores();
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var game = new Game();
});
</script>
</head>
<body>
<div id="page">
<section id="game">
<span class="score">0</span>
<span class="time">0</span>
<span class="start">START!
<ol class="high-scores"></ol>
</span>
</section>
</div>
</body>
</html>
For starters, you shouldn't include a style sheet and your entire HTML file since neither is relevant and you should use a canvas element instead of this chaotic use of CSS and html elements, which would allow the size of your code to be halved. Furthermore, you should be able to fix this by just changing some global boolean variable to false when the red gem is clicked and when the boolean variable is false (this if statement belongs at the end of your game loop) you call Stop(arg)/clearInterval(arg). Given that your current code doesn't seem to have a global boolean variable indicating game state (using an enumeration would generally be a cleaner solution but a simple boolean seems to suit this case)

How would I make these animations animate at different times?

I'm making a whack-a-mole game and this is what I have so far, I'm aware this is sloppy and probably isn't the easiest/smartest way to do this. What I need to know is how to get my animations to animate at separate times. This current code works to animate 9 different moles coming out of holes but I need them to animate at different times(so none of them will come up at the same time, or within a few milliseconds of eachother) My current code is
<html>
<body>
<style type="text/css">
body, a, a:hover {cursor: url(http://cur.cursors-4u.net/others/oth-5/oth438.cur),
progress;}
</style>
<body background = "http://i52.tinypic.com/34e9ekj.jpg">
<b><center><font size="5"><div id='counter'>0</div></font></center><b>
<b><center><i>Whack-A-Mole</i> - by Steven</center></b>
<div
style="
top: 37;
left: 350;
position: absolute;
z-index: 1;
visibility: show;">
<center><img id='animation0' src ='http://i51.tinypic.com/sxheeo.gif'/></center>
</div>
<div
style="
top: 37;
left: 33;
position: absolute;
z-index: 1;
visibility: show;">
<left><img id='animation1' src ='http://i51.tinypic.com/sxheeo.gif'/></left>
</div>
<div
style="
top: 37;
left: 700;
position: absolute;
z-index: 1;
visibility: show;">
<right><img id='animation2' src ='http://i51.tinypic.com/sxheeo.gif'/></right>
</div>
<div
style="
top: 200;
left: 352;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation3' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 200;
left: 33;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation4' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 200;
left: 700;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation5' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 350;
left: 700;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation6' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 350;
left: 33;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation7' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
<div
style="
top: 350;
left: 352;
position: absolute;
z-index: 1;
visibility: show;">
<img id='animation8' src ='http://i51.tinypic.com/sxheeo.gif'/>
</div>
</body>
<head>
<script type="text/javascript">
var urls;
function animate0(pos) {
pos %= urls.length;
var animation0 = document.getElementById('animation0');
var counter = document.getElementById('counter');
animation0.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation0.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation0.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate0(++pos);
}, (Math.random()*500) + 1000);
}
function animate1(pos) {
pos %= urls.length;
var animation1 = document.getElementById('animation1');
var counter = document.getElementById('counter');
animation1.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation1.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation1.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate1(++pos);
}, (Math.random()*500) + 1000);
}
function animate2(pos) {
pos %= urls.length;
var animation2 = document.getElementById('animation2');
var counter = document.getElementById('counter');
animation2.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation2.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation2.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate2(++pos);
}, (Math.random()*500) + 1000);
}
function animate3(pos) {
pos %= urls.length;
var animation3 = document.getElementById('animation3');
var counter = document.getElementById('counter');
animation3.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation3.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation3.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate3(++pos);
}, (Math.random()*500) + 1000);
}
function animate4(pos) {
pos %= urls.length;
var animation4 = document.getElementById('animation4');
var counter = document.getElementById('counter');
animation4.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation4.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation4.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate4(++pos);
}, (Math.random()*500) + 1000);
}
function animate5(pos) {
pos %= urls.length;
var animation5 = document.getElementById('animation5');
var counter = document.getElementById('counter');
animation5.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation5.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation5.onclick = function() {
//do nothing onclick
}
}
setTimeout(function() {
animate5(++pos);
}, (Math.random()*500) + 1000);
}
function animate6(pos) {
pos %= urls.length;
var animation6 = document.getElementById('animation6');
var counter = document.getElementById('counter');
animation6.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation6.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation6.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate6(++pos);
}, (Math.random()*500) + 1000);
}
function animate7(pos) {
pos %= urls.length;
var animation7 = document.getElementById('animation7');
var counter = document.getElementById('counter');
animation7.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation7.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation7.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate7(++pos);
}, (Math.random()*500) + 1000);
}
function animate8(pos) {
pos %= urls.length;
var animation8 = document.getElementById('animation8');
var counter = document.getElementById('counter');
animation8.src = urls[pos];
if (pos == 1) { // only make onclick when have a certain image
animation8.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
}
else {
animation8.onclick = function() {
//do nothing
}
}
setTimeout(function() {
animate8(++pos);
}, (Math.random()*500) + 1000);
}
window.onload = function() { //Frames go below, seperated by commas format= , "URL");
urls = new Array("http://i51.tinypic.com/sxheeo.gif", "http://i56.tinypic.com/2i3tyw.gif");
animate0(0);
animate1(0);
animate2(0);
animate3(0);
animate4(0);
animate5(0);
animate6(0);
animate7(0);
animate8(0);
}
</script>
</head>
</html>
Generate 9 random numbers between 0 and your start time variation. Decide the max distance you want between the animations and scale the random numbers to that time frame. Then, set 9 timers to those times from now so each timer starts an animation.
If you wanted the animations to start over 500 milliseconds, you'd do something like this:
var randomTimes = [9];
for (var i = 0; i < 9; i++) {
randomTimes[i] = Math.floor(Math.random() * 501);
}
Now you have 9 random times spread out over 500 milliseconds and you can use those values with setTimeout to start each animation at a random time.
Copy/pasting a function this way is indeed sloppy!
You need to setup a flag:
var isMole = false;//at first there is no mole
if(!isMole){
//there is no mole, you can show one here
isMole = true;//there is a mole now!
}else{
//there is a mole, we wait.
}
Now set that flag to false when the mole times out or it struck by a hammer!

Categories