I am making a simple game using javascript. The game essentially is matching the correct colour to the item of food. For example, there is 5 items of food on a picnic blanket and 5 colours written out. The player has to match the correct colour to the food. I feel i have all the correct code, but when i started styling it, everything disappeared and now i can't get it working again. SO i dont know where i have gone missing!
i have a jfiddle with all the code, but the images don't appear (i dont know how to add them on jfiddle) any help is much appreciated!
http://jsfiddle.net/febidrench/395hvqqu/ this is the jfiddle
this is the javascript
var colours = ["Red", "Pink", "Purple", "Yellow", "Orange", "Green"];
//this function shuffles our country array
function shuffleArray(arr) {
var currentIndex = arr.length, temporaryValue, randomIndex ;
//while the array hasn't ended
while (0 !== currentIndex) {
//find a random element
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = arr[currentIndex];
arr[currentIndex] = arr[randomIndex];
arr[randomIndex] = temporaryValue;
}
//returns the shuffled array
return arr;
}
//variables for the fuctionality of the game
var selectedFood;
var score;
var count;
var wordClicked;
var winningScore;
//the game init fuction will contain the difficulty level within it that will be passed when the function is called
function gameInit(difficulty) {
// calculates the number of correct
winningScore = Math.round(difficulty/3*2);
// the score variable
score = 0;
//count = the difficulty
count = difficulty;
// is the map clicked yes/no
wordClicked = false;
//gamecountries and gamemaps
var gameFoods = [];
var gameColours = [];
// shuffles the existing countries array
gameFoods = shuffleArray(colours)
//cuts the number of countries to the difficulty level
gameFoods = gameFoods.slice(0, difficulty);
//loops through the countries and displays the attached flags
for (i = 0; i<gameFoods.length; i++ )
{
document.getElementById('gameFoods').innerHTML += "<div class='picnicFoods' id='" + gameFoods[i] + "' onclick='foodClick(this.id)'><img src='food/" + gameFoods[i] + ".gif'></div>" ;
}
//reshuffles the countries
gameColours = shuffleArray(gameCountries)
//loops through the countries and displays the attached maps
for (j = 0; j<gameColours.length; j++ )
{
document.getElementById('gameColour').innerHTML += "<div class='picnicColours' id='map-" + gameColours[j] + "' onclick='colourClick(this.id)'><img src='colours/" + gameColours[j] + ".gif'></div>" ;
}
}
//when a flag is clicked
function foodClick(foodClickedId)
{
//set the mapclicked function is true to stop the function being activated again
colourClicked = true;
//sets the selectedFlag to the id of the clicked flag
selectedFood = foodClickedId;
// removes the flag after 5 seconds after the click
setTimeout(function(){
document.getElementById(foodClickedId).style.display = "none";
}, 5000);
}
//when a map is clicked
function colourClick(colourClickId)
{
//if a flag has been clicked
if (colourClicked == true){
// if there remains elements to match
if (count > 0){
//does the map and flag clicked match
if( "map-" + selectedFood == colourClickId)
{
//add one to the score
score = score + 1;
//remove 1 from the count
count = count - 1;
//show the popup and score
document.getElementById("popupBox").innerHTML =
"<div>Correct</div><div>Your Score is : " + score
+ "</div>";
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//if the game isn't over close the popup and let the player continue, this is tracked by the count
if (count != 0)
{
setTimeout(function(){
//hide the related map to the selected flag
document.getElementById("map-" + selectedFood).style.display = "none";
//allow the users to select the next flag in the game.
colourClicked = false;
document.getElementById("gamePopup").style.display = "none";
document.getElementById("popupBox").style.display = "none";
}, 5000);
}
else{
//if the game is over call the game over function
gameOver();
}
}
else {
//if the answer doesn't match do not increase score but still reduce count
score = score ;
count = count - 1;
//show that the player got it wrong and show their score
document.getElementById("popupBox").innerHTML =
"<div>Incorrect</div><div>Your Score is : " + score
+ "</div>";
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//if the game isn't over close the popup and let the player continue, this is tracked by the count
if (count != 0)
{
setTimeout(function(){
//remove the correct map so the user cannot select it in further questions but leave the incorrect one
document.getElementById("map-" + selectedFood).style.display = "none";
//allow the user to continue playing the game
colourClicked = false;
document.getElementById("gamePopup").style.display = "none";
document.getElementById("popupBox").style.display = "none";
}, 5000);
}
else{
//else show the game is over
gameOver();
}
}
}
}
}
//if the game has ended
function gameOver (){
//store the win or lose message
var gameMessage;
//if the score is less than the winning score the player loses
if (score < winningScore){
gameMessage = "You Lose"
}
//otherwise they win
else {gameMessage = "You Win"}
//show the game over popup with the score
document.getElementById("popupBox").innerHTML =
"<div>Game Over</div><div>" + gameMessage +
"</div><div>Your Score is : " + score
+ "</div>";
document.getElementById("gamePopup").style.display = "block";
document.getElementById("gamePopup").style.height = scnHei*2;
document.getElementById("popupBox").style.display = "block";
document.getElementById("popupBox").style.top = scnHei+150;
//after 5 seconds redirect the user to the level select menu
setTimeout(function(){
window.location = "level.html";
}, 5000);
}
Related
I am making a simulation of a stock market i want to make it so when the market increases the numbers are green and lowering red. For some reason the color only stays green.
I have a list of bools to see if the market is climbing or not.
this is the java code:
var climbingIDK = new Array(true, true, true, true, true);
function update_stonks() {
var stockValues = document.getElementsByClassName("value");
for (let i = 0; i < stockValues.length; i++) {
var incrementer = Math.round(Math.random()*11) /100;
if (incrementer === 11){
if(climbingIDK[i]){
climbingIDK[i] = false;
}
else{
climbingIDK[i] = true;
}
}
else{
var currentValue = parseInt(stockValues[i].innerHTML);
if(climbingIDK[i]){
stockValues[i].style.color = "#00ff00";
stockValues[i].innerHTML = currentValue + incrementer;
}
else{
if(currentValue - incrementer < 1){
stockValues[i].innerHTML = currentValue + incrementer;
}
else{
stockValues[i].style.color = "#ff0000";
stockValues[i].innerHTML = currentValue - incrementer;
}
}
}
}
setTimeout(update_stonks, 2000);
}
update_stonks();
this is my html:
Scenario :
Working on an e-commerce website.
I have put together a function which :
updates the total number of
items in the basket icon, and
also adjusts it when the user increases
or decreases the qty amount for an item in the actual basket page.
I am using local storage to fetch and update the information.
This particular basket page opens up in a new window. The basket icon is shown in pretty much all other pages of the website.
Problem :
Even if the user has another page open in the background, I want that page to also refresh to reflect the new qty amount displayed in the basket icon, the second they adjusts the qty amount from the basket page.
When the user closes the basket page and wants to continue
shopping, the original page - prior to opening the basket page - has
the updated number of items in the basket icon.
There are three ways a user can adjust the number of items in the basket. Each product has an increase / decrease button, and also an input field where the user can enter a number manually and the basket qty icon will reflect the new change.
Following function will change the qty of the item when user clicks either increase or decrease symbol
document.body.addEventListener("click", function(e) {
var reg = /\w{7}\d+/g;
if (e.target.classList[0] === "increaseQty") {
var getItem = getLocalStorageData("basketData");
getItem.basketQty++;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.previousSibling.value++;
var currentProduct = e.target.previousSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]++;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.previousSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else if (e.target.classList[0] === "decreaseQty") {
if (e.target.nextSibling.value > 0)
var getItem = getLocalStorageData("basketData");
getItem.basketQty--;
document.getElementById("item-count").innerHTML = getItem.basketQty;
e.target.nextSibling.value--;
var currentProduct = e.target.nextSibling.id;
currentProduct = currentProduct.match(reg);
currentProduct = currentProduct.toString();
getItem[currentProduct]--;
updateLocalStorage(getItem);
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][currentProduct]) {
var currentPrice = e.target.nextSibling.value * productCats[i][currentProduct].price;
var currentLi = e.target.parentNode;
currentLi.parentNode.lastChild.innerHTML = "£" + currentPrice;
getTotalCost();
}
}
} else {
return;
}
})
$("#basket-content").on("change", 'input[name="nameQty"]', function() {
var getItem = getLocalStorageData("basketData");
var regNum = /\d+/;
var currentQty = this.id;
var currentVal = this.value;
var reg = /\w{7}\d+/g;
var product = currentQty.match(reg);
product = product.toString();
if (!regNum.test(currentVal) || currentVal < 0) {
alert("Please enter a valid number");
document.getElementById(currentQty).value = getItem[product];
return;
} else if (currentVal > getItem[product]) {
var addQty = currentVal - getItem[product];
getItem.basketQty += addQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
} else if (currentVal < getItem[product]) {
var minusQty = getItem[product] - currentVal;
getItem.basketQty -= minusQty;
document.getElementById("item-count").innerHTML = getItem.basketQty;
getItem[product] = currentVal;
}
for (var i = 0; i < productCats.length; i++) {
if (productCats[i][product]) {
var currentPrice = currentVal * productCats[i][product].price;
document.getElementById(currentQty).parentNode.nextSibling.innerText = "£" + currentPrice.toFixed(2);
getTotalCost();
}
}
updateLocalStorage(getItem);
});
Super new to javascript. I'm trying to make a psychic guessing game. Everything here works except the onkeyup function. When I open the console log and type letters, it tells me that the userGuess variable is undefined. How do I defined the userGuess variable to match the onkeyup function?
Thanks:
//Available choices
var letterChoices = ['a', 'b', 'c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
//score
var wins = 0;
var losses = 0;
var guesses = 9;
var guessesLeft = 9;
var guessedLetters = [];
var letterToGuess = null;
//computer randomly chooses a letter
var computerGuess = letterChoices [Math.floor(Math.random()*letterChoices.length)];
//guesses left function
var updateGuessesLeft = function() {
document.querySelector('#guessLeft').innerHTML = "Guesses Left: " + guessesLeft;
};
//letter to guess function
var updateletterToGuess = function(){
this.letterToGuess = this.letterChoices[Math.floor(Math.random() * this.letterChoices.length)];
};
var updateGuessesSoFar = function(){
document.querySelector('#let').innerHTML = "Your guesses so far: " + guessedLetters.join(', ');
};
//reset
var reset = function(){
totalGuesses = 9;
guessesLeft = 9;
guessedLetters = [];
updateletterToGuess();
updateGuessesSoFar();
updateGuessesLeft();
};
updateGuessesLeft();
updateletterToGuess();
//user input key
document.onkeyup = function(event) {
guessesLeft--;
var userGuess;
console.log(userGuess)
guessedLetters.push(userGuess);
updateGuessesLeft();
updateGuessesSoFar();
if (guessesLeft > 0){
if (userGuess === letterToGuess){
wins++;
document.querySelector('#wins').innerHTML = 'Wins: ' + wins;
alert("How did you know!?!");
reset();
}
} else if (guessesLeft == 0){
losses++;
document.querySelector('#losses').innerHTML = 'Losses: ' + losses;
alert("Sorry, you're not a psychic!");
reset();
}
}
The variable userGuess is undefined because it is just declared. There is no assignment operation happening to this variable. I looked at the working sample, modified it in the browser, and it seems to be working as expected. The only change I did was to assign userGuess to the key pressed, as follows
var userGuess = event.key;
Here is the output I got by playing around a bit with your code
Since you have a list of characters that you want to allow, you could add the following code at the beginning, to make sure anything other than the allowed characters are not considered
if (letterChoices.indexOf(userGuess) === -1) return;
I am very new to Javascript, and have a question about one of my functions(checkOrBet). I am trying to make a Texas Hold'em poker game, and the part that doesn't seem to be working is where I test for a regular pair. It doesn't seem to recognize that a pair has been made, when the cards are dealt to the deck.
function game() {
function Playert(name, chips) {
this.name = name;
this.chips = chips;
this.firstCard = [];
this.secondCard = [];
this.blind = {};
// this.turnpos = 0; //1 for current turn
//will be computer's response when prompted during the flop
this.checkOrBet = function checkOrBet() {
var response;
//Ace High
if (this.firstCard.rank == "A") {
response = "call";
console.log("Ace High!");
} else if (this.secondCard.rank == "A") {
response = "call";
console.log("Ace High!");
}
//Tests for a pocket pair
if (this.firstCard.rank == this.secondCard.rank) {
response = "call";
console.log("Pocket pairs!");
}
//Test for a regular pair
if (this.firstCard.rank == communityCards.cards[0].rank || communityCards.cards[1].rank || communityCards.cards[2].rank) {
response = "call";
console.log("pairs");
} else if (this.secondCard.rank == communityCards.cards[
0]) {
response = "call";
console.log("pairs");
}
}
}
function Pot(chipsp) {
this.chipsp = 0;
}
//clears text every time start button is pressed
function clearBox() {
document.getElementById("computer").innerHTML = "";
document.getElementById("flop").innerHTML = "";
document.getElementById("hand1").innerHTML = "";
}
clearBox();
//players start with chips, low blind, big blind.
var computer = new Playert("Computer", 200);
var player = new Playert("Player1", 200);
//Need a deck to deal the cards for the players.
var deck = new Stack();
//player's hand
var phand = new Stack();
//computer's hand
var chand = new Stack();
//game cards
var gamehand = new Stack();
//make pot
var pot1 = new Pot();
//community cards variable
var communityCards = new Stack();
deck.makeDeck(1);
deck.shuffle(1);
//deal 2 cards to player hand
if (phand.cardCount < 2) {
alert("Not enough cards in deck");
} else {
for (i = 0; i < 2; i++) {
phand.addCard(deck.deal());
}
}
//grab player div by the ID
playerhand = document.getElementById("hand1");
//create p element to show cards in player div
var pdoc = document.createElement("p");
//create text node to append to p element
var ptext = document.createTextNode(phand.cards);
//append text node to p element
pdoc.appendChild(ptext);
//append p element with cards to the hand1 div
playerhand.appendChild(pdoc);
//deal cards to computer's hand
if (chand.cardCount < 2) {
alert("Not enough cards in deck");
} else {
for (i = 0; i < 2; i++) {
chand.addCard(deck.deal());
}
}
//tie computer's hand to firstCard/secondCard
computer.firstCard = chand.cards[0];
computer.secondCard = chand.cards[1];
console.log(computer.firstCard.rank);
console.log(computer.secondCard.rank);
//grab computer div by id
d = document.getElementById("computer");
//create p element to show cards in computer div
var cdoc = document.createElement("p");
//create text node to append to p element
var ctext = document.createTextNode(chand.cards.toString());
//append text node to p element
cdoc.appendChild(ctext);
//append p element to computer div
d.appendChild(cdoc);
//grab game cards div
g = document.getElementById("flop");
//create p element for appending
var fdoc = document.createElement("p");
//create text node to append to paragraph element
//choose which player has the blind
function blinds() {
var small = 5;
var big = 10;
var random = Math.floor(Math.random() * 2) + 1;
if (random == 1) {
player.blind = small;
player.chips -= small;
computer.blind = big;
computer.chips -= big;
pot1.chipsp += 15;
} else if (random == 2) {
player.blind = big;
player.chips -= big;
computer.blind = small;
computer.chips -= small;
pot1.chipsp += 15;
}
}
blinds();
//Show chips for player
var chips = document.getElementById("hand1");
var chipsp = document.createElement("p");
var chipsn = document.createTextNode("You have " + player.chips +
" chips");
chipsp.appendChild(chipsn);
chips.appendChild(chipsp);
//Show chips for the computer
var cchips = document.getElementById("computer");
var pchips = document.createElement("p");
var chipsnc = document.createTextNode("You have " + computer.chips +
" chips");
pchips.appendChild(chipsnc);
cchips.appendChild(pchips);
//grab computer hand div for printing out chips
function grab(x) {
d = document.getElementById(x);
return d;
}
//grab computer div
var cblind = grab("computer");
//create p element
var cpblind = document.createElement("p");
//create text node
var ctblind = document.createTextNode("Computer's blind is" + " " +
computer.blind);
//append text to p
cpblind.appendChild(ctblind);
//append p to computer div
cblind.appendChild(cpblind);
//grab hand1 for showing player blind
var ghand1 = grab("hand1");
//create element
var ghand2 = document.createElement("p");
//create text node
var ghand3 = document.createTextNode("Player's blind is" + " " + player
.blind);
//append text to para
ghand2.appendChild(ghand3);
//append p to div
ghand1.appendChild(ghand2);
//if computer gets the blind of 5,call no matter what
if (computer.blind = 5) {
computer.chips -= 5;
}
//if player is low blind, prompt for call, fold, or bet
if (player.blind == 5) {
var cfb = prompt("Would you like to call, fold, or bet?");
switch (cfb) {
case "call":
//do something
//draw 3 cards from the deck and append
for (i = 0; i < 3; i++) {
communityCards.addCard(deck.draw(1));
}
player.chips -= 5;
pot1.chipsp += 5;
chipsn.nodeValue = "You have " + player.chips + " chips";
player.turnpos = 1; //has acted
break;
case "fold":
//do something
computer.chips += pot1.chipsp;
break;
case "bet":
//do something
break;
default:
//do something
}
//start flop round
//draw 3 cards from the deck / switch statement for check,fold, bet?
//prompt computer and player on what they want to do
} else if (player.chips = 10) {
//draw 3 cards from the deck and append
for (i = 0; i < 3; i++) {
communityCards.addCard(deck.draw(1));
}
player.chips -= 5;
pot1.chipsp += 5;
}
//print flop cards to flop div
var flopc = document.getElementById("flop");
var flopcr = document.createElement("p");
var floptn = document.createTextNode(communityCards.cards.toString());
flopcr.appendChild(floptn);
flopc.appendChild(flopcr);
//print pot to flop div
var potf = document.createElement("p");
var pottn = document.createTextNode("The pot is " + pot1.chipsp);
potf.appendChild(pottn);
flopc.appendChild(potf);
//if player has acted, prompt computer to check, bet or fold
// if (player.turnpos == 1) {
//computer evaluates hands
//}
//test function
computer.checkOrBet();
}
Go with this :
//Test for a regular pair
if (this.firstCard.rank == communityCards.cards[0].rank || this.firstCard.rank == communityCards.cards[1].rank || this.firstCard.rank == communityCards.cards[2].rank) {
response = "call";
console.log("pairs");
} else if (this.secondCard.rank == communityCards.cards[
0]) {
response = "call";
console.log("pairs");
}
same for the second card.
You have a div, with 3 images in it.
How to create a simple slideshow that cycles through the images, and displays each image for 5 seconds and goes back to the first image when done and continues looping.
Without using jquery or any other framework.
(function () {
var imgs = document.getElementById('your_div').getElementsByTagName('img'),
index = 0;
imgs[0].style.display = 'block';
setInterval(function () {
imgs[index].style.display = 'none';
index = (index + 1) % imgs.length;
imgs[index].style.display = 'block';
}, 5000);
}());
Example HTML: http://jsfiddle.net/Zq7KB/1/
Edit: Saw a more elegant example above that used .length.
You can use setInterval to set up the timed callback, and set the src of an img element:
window.onload = function() {
var slides = [ "path_to_image_one",
"path_to_image_two",
"path_to_image_three" // ...
],
index = 0,
timer = 0;
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
...where your markup for the image is:
<img id="theImage" src="path_to_initial_placeholder">
Note that I've stored the timer handle in timer but not used it. This is just because you might use it to cancel the timer if you need to stop the slideshow.
Update: Just saw that you want to get the images from a div somewhere (whereas above I've supplied the paths in the code itself). Simple enough to create slides dynamically; revised edition of the above that grabs the images that are direct children of the div with the ID "theDiv":
window.onload = function() {
var slides = [],
index = 0,
timer = 0,
node;
// Get the slides
for (node = document.getElementById('theDiv').childNodes;
node;
node = node.nextSibling) {
if (node.nodeType == 1 && node.tagName == "IMG") {
slides.push(node.src);
}
}
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
Well you'd have to get a handle for the <div> first, so if it has an "id" value:
var theDiv = document.getElementById("imgContainer");
Now you just have to set up a timer to cycle through the images:
(function(div, sleep) {
var idx = 0;
var imgs = div.getElementsByTagName('img');
function showOne() {
for (var i = 0; i < imgs.length; ++i)
imgs[i].style.display = 'none';
imgs[idx].style.display = '';
idx = (idx + 1) % imgs.length;
setTimeout(showOne, sleep);
}
showOne();
})(theDiv, 5000);
var image = new Array('/img/1.jpg', '/img/2.jpg', '/img/3.jpg');
setTimeout("show_next()",5000);
function show_next()
{
var container = document.getElementById('image_container');
container.innerHTML = "<img src='" + image[i] + "' />";
if(i==2) { i = 1; }else { i = i + 1; }
}
I thought this was a nice simple answer, but there were a couple of errors.
setInterval rather than setTimeout and the initial index was not set. I also amended to load first image immediately.
var image = new Array('imgs/18/P1050294-XL.jpg', 'imgs/18/P1050293-XL.jpg', 'imgs/18/P1040984-XL.jpg', 'imgs/18/P1040983-XL.jpg', 'imgs/18/P1040982-XL.jpg');
var path = 'mypath';
document.getElementById('slideShow').innerHTML = "<img width='600px' src='" + path + image[0] + "' />" // Load First image
var i = 1; // Set counter to second image, for first use of loop
setInterval("show_next(path)",5000);
function show_next(path)
{
var container = document.getElementById('slideShow');
container.innerHTML = "<img width='600px' src='" + path + image[i] + "' />";
if(i==4) { i = 0; } else { i = i + 1; }
}