Triggering a "Win" in a Vanilla JavaScript Hangman Game - javascript

So I've already asked a few questions regarding this Hangman game (and have gotten awesome answers), but I've been continually tripped up by my "score keeper". The game almost does everything I need it too, but a "win" will not be logged until after a random key is pressed AFTER the entire word has been filled in...
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>Hangman!</h1>
<p>
<font size="+3"><span id="answer"></span></font>
</p>
<p>Lives: <span id="counter"></span></p>
<p id="wrongGuesses"></p>
<p>Wins: <span id="wins"></span></p>
<p>Losses: <span id="losses"></span></p>
<script type="text/javascript">
var word;
var guess; //user guess
var letters = []; //correctly guessed letters
var wrongLetters = []; //incorrectly guessed letters
var counter; //counts correct letters
var losses = 0;
var wins = 0;
document.getElementById("losses").innerHTML = losses;
document.getElementById("wins").innerHTML = wins;
var wordList = ["cat", "dog", "wolf", "laser", "apple"]; //FILL LIST LATER!!
//randomly chooses a word from the array and replaces letters with underscores
function start() {
word = wordList[Math.floor(Math.random() * wordList.length)];
counter = 7;
document.getElementById("counter").innerHTML = counter;
for (i = 0; i < word.length; i++) {
letters[i] = "__";
}
document.getElementById("answer").innerHTML = letters.join(" ");
console.log(word);
}
//checks if letter is in the word or not
function checkLetter() {
document.onkeyup = function(event) {
guess = event.key.toLowerCase();
//var found = false;
for (i = 0; i < word.length; i++) {
if (guess === word[i]) {
letters[i] = guess;
document.getElementById("answer").innerHTML = letters.join(" ");
//found = true;
}
}
//wrong letters go into the wrongLetters array and are displayed
//if (found) return;
if (wrongLetters.indexOf(guess) < 0) {
wrongLetters.push(guess);
document.getElementById("wrongGuesses").innerHTML = wrongLetters.join(" ");
//every wrong guess subtracts one from the counter
counter--;
console.log(counter);
document.getElementById("counter").innerHTML = counter;
//when counter reaches 0 it's Game Over
//+1 to the losses if 7 words are missed
if (counter > 0 && letters.join("") === word) { //THE ISSUE
document.getElementById("wins").innerHTML = wins + 1;
console.log(wins);
confirm("YOU WIN! Play Again?");
wins++;
counter = 7;
letters = [ ];
wrongLetters = [ ];
start();
}
else if (counter === 0) {
document.getElementById("losses").innerHTML = losses + 1;
console.log(losses);
confirm("YOU LOOSE... play again?"); {
losses++;
counter = 7;
letters = [];
wrongLetters = [];
start();
}
}
}
}
}
start();
checkLetter();
</script>
</body>
</html>
Here's what I have so far and here is a jsfiddle link: https://jsfiddle.net/t57zfv3t/11/
I know the main issue is with the found bool and the return, but I can't seem to find a way to work around it. If anyone has any insight it would be greatly appreciated and I apologize in advanced to anyone who I have already bothered with this. THANKS!!

You return if the letter is found even if it's a whole word match, so just check that in the condition too
//wrong letters go into the wrongLetters array and are displayed
if (found && letters.join("") !== word) return;

Related

Javascript Hangman Game Running Functions += Times After Reset

Ok this is my very first ever coding project. I'm self taught and thought creating a hangman game my 2 young kiddos could enjoy would be fun.
I have the game coded and it runs perfectly fine the first time through however, once I click on my reset button to restart the game, my lives start going down by 2 instead of one. After a third reset it goes down by three, and so on. Any console.log()s I put in to check run as many times as well.
I've spend hours racking my brain trying to figure it out and I've looked all over and I'm just not getting what's wrong. I thought about just saying screw it and resort to refreshing the page after every play through to avoid the problem but my brain wont let me do that.
Does anyone have any idea how to fix the problem? I know my code is probably not the most efficient and can definitely use to touch ups, but like I said, this is my first ever project and I know efficiency and skill will come with time and practice (like this). Below is the main chunk of my code.
function gameStart() {
// user writes in a word
pickedWord = prompt('pick a word').toUpperCase();
pickLetterHeading.innerText = 'Pick a Letter'
numLivesSec.hidden = false;
startBtn.disabled = true;
gameIsGoing = true;
resetBtn.disabled = false;
// enables buttons to press
for (let j = 0; j < alphabet.length; j++) {
document.getElementsByClassName('letterBtnClass')[j].disabled = false;
}
numLives = 7;
numLivesRemaining.innerText = numLives;
// calls the main game function
gameInProgress();
}
function reset() {
startBtn.disabled = false;
pickedWord = '';
gameIsGoing = false;
resetBtn.disabled = true;
pickLetterHeading.hidden = true;
numLivesSec.hidden = true;
while (guessedSec.firstChild) {
guessedSec.removeChild(guessedSec.firstChild);
}
for (let l = 0; l < alphabet.length; l++) {
document.getElementsByClassName('letterBtnClass')[l].disabled = true;
letters[l].classList.replace('correct', 'letterBtnClass');
letters[l].classList.replace('incorrect', 'letterBtnClass');
}
numLives = 7;
}
function gameInProgress() {
pickLetterHeading.hidden = false;
wordInProgress = '';
for (let i = 0; i < pickedWord.length; i++) {
let lettersToGuess = document.createElement('span');
lettersToGuess.innerText = '_';
guessedSec.appendChild(lettersToGuess);
wordInProgress += '_';
}
for (let btn = 0; btn < letters.length; btn++) {
letters[btn].addEventListener('click', function (e) {
letters[btn].disabled = true;
if (pickedWord.indexOf(letters[btn].innerText) == -1) {
console.log('letter not there!');
numLives -= 1;
numLivesRemaining.innerText = numLives;
console.log('TESTING!')
// checks if you have any tries left. If you have 0, then runs game over
if (numLives == 0) {
console.log('GAME OVER!')
gameIsGoing = false;
pickLetterHeading.innerText = 'You lose. Try again.'
for (let j = 0; j < alphabet.length; j++) {
document.getElementsByClassName('letterBtnClass')[j].disabled = true;
}
}
}
// checks if the letter picked matches anything in the chosen word
for (let x = 0; x < pickedWord.length; x++) {
if (letters[btn].innerText == pickedWord[x]) {
// adds class to chosen letter to show you guess correctly
letters[btn].classList.add('correct');
document.getElementsByTagName('span')[x].innerText = pickedWord[x];
wordInProgress[x] = pickedWord[x];
// if picked letter matches something in the chosen word, changes the "_" to the correct letter to show user progress
String.prototype.replaceAt = function (index, char) {
let a = this.split("");
a[index] = char;
return a.join("");
}
wordInProgress = wordInProgress.replaceAt(x, pickedWord[x]);
// when the word is complete. will show you win
if (wordInProgress == pickedWord) {
console.log("WINNER WINNER CHICKEN DINNER!");
pickLetterHeading.innerText = 'YOU WIN!'
for (let j = 0; j < alphabet.length; j++) {
document.getElementsByClassName('letterBtnClass')[j].disabled = true;
}
}
} else {
// since you chose incorrectly it adds a class to the button to show a bad choice
letters[btn].classList.add('incorrect');
}
}
})
}
}

(Javascript) Trying to allow a key press only once in hangman game when it is deemed to be incorrect

Please let me know if there is any additional information I can add to help make my problem more clear!
Im trying to get my hangman game to not allow another key press of the same kind if it is deemed to be incorrect. Once a key press is deemed incorrect it is shown on screen as an incorrect guess and I don't want it to be shown more than once or to count as another incorrect guess as guesses are limited.
Here's a link to my site: https://thy-turk.github.io/Word-Guess-Game/
Here is the code I've been trying to manipulate to allow this.
//if else comparing letter guessed with the current word
if (letterPos.length) {
for(i = 0; i < letterPos.length; i++) {
currentWord[letterPos[i]] = lettersGuessed;
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
} else {
// if (lettersGuessed.includes(letter)) {
// return;
// }
document.getElementById("letters-guessed").innerHTML += lettersGuessed + " ";
guessesLeft--;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
}
The stuff I have commented out is the attempt I kept coming back to, but could never make work.
I know the way I've set this up is less than ideal. I've tried using functions throughout, but just ended up breaking everything.
Here is the entirety of the code for reference.
var currentWord = [];
var answerWord = [];
var lettersReset = "";
var i;
var guessesLeft = 15;
// Array for the word bank of possible answers
var wordAnswers = ["vapor", "wave", "keyboard", "javascript", "coding", "practice", "technology", "hangman", "retro", "internet", "lamborgini", "ferrari", "cellphone", "computer", "headphones", "speakers", "vinyl", "record"];
// Math function to randomly pick a word from the wordbank
var answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
// Variable that counts the number of guesses left
document.getElementById("guesses-remain").innerHTML = guessesLeft;
// Variable that counts the number of wins
var wins = 0;
document.getElementById("num-of-wins").innerHTML = wins;
// Loop that creates empty spaces for the words
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
//Function that will evaluate the position of a letter in the word
function wordLetters(letter) {
var letterPos = new Array();
for (i = 0; i < answer.length; i++) {
if (answer[i] === letter)
letterPos.push(i);
}
return letterPos;
}
//Return letters that arent guessed still
function lettersToGuess() {
var i;
var toGuess = 0;
for (i in currentWord) {
if (currentWord[i] === "_")
toGuess++;
}
return toGuess;
}
//Function to capture user input
document.onkeyup = function(event) {
var letter = event.key.toLowerCase();
var lettersGuessed = letter;
var i;
var letterPos = wordLetters(lettersGuessed);
console.log(letter);
//if else comparing letter guessed with the current word
if (letterPos.length) {
for (i = 0; i < letterPos.length; i++) {
currentWord[letterPos[i]] = lettersGuessed;
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
} else {
// if (lettersGuessed.includes(letter)) {
// return;
// }
document.getElementById("letters-guessed").innerHTML += lettersGuessed + " ";
guessesLeft--;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
}
// If user correctly guesses word the game is reset
if (lettersToGuess() == 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
wins++;
document.getElementById("num-of-wins").innerHTML = wins;
}
//Resets game if out of guesses
if (guessesLeft === 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
}
}
<h1>Press any key to get started!</h1>
<br />
<div class="container">
<p>Wins: </p>
<p><span id="num-of-wins"></span></p><br />
<p>Current Word: </p><br />
<p><span id="active-word"></span></p>
<p>Number of guesses remaining: </p><br />
<p><span id="guesses-remain"></span></p><br />
<p>Letters already Guessed: </p><br />
<p><span id="letters-guessed"></span></p>
</div>
Ok, so I'm gonna put my edited version of your code at the bottom and do the explaining up here.
First, you needed somewhere to keep track of the letters that you had already pressed. I added an array at the top of your script section to keep everything together. This is also important because it is outside the scope of the keyup event
Second, I actually added a little quality of life change in there. You weren't checking if the button pressed was actually a letter so I fixed that by wrapping everything in an if statement and then checking for the letter codes.
Then finally all were doing is using the includes() function. That's gonna check if the letter that was pressed has been seen already. If it has we do nothing. If it hasn't then we'll push that letter into the pastLetters array so that if we see it again we don't punish the user for it. Since the pastLetters array if in the parent scope of this it's persistent and won't be overridden if there's another keydown event.
Also important to note! I added that array to your reset pieces too so that when the game gets reset, the pastLetters array also gets reset.
var currentWord = [];
var answerWord = [];
// Making an array to put the letters that we've already seen into.
var pastLetters = [];
var lettersReset = "";
var i;
var guessesLeft = 15;
// Array for the word bank of possible answers
var wordAnswers = ["vapor", "wave", "keyboard", "javascript", "coding", "practice", "technology", "hangman", "retro", "internet", "lamborgini", "ferrari", "cellphone", "computer", "headphones", "speakers", "vinyl", "record"];
// Math function to randomly pick a word from the wordbank
var answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
// Variable that counts the number of guesses left
document.getElementById("guesses-remain").innerHTML = guessesLeft;
// Variable that counts the number of wins
var wins = 0;
document.getElementById("num-of-wins").innerHTML = wins;
// Loop that creates empty spaces for the words
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
//Function that will evaluate the position of a letter in the word
function wordLetters(letter) {
var letterPos = new Array();
for (i = 0; i < answer.length; i++) {
if (answer[i] === letter)
letterPos.push(i);
}
return letterPos;
}
//Return letters that arent guessed still
function lettersToGuess() {
var i;
var toGuess = 0;
for (i in currentWord) {
if (currentWord[i] === "_")
toGuess++;
}
return toGuess;
}
//Function to capture user input
document.onkeyup = function(event) {
// Checking to make sure that the key pressed is actually a letter.
if ((event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode >= 97 && event.keyCode <= 122) {
var letter = event.key.toLowerCase();
var lettersGuessed = letter;
var i;
var letterPos = wordLetters(lettersGuessed);
//if else comparing letter guessed with the current word
if (letterPos.length) {
for (i = 0; i < letterPos.length; i++) {
currentWord[letterPos[i]] = lettersGuessed;
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
} else {
// If the letter has already been seen don't do it again.
if (!pastLetters.includes(letter)) {
// Placing the letter into an array that we can reference outside the scope of the key up event.
pastLetters.push(letter);
document.getElementById("letters-guessed").innerHTML += lettersGuessed + " ";
guessesLeft--;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
}
}
// If user correctly guesses word the game is reset
if (lettersToGuess() == 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
pastLetters = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
wins++;
document.getElementById("num-of-wins").innerHTML = wins;
}
//Resets game if out of guesses
if (guessesLeft === 0) {
guessesLeft = 15;
document.getElementById("guesses-remain").innerHTML = guessesLeft;
document.getElementById("letters-guessed").innerHTML = lettersReset;
answer = wordAnswers[Math.floor(Math.random() * wordAnswers.length)];
currentWord = [];
pastLetters = [];
for (i = 0; i < answer.length; i++) {
currentWord.push("_");
}
document.getElementById("active-word").innerHTML = currentWord.join(" ");
}
}
}
<h1>Press any key to get started!</h1>
<br />
<p>Wins: </p>
<p><span id="num-of-wins"></span></p><br />
<p>Current Word: </p><br />
<p><span id="active-word"></span></p>
<p>Number of guesses remaining: </p><br />
<p><span id="guesses-remain"></span></p><br />
<p>Letters already Guessed: </p><br />
<p><span id="letters-guessed"></span></p>

Javascript guessing game, defining onkeyup variable

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;

Javascript Hangman - Replace Character In String

I've seen similar questions asked on Stack Overflow regarding this topic, but I haven't seen anything specific that would help me. My issue is that I can't seem to figure out how to replace a dash in hiddenWord with a correctly guessed letter while still retaining the dashes for un-guessed letters. Here is what I have so far and I'm not even sure if it's on the right track.
<script type="text/javascript">
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
for(i = 0; i < wordChoice.length; i++){
hiddenWord = wordChoice.replace(/./g,"- ");
}
console.log(hiddenWord);
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
selectedWord();
}
console.log(myLetter);
}
</script>
I have seen some stuff with jQuery and PHP but I have to do it in javascript for class. Any help would be appreciated and if this has been addressed before please let me know.
You can check each character at the word string, compare it with the chosen character and replace it, if it is the same character.
I changed your code a bit to reflect what you are looking for.
Also make sure to lowercase all characters to make it easier for the player.
// Declaration of Variables
var wordPool= ["Alf", "MarriedWithChildren", "Cheers", "MASH", "CharlesInCharge", "FmailyTies", "KnightRider", "MagnumPI", "MiamiVice"];
var lives = 6;
var myLetter;
var letter;
var wordChoice;
var hiddenWord;
var i;
var enter;
// Change character to selected one
function checkCharacter(n) {
for(i = 0; i < wordChoice.length; i++){
console.log(wordChoice[i].toLowerCase() + "==" + n);
if(wordChoice[i].toLowerCase() == n.toLowerCase()){
hiddenWord = setCharAt(hiddenWord,i,n);
}
}
console.log("[" + hiddenWord + "]");
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
// Selects word randomly from wordPool[]. Then replaces the letters with "- ".
function selectedWord() {
var number = Math.round(Math.random() * (wordPool.length - 1));
wordChoice = wordPool[number];
hiddenWord = wordChoice.replace(/./gi,"-");
console.log(wordChoice + "[" + hiddenWord + "]");
}
// Gives myLetter a value of key pressed. If key is "Enter" selectedWord() initiates
document.onkeyup = function(event) {
var myLetter = event.key;
if(myLetter === "Enter"){
if(lives == 0){
selectedWord();
lives = 6;
}else{
lives--;
}
}
console.log(myLetter);
checkCharacter(myLetter);
}
//Select a random word at start
selectedWord();
I made a JSfiddle that is working and playable:
Check it out here...
Try
hiddenWord += "- "
Instead of replace
Or
hiddenWord += wordChoice[i].replace(/./g,"- ");
Here's an example:
var word = "do this";
var displayWord = [];
for (var i = 0; i < word.length; i++) {//build array
if (word[i] === " ") {
displayWord.push(" ");
} else {
displayWord.push("-");
}
}
function update(userGuess) {//update array
for (var i = 0; i < word.length; i++) {
if (word[i] === userGuess) {
displayWord[i] = userGuess;
} else {
displayWord[i] = displayWord[i];
}
}
}
//Guess letters
update("h");
update("o");
displayWord = displayWord.join('');//convert to string
alert(displayWord);
Check out the pen - https://codepen.io/SkiZer0/pen/VbQKPx?editors=0110

simple matching game using javascript

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);
}

Categories