js / css flip card game bug in shuffle function - javascript

I have created a js memory game. It has a 24-card grid, and it is supposed to shuffle randomly out of a deck of 15 cards in order to create a little variety. The game should be different every time. However, at random the game shuffles the initial deck and builds the board with 11 pairs and one non-pair of cards. Here's the whole js file:
`var score;
var cardsmatched;
var ui = $("#gameUI");
var uiIntro =$("#gameIntro");
var uiStats = $("# gameStats");
var uiComplete = $("#gameComplete");
var uiCards = $("#cards");
var uiScore = $(".gameScore");
var uiReset = $(".gameReset");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var matchingGame = {};
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
$(function(){
init();
});
function init() {
uiComplete.hide();
uiCards.hide();
playGame = false;
uiPlay.click(function(e){
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e){
e.preventDefault();
uiComplete.hide();
reStartGame();
});
}
function startGame(){
uiTimer.show();
uiScore.html("0 seconds");
uiStats.show();
uiCards.show();
score = 0;
cardsmatched= 0;
if (playGame == false) {
playGame = true;
matchingGame.deck.sort(shuffle);
for (var i=0; i<25; i++){
$(".card:first-child").clone().appendTo("#cards");
}
uiCards.children().each(function(index) {
$(this).css({
"left" : ($(this).width() + 20) * (index % 6),
"top" : ($(this).height() + 20) * Math.floor(index / 6)
});
var pattern = matchingGame.deck.pop();
$(this).find(".back").addClass(pattern);
$(this).attr("data-pattern",pattern);
$(this).click(selectCard);
});
timer();
};
}
function timer(){
if (playGame){
scoreTimeout = setTimeout(function(){
uiScore.html(++score = "seconds");
timer();
}, 1000);
};
};
function shuffle() {
return 0.5 - Math.random();
}
function selectCard(){
if($(".card-flipped").size()> 1){
return;
}
$(this).addClass("card-flipped");
if($(".card-flipped").size() == 2) {
setTimeout(checkPattern, 1000);
};
};
function checkPattern(){
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
removeTookCards();
} else {
$(".card-flipped").removeClass("card-flipped");
}
}
function isMatchPattern(){
var cards = $(".card-flipped");
var pattern = $(cards[0]).data("pattern");
var anotherPattern = $(cards[1]).data("pattern");
return (pattern == anotherPattern);
}
function removeTookCards() {
if (cardsmatched < 12) {
cardsmatched++;
$(".card-removed").remove();
}else{
$(".card-removed").remove();
uiCards.hide();
uiComplete.show();
clearTimeout(scoreTimeout);
}
}
function reStartGame(){
playGame = false;
uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
clearTimeout(scoreTimeout);
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
startGame();
}
`

Related

how can i make game over function in memory card game?

i need to make function, this function check if all the cards matched and i reach to the end of the game or not .
i do class called hidden for matched cards and make condition check if all cards include this class this mean i reach to the end if not this mean i can continue playing.
the problem that the condition don't work perfectly and always active else condition
enter code here
var images = ["fas fa-american-sign-language-interpreting" , "fas fa-american-sign-language-interpreting" , "fas fa-cut" ,"fas fa-cut", "fas fa-bicycle" , "fas fa-bicycle" ,"fas fa-asterisk","fas fa-asterisk","fas fa-atom","fas fa-atom","fas fa-car-crash","fas fa-car-crash", "fas fa-chess", "fas fa-chess", "fas fa-drum" , "fas fa-drum"];
var image_card=images.length-3;
var image_start=0;
var oppened_card=[];
var matched_card=[];
var Showen_card=[];
var moves=0;
var unmatch_element = [];
Shuffle(images);
const game_structure = document.getElementById('game_structure');
const fragment = document.createDocumentFragment();
for (let i=0 ; i<images.length ; i++){
var card= document.createElement("section");
var front = document.createElement("div");
var back = document.createElement("div");
front.classList.add("front");
back.classList.add("back");
card.appendChild(front);
card.appendChild(back);
back.innerHTML=`<i class="${images[i]}"></i>`;
fragment.appendChild(card);
}
game_structure.appendChild(fragment);
game_structure.addEventListener('click' , element_Listener);
function Shuffle(array){
var i= array.length , tempValue , randomindex ;
while (--i >0){
randomindex = Math.floor(Math.random() * (i+1));
tempValue = array[randomindex];
array[randomindex] = array[i] ;
array[i] = tempValue ;
}
return array;
}
function element_Listener(event){
if (event.target.nodeName === 'SECTION') {
startTimer();
console.log(event.target.childNodes);
if (oppened_card.length<2){
flip_Card(event);
}
}
}
function flip_Card(event){
event.target.childNodes[0].classList.add('front_ro');
event.target.childNodes[1].classList.add('back_ro' , "open");
if(oppened_card.length==0){
oppened_card.push(event.target.childNodes[1].innerHTML);
matched_card.push(event.target);
console.log(matched_card[0]);
}
else if(oppened_card.length==1){
oppened_card.push(event.target.childNodes[1].innerHTML);
matched_card.push(event.target);
moveCounter();
if (oppened_card[0]==oppened_card[1]){
match();
**// here i invoke the function**
var finished_game = game_over();
console.log(finished_game);
oppened_card=[];
}
else{
// unmatch();
}
}
}
function moveCounter(){
moves++;
document.getElementById("steps").innerHTML = moves ;
}
function match(){
var allCards = document.getElementsByClassName("flip");
matched_card[0].classList.add('cardAnimate');
console.log(matched_card[0].childNodes[1]);
matched_card[1].classList.add('cardAnimate');
setTimeout(function(){
matched_card[0].classList.add('hidden');
matched_card[1].classList.add('hidden');
},1000);
oppened_card=[];
}
let timerRunning = false;
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var gameTime;
function startTimer(){
if(!timerRunning){
timerRunning = true;
var totalSeconds = 0;
gameTime=setInterval(setTime, 1000);
}
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
}
function stopTimer(){
if(timerRunning){
timerRunning = false;
clearInterval(gameTime);
}
}
**// here is the beginning of my function**
var checked_classes =[];
function game_over(){
var hidden_cards = document.getElementsByTagName('section');
for (let hidden_card of hidden_cards){
console.log(hidden_card.classList.contains("hidden"));
let checked_class = hidden_card.classList.contains("hidden");
checked_classes.push(checked_class);
}
if (checked_classes.includes('false') == true){
return false;
}
else {
return true;
}
}
i expect to return false when the game has unmatched cards but it return true always.
You are pushing booleans to the checked_classes array, but checking if it contains a string. This causes the contain method to always return false. Try searching for a boolean instead.
if (checked_classes.includes(false)){
return false;
}
else {
return true;
}
}

How can i limit function-(slot play) just for 5 turn - with do/while loop

I wanna create a slot machine with 3 number by javascript - but I want to finish my function when three numbers are equal.
I think that if I write it with do/while it will be work, but I can't do it
this is my js code:
function myF() {
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if(slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
}
}
this function is set onclick attr of a button tag
Adding to comment, if you want to run function for no of times then just use a counter variable to check no of attempts:
Added a reset button to reset the game.
var counter = 0;
function myF() {
if (counter != 5) {
counter++;
document.getElementById("slotLeft").innerHTML = "Try count: " + counter;
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if (slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
counter = 5; // Edited this line
}
} else {
console.log('Game over');
}
}
function myF1(){
counter = 0;
document.getElementById("slotOne").innerHTML = "";
document.getElementById("slotTwo").innerHTML = "";
document.getElementById("slotThree").innerHTML = "";
}
<button onclick="myF()">Check</button>
<button onclick="myF1()">Restart Game</button>
<div id="slotLeft">
</div>
<div id="slotOne">
</div>
<div id="slotTwo">
</div>
<div id="slotThree">
</div>
<div id="winner">
</div>
function myF() {
var slotOneElem = document.getElementById("slotOne");
var slotTwoElem = document.getElementById("slotTwo");
var slotThreeElem = document.getElementById("slotThree");
var generateRand = function() {
return Math.floor(Math.random() * 3) + 1;
}
return (function () {
var slotOne = generateRand();
var slotTwo = generateRand();
var slotThree = generateRand();
slotOneElem.innerHTML = slotOne;
slotTwoElem.innerHTML = slotTwo;
slotThreeElem.innerHTML = slotThree;
if (slotOne === slotTwo && slotTwo === slotThree) {
slotOneElem.style.backgroundColor = "#48bd48";
slotTwoElem.style.backgroundColor = "#48bd48";
slotThreeElem.style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
// Here is the win
return true;
}
return false;
})();
}
var finished = myF();
while (!finished) {
finished = myF();
}

JavaScript function dosen't work correct

I have a function that checking board is there a searching element.
First script creating a board with different elements. Element in the square next to board is element that user has to find on the board and click them.
User has to click (as quick as possible) all searching elements. After click on element function checking a board, is there more elements. If yes then nothing happen and user has to click another one. If on board there isn’t searching elements then function display a time and new board create.
But some reason function works correct only first time after page load. Latter function ignore more then one element on board or see element that doesn’t exist on board any more.
Can you tell me what is wrong.
Part of code bellow and there is a link to testing page.
http://doomini2.linuxpl.info/font/
Thank you
function secondStage() {
createBoxes(59);
var usingSet = [];
var i = 0;
var boxList = document.querySelectorAll("#board > div");
createSet(usingSet, 20, shapes);
(function paint() {
if (i <= 59) {
var curentBox = boxList[i];
curentBox.className = usingSet[draw(20)];
curentBox.style.color = colors[draw(colors.length - 5)];
timeStop = setTimeout(paint, 50);
i++;
} else {
var findShape = boxList[draw(59)];
toFind.className = findShape.className;
toFind.style.color = findShape.style.color;
findBoxes(boxList);
clearTimeout(timeStop);
}
})();
}
//function checks boxes to find a proper shape
function findBoxes(boxList) {
startTime = Date.now();
board.addEventListener("mousedown", function (e) {
if ((e.target.className === toFind.className)) {
e.target.className = "correct";
e.target.innerHTML = "OK";
checkBoard();
} else if (e.target.id === "board" || e.target.className === "correct") {
} else {
e.target.className = "false";
e.target.innerHTML = "NO";
}
}, false);
function checkBoard() {
var condition = false;
console.log(condition);
for (var x = 0; x < boxList.length; x++) {
if ((boxList[x].className === toFind.className)) {
condition = true;
console.log(condition);
}
}
if (condition === false) {
var clickTime = Date.now();
var timeResult = parseFloat(((clickTime - startTime) / 1000).toFixed(3));
lastResult.innerHTML = timeResult + "s";
secondResult[secondResult.length] = timeResult;
console.log(secondResult);
displayResult(secondStage);
}
}
}
//function displaig results after every single round
function displayResult(stage) {
cover.className = "";
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeOut, right: (winWidth / 4), });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: (winWidth / 3), onComplete: function () {
goButton.addEventListener("click", function () {
clear();
}, false);
}});
//clear board and return to play
function clear() {
TweenMax.to("#lastResultDiv", 1, {ease: Back.easeIn, right: winWidth, });
TweenMax.to("#go", 1, {ease: Back.easeOut, top: -100, onComplete: function () {
cover.className = "hide";
lastResultDiv.style.right = "-592px";
toFind.className = "";
board.innerHTML = "";
if (firstStageRound === 10) {
secondStage();
} else if (secondStageRound === 5) {
thirdStage();
} else {
stage();
}
}});
}
}
Not Load this File http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js
try to local path

function is undefined in firefox only

ok, the following code works ok in IE7+ and Chrome.
but for some reason, xfade is undefined in firefox
<html>
<body>
<div id="slider"></div>
<script type="text/javascript">
var Klimateka = {
Slider: function () {
// Check if we have a slider div on page
var slider = document.getElementById('slider');
if (slider != null) {
var images = ["slide-image-1.jpg", "slide-image-2.jpg", "slide-image-3.jpg", "slide-image-4.jpg"];
var i = images.length;
while (i) {
i -= 1;
var img = document.createElement("img");
img.src = "images/" + images[i];
slider.appendChild(img);
}
var d = document, imgs = new Array(), zInterval = null, current = 0, pause = false;
imgs = d.getElementById("slider").getElementsByTagName("img");
for (i = 1; i < imgs.length; i++) imgs[i].xOpacity = 0;
imgs[0].style.display = "block";
imgs[0].xOpacity = .99;
setTimeout("xfade()", 3500);
function xfade() {
cOpacity = imgs[current].xOpacity;
nIndex = imgs[current + 1] ? current + 1 : 0;
nOpacity = imgs[nIndex].xOpacity;
cOpacity -= .05;
nOpacity += .05;
imgs[nIndex].style.display = "block";
imgs[current].xOpacity = cOpacity;
imgs[nIndex].xOpacity = nOpacity;
setOpacity(imgs[current]);
setOpacity(imgs[nIndex]);
if (cOpacity <= 0) {
imgs[current].style.display = "none";
current = nIndex;
setTimeout(xfade, 3500);
} else {
setTimeout(xfade, 50);
}
function setOpacity(obj) {
if (obj.xOpacity > .99) {
obj.xOpacity = .99;
return;
}
obj.style.opacity = obj.xOpacity;
obj.style.MozOpacity = obj.xOpacity;
obj.style.filter = "alpha(opacity=" + (obj.xOpacity * 100) + ")";
}
}
}
},
bar: function () {
}
};
Klimateka.Slider();
i have setup a jsfiddler for testing:
http://jsfiddle.net/rTtKh/10/
This might only apply to Firefox:
functions do not hoist when declared inside a child block.
You declare xfade inside the if block, but you are calling it prior to the declaration:
setTimeout(xfade, 3500);
Put the function declaration on top.
You have to do the same with setOpacity inside xfade. <- That is not necessary.
Fix your line that says this: setTimeout("xfade()", 3500); to match your others:
setTimeout(xfade, 3500);
Use setTimeout(xfade, 3500) instead.

javascript countdown with showing milliseconds

I want to do a count down and want to show like format as Minutes:Seconds:Milliseconds. I made a count down with jquery plug-in countdown but it shows just Minutes:Seconds format.
Is there any way to make it right?
Many Thanks!
Hi guys I have developed a code for my self use the following code
counter for 20 seconds
var _STOP =0;
var value=1999;
function settimer()
{
var svalue = value.toString();
if(svalue.length == 3)
svalue = '0'+svalue;
else if(svalue.length == 2)
svalue = '00'+svalue;
else if(svalue.length == 1)
svalue = '000'+svalue;
else if(value == 0)
svalue = '0000';
document.getElementById('cn1').innerHTML = svalue[0];
document.getElementById('cn2').innerHTML = svalue[1];
document.getElementById('cn3').innerHTML = svalue[2];
document.getElementById('cn4').innerHTML = svalue[3];
value--;
if (_STOP==0 && value>=0) setTimeout("settimer();", 10);
}
setTimeout("settimer()", 10);
Try this: http://jsfiddle.net/aamir/TaHtz/76/
HTML:
<div id="timer"></div>
​
JS:
var el = document.getElementById('timer');
var milliSecondsTime = 10000;
var timer;
el.innerHTML = milliSecondsTime/1000;
timer = setInterval(function(){
milliSecondsTime = milliSecondsTime - 1000;
if(milliSecondsTime/1000 == 0) {
clearTimeout(timer);
el.innerHTML = 'BOOOOM';
}
else {
el.innerHTML = milliSecondsTime/1000;
}
},1000);
​
If you want to make your own timer.
read this earlier question
How to create a JQuery Clock / Timer
Try setting the format parameter - http://keith-wood.name/countdownRef.html#format
On further reading, this plugin doesn't do milliseconds. At this point, you either have to edit the actual plugin code or find a new plugin.
I completely agree with #Matt Ball's comment.It may also cause the browser to crash.
Why don't you try this solution instead
jQuery 1 minute countdown with milliseconds and callback
I did it like this (generic counter from N to X (X > N)):
var dynamicCounterAddNewValue = 20;
var currentDynamicUpdater;
function dynamicCounterForValueForControlUpdater(_updaterData) {
_updaterData.from += dynamicCounterAddNewValue;
if (_updaterData.from > _updaterData.to) {
_updaterData.from = _updaterData.to;
}
_updaterData.c.html(_updaterData.from.toString());
if (_updaterData.from < _updaterData.to) {
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
10,
{
c: _updaterData.c,
from: _updaterData.from,
to: _updaterData.to
}
);
}
else {
clearTimeout(currentDynamicUpdater);
}
return;
}
// _c -> jQuery object (div,span)
// _from -> starting number
// _to -> ending number
function dynamicCounterForValueForControl(_c, _from, _to) {
clearTimeout(currentDynamicUpdater);
dynamicCounterForValueForControlUpdater(
{
c: _c,
from: _from,
to: _to
}
);
return;
}
EDIT: Updated version (more flexible - for N elements one after another):
(input element is Array of elements for making them dynamic-counts)
var dynamicCounterTimeout = 10;
var currentDynamicUpdater;
function odcArray(_odca) {
this.odca = _odca;
return;
}
function odc(_c, _from, _to) {
this.c = _c; // $('#control_id')
this.from = _from; // e.g. N
this.to = _to; // e.g. M => (M >= N)
var di = parseInt(_to / 45, 10);
if (di < 1) {
di = 1;
}
this.dynamicInc = di;
return;
}
function dynamicCounterForValueForControlUpdater(_odca) {
if (
_odca.odca === null
||
!_odca.odca.length
) {
clearTimeout(currentDynamicUpdater);
return;
}
var o = _odca.odca[0];
o.from += o.dynamicInc;
if (o.from > o.to) {
o.from = o.to;
_odca.odca.shift(); // Remove first element
}
o.c.html(o.from.toString());
currentDynamicUpdater = setTimeout(
dynamicCounterForValueForControlUpdater,
dynamicCounterTimeout,
_odca
);
return;
}
function dynamicCounterForValueForControl(_odca) {
clearTimeout(currentDynamicUpdater);
// SETUP all counters to default
for (var i = 0; i < _odca.odca.length; i++) {
_odca.odca[i].c.html(_odca.odca[i].from.toString());
}
dynamicCounterForValueForControlUpdater(
_odca
);
return;
}

Categories