I am writing this post to get help on passing between players using JQuery. I am currently designing a dominos game with four players. My current version works until the end but it gets extremely laggy by the last four pieces. I have determined that this is due to the recursion in the playTurn function. I have tried to use events but that has not worked well for me. My question is if you know how to create a better game loop using JQuery. I would like to finish the basics for this game using JQuery but any suggestions on a better path would be much appreciated. The code is below.
P.S. The game is nowhere near complete but I would very much like to get this problem fixed before proceeding. I am also a beginner to javascript. Thank you for your assistance.
Edit: After some tinkering and help from a stackover flow user, I realized that my addDominoToBoard function in my playTurn function was the main culprit of the lag. Any suggestions on how to better redraw my board. Thank you once again.
var makeBoard = function(){
var totalkeys = [
[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6],
[1,1],[1,2],[1,3],[1,4],[1,5],[1,6],
[2,2],[2,3],[2,4],[2,5],[2,6],
[3,3],[3,4],[3,5],[3,6],
[4,4],[4,5],[4,6],
[5,5],[5,6],
[6,6]
];
return totalkeys;
}
var randomInt = function(min,max)
{
return Math.floor(Math.random()*(max-min)+min);
}
var makeHand = function(board){
var hand = [];
for(x = 0;x<7;x++){
var ranInt = randomInt(0,board.length);
var key = board[ranInt];
hand.push(key);
board.splice(ranInt,1);
}
return hand;
}
var hideItems = function(){
if($("#player1").hasClass('first')){
$("#player2").hide();
$("#player3").hide();
$("#player4").hide();
}else if ($("#player2").hasClass('first')){
$("#player1").hide();
$("#player3").hide();
$("#player4").hide();
}else if($("#player3").hasClass('first')){
$("#player2").hide();
$("#player1").hide();
$("#player4").hide();
}else{
$("#player2").hide();
$("#player3").hide();
$("#player1").hide();
};
}
var loadGame = function(){
var board = makeBoard();
var player1Hand = makeHand(board);
var player2Hand = makeHand(board);
var player3Hand = makeHand(board);
var player4Hand = makeHand(board);
createHands(player1Hand,player2Hand,player3Hand,player4Hand);
hideItems()
}
var createHands = function(player1Hand,player2Hand,player3Hand,player4Hand){
for(x = 0; x < player1Hand.length;x++){
var domino = player1Hand[x].toString();
if(domino == "6,6"){
$("#player1").addClass("first")
};
var src = ' src =images/Dominos/['+domino+'].png>';
$('#player1 #hand').append('<img class = "domino" id ='+domino+src);
};
for(x = 0; x < player2Hand.length;x++){
var domino = player2Hand[x].toString();
if(domino == "6,6"){
$("#player2").addClass("first")
};
var src = ' src =images/Dominos/['+domino+'].png>';
$('#player2 #hand').append('<img class = "domino" id ='+domino+src);
};
for(x = 0; x < player3Hand.length;x++){
var domino = player3Hand[x].toString();
if(domino == "6,6"){
$("#player3").addClass("first")
};
var src = ' src =images/Dominos/['+domino+'].png>';
$('#player3 #hand').append('<img id ='+domino+src);
};
for(x = 0; x < player4Hand.length;x++){
var domino = player4Hand[x].toString();
if(domino == "6,6"){
$("#player4").addClass("first")
};
var src = ' src =images/Dominos/['+domino+'].png>';
$('#player4 #hand').append('<img id ='+domino+src);
};
}
var choseFirstPlayer = function(){
//console.log("I def shouldnt be here");
if($("#player1").hasClass('first')){
return "player1";
}else if ($("#player2").hasClass('first')){
return "player2";
}else if($("#player3").hasClass('first')){
return "player3";
}else{
return "player4";
};
}
var playTurn = function(player){
player = choseNextPlayer(player);
$('#'+player+" #hand img").click(function(){
var dominoSrc = $(this).attr('src');
var dominoNumber = $(this).attr('id');
addDominoToBoard(dominoSrc,dominoNumber);
$(this).remove();
//console.log("This is the player after calling choseNextPlayer. This should be the same as the next player:"+player);
playTurn(player);
});
}
var choseNextPlayer = function(player){
//console.log("This is the player at the beginning of choseNextPlayer:"+player);
if(player == "player1"){
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player2");
$("#player1").hide();
$("#player2").show();
return "player2";
}else if(player == "player2"){
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player3");
$("#player2").hide();
$("#player3").show();
return "player3";
}else if(player == "player3"){
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player4");
$("#player3").hide();
$("#player4").show();
return "player4";
}else{
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player1");
$("#player4").hide();
$("#player1").show();
return "player1";
};
}
var checkGame = function(){
return true;
}
var addDominoToBoard = function(dominoSrc,dominoNumber){
$("#board #notPlaced").append("<img id =" + dominoNumber + " src ="+dominoSrc+">");
drawDominoOnBoard(dominoNumber);
}
var drawDominoOnBoard = function(initalXposition,initalYposition,dominoNumber){
var initalXposition = ($(window).width()/2) + "px";
var initalYposition = ($(window).height()/2 -100) + "px";
var domino = $("#board #notPlaced img");
domino.css({"position": "absolute", "top": initalYposition, "left": initalXposition});
var domino2 = domino.clone();
$("#board #placed").append(domino2);
domino.remove();
}
$(document).ready(function(){
var windowWidth = $(window).width() - $(window).width()/10;
var windowHeight = $(window).height() - $(window).height()/6;
var gameOn = true;
$("#board img").css({"width":windowWidth.toString(),"height":windowHeight.toString()}).hide();
$("#pressed").hide();
$("#notPressed").hover(
function(){
$(this).hide();
$("#pressed").show();
});
$("#pressed").click(function(){
$(this).fadeOut("slow",function(){
$("#board img").show("slow",function(){
loadGame();
//console.log("Here again");
var player = choseFirstPlayer();
$('#'+player+" #hand img").click(function(){
//console.log("I should not be here");
var dominoSrc = $(this).attr('src');
var dominoNumber = $(this).attr('id');
addDominoToBoard(dominoSrc,dominoNumber);
$(this).remove();
playTurn(player);
});
});
});
});
});
First, I want to thank KKetch for making me realize that I was doing a bunch of unnecessary DOM manipulations. After doing more research on jQuery, I realized that it is much better to declare variables instead of constantly getting HTML elements. However, that did not solve my lag problem. I solved my lag problem by eliminating the recursion and using events handlers. My solution was to rely on hiding and showing the hands on the screen. My game loop is self implied by the user being on the web page itself. The solution is below for anyone interested and if you want to keep track of this project, here is the link to the github page. Thanks once again.
Link:
https://github.com/aneurycasado/Dominos-Para-Los-Dominicanos
Solution:
domino00 = new Image();
domino00.src = "images/Dominos/[0,0].png"
domino01 = new Image();
domino01.src = "images/Dominos/[0,1].png"
domino02 = new Image();
domino02.src = "images/Dominos/[0,2].png"
domino03 = new Image();
domino03.src = "images/Dominos/[0,3].png"
domino04 = new Image();
domino04.src = "images/Dominos/[0,4].png"
domino05 = new Image();
domino05.src = "images/Dominos/[0,5].png"
domino06 = new Image();
domino06.src = "images/Dominos/[0,6].png"
domino11 = new Image();
domino11.src = "images/Dominos/[1,1].png"
domino12 = new Image();
domino12.src = "images/Dominos/[1,2].png"
domino13 = new Image();
domino13.src = "images/Dominos/[1,3].png"
domino14 = new Image();
domino14.src = "images/Dominos/[1,4].png"
domino15 = new Image();
domino15.src = "images/Dominos/[1,5].png"
domino16 = new Image();
domino16.src = "images/Dominos/[1,6].png"
domino22 = new Image();
domino22.src = "images/Dominos/[2,2].png"
domino23 = new Image();
domino23.src = "images/Dominos/[2,3].png"
domino24 = new Image();
domino24.src = "images/Dominos/[2,4].png"
domino25 = new Image();
domino25.src = "images/Dominos/[2,5].png"
domino26 = new Image();
domino26.src = "images/Dominos/[2,6].png"
domino33 = new Image();
domino33.src = "images/Dominos/[3,3].png"
domino34 = new Image();
domino34.src = "images/Dominos/[3,4].png"
domino35 = new Image();
domino35.src = "images/Dominos/[3,5].png"
domino36 = new Image();
domino36.src = "images/Dominos/[3,6].png"
domino44 = new Image();
domino44.src = "images/Dominos/[4,4].png"
domino45 = new Image();
domino45.src = "images/Dominos/[4,5].png"
domino46 = new Image();
domino46.src = "images/Dominos/[4,6].png"
domino55 = new Image();
domino55.src = "images/Dominos/[5,5].png"
domino56 = new Image();
domino56.src = "images/Dominos/[5,6].png"
domino66 = new Image();
domino66.src = "images/Dominos/[6,6].png"
dominoImages = [ domino00,domino01,domino02,domino03,domino04,domino05,domino06,
domino11,domino12,domino13,domino14,domino15,domino16,
domino22,domino23,domino24,domino25,domino26,
domino33,domino34,domino35,domino36,
domino44,domino45,domino46,
domino55,domino56,
domino66
]
var drawDominoOnBoard = function(initalXposition,initalYposition,dominoNumber){
var initalXposition = ($(window).width()/2) + "px";
var initalYposition = ($(window).height()/2 -100) + "px";
var domino = $("#board #notPlaced img");
domino.css({"position": "absolute", "top": initalYposition, "left": initalXposition});
var domino2 = domino.clone();
$("#board #placed").append(domino2);
domino.remove();
}
var playTurn = function(player, player1, player2,
player3, player4, dominosPlaced){
player = choseNextPlayer(player,player1,player2,player3,player4);
$('#'+player+" #hand img").click(function(){
var domino = $(this);
addDominoToBoard(domino,dominosPlaced);
$(this).remove();
$(this).unbind("click");
playTurn(player,player1,player2,player3,player4,dominosPlaced);
});
}
var choseNextPlayer = function(player,player1,player2,player3,player4){
//console.log("This is the player at the beginning of choseNextPlayer:"+player);
if(player == "player1"){
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player2");
player1.hide();
player2.show();
return "player2";
}else if(player == "player2"){
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player3");
player2.hide();
player3.show();
return "player3";
}else if(player == "player3"){
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player4");
player3.hide();
player4.show();
return "player4";
}else{
//console.log("This is the previous player in choseNextPlayer. Should be the same as the player above:" + player);
//console.log("This is the next player. Should follow the sequence" + "player1");
player4.hide();
player1.show();
return "player1";
};
}
var addDominoToBoard = function(domino,dominoPlaced){
var dominoClone = domino.clone();
dominoPlaced.append(dominoClone);
drawDominoOnBoard(dominoPlaced);
}
var choseFirstPlayer = function(player1,player2,player3,player4){
//console.log("I def shouldnt be here");
if(player1.find("#hand").hasClass('first')){
player1.show();
return "player1";
}else if (player2.find("#hand").hasClass('first')){
player2.show();
return "player2";
}else if(player3.find("#hand").hasClass('first')){
player3.show();
return "player3";
}else{
player4.show();
return "player4";
};
}
var hideHands = function(player1,player2,player3,player4){
player1.hide();
player2.hide();
player3.hide();
player4.hide();
}
var randomInt = function(number){
return Math.floor(Math.random()*number);
}
var makeHand = function(player){
var hand = [];
var player = $(player);
var src = domino66.src
for(x = 0;x<7;x++){
var ranInt = randomInt(dominoImages.length);
var domino = dominoImages[ranInt];
if(domino.src == src){
player.addClass("first");
}
player.append(domino);
dominoImages.splice(ranInt,1);
}
return hand;
}
var hideHands = function(player1,player2,player3,player4){
player1.hide();
player2.hide();
player3.hide();
player4.hide();
}
var loadGame = function(){
makeHand("#player1 #hand");
makeHand("#player2 #hand");
makeHand("#player3 #hand");
makeHand("#player4 #hand");
}
$(document).ready(function(){
loadGame();
var windowWidth = $(window).width() - $(window).width()/10;
var windowHeight = $(window).height() - $(window).height()/6;
var gameOn = true;
var boardImg = $("#board img");
var dominosPlaced = $("#board #placed");
var pressed = $("#pressed");
var notPressed = $("#notPressed");
var player1 = $("#player1");
var player2 = $("#player2");
var player3 = $("#player3");
var player4 = $("#player4");
hideHands(player1,player2,player3,player4);
var player = ""
boardImg.css({"width":windowWidth.toString(),"height":windowHeight.toString()}).hide();
pressed.hide();
notPressed.hover(function(){
$(this).hide();
pressed.show();
});
pressed.click(function(){
$(this).fadeOut("slow",function(){
boardImg.show("slow",function(){
player = choseFirstPlayer(player1,player2,player3,player4);
});
});
});
$("#player1 #hand img").click(function(){
var domino = $(this);
addDominoToBoard(domino,dominosPlaced);
$(this).remove();
player = choseNextPlayer(player,player1,player2,player3,player4)
});
$("#player2 #hand img").click(function(){
var domino = $(this);
addDominoToBoard(domino,dominosPlaced);
$(this).remove();
player = choseNextPlayer(player,player1,player2,player3,player4)
});
$("#player3 #hand img").click(function(){
var domino = $(this);
addDominoToBoard(domino,dominosPlaced);
$(this).remove();
player = choseNextPlayer(player,player1,player2,player3,player4)
});
$("#player4 #hand img").click(function(){
var domino = $(this);
addDominoToBoard(domino,dominosPlaced);
$(this).remove();
player = choseNextPlayer(player,player1,player2,player3,player4)
});
});
Related
I worked on building this template using the javascript and I can't seem to get the video I have on the screen to activate an event once the video finishes. The page content is pulled in via JSON file. The "videoDemo1" is set to autoplay, so I hope I'm not call the eventListener before the video exist in the HTML document. If there's any questions, just ask, thanks. Here's my code:
function buildVideoContent(pageData) {
// build the layout
let layout = buildColumns(pageData.layout);
// get page container from DOM
let page = document.getElementById('page_frame');
// clear the page frame
page.innerHTML = "";
// main video container
let mainVidCont = document.createElement('div');
mainVidCont.id = "main-cont";
mainVidCont.classList.add('bg-height');
page.appendChild(mainVidCont);
// add video wrapper and video content (start video and end video)
let vidWrapper = document.createElement('div');
vidWrapper.id = "vDemoWrapper";
vidWrapper.classList.add('vid-wrapper-bg');
vidWrapper.innerHTML = "<video id='videoDemo1' controls autoplay muted loop class='video-bg'><source src='assets/media/0010.mp4' type='video/mp4'>Your browser does not support the video tag.</video><video id='videoDemo2' controls loop class='video-bg btn-hide'><source src='assets/media/0010.mp4' type='video/mp4'>Your browser does not support the video tag.</video>";
mainVidCont.appendChild(vidWrapper);
// create the containers for content and buttons
for(let i = 1; i <= 10; i++){
let innerContent = document.createElement('div');
innerContent.id = "aniContentInfo" + i + "";
innerContent.classList.add('inner-cont');
//innerContent.classList.add('animation-fadein');
innerContent.classList.add('col-4');
innerContent.classList.add('float-left');
mainVidCont.appendChild(innerContent);
}
let sumDiv1 = document.getElementById('aniContentInfo1');
let sumDiv2 = document.getElementById('aniContentInfo2');
let sumDiv3 = document.getElementById('aniContentInfo3');
let sumDiv4 = document.getElementById('aniContentInfo4');
let sumDiv5 = document.getElementById('aniContentInfo5');
let sumDiv6 = document.getElementById('aniContentInfo6');
let sumDiv7 = document.getElementById('aniContentInfo7');
let sumDiv8 = document.getElementById('aniContentInfo8');
let sumDiv9 = document.getElementById('aniContentInfo9');
let sumDiv10 = document.getElementById('aniContentInfo10');
let viewerText1 = buildContentCard(pageData.content1.text_elements, false);
let viewerText2 = buildContentCard(pageData.content2.text_elements, false);
let viewerText3 = buildContentCard(pageData.content3.text_elements, false);
let viewerText4 = buildContentCard(pageData.content4.text_elements, false);
let viewerText5 = buildContentCard(pageData.content5.text_elements, false);
let viewerText6 = buildContentCard(pageData.content6.text_elements, false);
let viewerText7 = buildContentCard(pageData.content7.text_elements, false);
let viewerText8 = buildContentCard(pageData.content8.text_elements, false);
let viewerText9 = buildContentCard(pageData.content9.text_elements, false);
let viewerText10 = buildContentCard(pageData.content10.text_elements, false);
sumDiv1.appendChild(viewerText1);
sumDiv2.appendChild(viewerText2);
sumDiv3.appendChild(viewerText3);
sumDiv4.appendChild(viewerText4);
sumDiv5.appendChild(viewerText5);
sumDiv6.appendChild(viewerText6);
sumDiv7.appendChild(viewerText7);
sumDiv8.appendChild(viewerText8);
sumDiv9.appendChild(viewerText9);
sumDiv10.appendChild(viewerText10);
// create buttons and add them to content container
for(let v = 1; v <= 10; v++){
let continueBtn = document.createElement('BUTTON');
continueBtn.id = "continue-btn" + v + "";
continueBtn.classList.add('btn-primary');
continueBtn.classList.add('btn');
continueBtn.innerHTML = "CONTINUE";
let paraCont = document.getElementById("aniContentInfo" + v + "");
paraCont.appendChild(continueBtn);
for(let c = 1; c <= 9; c++){
let count = document.getElementById("aniContentInfo" + c + "");
count.classList.add('btn-hide');
}
if(v = 10){
document.getElementById("aniContentInfo10").classList.add('animation-fadein');
}
};
// THE CODE COMMENTED OUT BELOW ARE ADDITIONAL EVENTLISTENERS THAT I'VE TRIED
/* document.addEventListener('DOMContentLoaded', () => {
var vid = document.getElementById("videoDemo1");
vid.onended = function() {
document.getElementById("aniContentInfo10").classList.add('animation-fadein');
};
if ( video.readyState === 4 ) {
let vid = document.getElementById('videoDemo1');
vid.addEventListener("ended", function(e){
if(state === 0){
let videoElement = document.getElementById('videoDemo1');
videoElement.classList.add('vid-opacity');
}
});
}
}); */
// BELOW IS WHERE I WROTE THE ADDEVENTLISTENER
document.getElementById('videoDemo1').addEventListener('ended',myHandler,false);
function myHandler(e) {
// What you want to do after the event
document.getElementById("aniContentInfo10").classList.add('animation-fadein');
};
// APPARENTLY THIS DOESN'T WORK WHEN I RUN THE CODE
// create click events for each button to proceed to next content container
for(let h = 1; h <= 10; h++){
continueBtn = document.getElementById('continue-btn' + h + '');
document.getElementById('continue-btn' + h + '').addEventListener("click", function userProgression(e){
let subOne = h - 1;
let videoElement = document.getElementById('videoDemo1');
videoElement.classList.remove('vid-opacity');
videoElement.classList.add('vid-visible');
let videoElement2 = document.getElementById('videoDemo2');
videoElement2.classList.remove('btn-hide');
videoElement2.classList.add('btn-show');
// remove button and content from screen to reveal new content container
setTimeout(function(){
let hMinus = h - 1;
let contentInnerNum = document.getElementById('aniContentInfo' + h + '');
contentInnerNum.classList.remove('btn-hide');
contentInnerNum.classList.remove('animation-fadein');
contentInnerNum.classList.add('animation-fadeout');
if(hMinus !== 0){
let contentNumMinus = document.getElementById('aniContentInfo' + hMinus + '');
contentNumMinus.classList.remove('btn-hide');
contentNumMinus.classList.add('animation-fadein');
contentNumMinus.classList.remove('animation-fadeout');
}
let contentBtn = document.getElementById('continue-btn' + h + '');
contentBtn.classList.add('animation-fadeout');
let contentInner = document.getElementById('continue-btn' + subOne + '');
contentInner.classList.remove('btn-hide');
contentInner.classList.remove('btn-show');
contentInner.classList.add('btn-center');
}, 3000);
// add classes to content elements from the above lines to to remove them completely
setTimeout(function(){
let topBtn = document.getElementById('continue-btn' + h + '');
topBtn.classList.add('btn-hide');
let contentInner = document.getElementById('aniContentInfo' + h + '');
contentInner.classList.add('btn-hide');
}, 6000);
// set timer to make next second video visible.
setTimeout(function(){
let hMinus = h - 1;
if(hMinus !== 0){
let videoElement1a = document.getElementById('videoDemo1');
videoElement1a.classList.remove('vid-opacity');
videoElement1a.classList.add('vid-visible');
}
let videoElement2 = document.getElementById('videoDemo2');
videoElement2.classList.remove('btn-show');
videoElement2.classList.add('btn-hide');
}, 8000);
// important! bring back original first video at the exact second the second video ends
setTimeout(function(){
let videoElement1b = document.getElementById('videoDemo1');
videoElement1b.classList.remove('vid-visible');
videoElement1b.classList.add('vid-opacity');
}, 60000);
});
}
// I ALSO TRIED PLACING THE EVENTLISTENER HERE, BUT NO LUCK
/* document.addEventListener("DOMContentLoaded", function(event) {
let vid1 = document.getElementById("videoDemo1");
if ( vid1.readyState === 4 ) {
vid1.onended = () => {
vid1.classList.add('vid-opacity');
};
}
});*/
}
If it's something I'm missing, any help would be appreciated, thanks
Building a dice game and you get 3 rolls. Once you finish your turn i'm trying to have a "reset" button that will reset the values back to the original spot so the "next person" can play. The values reset as I expected but when I "roll" none of the functions are taking place and i'm pretty new in js so i'm not sure what the problem is.
var playerScore = document.getElementById('firstPlayerScore');
var rollButton = document.getElementById('roll_button');
var dice1 = new dice(1);
var dice2 = new dice(2);
var dice3 = new dice(3);
var dice4 = new dice(4);
var dice5 = new dice(5);
var diceArray = [dice1, dice2, dice3, dice4, dice5];
var cargo = 0;
var numOfRolls = 0;
var cargoButton = document.getElementById('cargo');
var canHaveCargo = false;
function restart(){
dice1 = new dice(1);
dice2 = new dice(2);
dice3 = new dice(3);
dice4 = new dice(4);
dice5 = new dice(5);
diceArray = [dice1, dice2, dice3, dice4, dice5];
cargo = 0;
numOfRolls = 0;
canHaveCargo = false;
addGlow();
updateDiceImageUrl();
document.getElementById("dice1").classList.remove('glowing');
document.getElementById("dice2").classList.remove('glowing');
document.getElementById("dice3").classList.remove('glowing');
document.getElementById("dice4").classList.remove('glowing');
document.getElementById("dice5").classList.remove('glowing');
}
//dice object
function dice(id){
this.id = id;
this.currentRoll = 1;
this.previousRoll = 1;
this.isSelected = false;
this.diceImageUrl = "img/dice/dice1.png";
this.roll = function(){
this.previousRoll = this.currentRoll;
this.currentRoll = getRandomRoll(1, 6);
}
}
//returns an array of all dice that are not currently selected so they can be rolled.
function getRollableDiceList(){
var tempDiceList = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempDiceList.push(diceArray[i]);
}
}
return tempDiceList;
}
// gets a random number between min and max (including min and max)
function getRandomRoll(min,max){
return Math.floor(Math.random() * (max-min + 1) + min);
}
// calls the roll function on each dice
function rollDice(rollableDiceList){
for(var i = 0; i < rollableDiceList.length; i++){
rollableDiceList[i].roll();
}
}
// updates each dice with the new url for the image that corresponds to what their current roll is
function updateDiceImageUrl(){
for(var i = 0; i < diceArray.length; i++){
var currentDice = diceArray[i];
currentDice.diceImageUrl = "http://boomersplayground.com/img/dice/dice" + currentDice.currentRoll + ".png";
//update div image with img that cooresponds to their current roll
updateDiceDivImage(currentDice);
}
}
//Displays the image that matches the roll on each dice
function updateDiceDivImage(currentDice) {
document.getElementById("dice"+currentDice.id).style.backgroundImage = "url('" + currentDice.diceImageUrl +"')";
}
// returns an array of all
function getNonSelectedDice(){
var tempArray = [];
for(var i = 0; i < diceArray.length; i++){
if(!diceArray[i].isSelected){
tempArray.push(diceArray[i]);
}
tempArray.sort(function(a, b){
return b.currentRoll - a.currentRoll;
});
}
return tempArray;
}
function getSelectedDice(){
var selectedDice = [];
for(var i = 0; i < diceArray.length; i++){
if(diceArray[i].isSelected){
selectedDice.push(diceArray[i]);
}
}
return selectedDice;
}
//boolean variables
var shipExist = false;
var captExist = false;
var crewExist = false;
//checks each dice for ship captain and crew. Auto select the first 6, 5 , 4.
function checkForShipCaptCrew(){
//array of dice that are not marked selected
var nonSelectedDice = getNonSelectedDice();
for(var i = 0; i < nonSelectedDice.length; i++){
//temp variable that represents the current dice in the list
currentDice = nonSelectedDice[i];
if (!shipExist) {
if (currentDice.currentRoll == 6) {
shipExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && !captExist) {
if (currentDice.currentRoll == 5) {
captExist = true;
currentDice.isSelected = true;
}
}
if (shipExist && captExist && !crewExist) {
if (currentDice.currentRoll == 4) {
crewExist = true;
currentDice.isSelected = true;
canHaveCargo = true;
}
}
}
}
function addGlow(){
var selectedDice = getSelectedDice();
for (var i = 0; i < selectedDice.length; i++){
var addGlowDice = selectedDice[i];
var element = document.getElementById('dice' + addGlowDice.id);
element.className = element.className + " glowing";
}
}
function getCargo(){
var cargo = 0;
var moreDice = getNonSelectedDice();
if (canHaveCargo){
for(var i=0; i < moreDice.length; i++){
cargo += moreDice[i].currentRoll;
playerScore.innerHTML = 'You have got ' + cargo + ' in ' + numOfRolls + ' rolls!';
}
} else {
alert("You don't have Ship Captain and the Crew yet!");
}
}
rollButton.addEventListener('click', function(){
//generate rollable dice list
if (numOfRolls < 3) {
var rollableDiceList = getRollableDiceList();
//roll each dice
rollDice(rollableDiceList);
//update dice images
updateDiceImageUrl();
getNonSelectedDice();
// //auto select first 6, 5, 4 (in that order)
checkForShipCaptCrew();
addGlow();
// //adds a red glow to each dice that is selected
numOfRolls++;
}
});
cargoButton.addEventListener('click', getCargo);
var startButton = document.getElementById('restart');
startButton.addEventListener('click', restart);
http://boomer1204.github.io/shipCaptainCrew/
Here is a link to the live game since it's the only way I can describe the problem since I don't know what's not working. If you roll the dice a couple times the dice will get a blue border and be "saved" according to the rules. Now after you hit th restart button that doesn't happen anymore.
Thanks for the help in advance guys
Just add this to your restart()
function restart(){
...
shipExist = false;
capExist = false;
crewExist = false;
...
}
It's hard to replicate without a fiddle, but it seems that you are adding and removing the 'glowing' class using separate processes. Have you tried adding the glowing class the same way you are removing it?
element.classList.add("glowing")
See an example within a fiddle: https://jsfiddle.net/5tstf2f8/
its been a while since I've dug my heals into JS and could use some help. Looking to modify this existing script to include a link for each rotating image... want to link the object called "text" to the same URL for each image. any ideas?
//cur_index = 1;
cur_index = Math.floor(Math.random()*6);
//var randomnumber=Math.floor(Math.random()*11)
num_image = 5;
//alert(cur_index);
interval = 300000; // 5min between rotations
function rotate(){
// if(cur_index > num_image)
// cur_index = 1;
if(cur_index == 0)
cur_index = 1;
var imag,text;
if(document.getElementById){
imag = document.getElementById("faceImage");
text = document.getElementById("faceText");
}else if(document.all) {
imag = document.all["faceImage"];
text = document.all["faceText"];
}else if(document.layers){
imag = document.layers["faceImage"];
text = document.layers["faceText"];
}
var imageUrl = "/path/face" + cur_index + ".jpg";
var textUrl = "/path/face" + cur_index + "_text.gif";
imag.src = imageUrl;
text.src = textUrl;
//cur_index++;
cur_index = Math.floor(Math.random()*6);
setTimeout('rotate()',interval);
}
I have a table with a background image that, when clicked, displays other images for the user to choose from. This is working and appears or hides on click events. However, when the user clicks to add a second image the menu of images appears again (as it should) but twice. I have commented out a solution I tried. I thought on first click I could display my_div and then delete it in allImages.onclick. This is throwing up a null error in Chrome, probably understandably. The problem here is similar. Hope I added link correctly. Anyway, advice or help appreciated.
function addImage(col) {
var img = new Image();
img.src = "../www/images/TEST.png";
col.appendChild(img);
img.onclick = function () {
var myImages = new Array();
myImages[0] = "../www/images/TEST3.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST4.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var newList = document.createElement("ul");
newList.appendChild(allImages);
my_div = document.getElementById("showPics");
my_div.appendChild(newList);
my_div.style.display = 'block';
allImages.onclick = function (e) {
img.src = e.target.src;
my_div.style.display = 'none';
//var element = document.getElementById("showPics");
//element.parentNode.removeChild(element);
};
}
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
}
}
document.getElementById('holdTable').appendChild(table);
I modified your code adding ul to hold all img. It works, but could be better.
function addImage(col) {
var img = new Image();
img.src = "../www/images/TEST.png";
col.appendChild(img);
var myImages = new Array();
myImages[0] = "../www/images/TEST1.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST3.png";
var container = document.createElement("ul"); //ul to simplify hide/show
container.style.display = "none";
for (var i = 0; i < myImages.length; i++) {
var newList = document.createElement("li");
var im = document.createElement("img");
im.src = myImages[i];
newList.appendChild(im);
im.onclick = function () {
img.src = this.src;
};
container.appendChild(newList);
}
col.appendChild(container);
col.onclick = function () {
if (container.style.display == "none")
container.style.display = "block";
else
container.style.display = "none";
};
}
what I want to do is to display videos which differ in their number.
I do know that I have to use appendChild, but I have no clue how and I couldn't find anything helpful so far.
I'd really apreciate it if someone could give me a hint how to do this.
[UPDATE]
Ok .. I have my basic function now, but I still have one little problem. I need to place the videowindows below each other. I have an idea how to do that, but I'm not quite sure if its possible the way I want to do it. I want to use the top attribute of the last video and sum it up by some static value:
<script type="text/javascript">
var myVideo;
var i;
//Funktion zum Videoaufruf
function getVideo(){
var mp4Array = new Array();
var ogvArray = new Array();
mp4Array[0] = "http://poirecognition.konscio.de/media/BBB_H264_HB.mp4";
ogvArray[0] = "http://poirecognition.konscio.de/media/BBB_theora.ogv";
mp4Array[1] = "http://poirecognition.konscio.de/media/FHBocholt.mp4";
ogvArray[1] = "http://poirecognition.konscio.de/media/FHBocholt.ogv";
var myVideo = new Array();
for(i = 0; i < mp4Array.length; i++){
myVideo[i] = document.createElement("video");
if(Modernizr.video){
if(Modernizr.video.ogg){
//Firefox, Opera, Chrome
myVideo[i].src = ogvArray[i];
setVideoOptions(myVideo[i], i);
}else if(Modernizr.video.h264){
//Safari, Chrome, IE, IPhone, Android
myVideo[i].src = mp4Array[i];
setVideoOptions(myVideo[i]);
}
}else{
alert("HTML5 Video-Tag wird nicht unterstützt");
}
};
}
function setVideoOptions(tempVideo, i){
tempVideo.controls = true;
tempVideo.style.position = "absolute";
tempVideo.style.left = "650px";
tempVideo.style.width = "360";
tempVideo.style.height = "240";
if (i>0) {
tempVideo.style.top = myVideo[i-1]+"300px";
} else{
tempVideo.style.top = "20px";
};
}
</script>
[UPDATE 2]
Ok .. I found a way to solve my problem, but now I have another: The videowindows are not visible which has something to do with the video element being created via JS... no clue how to solve this. Strange enough if I set the video to load and play I do hear the audio from the video ..
<script type="text/javascript">
var myVideo = new Array();
var i;
//Funktion zum Videoaufruf
function getVideo(){
var mp4Array = new Array();
var ogvArray = new Array();
mp4Array[0] = "http://poirecognition.konscio.de/media/BBB_H264_HB.mp4";
ogvArray[0] = "http://poirecognition.konscio.de/media/BBB_theora.ogv";
mp4Array[1] = "http://poirecognition.konscio.de/media/FHBocholt.mp4";
ogvArray[1] = "http://poirecognition.konscio.de/media/FHBocholt.ogv";
for(i = 0; i < mp4Array.length; i++){
myVideo[i] = document.createElement("video");
if(Modernizr.video){
if(Modernizr.video.ogg){
//Firefox, Opera, Chrome
myVideo[i].src = ogvArray[i];
setVideoOptions(myVideo[i], i);
}else if(Modernizr.video.h264){
//Safari, Chrome, IE, IPhone, Android
myVideo[i].src = mp4Array[i];
setVideoOptions(myVideo[i]);
}
}else{
alert("HTML5 Video-Tag wird nicht unterstützt");
}
};
}
function setVideoOptions(tempVideo, i){
tempVideo.controls = true;
tempVideo.style.position = "absolute";
tempVideo.style.left = "650px";
tempVideo.style.width = "360";
tempVideo.style.height = "240";
if (i>0) {
var tmpTop = myVideo[i-1].style.top.substring(0, myVideo[i-1].style.top.length-2);
tmpTop = parseInt(tmpTop);
tmpTop += 300;
tempVideo.style.top = tmpTop;
} else{
tempVideo.style.top = "20px";
};
}
</script>
[UPDATE 3]
Ok .. I simply forgot the appendChild function. :)
<script type="text/javascript">
var myVideo = new Array();
var i;
//Funktion zum Videoaufruf
function getVideo(){
var mp4Array = new Array();
var ogvArray = new Array();
mp4Array[0] = "http://poirecognition.konscio.de/media/BBB_H264_HB.mp4";
ogvArray[0] = "http://poirecognition.konscio.de/media/BBB_theora.ogv";
mp4Array[1] = "http://poirecognition.konscio.de/media/FHBocholt.mp4";
ogvArray[1] = "http://poirecognition.konscio.de/media/FHBocholt.ogv";
for(i = 0; i < mp4Array.length; i++){
myVideo[i] = document.createElement("video");
if(Modernizr.video){
if(Modernizr.video.ogg){
//Firefox, Opera, Chrome
myVideo[i].src = ogvArray[i];
setVideoOptions(myVideo[i], i);
}else if(Modernizr.video.h264){
//Safari, Chrome, IE, IPhone, Android
myVideo[i].src = mp4Array[i];
setVideoOptions(myVideo[i]);
}
}else{
alert("HTML5 Video-Tag wird nicht unterstützt");
}
};
}
function setVideoOptions(tempVideo, i){
tempVideo.controls = true;
tempVideo.style.position = "absolute";
tempVideo.style.left = "650px";
tempVideo.style.width = "360";
tempVideo.style.height = "240";
if (i>0) {
var tmpTop = myVideo[i-1].style.top.substring(0, myVideo[i-1].style.top.length-2);
tmpTop = parseInt(tmpTop);
tmpTop += 300;
tempVideo.style.top = tmpTop;
} else{
tempVideo.style.top = "20px";
};
document.body.appendChild(tempVideo);
}
</script>