D3 World Map Game
Guess the Country Game
After creating my last D3 game, I wanted to follow up with a similar concept but focus more on country names and zooming animation. It’s basically a recreation of Mike Bostock’s World Tour but in a game format with some extra features, like zooming into a country, keeping score, and providing hints. Most of the code has been re-implemented from my other D3 demos and I have added capitals data directly into the TopoJSON. Let’s look at the code.
The setup code looks very similar to my previous game. Since we are using zoom and only want to look at sovereign states, I filter the TopoJSON by country. I have previously placed territory type and capital data into the Natural Earth transformed JSON file. Instead of placing the bordering countries information into the object array, as I did in the previous game, I am going to calculate that when the hint is requested. I draw all the countries and then use d3.shuffle and d3.range to create a shuffled array mapping of all the possible countries on the map. This is mostly for randomness in country order when you refresh the game. Since we are using the 110m scale of the Natural Earth shapefile, the amount of sovereign states is 166 (small countries like Vatican City do not exist at this scale).
The game starts by popping the last element of our shuffled array and sending that to the click function. There, I retrieve the selected country, highlight it with a black color using a CSS class, and figure out the bordering country names using topojson.neighbors. After that, I use path.bounds and some math around scaling to zoom into the selected country. I have an if/else block there to handle scaling on really large countries like Russia and really small countries like Kosovo. If a player clicks on the skip button, the score gets updated and we move to the next country. If a player clicks on hint button, I first show the surrounding countries information and then show capital information. A third hint click results in the same action as pressing the skip button: score gets updated and we move to the next country.
Clicking the submit button with a blank or incorrect name is the same as clicking on the hint button. However, if you do have the correct name (I use the toLowerCase() function so that there is no issues with capitalization), then your score is updated and you get to move to the next country. How many countries can you identify?
Here is the D3 Country Game.