My older daughter Farida is studying the Catalan regions, called comarques. There are some online resources to test your knowledge about the regions, but we didn’t like them, so we decided to design and code one.

You can check the game: http://geoexamples.com/comarques/ and take a look to its code at GitHub

## The main structure

After looking several examples on creating a quiz using JavaScript, I finally got the simplest code to do this kind of things.

So we need two functions. I’ve called them drawOptions and checkAnswer. The code would be more or less:

Basically, the first thing to do is drawing the region to ask for, and the buttons with the options. All this is made in the drawOptions function, we will se how a bit later.

The buttons will have an event that will call the checkAnswer function, passing the selected option and the correct result. This function will add the score, change the score bar and finish the game if all the regions have been asked.

Finally, drawOptions() has to be called at the beginning so the game can start.

## Detailed code

The complete code can be found at GitHub, but the most important parts are:

# Creating the svg

As you can see, I create the svg with the desired size here, and add three rect elements, that will be the score bar. All them are in a group called results

# Creating the base map

To create the base map, I just draw a simple polygon map as usual:

• The land and the capitals are both in the same topojson.
• ids will have all the regions id nmbers (they go from 1 to 41)
• remaining_ids is the same array as the ids, but when a region is put as a question, it’s removed from it. This way, we know which regions haven’t been asked yet, and have all the numbers so the random buttons can be generated from ids. I found that using slice is the fastest way to clone an array.

# drawOptions()

This first part takes the region to ask from the remaining_ids array, and three more false answers to create the buttons.

Here, the buttons are drawn. Note the use of selection.exit(). This will remove the buttons when the new question comes, since the options will be different.

Finally, the selected region is drawn, along with the point indicating the capital name and the capital nema. Again, the selection.exit() method is used to remove the elements when a new one is created.

The first lines match the region id with the capital.