JS & Jquery: functions goes crazy after being called. - javascript

in the game, when it shows the colors that you need to click and you click on the wrong color, after it alerts the colors start going crazy, the 2 functions that possibly doing that are in lines 24 and 55, but i cant find the problem in both.
i want after the fail alert the colors run normaly.
how can i fix this?
here is the code:
CodePen
// Setting Variables
var gameStatus = false;
var strict = false;
var playerTurn = true;
var colors = ['green', 'red', 'yellow', 'blue'];
var colorsPicked = ['red', 'red', 'yellow', 'blue', 'green'];
var colorsClicked = [];
var level = 1;
var index = 0;
var lindex = 0;
var showOn = false;
// Game Status Function
$('#start').click(function(){
if(gameStatus == false){
gameStatus = true;
gameStart();
}
});
// Game Start Function
function gameStart(){
// left this function for later
}
// Chaning color buttons
$('.cubes').click(function(e){
if(playerTurn == true){
$(e.target).addClass(e.target.id);
colorsClicked.push(e.target.id);
setTimeout(function(){
$(e.target).removeClass(e.target.id);
}, 500);
// Player's turn & check if got the right colors
if(colorsPicked[index] !== colorsClicked[index]){
alert('Failed! Try again.');
showColorStart();
index=0;
} else {
if(colorsPicked.length == colorsClicked.length){
level++;
randomColor();
showColorStart();
}
}
index++;
} else {
return;
}
});
// Random Color Picking Function
function randomColor(){
var random = Math.floor(Math.random() * 4);
colorsPicked.push(colors[random]);
}
// Colors Showing at Start of a level
function showColorStart(){
if(showOn == false){
showOn == true;
playerTurn = false;
lindex = 0;
setInterval(function(){
if(colorsPicked[lindex] == 'green'){
$('#green').addClass('green');
} else if(colorsPicked[lindex] == 'red'){
$('#red').addClass('red');
} else if(colorsPicked[lindex] == 'yellow'){
$('#yellow').addClass('yellow');
} else if(colorsPicked[lindex] == 'blue'){
$('#blue').addClass('blue');
}
setTimeout(function(){
$('#green').removeClass('green');
$('#red').removeClass('red');
$('#yellow').removeClass('yellow');
$('#blue').removeClass('blue');
}, 1000);
if(lindex == colorsPicked.length){
clearInterval();
lindex = 0;
index = 0;
playerTurn = true;
}
lindex++;
}, 1500);
} else {
return;
}
}
showColorStart();
<DOCTYPE html>
<html>
<head>
<title>Simon Game</title>
<link href="style.css" type="text/css" rel="stylesheet"/>
<link href='bootstrap.min.css' type="text/css"/>
</head>
<body>
<div class="container">
<div class="menu">
<input type='button' value='Start' id='start' class='btn'>
<input type='button' value='Restart' id='restart' class='btn'>
<input type='button' value='Strict' id='strict' class='btn'>
</div>
<div class='board'>
<div class='display'><p id='disp'></p></div>
<br>
<table>
<tbody>
<tr>
<td class='cubes' id='green'></td>
<td class='cubes' id='red'></td>
</tr>
<tr>
<td class='cubes' id='yellow'></td>
<td class='cubes' id='blue'></td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>

On your code you are never actually clearing the interval, and that might be causing the issue. There are some minor things, like instead of if(playerTurn == true) you could just do if(playerTurn)these not causing the issue you are having but it's just good practice.
Not sure how this whole thing should work, but clearing the interval does seems to fix the issue you were having.
// Setting Variables
var gameStatus = false;
var strict = false;
var playerTurn = true;
var colors = ['green', 'red', 'yellow', 'blue'];
var colorsPicked = ['red', 'red', 'yellow', 'blue', 'green'];
var colorsClicked = [];
var level = 1;
var index = 0;
var lindex = 0;
var showOn = false;
// Game Status Function
$('#start').click(function(){
if(!gameStatus){
gameStatus = true;
gameStart();
}
});
// Game Start Function
function gameStart(){
// left this function for later
}
// Chaning color buttons
$('.cubes').click(function(e){
if(playerTurn){
$(e.target).addClass(e.target.id);
colorsClicked.push(e.target.id);
setTimeout(function(){
$(e.target).removeClass(e.target.id);
}, 500);
// Player's turn & check if got the right colors
console.log(colorsPicked[index], colorsClicked[index]);
if(colorsPicked[index] !== colorsClicked[index]){
alert('Failed! Try again.');
showColorStart();
index = 0;
} else {
if(colorsPicked.length == colorsClicked.length){
level++;
randomColor();
showColorStart();
}
}
index++;
} else {
return;
}
});
// Random Color Picking Function
function randomColor(){
var random = Math.floor(Math.random() * 4);
colorsPicked.push(colors[random]);
}
// Colors Showing at Start of a level
function showColorStart(){
if(!showOn){
showOn == true;
playerTurn = false;
lindex = 0;
// save timer
var gameTimer = setInterval(function(){
if(colorsPicked[lindex] == 'green'){
$('#green').addClass('green');
} else if(colorsPicked[lindex] == 'red'){
$('#red').addClass('red');
} else if(colorsPicked[lindex] == 'yellow'){
$('#yellow').addClass('yellow');
} else if(colorsPicked[lindex] == 'blue'){
$('#blue').addClass('blue');
}
setTimeout(function(){
$('#green').removeClass('green');
$('#red').removeClass('red');
$('#yellow').removeClass('yellow');
$('#blue').removeClass('blue');
}, 1000);
if(lindex === colorsPicked.length){
// clear timer
clearInterval(gameTimer);
lindex = 0;
index = 0;
playerTurn = true;
}
lindex++;
}, 1500);
} else {
return;
}
}
showColorStart();
#import url('https://fonts.googleapis.com/css?family=Orbitron');
body {
background-color: #000;
margin: 0;
padding: 0;
}
.container {
margin: 0 auto;
text-align: center;
padding: 20px;
}
.menu {
margin-bottom: 20px;
}
.display {
width: 130px;
height: 40px;
background-color: #282828;
margin: 0 auto;
text-align: center;
font-family: Orbitron, sans-serif;
}
table {
margin: 0 auto;
}
.cubes {
width: 150px;
height: 150px;
}
#green {
border: 2px solid green;
border-right: 2px solid red;
}
#red {
border: 2px solid red;
border-bottom: 2px solid blue;
}
#yellow {
border: 2px solid yellow;
}
#blue {
border: 2px solid blue;
}
.green {
background-color: green;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.blue {
background-color: blue;
}
#disp {
font-size: 12px;
color: #000;
padding: 8px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Game</title>
</head>
<body>
<div class="container">
<div class="menu">
<input type='button' value='Start/Restart' id='start' class='btn'>
<input type='button' value='Strict' id='strict' class='btn'>
</div>
<div class='board'>
<div class='display'><p id='disp'></p></div>
<br>
<table>
<tbody>
<tr>
<td class='cubes' id='green'></td>
<td class='cubes' id='red'></td>
</tr>
<tr>
<td class='cubes' id='yellow'></td>
<td class='cubes' id='blue'></td>
</tr>
</tbody>
</table>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
Codepen link https://codepen.io/azs06/pen/eGRgeK

Instead of calling showColorStart() in case of failure you can also call $('#start').click(); to reset the game.
When you are calling showColorStart() in case of failure it is only resetting index and that too after showColorStart() is called. So there might me some variables that you need to reset before calling showColorStart().

Related

Sequential animations on HTML element

guys. I'm trying to create a group of sequential "animations" through css classes on my buttons, but i keep getting a problem where all my buttons receive the effect on the same time and not one after another.
The function playAllSequence should hightlight each button one after another following the sequence present in an array.
I've already tried to put the setTimeOut function inside a closure and tried changed my declaration to let instead of var.
What am i missing?
Thanks in advance
// Get number of buttons on the document
var numberOfButtons = document.querySelectorAll(".btn").length;
var collectionButtonsClicked = [];
var collectionOfRandomColors = [];
var buttonsColors = ["blue", "green", "red", "yellow"];
var gameTitle = document.querySelector("#level-title");
// detecting clicks on the buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].addEventListener("click", function () {
collectionButtonsClicked.push(this.id);
// call click animation function
clickAnimation ();
// Only checks when arrays have the same length so the user have to click all the sequence again
if (collectionButtonsClicked.length === collectionOfRandomColors.length) {
checkClick();
}
})};
// detecting button press to start the game
document.addEventListener("keydown", function (event) {
if (event.key === "a") {
gameTitle.innerHTML = "Game Started";
generateRandomColor();
playAllSequence();
}
});
// check if the click is correct
function checkClick () {
// if correct - Generate new color, disable buttons and play the sequence on all buttons
let arrayRandomStringfied = JSON.stringify(collectionOfRandomColors);
let arrayClickedStringfied = JSON.stringify(collectionButtonsClicked);
if (arrayRandomStringfied === arrayClickedStringfied) {
generateRandomColor();
playAllSequence();
console.log("acertou!")
// erasing click array so the player has to click all the color again
collectionButtonsClicked = [];
} else {
//call fail animation function
failAnimation();
// function to reset the arrays and the title
restartGame();
console.log("errou!")
}
}
//Generate random color and return array - User will have to follow this colors
function generateRandomColor () {
let randomIndex = Math.floor(Math.random() * 4);
collectionOfRandomColors.push(buttonsColors[randomIndex]);
return collectionOfRandomColors;
}
function playAllSequence () {
// disabling all buttons
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = true;
}
for ( let i = 0; i < collectionOfRandomColors.length; i++ ) {
doSetTimeOut(i);
}
// Enabling all buttons again
for ( let i = 0; i < numberOfButtons; i++) {
document.querySelectorAll(".btn")[i].disabled = false;
}
}
function doSetTimeOut (i) {
let activeButton = document.querySelector("." + collectionOfRandomColors[i]);
// Add pressed effect
activeButton.classList.add("pressed");
// Remove pressed effect after 1 second
setTimeout(function() {
activeButton.classList.remove("pressed")
}, 1000);
}
function clickAnimation () {
}
function failAnimation () {
}
function restartGame () {
collectionOfRandomColors = [];
collectionButtonsClicked = [];
gameTitle.innerHTML = "Press A key to Start";
}
body {
text-align: center;
background-color: #011F3F;
}
#level-title {
font-family: 'Press Start 2P', cursive;
font-size: 3rem;
margin: 5%;
color: #FEF2BF;
}
.container {
display: block;
width: 50%;
margin: auto;
}
.btn {
margin: 25px;
display: inline-block;
height: 200px;
width: 200px;
border: 10px solid black;
border-radius: 20%;
}
.game-over {
background-color: red;
opacity: 0.8;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blue {
background-color: blue;
}
.yellow {
background-color: yellow;
}
.pressed {
box-shadow: 0 0 20px white;
background-color: grey;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Simon</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>
<body>
<h1 id="level-title">Press A Key to Start</h1>
<div class="container">
<div class="row">
<div type="button" id="green" class="btn green">
</div>
<div type="button" id="red" class="btn red">
</div>
</div>
<div class="row">
<div type="button" id="yellow" class="btn yellow">
</div>
<div type="button" id="blue" class="btn blue">
</div>
</div>
</div>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
Well, I don't see your sample code to animate even the first button.
If you need independent separate events to happen '1 by 1' visually, you might use a i*1000 as a setTimeout second argument.
If not, here's the code doing something close to what you want to achieve, i believe. Define a function that sets the props you need (box-shadow in this example) for an element taken by index, and sets timeout for a function that will remove the props and call the first function again with the next index:
function animateBtnsSequence( i ){
var btns = document.querySelectorAll(".btn");
btns[i].style.boxShadow = '0 0 20px 1px white';
window.setTimeout(function(){
btns[i].style.boxShadow = '';
if( btns[i+1] )
animateBtnsSequence( i + 1 );
}, 1000)
}
function playAllSequence () {
animateBtnsSequence( 0 );
}

What is wrong with my code - It does not close

What I am trying to achieve is to change the name of the btn when opening and closing, however, when I test the functions individually it works fine however when I combine both function in one btn it doesn't could someone help, please.
What I am trying to achieve is to change the name of the btn when opening and closing, however, when I test the functions individually it works fine however when I combine both function in one btn it doesn't could someone help, please.
// JavaScript Document
let myBtn = document.querySelector("#btn");
let myBase = document.querySelector("#base");
let status = false;
myBase.style.marginTop = "-250px";
function myFunction() {
if (status === false) {
myBase.style.marginTop = "-120px";
status = true;
} else if (status = true) {
myBase.style.marginTop = "-250px"
status = false;
}
}
//myBtn.onclick = myFunction;
myBtn.innerHTML = "<P>OPEN</P>";
function nameFunction() {
if (status === false) {
myBtn.innerHTML = "<P>OPEN</P>";
status = true;
} else if (status = true) {
myBtn.innerHTML = "<P>CLOSE</P>";
status = false;
}
}
// myBtn.onclick = nameFunction;
function twoFunction() {
myFunction();
nameFunction();
}
myBtn.onclick = twoFunction;
#btn {
height: 30px;
width: 50px;
color: white;
background: orange;
line-height: 30px;
margin-top: 50px;
margin-left: 250px;
padding: 10px;
cursor: pointer
}
#base {
padding: 10px;
background: pink;
width: 200px;
height: 110px;
margin-top: 0px;
transition: 1s ease-in-out;
}
#base>div {
height: 30px;
width: auto;
background: red;
}
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="btn">
<p>OPEN</p>
</div>
<div id="base">
<div></div>
<div></div>
<div></div>
</div>
</body>
<script src="js/scripts.js"></script>
</html>
You have two main problems with the code:
if (status = true) will perform assignment, not equality check.
You should use == or === for that. Although since you're checking a boolean, you don't need an else if - if status is not false, then it can only be true. You can just do
if (status === false) {
/* ... code if false ... */
} else {
/* ... code if true ... */
}
You set status = false and status = true twice. First in myFunction, then in nameFunction. So when you the handler is invoked myFunction checks the status, sees status is false switches it to true and then when nameFunction runs, status is now true, where it should have been false.
you can extract the code to change the status value and only call it from one place. I moved it to twoFunction after both other functions have completed:
// JavaScript Document
let myBtn = document.querySelector("#btn");
let myBase = document.querySelector("#base");
let status = false;
myBase.style.marginTop = "-250px";
function myFunction() {
console.log(status)
if (status === false) {
myBase.style.marginTop = "-120px";
} else { //no need for else if
myBase.style.marginTop = "-250px"
}
}
//myBtn.onclick = myFunction;
myBtn.innerHTML = "<P>OPEN</P>";
function nameFunction() {
if (status === false) {
myBtn.innerHTML = "<P>OPEN</P>";
} else { //no need for else if
myBtn.innerHTML = "<P>CLOSE</P>";
}
}
// myBtn.onclick = nameFunction;
function twoFunction() {
myFunction();
nameFunction();
//only set the status once
if (status === false) {
status = true;
} else {
status = false;
}
}
myBtn.onclick = twoFunction;
#btn {
height: 30px;
width: 50px;
color: white;
background: orange;
line-height: 30px;
margin-top: 50px;
margin-left: 250px;
padding: 10px;
cursor: pointer
}
#base {
padding: 10px;
background: pink;
width: 200px;
height: 110px;
margin-top: 0px;
transition: 1s ease-in-out;
}
#base>div {
height: 30px;
width: auto;
background: red;
}
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="btn">
<p>OPEN</p>
</div>
<div id="base">
<div></div>
<div></div>
<div></div>
</div>
</body>
<script src="js/scripts.js"></script>
</html>
From your code, else if (status = true) should be else if (status == true) or else if (status === true)

Adding images to my array?

I would like to know if there's any way to add images to the arrays of my Slot machine? Right now i've just been able to add numbers in the array.
So far i got this, i know there's only one choice in my array, it's on purpose:
var arr = ["#7.png"];
// var arr = [5];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").innerHTML = arr[Math.floor(Math.random() * arr.length)];
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").innerHTML = arr[Math.floor(Math.random() * arr.length)];
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
You should use the backgroundImage javascript property and provide value with a source from the array arr.
Refer code:
var arr = ['image1.png', 'image2.png', 'image3.png'];
var credits = 10;
function freezeCheck() {
if (document.getElementById("hold1").checked == true || document.getElementById("hold2").checked == true || document.getElementById("hold3").checked == true) {
// if any is checked, freeze hold buttons.
document.getElementById("hold1").checked = false;
document.getElementById("hold2").checked = false;
document.getElementById("hold3").checked = false;
document.getElementById("hold1").disabled = true;
document.getElementById("hold2").disabled = true;
document.getElementById("hold3").disabled = true;
} else if (document.getElementById("hold1").disabled == true) {
// if any diabled, enable (unfreeze) all hold buttons.
document.getElementById("hold1").disabled = false;
document.getElementById("hold2").disabled = false;
document.getElementById("hold3").disabled = false;
document.getElementById("reel1").classList.remove('hold');
document.getElementById("reel2").classList.remove('hold');
document.getElementById("reel3").classList.remove('hold');
}
};
function getNumbers() {
if(document.getElementById("hold1").checked == false){
document.getElementById("reel1").backgroundImage = "url(" + arr[0] + ")";
} if (document.getElementById("hold2").checked == false){
document.getElementById("reel2").backgroundImage = "url(" + arr[1] + ")";
} if (document.getElementById("hold3").checked == false){
document.getElementById("reel3").backgroundImage = "url(" + arr[2] + ")";
}
updateScore();
insertCoins();
};
function calculateScore() {
document.getElementById('credits').innerHTML = credits;
}
// Win, three alike.
function updateScore() {
if(document.getElementById("reel1").textContent == document.getElementById("reel2").textContent && document.getElementById("reel1").textContent == document.getElementById("reel3").textContent){
credits += document.getElementById("reel1").textContent * 10;
} else if("reel1" != "reel2"){
credits -= 2;
}
};
function insertCoins() {
if (credits <1){
document.getElementById("spin").disabled = true;
}
};
function freezeReel(num) {
if (document.getElementById('hold'+num).checked == true) {
// Unfreeze reel
document.getElementById("hold"+num).checked = false;
document.getElementById("reel"+num).classList.remove('hold');
} else {
// Freeze reel:
document.getElementById("hold"+num).checked = true;
document.getElementById("reel"+num).classList.add('hold');
}
}
* {
margin: 0;
padding: 0;
}
.marginauto {
margin: 0 auto;
}
.button-wrapper {
text-align: center;
margin-top: 15%;
}
.hold-wrapper {
text-align: center;
margin: 10px;
font-size: 48px;
}
.holdbutton {
width: 140px;
height: 200px;
visibility: hidden;
}
.credits {
width: 250px;
height: 100px;
margin: 0 auto;
text-align: center;
}
.reel-wrapper {
width: 1280px;
text-align: center;
margin-top: 10px;
background-color: #ffffff;
}
.button {
background-color: white;
}
.reels {
background-color: #ffffff;
display: inline-block;
font-size: 48px;
text-align: center;
width: 150px;
height: 200px;
border: 1px solid black;
border-radius: 2px;
}
.reels.hold {
border-color: blue;
background: #ccc;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> </title>
</head>
<body>
<header></header>
<div class="button-wrapper">
<input id="spin" type="button" onClick="getNumbers(); freezeCheck(); calculateScore();" value="Spin" />
</div>
<div class="reel-wrapper marginauto">
<div id="reel1" onClick="freezeReel(1);" class="reels"></div>
<div id="reel2" onClick="freezeReel(2);" class="reels"></div>
<div id="reel3" onClick="freezeReel(3);" class="reels"></div>
</div>
<div class="hold-wrapper">
<input id="hold1" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold2" type="checkbox" value="Hold" class="holdbutton" />
<input id="hold3" type="checkbox" value="Hold" class="holdbutton" />
</div>
<div class="credits">Your Credits: <span id="credits"></span></div>
<script src="script.js"></script>
</body>
</html>
innerHTML stands for standard font in your page and it will only shows text. Since in your array, the value of it is #7.png and it will only display #7.png.
Adding the following code will create img tag in your html code with the images being random.
var elem = document.createElement("img");
elem.setAttribute("src", arr[Math.floor(Math.random() * arr.length)]);
elem.setAttribute("alt", "Slotimg");
document.getElementById("reel1").appendChild(elem);
However if you can create a default image, i would suggest you just add a Img tag in your div, and just change the src attribute by src code, it is going to be much easier and effiecnt

Counter not working in jQuery

I am trying to run my counter for 3 times. once I reach 3 tries the button is supposed to be disabled. I tried couple variations of this solution to no avail. the issue is right on my rollItAgain function. I have my counter starting at 3, and a for loop with an if statement inside. I am also running my randomFunction() inside my if statement, not sure if this is good practice. As of now, I only click reroll once and it gets disabled. I would like it to run at least 3 times.
// 'use strict';
var array = [];
var random = Math.ceil(Math.random() * 9);
var newStars = "<div class='star'><img src='http://i.imgur.com/kXH65I7.png'></div>";
$(document).ready(init);
function init(){
for (var i = 0; i < random; i++){
$('#starbox').append(newStars);
//Create Event Handler for selectNumbers Function
}
$('.numbers').click(selectNumbers);
$('#checked').click(confirm);
$('.numbers').click(toggleButton);
$('#playagain').click(playItAgain);
$('#reroll').click(rollItAgain);
}
function randomFunction(){
$('#starbox').empty();
random = Math.ceil(Math.random() * 9);
for (var i = 0; i < random; i++){
$('#starbox').append(newStars);
}
}
//selectNumbers function
function selectNumbers(){
var num = $(this).text();
// $(this).css('background-color', 'red');
array.push(num);
// console.log(array);
sum = array.reduce(function(a, b){
return Number(a) + Number(b);
});
console.log(sum);
//Check if numbers has select class
console.log(num);
}
function toggleButton(){
$(this).toggleClass('select');
}
function confirm(){
if (sum === random){
$('#displayResult').append("Correct!");
// $('.select').css('display', 'none');
} else {
$('#displayResult').append("Wrong, try again!!");
}
$('.select').remove();
}
function rollItAgain(){
// debugger;
var counter = 3;
// debugger;
for (var j = 0; j < counter; j++){
if(j === counter){
randomFunction();
counter++;
} else {
$('#reroll').attr('disabled', 'disabled');
}
}
}
function playItAgain(){
location.reload();
}
#numberbox {
width: 400px;
height: 100px;
border: 2px solid green ;
}
.numbers {
height: 100px;
width: 100px;
background-color:transparent;
border: 2px solid #000;
margin: 5px;
line-height: 100px;
display: inline-block;
border-radius: 50%;
text-align: center;
border: 2px solid #000;
font-size: 30px;
}
#starbox {
min-height: 300px;
min-width: 400px;
background-color:transparent;
border: 2px solid #000;
margin:100px 100px;
}
.star {
display: inline-block;
}
.select {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mathgame1</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://code.jquery.com/jquery-2.2.1.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="starbox"></div>
<p id="displayResult"></p>
<table id="numberbox" >
<button id="playagain">Play it Again</button>
<button id="checked">checked</button>
<button id="reroll">reroll</button>
<tr >
<td class="numbers">1</td>
<td class="numbers">2</td>
<td class="numbers">3</td>
</tr>
<tr >
<td class="numbers">4</td>
<td class="numbers">5</td>
<td class="numbers">6</td>
</tr>
<tr >
<td class="numbers">7</td>
<td class="numbers">8</td>
<td class="numbers">9</td>
</tr>
</table>
</body>
</html>
Ask yourself why wouldn't this code run through three times? That's what a loop does. What you're really wanting is not a loop but just a counter. The thing that triggers the rolling is the click events, not a counting loop.
First off, you are misapplying a few concepts. You have a counter variable which looks to actually represent the counter maximum. j is more appropriately called your counter. But you need to keep track of the counter value between calls to rollItAgain, so declare it outside of your function. Then increment the counter whenever rollItAgain is called. You don't have to write a loop because the clicking of the button will take care of calling the function multiple times. Secondly, change your check; you want to run the random function when the counter is less than the limit:
var counter = 0;
var limit = 3;
function rollItAgain(){
if (counter < limit) {
randomFunction();
counter++;
} else {
$('#reroll').attr('disabled', 'disabled');
}
}
The problem in your code is that you never get to condition if(j === counter){ to roll dice because your iteration only goes as far as while j < counter. So this never happens.
Rewrite your function to as below, check demo - Fiddle:
function rollItAgain() {
// debugger;
var counter = 3;
// debugger;
for (var j = 0; j <= counter; j++) {
if (j < counter) {
randomFunction();
} else {
$('#reroll').attr('disabled', 'disabled');
}
}
}

Resetting timer and score values to 0 before a new game starts

Im new to this but I've been having some trouble with trying to get my timer and score values back to 0 before a new game of memory starts. The values do reset, but don't show it until that value is affected. For example, the value for the number of matches never goes back to 0, it stays on 10(the max number of pairs) until you find the first match of the next game where it will then turn to 1. Does anybody know how to get the values to show 0 again when a new board is called up instead of just resetting when that value is affected?
I have already set
var turns = 0
var matches = 0
and called in them up as 0 in the function newBoard().
My timer code is:
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
Where I have called up the resetTime() function in the function newBoard().
My full code is:
body{
background:#FFF;
font-family: Cooper Black;
}
h1{
font-family: Cooper Black;
text-align: center;
font-size: 64px;
color: #FF0066;
}
footer{
height: 150px;
background: -webkit-linear-gradient(#99CCFF, #FFF); /* For Safari 5.1 to 6.0 */
background: -o-linear-gradient(#99CCFF, #FFF); /* For Opera 11.1 to 12.0 */
background: -moz-linear-gradient(#99CCFF, #FFF); /* For Firefox 3.6 to 15 */
background: linear-gradient(#99CCFF, #FFF); /* Standard syntax (must be last) */
}
div#memory_board{
background: -webkit-radial-gradient(#FFF, #CC99FF); /* For Safari 5.1 to 6.0 */
background: -o-radial-gradient(#FFF, #CC99FF); /* For Opera 11.1 to 12.0 */
background: -moz-radial-gradient(#FFF, #CC99FF); /* For Firefox 3.6 to 15 */
background: radial-gradient(#FFF, #CC99FF); /* Standard syntax (must be last) */
border:#FF0066 10px ridge;
width:510px;
height:405px;
padding:24px;
}
div#memory_board > div{
background:url(tile_background.png) no-repeat;
border:#000 1px solid;
width:45px;
height:45px;
float:left;
margin:7px;
padding:20px;
cursor:pointer;
}
alert{
background: #FF0066;
}
button{
font-family: Cooper Black;
font-size: 20px;
color: #FF0066;
background: #5CE62E;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
}
input#txt{
background: yellow;
color: #FF0066;
font-family: Times New Roman;
font-size: 84px;
height: 150px;
width: 150px;
border-radius: 100%;
text-align: center;
border: none;
}
input#pause{
font-family: Cooper Black;
font-size: 18px;
color: #FF0066;
background: #C2E0FF;
border: #C2E0FF 2px outset;
border-radius: 25px;
padding: 10px;
cursor: pointer;
margin-top: 10px;
}
div.goes{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 48px;
margin-left: 5px;
}
div.matches{
text-align: center;
border: #C2E0FF 5px double;
height: 160px;
width: 120px;
margin-top: 30px;
margin-left: 10px;
}
p{
font-size: 28px;
}
span{
font-family: Times New Roman;
font-size: 84px;
}
.sprite {
width:96px;
height:96px;
position: relative;
margin:15px;
}
.toon{
background: url(explode.png);
}
}
#dialogoverlay{
display: none;
opacity: 0.8;
position: fixed;
top: 0px;
left: 0px;
background: #FFF;
width: 100%;
z-index: 10;
}
#dialogbox{
display: none;
position: fixed;
background: #FF0066;
border-radius:7px;
width:400px;
z-index: 10;
}
#dialogbox > div{ background: #FFF; margin:8px; }
#dialogbox > div > #dialogboxhead{ background: linear-gradient(#99CCFF, #FFF); height: 40px; color: #CCC; }
#dialogbox > div > #dialogboxbody{ background: #FFF; color: #FF0066; font-size: 36px; text-align:center;}
#dialogbox > div > #dialogboxfoot{ background: linear-gradient(#FFF, #99CCFF); padding-bottom: 20px; text-align:center; }
<!DOCTYPE html>
<html>
<head>
<title>Memory Card Game</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="reset.css" />
<link rel="stylesheet" type="text/css" href="text.css" />
<link rel="stylesheet" type="text/css" href="960.css" />
<link rel="stylesheet" type="text/css" href="mystyles.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type='text/javascript' src='jquery.animateSprite.js'></script>
<script>
var memory_array = ['A','A','B','B','C','C','D','D','E','E','F','F','G','G','H','H','I','I','J','J'];
var memory_values = [];
var memory_tile_ids = [];
var tiles_flipped = 0;
var turns = 0
var matches = 0
Array.prototype.memory_tile_shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard(){
tiles_flipped = 0;
var output = '';
memory_array.memory_tile_shuffle();
for(var i = 0; i < memory_array.length; i++){
output += '<div id="tile_'+i+'" onclick="memoryFlipTile(this,\''+memory_array[i]+'\')"></div>';
}
document.getElementById('memory_board').innerHTML = output;
//fade in
$(document).ready(function () {
$('#memory_board > div').hide().fadeIn(1500).delay(6000)
});
resetTime();
turns = 0;
matches = 0;
}
function memoryFlipTile(tile,val){
startTimer();
playClick();
if(tile.innerHTML == "" && memory_values.length < 2){
tile.style.background = '#FFF';
tile.innerHTML = '<img src="' + val + '.png"/>';
if(memory_values.length == 0){
memory_values.push(val);
memory_tile_ids.push(tile.id);
} else if(memory_values.length == 1){
memory_values.push(val);
memory_tile_ids.push(tile.id);
if(memory_values[0] == memory_values[1]){
tiles_flipped += 2;
//sound
playMatch();
//animation
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//number of matches
matches = matches + 1;
document.getElementById("matchNumber").innerHTML = matches;
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
// Check to see if the whole board is cleared
if(tiles_flipped == memory_array.length){
playEnd();
Alert.render("Congratulations! Board Cleared");
//resetTime()
//stopCount();
document.getElementById('memory_board').innerHTML = "";
newBoard();
}
} else {
function flipBack(){
// Flip the 2 tiles back over
var tile_1 = document.getElementById(memory_tile_ids[0]);
var tile_2 = document.getElementById(memory_tile_ids[1]);
tile_1.style.background = 'url(tile_background.png) no-repeat';
tile_1.innerHTML = "";
tile_2.style.background = 'url(tile_background.png) no-repeat';
tile_2.innerHTML = "";
//number of clicks
turns = turns + 1;
document.getElementById("Count").innerHTML = turns;
//clickNumber()
// Clear both arrays
memory_values = [];
memory_tile_ids = [];
}
setTimeout(flipBack, 700);
}
}
}
}
//timer
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}
function startTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetTime(){
clearTimeout(t);
timer_is_on = 0;
c = 0
}
//sound effects /*sounds from http://www.freesfx.co.uk*/
function playClick(){
var sound=document.getElementById("click");
sound.play();
}
function playMatch(){
var sound=document.getElementById("match_sound");
sound.play();
}
function playEnd(){
var sound=document.getElementById("finished");
sound.play();
}
//custom alert
function CustomAlert(){
this.render = function(dialog){
var winW = window.innerWidth;
var winH = window.innerHeight;
var dialogoverlay = document.getElementById('dialogoverlay');
var dialogbox = document.getElementById('dialogbox');
dialogoverlay.style.display = "block";
dialogoverlay.style.height = winH+"px";
dialogbox.style.left = (winW/2) - (400 * .5)+"px";
dialogbox.style.top = "200px";
dialogbox.style.display = "block";
document.getElementById('dialogboxhead').innerHTML = "";
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">New Game</button>';
}
this.ok = function(){
document.getElementById('dialogbox').style.display = "none";
document.getElementById('dialogoverlay').style.display = "none";
}
}
var Alert = new CustomAlert();
</script>
<script>//sparkle effect: http://www.rigzsoft.co.uk/how-to-implement-animated-sprite-sheets-on-a-web-page/
$(document).ready(function(){
$("#memory_board").click(function animation(){
$(".toon").animateSprite({
columns: 10,
totalFrames: 50,
duration: 1000,
});
});
});
</script>
</head>
<body>
<audio id = "click" src = "click.mp3" preload = "auto"></audio>
<audio id = "match_sound" src = "match.mp3" preload = "auto"></audio>
<audio id = "finished" src = "finished.wav" preload = "auto"></audio>
<div id = "dialogoverlay"></div>
<div id = "dialogbox">
<div>
<div id = "dialogboxhead"></div>
<div id = "dialogboxbody"></div>
<div id = "dialogboxfoot"></div>
</div>
</div>
<div class = "container_16">
<div id = "banner" class = "grid_16">
<p><br></p>
<h1>Memory</h1>
</div>
<div class = "grid_3">
<input type="text" id="txt" value="0"/>
<p><br></p>
<p><br></p>
<div class = "goes">
<p>Turns <br><span id = "Count">0</span></p>
</div>
</div>
<div class = "grid_10">
<div id="memory_board"></div>
<script>newBoard();</script>
<div style="position: relative; height: 110px;">
<div class="sprite toon"></div>
</div>
</div>
<div class = "grid_3">
<button id = "new_game" onclick="newBoard()">New Game</button>
<input type="button" id="pause" value="Pause Game" onclick="stopCount()">
<p><br></p>
<p><br></p>
<p><br></p>
<div class = "matches">
<p>Matches <br><span id = "matchNumber">0</span></p>
</div>
</div>
</div>
<footer> </footer>
</body>
</html>
Both of the variables you are settings are displayed in HTML span objects.
What seems to be happening is that when you reset the Javascript variable, the value is being changed, but the span object where it is displayed to the user is being left at its previous value until it needs to be updated again.
As far as I can tell, your objects have the ids: matchNumber and Count for the match and turn variables respectively. If this is the case, try changing your code to reset the values to zero in the HTML when the variables are reset to zero.
For example:
// Reset the Javascript Count
var turns = 0
// Reset the HTML object
document.getElementById('Count').innerHTML = 0;
// Reset the Javascript Match Count
var matches = 0
// Reset the HTML object
document.getElementById('matchNumber').innerHTML = 0;
If I failed to explain this well, please comment and I'll try to clarify further.
I am not 100% sure, but you can try replacing your function with this one:
function timedCount() {
if(c>10){
//flipBack();
resetTime();
return;
}
document.getElementById('txt').value = c;
c = c+1;
t = setTimeout(timedCount, 1000);
}

Categories

Resources