JavaScript Math.random() returning Nan [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am new to JavaScript and have been tasked with creating a simplified version of BlackJack. I've created 4 variables: var card1 = 0; same for card2, card3, and card4. To my understanding that would create a numeric variable. Then when I try to get a random number assigned to them, it's returning NaN.
var card1 = 0;
var card2 = 0;
var card3 = 0;
var card4 = 0;
card1 = Math.floor(Math.random() * 11 + 2);
card2 = Math.floor(Math.random() * 11 + 2);
card3 = Math.floor(Math.random() * 11 + 2);
card4 = Math.floor(Math.random() * 11 + 2);
console.log(card1, card2, card3, card4);
I've tried adding parseInt before the random with the same result. Any suggestions?

There's nothing wrong with the code you posted, at least in regards to NaN (Not a Number) values. Anyways, here is a nice fully-working HTML, CSS, JS Blackjack game. Maybe it can help you to find where you made mistakes, or at least inspire you go around this 'problem' in a slightly different manner.
<script>
window.addEventListener("load", start, false);
function start()
{
play();
}
function play()
{
var deck1 = new Deck();
deck1.createDeck();
deck1.shuffle();
deck1.deal21();
document.getElementById("hit").addEventListener("click", function(){deck1.hit();},false);
document.getElementById("stand").addEventListener("click", function(){deck1.stand();},false);
document.getElementById("replay").addEventListener("click", function(){deck1.deal21();}, false);
}
function Deck()
{
this.deck = new Array();
this.userTotal;
this.dealerTotal;
this.money = 100;
this.userBust;
this.dealerBust;
this.curusrHand;
this.curdlrHand;
var userHand = document.getElementById("user-hand");
var dealerHand = document.getElementById("dealer-hand");
var userScore = document.getElementById("user-score");
var dealerScore = document.getElementById("dealer-score");
var status = document.getElementById("game-status");
var moneyDiv = document.getElementById("money");
this.newDeck = function newDeck()
{
this.createDeck();
this.shuffle();
status.innerHTML="NEW DECK IN PLAY!";
}
this.createDeck = function createDeck()
{
var numCards=0;
var suit, symbol, name;
for(var k=1; k<=4; k++)
{
switch(k)
{
case 1: suit ="hearts";
break;
case 2: suit ="diamonds";
break;
case 3: suit ="spades";
break;
case 4: suit ="clubs";
break;
}
for(var i=1; i<=13; i++)
{
symbol = i;
switch(i)
{
case 1: name= "Ace";
symbol = "A";
break;
case 2: name= "two";
break;
case 3: name= "three";
break;
case 4: name= "four";
break;
case 5: name= "five";
break;
case 6: name= "six";
break;
case 7: name= "seven";
break;
case 8: name= "eight";
break;
case 9: name= "nine";
break;
case 10: name= "ten";
break;
case 11: name= "jack";
symbol = "J";
break;
case 12: name= "queen";
symbol = "Q";
break;
case 13: name= "king";
symbol = "K";
break;
}
this.deck[numCards] = new Card(suit, i, name, symbol);
numCards++;
}
}
}
this.shuffle = function shuffle()
{
var randomDeck = new Array();
var empty = false;
while(!empty)
{
var randomIndex = Math.floor(Math.random()*this.deck.length);
randomDeck.push(this.deck[randomIndex]);
this.deck.splice(randomIndex, 1);
if(this.deck.length <=0) empty = true;
}
for(var i=0; i<randomDeck.length; i++)
{
this.deck[i] = randomDeck[i];
}
};
this.calcValue = function calcValue(hand)
{
var val = 0;
var tempArr = hand;
tempArr.sort(function(a,b) { return parseFloat(a.val) - parseFloat(b.val) } );
for(var i=tempArr.length-1; i>=0; i--)
{
var temp = tempArr[i];
if(temp.val === 1 && val <=10)temp.val = 11;
else if(temp.val >=10) temp.val = 10;
val += temp.val;
}
return val;
};
this.emptyDeck = function emptyDeck()
{
if(this.deck.length < 1) return true;
else return false;
}
this.deal21 = function deal21()
{
status.innerHTML="";
this.money--;
//reset all the stuff that needs to be reset if the game is being replayed
money.innerHTML= "Money: " + this.money;
dealerHand.innerHTML="<h2>Dealer Hand</h2>";
userHand.innerHTML="<h2>User Hand</h2>";
this.userTotal=0;
this.dealerTotal=0;
this.userBust=false;
this.dealerBust=false;
hit.setAttribute("style", "");
stand.setAttribute("style", "");
dealerScore.setAttribute("style", "");
this.curusrHand = new Array();
this.curdlrHand = new Array();
for(i=0; i<2; i++)
{
if(this.emptyDeck())this.newDeck();
this.curusrHand.push(this.deck.pop());
userHand.innerHTML+=this.curusrHand[i].showCard();
}
this.userTotal = this.calcValue(this.curusrHand);
userScore.innerHTML=this.userTotal;
for(i=0; i<2; i++)
{
if(this.emptyDeck())this.newDeck();
this.curdlrHand.push(this.deck.pop());
dealerHand.innerHTML+=this.curdlrHand[i].showCard();
}
this.dealerTotal = this.calcValue(this.curdlrHand);
dealerScore.innerHTML=this.dealerTotal;
//hide dealers first card
var firstCard = dealerHand.getElementsByClassName("card")[0];
firstCard.setAttribute("id", "hidden-card");
var blackjack =true;
if(this.userTotal === 21 && this.dealerTotal < 21) this.gameOver(blackjack);
else if(this.dealerTotal === 21) this.gameOver();
};
this.hit = function hit()
{
if(this.emptyDeck())this.newDeck();
this.curusrHand.push(this.deck.pop());
userHand.innerHTML+=this.curusrHand[this.curusrHand.length-1].showCard();
this.userTotal = this.calcValue(this.curusrHand);
userScore.innerHTML=this.userTotal;
if(this.userTotal >21)
{
userScore.innerHTML+=" <span style='color:red; font-weight: bold;'> BUST</span>";
this.userBust = true;
this.gameOver();
}
};
this.stand = function stand()
{
while(this.dealerTotal < 17)
{
if(this.emptyDeck())this.newDeck();
this.curdlrHand.push(this.deck.pop());
dealerHand.innerHTML+=this.curdlrHand[this.curdlrHand.length-1].showCard();
this.dealerTotal = this.calcValue(this.curdlrHand);
dealerScore.innerHTML=this.dealerTotal;
if(this.dealerTotal > 21)
{
dealerScore.innerHTML+=" <span style='color:red; font-weight: bold;'> BUST</span>";
this.dealerBust = true;
}
}
this.gameOver();
}
this.gameOver = function gameOver(blackjack)
{
document.getElementById("hidden-card").setAttribute("id","");
dealerScore.setAttribute("style", "visibility: visible;");
hit.setAttribute("style", "visibility:hidden;");
stand.setAttribute("style", "visibility:hidden;");
if(blackjack)
{
this.money +=3;
status.innerHTML ="BLACKJACK!!!!!!!!!";
}
else if(this.userTotal > this.dealerTotal && this.userBust === false || this.dealerBust ===true)
{
//user wins
this.money+=2;
status.innerHTML ="YOU WIN!";
}
else if(this.userTotal === this.dealerTotal && this.userBust === false)
{
//push
this.money++;
status.innerHTML="PUSH :o";
}
else status.innerHTML="YOU LOSE!";
money.innerHTML="Money: "+this.money;
}
this.dump = function dump()
{
for(var i=0; i<this.deck.length; i++)
{
this.deck[i].showCard();
}
};
}
function Card(suit, val, name, symbol)
{
this.suit = suit;
this.val = val;
this.name = name;
this.symbol = symbol;
this.showCard =function showCard()
{
var html="";
switch(this.suit)
{
case "hearts": suit_text = "♥";
break;
case "diamonds": suit_text = "♦";
break;
case "spades": suit_text = "♠";
break;
case "clubs": suit_text = "♣";
break;
}
html="<div class='card " + this.suit + "'><div class='card-value'>" + this.symbol + "</div><div class='suit'>" + suit_text + "</div><div class='main-number'>"+this.symbol +"</div><div class='invert card-value'>"+this.symbol+"</div><div class='invert suit'>"+suit_text+"</div></div>";
return html;
}
}
</script>
div.card
{
display: inline-block;
width: 100px;
height: 150px;
border: solid 1px #333;
border-radius: 5px 5px 5px 5px;
float: left;
margin-right: 10px;
position: relative;
}
div.card.hearts, div.card.diamonds
{
color: red;
}
div.card div.main-number
{
font-size: 36px;
font-weight: bold;
text-align: center;
margin: 0px auto;
margin-top: 50px;
}
div.card-value, div.suit
{
position: absolute;
left: 5px;
}
div.card-value{top: 5px;}
div.card-value{top: 20px;}
div.card-value.invert, div.suit.invert
{
transform: rotate(180deg);
right: 5px;
text-align: right;
top: auto;
left: auto;
}
div.card-value.invert{bottom: 5px;}
div.suit.invert{bottom: 20px;}
div.dealer-area{}
div.user-area{float: left;}
div#user-score, div#dealer-score
{
display: inline-block;
}
div.score-parent
{
width: 100%;
display: inline-block;
}
div.score-parent p
{
display: inline-block;
}
div#dealer-score
{
visibility: hidden;
}
div.card#hidden-card
{
background-color: #CBE0FD;
}
div.card#hidden-card div
{
visibility: hidden;
}
div.controls input
{
margin-left: 20px;
width: 200px;
}
.score-parent {
color: blue;
font-weight: bold;
}
#user-hand {
font-family: cursive;
color: green;
font-weight: bold;
}
#dealer-hand {
font-family: cursive;
color: orange;
font-weight: bold;
}
input {
display: inline-block;
color: green;
font-weight: bold;
}
#money {
padding-bottom: 1rem;
color: gold;
letter-spacing: 3px;
font-weight: bold;
font-family: Arial;
}
<html>
<head>
</head>
<body>
<div id="game-status"></div>
<div class="user-area">
<div id="money"></div>
<div id="user-buttons" class="controls">
<input type="button" id="hit" value="Hit">
<input type="button" id="stand" value="Stand">
<input type="button" id="replay" value="Play Again">
</div>
<div class="score-parent">
<p>Score</p>
<div id="user-score"class="score">
</div>
</div>
<div id="user-hand" class="hand">
<h2>User Hand</h2>
</div>
</div>
<div class="dealer-area">
<div class="score-parent">
<p>Current Score: </p>
<div id="dealer-score"class="score">
</div>
</div>
<div id="dealer-hand" class="hand">
<h2>Dealer Hand</h2>
</div>
</div>
</body>
</html

Related

Looping a lotto game from codepen

Recently I've been looking at different projects and trying to modify them to try and understand the JS code much better. Recently I came across this lotto game from code pen. So I thought to try to make it to a game where you had coins as lives, then you get some stars based on how many numbers you got right.
The thing that I am struggling at is trying to loop the code on the click of a button. Currently the code is restarting the game by recalling its own link, in this case I just used my index.html as replacement for the href just to work on it for now. I want to change this because it doesn't let me consume all my coins (lives) without refreshing the page.
I tried putting everything in a function instead of calling it through the DOM being loaded. I then called that function when the dom has loaded, then after each draw I tried calling it again by using another button but it doesn't work. Tried changing the href to the function but that doesn't work as well. I also tried a few other things but I cannot make a work around this. Any help is appreciated! I'm still learning Javascript, so please pardon my question.
The code is not owned by me, I am just playing around with it, here's the original codepen link. https://codepen.io/EwaTrojanowskaGrela/pen/KmJMWb
// Declaration of scores and lives
var stars = 0;
var coins = 5;
// End of comment
// For redeclaration in innerHTML
var starsEarned;
// End of comment
// For displaying current score
document.getElementById("star-count").innerHTML = stars;
document.getElementById("coin-count").innerHTML = coins;
// End of comment
document.addEventListener("DOMContentLoaded", function(e){
var body = document.querySelector("body");
var section = document.querySelector("section");
var articleLotto = document.querySelector(".lotto");
var articleBalls = document.querySelector(".balls");
var numbers = [];
var balls = document.getElementsByClassName("ball");
var drawnNums = [];
var chosenByMachine = [];
function createNumberBoard(number){
console.log("I work");
var board = document.createElement("div");
board.classList.add("board");
articleLotto.appendChild(board);
for( var i = 0; i<number; i ++){
var boardEl = document.createElement("button");
boardEl.classList.add("boardEl");
board.appendChild(boardEl);
}
var boardEls = document.getElementsByClassName("boardEl");
for( var i =0; i<boardEls.length; i++){
boardEls[i].setAttribute("data-number", i+1);
var dataNumber = boardEls[i].getAttribute("data-number");
var number = parseInt(dataNumber, 10);
numbers.push(number);
boardEls[i].textContent = number;
}
}
createNumberBoard(49);
var board = document.querySelector(".board");
var boardEls = document.querySelectorAll(".boardEl");
function drawNumbers(){
//boardEls.forEach(boardEl => boardEl.addEventListener("click", selectNums));
for (var i = 0; i<boardEls.length; i++){
boardEls[i].addEventListener("click", selectNums);
}
function selectNums(){
var number = parseInt(this.dataset.number, 10);
if(this.hasAttribute("data-number")){
drawnNums.push(number);
this.removeAttribute("data-number");
this.classList.add("crossedOut");
}
if(drawnNums.length=== 6){
//boardEls.forEach( boardEl => boardEl.removeAttribute("data-number"));
//boardEls.forEach(boardEl => boardEl.addEventListener("click", makeAlert));
for ( var i = 0; i<boardEls.length; i++){
boardEls[i].removeAttribute("data-number");
boardEls[i].addEventListener("click", makeAlert);
}
var startDraw = document.querySelector(".startDraw");
if(startDraw === null){ // you have to prevent creating the button if it is already there!
createButtonForMachineDraw();
} else {
return;
}
}
}
return drawnNums;
}
drawNumbers();
function makeAlert() {
var alertBox = document.createElement("div");
board.appendChild(alertBox);
alertBox.classList.add("alertBox");
alertBox.textContent = "You can only choose 6!";
setTimeout(function() {
alertBox.parentNode.removeChild(alertBox);
}, 1500);
}
function machineDraw(){
for( var i =0; i<6; i++){
var idx = Math.floor(Math.random() * numbers.length)
chosenByMachine.push(numbers[idx]);
/*a very important line of code which prevents machine from drawing the same number again
*/
numbers.splice(idx,1);
console.log(numbers)
/*this line of code allows to check if numbers are taken out*/
}
var btnToRemove = document.querySelector(".startDraw");
btnToRemove.classList.add("invisible");
/* why not remove it entirely? because it might then be accidentally created if for some reason you happen to try to click on board!!! and you may do that*/
return chosenByMachine;
}
//machineDraw();
function createButtonForMachineDraw(){
var startDraw = document.createElement("button");
startDraw.classList.add("startDraw");
section.appendChild(startDraw);
startDraw.textContent ="Release the balls";
startDraw.addEventListener("click", machineDraw);
startDraw.addEventListener("click", compareArrays);
}
function compareArrays(){
for( var i =0; i<balls.length; i++) {
balls[i].textContent = chosenByMachine[i];
(function() {
var j = i;
var f = function(){
balls[j].classList.remove("invisible");
balls[j].classList.add("ball-align");
}
setTimeout(f, 1000*(j+1));
})();
}
var common =[];
var arr1 = chosenByMachine;
var arr2 = drawnNums;
for(var i = 0; i<arr1.length; i++){
for(var j= 0; j<arr2.length; j++){
if(arr1[i]===arr2[j]){
common.push(arr1[i]);
}
}
}
console.log(arr1, arr2, common); /* you can monitor your arrays in console*/
function generateResult(){
// Deduction of coins once draw started
coins = coins - 1;
// End of comment
var resultsBoard = document.createElement("article");
section.appendChild(resultsBoard);
var paragraph = document.createElement("p");
resultsBoard.appendChild(paragraph);
resultsBoard.classList.add("resultsBoard");
resultsBoard.classList.add("invisible");
if(common.length === 0){
paragraph.textContent ="Oh no! You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 1){
paragraph.textContent ="You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 2){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 3) {
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 4){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return ststarsEarnedars;
} else if(common.length === 5){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
}
else if(common.length===6){
paragraph.textContent ="A true winner! You got " + common.length + " Stars!";
stars = stars + common.length;
return starsEarned;
}
// Returning of new coins
return coins;
// End of comment
}
setTimeout(function() {
makeComebackBtn();
document.querySelector(".resultsBoard").classList.remove("invisible"); //well, you cannot acces this outside the code
// Displaying of new scores
stars = stars + starsEarned;
document.getElementById("coin-count").innerHTML = coins;
document.getElementById("star-count").innerHTML = stars;
// End of comment
}, 8000);
generateResult();
}
function makeComebackBtn(){
var comebackBtn = document.createElement("a");
comebackBtn.classList.add("comebackBtn");
section.appendChild(comebackBtn);
comebackBtn.textContent ="Go again"
comebackBtn.setAttribute("href", "index.html");
}
})
body {
padding: 0 15%;
}
.game-container {
height: auto;
background-color:#424B54;
font-family: "Allerta", sans-serif;
margin: 0;
max-width: 425px;
height: 750px;
/* padding: 0 2%; */
box-sizing: border-box;
}
section {
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: auto;
padding-bottom: 15px;
}
h1,
p {
width: 100%;
text-align: center;
color: #FF6663;
text-shadow: 3px 3px #A20202;
font-family: "Bungee", cursive;
}
h1 {
font-size: 35px;
margin: 0;
}
p {
font-size: 30px;
margin: 0;
}
h3 {
color: #FF6663;
text-align: center;
text-shadow: 2px 2px #A20202;
font-size: 25px;
margin-bottom: 5px;
}
article {
height: 90%;
width: 250px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
margin-bottom: 1rem;
}
.scores {
width: 100%;
}
.coins,
.stars{
display: flex;
align-items: center;
gap: .5rem;
}
.score-icons {
color: #F6BD60;
font-size: 3rem;
}
.scores span {
color: white;
}
#star-count,
#coin-count{
font-size: 1.5 rem;
}
.invisible {
display: none;
}
.ball-align {
display: flex;
justify-content: center;
align-items: center;
}
.board {
position: relative;
background-color: #FF6663;
width: 13.125rem;
height: 13.125rem;
border: 1px solid #FF6663;
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
}
.boardEl {
background-color: #E8F7EE;
width: 28px;
height: 28px;
color: #000000;
text-align: center;
font-size: 15px;
border: none;
}
.crossedOut {
background-color: #424B54;
color: #F7EDE2;
}
.startDraw {
background: #FF6663;
border: none;
font-size: 1.3rem;
font-weight: bolder;
color: #ffffff;
padding: 0.5rem 1rem;
margin: 0 auto;
border-radius: .5rem;
padding: .5rem 1rem;
}
.ball {
width: 2rem;
height: 2rem;
border-radius: 50%;
line-height: 2;
color: #efefef;
font-weight: bold;
text-align: center;
}
.ball:nth-of-type(2n) {
align-self: flex-end;
}
.ball:nth-of-type(2n + 1) {
align-self: flex-start;
}
.ball:first-of-type {
background-color: gold;
border: 1px solid #ccac00;
}
.ball:nth-of-type(2) {
background-color: hotpink;
border: 1px solid #ff369b;
}
.ball:nth-of-type(3) {
background-color: teal;
border: 1px solid #004d4d;
}
.ball:nth-of-type(4) {
background-color: #009900;
border: 1px solid #006600;
}
.ball:nth-of-type(5) {
background-color: #339999;
border: 1px solid #267373;
}
.ball:last-of-type {
background-color: #ff6633;
border: 1px solid #ff4000;
}
#ballContainer {
background-color: inherit;
border-bottom: none;
display: flex;
align-items: center;
gap: 0.1rem;
}
.resultsBoard {
margin-top: .5rem;
text-align: center;
width: 100%;
}
.resultsBoard p {
color: #F6BD60;
font-size: 2rem;
font-family: "Allerta", sans-serif;
text-shadow: none;
}
.comebackBtn {
line-height: 2;
margin-top: 2rem;
font-size: 1.3rem;
text-align: center;
background-color: #FF6663;
text-decoration: none;
color: #ffffff;
padding: .3rem 1rem;
border-radius: .3rem;
text-transform: uppercase;
}
.alertBox {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 3;
color: #ffffff;
background-color: #FF6663;
text-align: center;
line-height: 210px;
}
<!DOCTYPE html>
<html lang="eng-ENG">
<head>
<meta charset="UTF-8">
<title>lotto</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Allerta|Bungee" rel="stylesheet">
<link href='https://unpkg.com/boxicons#2.1.2/css/boxicons.min.css' rel='stylesheet'>
</head>
<body>
<main>
<div class="game-container">
<section>
<h1>Lottery</h1>
<div class="scores">
<div class="coins">
<i class='score-icons bx bxs-star'></i><span id="star-count"></span>
</div>
<div class="stars">
<i class='score-icons bx bx-coin'></i><span id="coin-count"></span>
</div>
</div>
<article class="lotto">
<h3>Pick 6 numbers:</h3>
</article>
<article class="balls">
<div id="ballContainer">
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
<div class="ball invisible"></div>
</div>
</article>
</section>
</div>
</main>
<script type="text/javascript" src="index.js"></script>
<!--<script type="text/javascript" src="js/app2.js"></script>-->
</body>
</html>
[UPDATED]
I've tried and modified the js script code and no need to save values in local storage. And in addition, no need to refresh page to reload game state. I implemented in JSFiddle here
var stars = 0;
var coins = 5;
var starsEarned = 0;
// For displaying current score
document.getElementById("star-count").innerHTML = stars;
document.getElementById("coin-count").innerHTML = coins;
document.addEventListener("DOMContentLoaded", function(e){
var body = document.querySelector("body");
var section = document.querySelector("section");
var articleLotto = document.querySelector(".lotto");
var articleBalls = document.querySelector(".balls");
var numbers = [];
var balls = document.getElementsByClassName("ball");
var drawnNums = [];
var chosenByMachine = [];
var board;
var boardEls;
function createNumberBoard(number){
console.log("I work");
numbers = [];
drawnNums = [];
chosenByMachine = [];
var board = document.createElement("div");
board.classList.add("board");
articleLotto.appendChild(board);
for( var i = 0; i<number; i ++){
var boardEl = document.createElement("button");
boardEl.classList.add("boardEl");
board.appendChild(boardEl);
}
var boardEls = document.getElementsByClassName("boardEl");
for( var i =0; i<boardEls.length; i++){
boardEls[i].setAttribute("data-number", i+1);
var dataNumber = boardEls[i].getAttribute("data-number");
var number = parseInt(dataNumber, 10);
numbers.push(number);
boardEls[i].textContent = number;
}
}
createNumberBoard(49);
board = document.querySelector(".board");
boardEls = document.querySelectorAll(".boardEl");
function drawNumbers(){
//boardEls.forEach(boardEl => boardEl.addEventListener("click", selectNums));
for (var i = 0; i<boardEls.length; i++){
boardEls[i].addEventListener("click", selectNums);
}
function selectNums(){
var number = parseInt(this.dataset.number, 10);
if(this.hasAttribute("data-number")){
drawnNums.push(number);
this.removeAttribute("data-number");
this.classList.add("crossedOut");
}
if(drawnNums.length=== 6){
//boardEls.forEach( boardEl => boardEl.removeAttribute("data-number"));
//boardEls.forEach(boardEl => boardEl.addEventListener("click", makeAlert));
for ( var i = 0; i<boardEls.length; i++){
boardEls[i].removeAttribute("data-number");
boardEls[i].addEventListener("click", makeAlert);
}
var startDraw = document.querySelector(".startDraw");
if(startDraw === null){ // you have to prevent creating the button if it is already there!
createButtonForMachineDraw();
} else {
return;
}
}
}
return drawnNums;
}
drawNumbers();
function makeAlert() {
var alertBox = document.createElement("div");
board.appendChild(alertBox);
alertBox.classList.add("alertBox");
alertBox.textContent = "You can only choose 6!";
setTimeout(function() {
alertBox.parentNode.removeChild(alertBox);
}, 1500);
}
function machineDraw(){
for( var i =0; i<6; i++){
var idx = Math.floor(Math.random() * numbers.length)
chosenByMachine.push(numbers[idx]);
/*a very important line of code which prevents machine from drawing the same number again
*/
numbers.splice(idx,1);
/* console.log(numbers) */
/*this line of code allows to check if numbers are taken out*/
}
var btnToRemove = document.querySelector(".startDraw");
btnToRemove.classList.add("invisible");
/* why not remove it entirely? because it might then be accidentally created if for some reason you happen to try to click on board!!! and you may do that*/
return chosenByMachine;
}
//machineDraw();
function createButtonForMachineDraw(){
var startDraw = document.createElement("button");
startDraw.classList.add("startDraw");
section.appendChild(startDraw);
startDraw.textContent ="Release the balls";
startDraw.addEventListener("click", machineDraw);
startDraw.addEventListener("click", compareArrays);
}
function compareArrays(){
for( var i =0; i<balls.length; i++) {
balls[i].textContent = chosenByMachine[i];
(function() {
var j = i;
var f = function(){
balls[j].classList.remove("invisible");
balls[j].classList.add("ball-align");
}
setTimeout(f, 1000*(j+1));
})();
}
var common =[];
var arr1 = chosenByMachine;
var arr2 = drawnNums;
for(var i = 0; i<arr1.length; i++){
for(var j= 0; j<arr2.length; j++){
if(arr1[i]===arr2[j]){
common.push(arr1[i]);
}
}
}
/* console.log(arr1, arr2, common) */; /* you can monitor your arrays in console*/
function generateResult(){
// Deduction of coins once draw started
coins = coins - 1;
// End of comment
var resultsBoard = document.createElement("article");
section.appendChild(resultsBoard);
var paragraph = document.createElement("p");
resultsBoard.appendChild(paragraph);
resultsBoard.classList.add("resultsBoard");
resultsBoard.classList.add("invisible");
if(common.length === 0){
paragraph.textContent ="Oh no! You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 1){
paragraph.textContent ="You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 2){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 3) {
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 4){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return ststarsEarnedars;
} else if(common.length === 5){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
}
else if(common.length===6){
paragraph.textContent ="A true winner! You got " + common.length + " Stars!";
stars = stars + common.length;
return starsEarned;
}
// Returning of new coins
return coins;
// End of comment
}
setTimeout(function() {
makeComebackBtn();
document.querySelector(".resultsBoard").classList.remove("invisible"); //well, you cannot acces this outside the code
// Displaying of new scores
stars = starsEarned;
document.getElementById("coin-count").innerHTML = coins;
document.getElementById("star-count").innerHTML = stars;
// End of comment
}, 8000);
generateResult();
}
function makeComebackBtn(){
var comebackBtn = document.createElement("a");
comebackBtn.classList.add("comebackBtn");
section.appendChild(comebackBtn);
comebackBtn.textContent ="Go again";
if (coins === 0) {
comebackBtn.addEventListener("click", function () {
alert("You ran out of coins");
});
} else {
comebackBtn.addEventListener("click", function () {
const board_ = document.querySelector(".board");
board_.parentNode.removeChild(board_);
const startDraw_ = document.querySelector(".startDraw");
startDraw_.parentNode.removeChild(startDraw_);
for( let i=0; i<balls.length; i++) {
balls[i].classList.add("invisible");
balls[i].classList.remove("ball-align");
}
const resultsBoard_ = document.querySelector(".resultsBoard");
resultsBoard_.parentNode.removeChild(resultsBoard_);
createNumberBoard(49);
board = document.querySelector(".board");
boardEls = document.querySelectorAll(".boardEl");
drawNumbers();
const comebackBtn_ = document.querySelector(".comebackBtn");
comebackBtn_.parentNode.removeChild(comebackBtn_);
});
}
}
})
You need to save the values of stars and coins to localStorage using localStorage.setItem("stars", stars) or sessionStorage and get the values again at beginning of each turn.
Also initialize value of variable starsEarned = 0 and check condition of number of coins when reload the page. If run out of coins, alert player.
You can see following code I modified from your
// Declaration of scores and lives
var stars = Number(localStorage.getItem("stars")) || 0;
var coins = Number(localStorage.getItem("coins")) || 5;
// End of comment
// For redeclaration in innerHTML
var starsEarned = 0;
// End of comment
// For displaying current score
document.getElementById("star-count").innerHTML = stars;
document.getElementById("coin-count").innerHTML = coins;
// End of comment
document.addEventListener("DOMContentLoaded", function(e){
var body = document.querySelector("body");
var section = document.querySelector("section");
var articleLotto = document.querySelector(".lotto");
var articleBalls = document.querySelector(".balls");
var numbers = [];
var balls = document.getElementsByClassName("ball");
var drawnNums = [];
var chosenByMachine = [];
function createNumberBoard(number){
console.log("I work");
var board = document.createElement("div");
board.classList.add("board");
articleLotto.appendChild(board);
for( var i = 0; i<number; i ++){
var boardEl = document.createElement("button");
boardEl.classList.add("boardEl");
board.appendChild(boardEl);
}
var boardEls = document.getElementsByClassName("boardEl");
for( var i =0; i<boardEls.length; i++){
boardEls[i].setAttribute("data-number", i+1);
var dataNumber = boardEls[i].getAttribute("data-number");
var number = parseInt(dataNumber, 10);
numbers.push(number);
boardEls[i].textContent = number;
}
}
createNumberBoard(49);
var board = document.querySelector(".board");
var boardEls = document.querySelectorAll(".boardEl");
function drawNumbers(){
//boardEls.forEach(boardEl => boardEl.addEventListener("click", selectNums));
for (var i = 0; i<boardEls.length; i++){
boardEls[i].addEventListener("click", selectNums);
}
function selectNums(){
var number = parseInt(this.dataset.number, 10);
if(this.hasAttribute("data-number")){
drawnNums.push(number);
this.removeAttribute("data-number");
this.classList.add("crossedOut");
}
if(drawnNums.length=== 6){
//boardEls.forEach( boardEl => boardEl.removeAttribute("data-number"));
//boardEls.forEach(boardEl => boardEl.addEventListener("click", makeAlert));
for ( var i = 0; i<boardEls.length; i++){
boardEls[i].removeAttribute("data-number");
boardEls[i].addEventListener("click", makeAlert);
}
var startDraw = document.querySelector(".startDraw");
if(startDraw === null){ // you have to prevent creating the button if it is already there!
createButtonForMachineDraw();
} else {
return;
}
}
}
return drawnNums;
}
drawNumbers();
function makeAlert() {
var alertBox = document.createElement("div");
board.appendChild(alertBox);
alertBox.classList.add("alertBox");
alertBox.textContent = "You can only choose 6!";
setTimeout(function() {
alertBox.parentNode.removeChild(alertBox);
}, 1500);
}
function machineDraw(){
for( var i =0; i<6; i++){
var idx = Math.floor(Math.random() * numbers.length)
chosenByMachine.push(numbers[idx]);
/*a very important line of code which prevents machine from drawing the same number again
*/
numbers.splice(idx,1);
/* console.log(numbers) */
/*this line of code allows to check if numbers are taken out*/
}
var btnToRemove = document.querySelector(".startDraw");
btnToRemove.classList.add("invisible");
/* why not remove it entirely? because it might then be accidentally created if for some reason you happen to try to click on board!!! and you may do that*/
return chosenByMachine;
}
//machineDraw();
function createButtonForMachineDraw(){
var startDraw = document.createElement("button");
startDraw.classList.add("startDraw");
section.appendChild(startDraw);
startDraw.textContent ="Release the balls";
startDraw.addEventListener("click", machineDraw);
startDraw.addEventListener("click", compareArrays);
}
function compareArrays(){
for( var i =0; i<balls.length; i++) {
balls[i].textContent = chosenByMachine[i];
(function() {
var j = i;
var f = function(){
balls[j].classList.remove("invisible");
balls[j].classList.add("ball-align");
}
setTimeout(f, 1000*(j+1));
})();
}
var common =[];
var arr1 = chosenByMachine;
var arr2 = drawnNums;
for(var i = 0; i<arr1.length; i++){
for(var j= 0; j<arr2.length; j++){
if(arr1[i]===arr2[j]){
common.push(arr1[i]);
}
}
}
/* console.log(arr1, arr2, common) */; /* you can monitor your arrays in console*/
function generateResult(){
// Deduction of coins once draw started
coins = coins - 1;
// End of comment
var resultsBoard = document.createElement("article");
section.appendChild(resultsBoard);
var paragraph = document.createElement("p");
resultsBoard.appendChild(paragraph);
resultsBoard.classList.add("resultsBoard");
resultsBoard.classList.add("invisible");
if(common.length === 0){
paragraph.textContent ="Oh no! You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 1){
paragraph.textContent ="You got " + common.length + " Star!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 2){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 3) {
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
} else if(common.length === 4){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return ststarsEarnedars;
} else if(common.length === 5){
paragraph.textContent ="You got " + common.length + " Stars!";
starsEarned = stars + common.length;
return starsEarned;
}
else if(common.length===6){
paragraph.textContent ="A true winner! You got " + common.length + " Stars!";
stars = stars + common.length;
return starsEarned;
}
// Returning of new coins
return coins;
// End of comment
}
setTimeout(function() {
makeComebackBtn();
document.querySelector(".resultsBoard").classList.remove("invisible"); //well, you cannot acces this outside the code
// Displaying of new scores
stars = starsEarned;
document.getElementById("coin-count").innerHTML = coins;
document.getElementById("star-count").innerHTML = stars;
localStorage.setItem("stars", stars);
localStorage.setItem("coins", coins);
// End of comment
}, 8000);
generateResult();
}
function makeComebackBtn(){
var comebackBtn = document.createElement("a");
comebackBtn.classList.add("comebackBtn");
section.appendChild(comebackBtn);
comebackBtn.textContent ="Go again";
if (coins === 0) {
comebackBtn.setAttribute("onClick", "alert('You ran out of coins')");
} else {
comebackBtn.setAttribute("onClick", "window.location.reload();");
}
}
})

Snake Code - Make the face of the snake an image

I would like to make the face of this snake an image. Currently, it using a fill style with a color but I would like it to be an image. How can I do it with this code?
In addition, I want to find out how to add arrows so that it could work on a mobile phone. Thank you for anyone who can help or provide insight.
(function() {
/////////////////////////////////////////////////////////////
// Canvas & Context
var canvas;
var ctx;
// Snake
var snake;
var snake_dir;
var snake_next_dir;
var snake_speed;
// Food
var food = {
x: 0,
y: 0
};
// Score
var score;
// Wall
var wall;
// HTML Elements
var screen_snake;
var screen_menu;
var screen_setting;
var screen_gameover;
var button_newgame_menu;
var button_newgame_setting;
var button_newgame_gameover;
var button_setting_menu;
var button_setting_gameover;
var ele_score;
var speed_setting;
var wall_setting;
/////////////////////////////////////////////////////////////
var activeDot = function(x, y) {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(x * 10, y * 10, 10, 10);
}
/////////////////////////////////////////////////////////////
var changeDir = function(key) {
if (key == 38 && snake_dir != 2) {
snake_next_dir = 0;
} else {
if (key == 39 && snake_dir != 3) {
snake_next_dir = 1;
} else {
if (key == 40 && snake_dir != 0) {
snake_next_dir = 2;
} else {
if (key == 37 && snake_dir != 1) {
snake_next_dir = 3;
}
}
}
}
}
/////////////////////////////////////////////////////////////
var addFood = function() {
food.x = Math.floor(Math.random() * ((canvas.width / 10) - 1));
food.y = Math.floor(Math.random() * ((canvas.height / 10) - 1));
for (var i = 0; i < snake.length; i++) {
if (checkBlock(food.x, food.y, snake[i].x, snake[i].y)) {
addFood();
}
}
}
/////////////////////////////////////////////////////////////
var checkBlock = function(x, y, _x, _y) {
return (x == _x && y == _y) ? true : false;
}
/////////////////////////////////////////////////////////////
var altScore = function(score_val) {
ele_score.innerHTML = String(score_val);
}
/////////////////////////////////////////////////////////////
var mainLoop = function() {
var _x = snake[0].x;
var _y = snake[0].y;
snake_dir = snake_next_dir;
// 0 - Up, 1 - Right, 2 - Down, 3 - Left
switch (snake_dir) {
case 0:
_y--;
break;
case 1:
_x++;
break;
case 2:
_y++;
break;
case 3:
_x--;
break;
}
snake.pop();
snake.unshift({
x: _x,
y: _y
});
// --------------------
// Wall
if (wall == 1) {
// On
if (snake[0].x < 0 || snake[0].x == canvas.width / 10 || snake[0].y < 0 || snake[0].y == canvas.height / 10) {
showScreen(3);
return;
}
} else {
// Off
for (var i = 0, x = snake.length; i < x; i++) {
if (snake[i].x < 0) {
snake[i].x = snake[i].x + (canvas.width / 10);
}
if (snake[i].x == canvas.width / 10) {
snake[i].x = snake[i].x - (canvas.width / 10);
}
if (snake[i].y < 0) {
snake[i].y = snake[i].y + (canvas.height / 10);
}
if (snake[i].y == canvas.height / 10) {
snake[i].y = snake[i].y - (canvas.height / 10);
}
}
}
// --------------------
// Autophagy death
for (var i = 1; i < snake.length; i++) {
if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
showScreen(3);
return;
}
}
// --------------------
// Eat Food
if (checkBlock(snake[0].x, snake[0].y, food.x, food.y)) {
snake[snake.length] = {
x: snake[0].x,
y: snake[0].y
};
score += 1;
altScore(score);
addFood();
activeDot(food.x, food.y);
}
// --------------------
ctx.beginPath();
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// --------------------
for (var i = 0; i < snake.length; i++) {
activeDot(snake[i].x, snake[i].y);
}
// --------------------
activeDot(food.x, food.y);
// Debug
//document.getElementById("debug").innerHTML = snake_dir + " " + snake_next_dir + " " + snake[0].x + " " + snake[0].y;
setTimeout(mainLoop, snake_speed);
}
/////////////////////////////////////////////////////////////
var newGame = function() {
showScreen(0);
screen_snake.focus();
snake = [];
for (var i = 4; i >= 0; i--) {
snake.push({
x: i,
y: 15
});
}
snake_next_dir = 1;
score = 0;
altScore(score);
addFood();
canvas.onkeydown = function(evt) {
evt = evt || window.event;
changeDir(evt.keyCode);
}
mainLoop();
}
/////////////////////////////////////////////////////////////
// Change the snake speed...
// 150 = slow
// 100 = normal
// 50 = fast
var setSnakeSpeed = function(speed_value) {
snake_speed = speed_value;
}
/////////////////////////////////////////////////////////////
var setWall = function(wall_value) {
wall = wall_value;
if (wall == 0) {
screen_snake.style.borderColor = "#606060";
}
if (wall == 1) {
screen_snake.style.borderColor = "#FFFFFF";
}
}
/////////////////////////////////////////////////////////////
// 0 for the game
// 1 for the main menu
// 2 for the settings screen
// 3 for the game over screen
var showScreen = function(screen_opt) {
switch (screen_opt) {
case 0:
screen_snake.style.display = "block";
screen_menu.style.display = "none";
screen_setting.style.display = "none";
screen_gameover.style.display = "none";
break;
case 1:
screen_snake.style.display = "none";
screen_menu.style.display = "block";
screen_setting.style.display = "none";
screen_gameover.style.display = "none";
break;
case 2:
screen_snake.style.display = "none";
screen_menu.style.display = "none";
screen_setting.style.display = "block";
screen_gameover.style.display = "none";
break;
case 3:
screen_snake.style.display = "none";
screen_menu.style.display = "none";
screen_setting.style.display = "none";
screen_gameover.style.display = "block";
break;
}
}
/////////////////////////////////////////////////////////////
window.onload = function() {
canvas = document.getElementById("snake");
ctx = canvas.getContext("2d");
// Screens
screen_snake = document.getElementById("snake");
screen_menu = document.getElementById("menu");
screen_gameover = document.getElementById("gameover");
screen_setting = document.getElementById("setting");
// Buttons
button_newgame_menu = document.getElementById("newgame_menu");
button_newgame_setting = document.getElementById("newgame_setting");
button_newgame_gameover = document.getElementById("newgame_gameover");
button_setting_menu = document.getElementById("setting_menu");
button_setting_gameover = document.getElementById("setting_gameover");
// etc
ele_score = document.getElementById("score_value");
speed_setting = document.getElementsByName("speed");
wall_setting = document.getElementsByName("wall");
// --------------------
button_newgame_menu.onclick = function() {
newGame();
};
button_newgame_gameover.onclick = function() {
newGame();
};
button_newgame_setting.onclick = function() {
newGame();
};
button_setting_menu.onclick = function() {
showScreen(2);
};
button_setting_gameover.onclick = function() {
showScreen(2)
};
setSnakeSpeed(150);
setWall(1);
showScreen("menu");
// --------------------
// Settings
// speed
for (var i = 0; i < speed_setting.length; i++) {
speed_setting[i].addEventListener("click", function() {
for (var i = 0; i < speed_setting.length; i++) {
if (speed_setting[i].checked) {
setSnakeSpeed(speed_setting[i].value);
}
}
});
}
// wall
for (var i = 0; i < wall_setting.length; i++) {
wall_setting[i].addEventListener("click", function() {
for (var i = 0; i < wall_setting.length; i++) {
if (wall_setting[i].checked) {
setWall(wall_setting[i].value);
}
}
});
}
document.onkeydown = function(evt) {
if (screen_gameover.style.display == "block") {
evt = evt || window.event;
if (evt.keyCode == 32) {
newGame();
}
}
}
}
})();
::selection {
color: #FFFFFF;
background: transparent;
}
::-moz-selection {
color: #FFFFFF;
background: transparent;
}
* {
margin: 0;
padding: 0;
font-family: "VT323";
}
body {
background-color: #000000;
}
.wrap {
margin-left: auto;
margin-right: auto;
}
header {
width: 340px;
font-size: 0;
}
canvas {
display: none;
border-style: solid;
border-width: 10px;
border-color: #FFFFFF;
}
canvas:focus {
outline: none;
}
/* Top Styles */
h1 {
display: inline-block;
width: 100px;
font-size: 32px;
color: #FFFFFF;
}
.score {
display: inline-block;
width: 240px;
font-size: 20px;
color: #FFFFFF;
text-align: right;
}
.score_value {
font-size: inherit;
}
/* All screens style */
#gameover a,
#setting a,
#menu a {
display: block;
}
#gameover a,
#setting a:hover,
#menu a:hover {
cursor: pointer;
}
#gameover a:hover::before,
#setting a:hover::before,
#menu a:hover::before {
content: ">";
margin-right: 10px;
}
/* Menu Screen Style */
#menu {
display: block;
width: 340px;
padding-top: 95px;
padding-bottom: 95px;
font-size: 40px;
margin-left: auto;
margin-right: auto;
text-align: center;
color: #FFF;
}
#menu h2 {
-webkit-animation: logo-ani 1000ms linear infinite;
animation: logo-ani 1000ms linear infinite;
margin-bottom: 30px;
}
#menu a {
font-size: 30px;
}
#-webkit-keyframes logo-ani {
50% {
-webkit-transform: scale(1.3, 1.3);
}
100% {
-webkit-transform: scale(1.0, 1.0);
}
}
#keyframes logo-ani {
50% {
transform: scale(1.3, 1.3);
}
100% {
transform: scale(1.0, 1.0);
}
}
/* Game Over Screen Style */
#gameover {
display: none;
width: 340px;
padding-top: 95px;
padding-bottom: 95px;
margin-left: auto;
margin-right: auto;
text-align: center;
font-size: 30px;
color: #FFF;
}
#gameover p {
margin-top: 25px;
font-size: 20px;
}
/* Settings Screen Style */
#setting {
display: none;
width: 340px;
margin-left: auto;
margin-right: auto;
padding-top: 85px;
padding-bottom: 85px;
font-size: 30px;
color: #FFF;
text-align: center;
}
#setting h2 {
margin-bottom: 15px;
}
#setting p {
margin-top: 10px;
}
#setting input {
display: none;
}
#setting label {
cursor: pointer;
}
#setting input:checked+label {
background-color: #FFF;
color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link href="https://fonts.googleapis.com/css2?family=VT323&display=swap" rel="stylesheet">
<header class="wrap">
<h1>Snake</h1>
<p class="score">Score: <span id="score_value">0</span></p>
</header>
<canvas class="wrap" id="snake" width="320" height="320" tabindex="1"></canvas>
<!-- Game Over Screen -->
<div id="gameover">
<h2>Game Over</h2>
<p>press <span style="background-color: #FFFFFF; color: #000000">space</span> to begin a</p>
<a id="newgame_gameover">new game</a>
<a id="setting_gameover">settings</a>
</div>
<!-- Setting screen -->
<div id="setting">
<h2>Settings</h2>
<a id="newgame_setting">new game</a>
<p>Speed:
<input id="speed1" type="radio" name="speed" value="120" checked/>
<label for="speed1">Slow</label>
<input id="speed2" type="radio" name="speed" value="75" />
<label for="speed2">Normal</label>
<input id="speed3" type="radio" name="speed" value="35" />
<label for="speed3">Fast</label>
</p>
<p>Wall:
<input id="wallon" type="radio" name="wall" value="1" checked/>
<label for="wallon">On</label>
<input id="walloff" type="radio" name="wall" value="0" />
<label for="walloff">Off</label>
</p>
</div>
<!-- Main Menu Screen -->
<div id="menu">
<h2>Snake</h2>
<a id="newgame_menu">new game</a>
<a id="setting_menu">settings</a>
</div>
Convert your image to a base64 string, then for the first dot/head use the image instead:
var img = new Image(); // Create new img element
img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAMAAAC67D+PAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAA21BMVEXoTTvqTTzpUD7nTjzmTTvrUkDpTjzmSznUPSrVPCrnTDrSOSfTOizlTDrvoJnoqJ/pVkTmU0P5urH1p53mSTjjPiv7nZF0f4NZaGvpn5b9s6qDl5iira/+nI/jPirkPyz7lop+iYtleHzsnpT7raOTpqqqtbf4lovnSjf0lorylonpSDbnTDj5oZf2mIzlSDXkOyjIY1vrd2rrWEbZZ1zYQDLsTTroTz/lRjPalY7+///////j19fVSz7tTjvmTjntRjPialzZhH3sVkXsSzniRTTYQTDmSTbmTT3qb45jAAAAAWJLR0Q7OQ70bAAAAAd0SU1FB+QEDw4AEYzMSFoAAABvSURBVAjXY2BgZGJiZmFlZWNgYGDn4GTn4ubhBTJZ+PgFBIWERdgYRMXEJSSlpGVk5RjkFRSVlFVU1dTlGRg0NLW0dXT19JkZGNgMDI2MTUzNgNrMLSytrG1s7eyBbGYHRydnFwYwYHN1c/dgYAAAtKsKjnGo4BwAAAAldEVYdGRhdGU6Y3JlYXRlADIwMjAtMDQtMTVUMTQ6MDA6MTctMDQ6MDAVi7z/AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDIwLTA0LTE1VDE0OjAwOjE3LTA0OjAwZNYEQwAAAABJRU5ErkJggg==";
for (var i = 0; i < snake.length; i++) {
if (!i) {
ctx.drawImage(img, snake[i].x * 10, snake[i].y * 10);
} else {
activeDot(snake[i].x, snake[i].y);
}
}

Add scores grid game JavaScript

I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)

JS Calculator variable prevKey doesn't register values properly

Still working on the JS Calculator for FreeCodeCamp. I've been working on this problem for the past few days. The problem is repeating operators. For example, if I press "5" then "+", but changed my mind and pressed "-". The history area should display "5-" instead of "5+".
After carefully studying what is wrong, I figured out how it's happening. If you check out my code at this Codepen, you can see how the variable prevKey isn't gathering the numbers and operators in right order...
If I press in this order "5", "+", "-". The prevKey should be a number at first then an operator, and then an operator, or something like that. However, since I listed the variable prevKey = null;, it's been messing up the order. The prevkey actually goes like that: "5", "+", "null", "-".
How do I fix it?
Here's my code in question. All the actions are happening in function addOperator(keyitem).
subMatharray.push(mainMath);
prevKey = mainMath;
console.log("addOpKeyItem: " + keyitem);
console.log("addOpPrevKey: " + prevKey);
if(["/", "*", "+", "-"].indexOf(prevKey) == -1) {
subMatharray.push(keyitem);
prevKey = keyitem;
console.log("addOpArraySubArrayElse: " + subMatharray);
console.log("addOpArrayPrevKeyElse: " + prevKey);
console.log("addOpArrayoppArrayElse: " + oppArray);
console.log("addOpArrayKeyItemElse: " + keyitem);
} else if (["/", "*", "+", "-"].indexOf(keyitem) > -1 && ["/", "*", "+", "-"].indexOf(prevKey) > -1 || prevKey == null) {
subMatharray.push("test");
console.log("addOpArraySubArray: " + subMatharray);
console.log("addOpArrayPrevKey: " + prevKey);
console.log("addOpArrayPrevKeyItem: " + keyitem);
console.log("addOpArrayoppArray: " + oppArray);
}
And here's my full code here:
$(document).ready(function() {
var mainMath = null;
var subMath = "0";
var finalset = "";
var subMatharray = [];
var oppArray = [];
var equalPressed = false;
var prevKey = null;
var regexChecked = /[0-9]/g;
var originalKey = "";
update();
$("button").click(function(){
calculate($(this).attr("value"));
});
function calculate(keyitem) {
originalKey = keyitem;
console.log("buttonpress: " + keyitem);
switch(keyitem) {
case "clear":
clearScreen();
break;
case "%":
percentageScreen();
break;
case "/":
case "*":
case "+":
case "-":
addOperator(keyitem);
break;
case "plusminus":
plusminusScreen();
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
addNumber(keyitem);
break;
case ".":
addDecimal(keyitem);
break;
case "=":
solveEqual(keyitem);
break;
}
update();
};
function clearScreen() {
mainMath = null;
subMath = "0";
prevKey = null;
subMatharray = [];
oppArray = [];
if(mainMath == null){
$(".entry").css("font-size", "4em");
}
console.log("clearMain: " + mainMath);
console.log("clearSub: " + subMath);
};
function plusminusScreen() {
mainMath = -1 * mainMath;
finalset = mainMath;
console.log("plusminusMain: " + mainMath);
console.log("plusminusFinal: " + finalset);
};
function addNumber(keyitem) {
if (mainMath === null){
mainMath = "0";
}
if (mainMath == "0"){
mainMath = keyitem/*mainMath.replace("0", keyitem);*/
finalset = mainMath;
return;
console.log("addedMainZero: " + mainMath);
console.log("addedFinalZero: " + finalset);
}
if (equalPressed == true){
mainMath = keyitem;
subMath = "0";
subMatharray = [];
equalPressed = false;
console.log("addNumberEqualmain: " + mainMath);
}
mainMath+=keyitem;
finalset = mainMath;
console.log("addedMain: " + mainMath);
console.log("addedFinalset: " + finalset);
console.log("addedarray: " + subMatharray);
if(mainMath.length > 8){
$(".entry").css("font-size", "1.5em");
}
};
function addOperator(keyitem){
if(mainMath === null && subMatharray.length === 0) {
return;
}
if (equalPressed == true){
subMatharray = [];
oppArray = [];
equalPressed = false;
console.log("addOpEqualarray: " + subMatharray);
}
oppArray.push(keyitem);
console.log("addOpArray: " + oppArray);
var opkeyitem = "";
subMatharray.push(mainMath);
prevKey = mainMath;
console.log("addOpKeyItem: " + keyitem);
console.log("addOpPrevKey: " + prevKey);
/*prevKey won't get numbers, only operators!!!!*/
if(["/", "*", "+", "-"].indexOf(prevKey) == -1) {
subMatharray.push(keyitem);
prevKey = keyitem;
console.log("addOpArraySubArrayElse: " + subMatharray);
console.log("addOpArrayPrevKeyElse: " + prevKey);
console.log("addOpArrayoppArrayElse: " + oppArray);
console.log("addOpArrayKeyItemElse: " + keyitem);
} else if (["/", "*", "+", "-"].indexOf(keyitem) > -1 && ["/", "*", "+", "-"].indexOf(prevKey) > -1 || prevKey == null) {
oppArray.shift();
opkeyitem = oppArray.toString();
/*subMatharray.splice(-2, 2);
/*subMatharray.pop();*/
/*subMatharray.push(opkeyitem);*/
subMatharray.push("test");
/*oppArray = [];*/
/*prevKey = null;*/
console.log("addOpArraySubArray: " + subMatharray);
console.log("addOpArrayPrevKey: " + prevKey);
console.log("addOpArrayPrevKeyItem: " + keyitem);
console.log("addOpArrayoppArray: " + oppArray);
} /*else if(prevKey == null) {
subMatharray.push(keyitem);
prevKey = keyitem;
console.log("addOpArraySubArrayElse: " + subMatharray);
console.log("addOpArrayPrevKeyElse: " + prevKey);
console.log("addOpArrayoppArrayElse: " + oppArray);
console.log("addOpArrayKeyItemElse: " + keyitem);
}*/
subMath = subMatharray.join("");
mainMath = null;
/*prevKey = null;*/
console.log("addOpSub: " + subMath);
console.log("addOpMain: " + mainMath);
console.log("addOpMainarray: " + subMatharray);
console.log("equaltrueTest: " + equalPressed);
};
function addDecimal(keyitem){
if (mainMath === null){
mainMath = "0";
}
if (mainMath.indexOf(keyitem) === -1){
if(mainMath == "0") {
mainMath = "0" + keyitem;
return;
}
} else {
return;
}
addNumber(keyitem);
};
function solveEqual(keyitem) {
subMatharray.push(finalset);
subMath = subMatharray.join("");
mainMath = eval(subMath);
console.log("solveEqualresult: " + mainMath);
console.log("solveEqualhistory: " + subMath);
console.log("solveEqualarray: " + subMatharray);
var finalresult = mainMath.toString();
if(finalresult.length > 8){
$(".entry").css("font-size", "1.5em");
}
equalPressed = true;
};
function update(){
$("#answer").html(mainMath === null ? "0" : mainMath);
$("#history").html(subMath);
};
});
#import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
h1, h2, h3, p {
font-family: 'Roboto', sans-serif;
}
html, body{
height:100%;
margin: 0;
background-color: #ffffff;
}
.wrapper {
width: 100%;
height: 100%;
position: relative;
display:flex;
flex-direction:column;
justify-content:center;
align-items:center;
background-repeat: no-repeat;
background-size: cover;
background-position: center center;
padding: 160px 0;
}
.calculatorbox {
width: 300px;
margin: 0 auto;
border: 1px solid #000000;
}
.calheader {
text-align: center;
}
.calwindow {
background: #000000;
position: relative;
display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: column; /* Safari */
flex-direction: column;
-webkit-justify-content: flex-end;
justify-content: flex-end;
-webkit-align-items: flex-end;
align-items: flex-end;
padding: 10px 0;
box-sizing: border-box;
}
.entry {
font-size: 4em;
display: block;
line-height: 1em;
}
.entryhistory {
font-size: 1em;
letter-spacing: 2px;
padding-right: 5px;
}
.entry p, .entryhistory p {
margin: 0;
color: #ffffff;
}
sup {
top: -0.5em;
}
sub {
bottom: -0em;
}
.row {
clear: both;
width: 100%;
display: flex;
}
button {
display: inline-block;
border: none;
padding: 0;
outline: none;
cursor: pointer;
}
.key {
width: 75px;
height: 70px;
font-size: 22px;
border-top: 1px solid rgba(0, 0, 0, 0.3);
border-right: 1px solid rgba(0, 0, 0, 0.3);
box-sizing: border-box;
}
.key.btnspan {
width: 150px;
}
.key.topcolor {
background: #d9d9d9;
}
.key.orange {
background: #ff8c00;
color: #ffffff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="calheader">
<h2>Simple Calculator</h2>
</div>
<div class="calculatorbox">
<div class="calwindow">
<!-- ENTRY BOX -->
<div class="entry">
<p id="answer"></p>
</div>
<div class="entryhistory">
<p id="history"></p>
</div>
</div>
<!-- BUTTONS -->
<div class="calbuttons">
<div class="row">
<button class="key topcolor" value="clear">C</button>
<button class="key topcolor" value="plusminus"><sup>+</sup>/<sub>−</sub></button>
<button class="key topcolor" value="%">%</button>
<button class="key orange" value="/">÷</button>
</div>
<div class="row">
<button class="key" value="7">7</button>
<button class="key" value="8">8</button>
<button class="key" value="9">9</button>
<button class="key orange" value="*">×</button>
</div>
<div class="row">
<button class="key" value="4">4</button>
<button class="key" value="5">5</button>
<button class="key" value="6">6</button>
<button class="key orange" value="-">−</button>
</div>
<div class="row">
<button class="key" value="1">1</button>
<button class="key" value="2">2</button>
<button class="key" value="3">3</button>
<button class="key orange" value="+">+</button>
</div>
<div class="row">
<button class="key btnspan" value="0">0</button>
<button class="key" value=".">.</button>
<button class="key orange" value="=">=</button>
</div>
</div>
</div>
</div>
Your code is pretty hard to follow. Eric Lippert has a great article to help you get started on debugging small programs. I think the answer will likely be in addOperand: before pushing the latest operand on your subMathArray, check if there already is an operand, and remove it.
function lastElement(array){
return array[array.length - 1];
}
function isOperator(char){
return '/*+-'.indexOf(char) >= 0;
}
function addOperator(keyitem){
if(mainMath === null && subMatharray.length === 0) {
return;
}
if (equalPressed == true){
subMatharray = [];
oppArray = [];
equalPressed = false;
console.log("addOpEqualarray: " + subMatharray);
}
oppArray.push(keyitem);
console.log("addOpArray: " + oppArray);
var opkeyitem = "";
const lastSubMath = lastElement(subMatharray);
if(isOperator(lastSubMath)){
subMatharray.pop();
}
subMatharray.push(mainMath);
prevKey = mainMath;
console.log("addOpKeyItem: " + keyitem);
console.log("addOpPrevKey: " + prevKey);
//etc
Since I was having a hard time following your code, I decided to refactor it. I used eslint to automatically detect all the warnings that could easily be deleted. There was a lot. I then renamed your variables so they matched the UI elements to make it clearer. After I did this, it became clear that you don't need any array, and you don't need to remember previous key presses. All you need is 2 strings.
$(document).ready(function() {
let entry = '0'; // mainMath
let history = null; // subMath
update();
$('button').click(function() {
calculate($(this).attr('value'));
});
function calculate(keyitem) {
switch (keyitem) {
case 'clear':
clearScreen();
break;
case '/':
case '*':
case '+':
case '-':
addOperator(keyitem);
break;
case 'plusminus':
plusminusScreen();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
addNumber(keyitem);
break;
case '.':
addDecimal();
break;
case '=':
solveEqual();
break;
}
update();
};
function clearScreen() {
entry = '0';
history = null;
};
function plusminusScreen() {
entry = -1 * entry;
};
function addNumber(keyitem) {
if (entry == '0') {
entry = keyitem;
history = keyitem;
return;
}
if (isOperator(entry)) {
entry = keyitem;
history += keyitem;
return;
}
entry += keyitem;
history += keyitem;
};
function isOperator(char) {
return '/*+-'.indexOf(char) >= 0;
}
function addOperator(keyitem) {
if (history === null) {
return;
}
if (isOperator(entry)) {
// This part solves your repeating operator problem
// If the current entry is an operator, replace the last
// character in history with the new operator.
history = history.substring(0, history.length - 1) + keyitem;
entry = keyitem;
return;
}
history += keyitem;
entry = keyitem;
};
function addDecimal() {
if (entry.indexOf('.') >= 0) {
return;
}
entry += '.';
if (history === null) {
history = '0';
}
history += '.';
};
function solveEqual() {
entry = eval(history);
history = entry;
};
function update() {
$('#answer').html(entry);
$('#history').html(history);
};
});

Why does the function return not defined?

My code returns "not defined" when I press on any of the buttons or type in a function in the console (for example if I press the Roll! button or type Roll() in the console). I don't think the HTML has anything to do with it but it might so I put it in. Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
.dropbtn {
color: black;
padding: 4px;
font-size: 16px;
border: none;
cursor: pointer;
min-width: 160px;
}
.dropbtn:hover, .dropbtn:focus {
background-color: gray;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #ffffff;
min-width: 160px;
overflow: auto;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>
<img id="Dice1" src="White.png"></img>
<img id="Dice2" src="White.png"></img>
<img id="Dice3" src="White.png"></img>
<p></p>
<div class="dropdown">
<button onclick="Dropdown()" class="dropbtn">Number of Dice</button>
<div id="myDropdown" class="dropdown-content">
<button class="dropbtn" onclick="DiceNum(1)">1 Dice</button>
<button class="dropbtn" onclick="DiceNum(2)">2 Die</button>
<button class="dropbtn" onclick="DiceNum(3)">3 Die</button>
</div>
</div>
<p></p>
<button class="dropbtn" onclick="Roll()">Roll!</button>
<script>
var Dice = 1;
function Dropdown() {
document.getElementById("myDropdown").classList.toggle("show");
}
var openDropdown
window.onclick = function(event) {
if (!event.target.matches(".dropbtn")) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i += 1) {
openDropdown = dropdowns[i];
if (openDropdown.classList.contains("show")) {
openDropdown.classList.remove("show");
}
}
}
}
var randNum1 = Math.floor((Math.random() * 6) + 1);
var randNum2 = Math.floor((Math.random() * 6) + 1);
var randNum3 = Math.floor((Math.random() * 6) + 1);
function Roll() {
if(Dice===1) {
randNum1 = Math.floor((Math.random() * 6) + 1);
document.getElementById("Dice1").src = "Dice"+randNum1+".png";
document.getElementById("Dice2").src = "White.png";
document.getElementById("Dice3").src = "White.png";
} else if(Dice===2) {
randNum1 = Math.floor((Math.random() * 6) + 1);
randNum2 = Math.floor((Math.random() * 6) + 1);
document.getElementById("Dice1").src = "Dice"+randNum1+".png";
document.getElementById("Dice2").src = "Dice"+randNum2+".png";
document.getElementById("Dice3").src = "White.png";
} else if(Dice===3) {
randNum1 = Math.floor((Math.random() * 6) + 1);
randNum2 = Math.floor((Math.random() * 6) + 1);
randNum3 = Math.floor((Math.random() * 6) + 1);
document.getElementById("Dice1").src = "Dice"+randNum1+".png";
document.getElementById("Dice2").src = "Dice"+randNum2+".png";
document.getElementById("Dice3").src = "Dice"+randNum3+".png";
}
}
var DiceNum = function (x) {
if(x===1) {
return var Dice = 1;
} else if(x===2) {
return var Dice = 2;
} else if(x===3) {
return var Dice = 3;
}
}
</script>
</body>
</html>
You can't return an variable assignment. Instead do it this way
var DiceNum = function(x) {
if (x === 1) {
Dice = 1;
} else if (x === 2) {
Dice = 2;
} else if (x === 3) {
Dice = 3;
}
}
There is an error in your DiceNum function:
var DiceNum = function (x) {
if(x===1) {
return var Dice = 1;
} else if(x===2) {
return var Dice = 2;
} else if(x===3) {
return var Dice = 3;
}
}
You return var Dice = 1 is not correct syntax in Javascript, try changing it to return Dice = 1(change it in the other places as well)
I hope this helps!
You can not declare the variable so many times your function should look like this:
var DiceNum = function (x) {
if(x===1) {
return Dice = 1;
} else if(x===2) {
return Dice = 2;
} else if(x===3) {
return Dice = 3;
}
}
DiceNum() is returning 'var Dice = 1' try commenting and see if it runs also,
try defining the function as var Roll = function(){.... similar to DiceNum

Categories

Resources