Skip to content
Advertisement

JavaScript: How to move through my question array

I am really stuck! As a newbie, I am trying to build a guessing game for Flags of the World. Here is what I’m trying to do:

  • I have an array of objects which I want to shuffle
  • I then want to select the correct country that matches the image
  • Add countries to three answer buttons below the image
  • I want to check for a correct/wrong answer
  • Add support for the user to click next which would load the next ‘correct’ country and image and two ‘incorrect’ countries from my array of objects.

Currently I am doing this by creating variables using a fixed index from the shuffled array for the currentFlagIndex (correct) and wrongFlagIndex (wrong) and anotherWrongIndex (also wrong). I can make this all work once, as per the code below, but I am completely stuck on how to move to the next question.

I am running this all against a 60 second timer. I have the timer counting down, but have not attempted to put a check in to ensure this is not at zero (I will do that once I know how to move my questions on).

Flags:

JavaScript

Game JavaScript:

JavaScript

I have commented out the above code as it will generate a new array of three but it also causes the current correct answer to return wrong, so must be changing the variables.

I think I have a problem where I am inserting the answer text and image outside of a function, but I have tried many things here, which all return errors.

Game HTML:

JavaScript

I have a solution where I can add two incorrect answers to my flags array, but that seems like a long-hand (there are 216 flags!) way to ‘solve’ this problem. I have all of the parts, I just need someone to help me move through the array to the next flag please!

The latest version of the full code is also deployed here: Git Hub

I am sure there is a lot wrong with my code, but any straightforward help to move me on would be much appreciated!

Advertisement

Answer

So you are trying to find a way to:

  • Generate the wrong answer flags(instead of hard coding it)
  • Regenerating a new game
  • Restart the X timer

Good question there are multiple ways to complete this.

One route would be to move/swap(swap items for faster Big O if you are worried about speed) the selected flags to the end of the array. (For most of the logic you will be reusing the random generated logic)

Flags c=correct s=selected

[s,x,x,c,x,s,x,…] => [x,x,x,x,…,s,c,s]

Now when generating the next correct flag for a new game you would reuse the random generated logic and reduce the length of the flags array by one (so you don’t choose the same flag as the previous game but I’ll leave that to you).

I have a snippet of logic here, you just need to restart the timer: https://jsfiddle.net/pmt3Ls2q/11/

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement