Coding “Know The World” educative game using Python Turtle Module

Nekembe Boris
7 min readSep 2, 2023

--

How many countries (across all continents) do you know? And when was the last time you tested yourself on this?

This article can guide you on the steps I took to create an educative program using the Python Turtle module. The inspiration to undertake this project came from Day 25 from the Udemy course 100 Days of Code by Angela Yu.

For better presentation of the code, I created 2 separate python files;

  • The “main.py” file to host the core steps of the code.
  • The “dependencies.py” file which contains all the code for the Turtle module.

- PHASE I

The first thing required for this project will be the world map, and maps of all the various continents(Africa, Asia, Americas, Europe and Oceania) and also the geographic coordinates for each country on the map.

(i) One website that can help you with free maps is d-maps.com. For all the continents, it has empty maps, colored as well as maps having all the countries labeled on them and it also gives you a list of all the countries in a particular continent.

After viewing all the maps, I choosed maps with States and color since it has different colors for each country and because it is also colorful. But you for it to be used on the project, it has to be downloaded in “GIF” format, because it is the only format that can be used when working with the Turtle module

(ii) To get the “x” and “y” coordinates for each country, create your main.py file and in it write the following code:

   import turtle

#This function prints the x and y coordinate of the screen area you clicked on.
def position(x,y):
pos_f = [x, y]
print(pos_f)

#creating the screen object from the Screen class
screen = turtle.Screen()

#using (1.0 not 1) for the height and width automatically sets up the screen to Fullcreen mode each time the file is runned.
screen.setup(1.0, 1.0)

#replace {continent.gif} with the name of the continent image file you are working on
image = './background_images/{continent.gif}'

#to use the continent gif image as the background.
screen.addshape(image)
turtle.shape(image)

#the onclick method calls the position function each time you click on the turtle screen.
screen.onscreenclick(position)

screen.mainloop()

To avoid mixing up the countries their corresponding coordinates, for each continent, you will need to;

- Click on the countries in alphabetical order as provided on the d-maps.com

- Create a list containing the country names using the same order

- Creating separate lists for the x and y coordinates you collected.

For each continent you will need to convert these lists into a csv file. To do this;


import pandas

continent_dict = {
"Country" : country_list, #list containing the country names
"x" : x_cor, #list containing x coordinates
"y" : y_cor, #list containing y coordinates
}

data = pandas.DataFrame(continent_dict) ### Turning the list to a pandas dataframe

data.to_csv("file_path/file_name.csv") ### File path(where you want to create and save the file, relative to your current working directory). If done well, you will 1 csv file for each continent

You can comment or delete the above code when the data for all the continents have been collected.

- PHASE II

For the next phase of this project, we will need to create the “dependencies.py” file.

(i) In this file we will create a list called “country_initials”. This list will contain dictionaries of countries as keys and their initials as values.

The reason for this list is because some country names are too long to be properly represented in or beside the country. In a case such as this, the country initials will be used. The list will look like:

country_initials = [
{"Central African Republic" : "CAR"},
{"Sao Tome and Principe": "STP"},
{"Bosnia-Herzegovina" : "BH"},
{"Liechtenstein" : "Lie"},
]

(After completing the project, you can include any country you deem necessary)

(ii) Next, a class called “Functions” (use whatever name you like) will be created. This class will inherit the Turtle() class from the turtle module. Methods created under this “Functions” class will be used in;

- Writing the country name at the precise location on the map using the x and y coordinates in the csv file if the country is spelt correctly by the user.

- Replacing country name with initials if the country is in the “country_initials” list.

- Checking if a country is in the “country initials” list and then prints the country initials and full name at the side of the screen.

- After the user can no longer continue, this function prints all the unguessed countries in the unlisted list on the screen in red.

This Functions class will be written as follows;

class Functions(turtle.Turtle):

def __init__(self):
super().__init__() ### Inheriting from the Turtle() class
self.hideturtle() ### hide the turtle object so that only the text displays
self.penup() ###prevents the turtle from drawing lines on the screen

def create(self,country_name, posx, pos_y):
"""Creates a turtle and writes the country name at the precise location on the map using the x and y coordinates"""
self.goto(posx, pos_y)
self.write(arg=f"*{country_name}", move=True, align="left", font=("Century Gothic", 8, "bold"))


def rename(self, country_name):
"""This function replaces country name with initials if the country is in the country_initials list and then returns the initials else returns none
"""
for element in country_initials:
for (country, initials) in element.items():
if country == country_name:
return initials


def abbreviations(self, country_name, posx, pos_y):
"""This function checks if a country is in the country initials list and then prints the country initials and full name at the side of the screen
"""
for element in country_initials:
for (country, intials) in element.items():
if country == country_name:
self.goto(posx, pos_y)
self.write(arg=f"{initials} - {country}", move=True, align="left", font=("Century Gothic", 8, "bold"))


def unlisted_countries(self, country, pos_x, pos_y):
"""After the user can no longer continue, this function prints all the countries in the unlisted list in red"""
self.goto(pos_x, pos_y)
self.color('red')
self.write(arg=f"*{country}", move=True, align="left", font=("Century Gothic", 8, "bold"))

(i) To start, we will import all the modules and needed for this program and setup our screen;

import turtle
import pandas
from dependencies import Functions

turtle = Functions() ## creating a turtle from the Functions class

screen = turtle.Screen() ### setting up the turtle screen and background image
screen.setup(width=1.0, height=1.0)
screen.title("KNOW THE WORLD")
image = './file_path/world_map.gif' ## mine was "./background_images/world.gif"
screen.addshape(image)

screen.mainloop() ##keeps your screen on even if you click on it. Usually is the last line of code in your file.

(ii) Next, we ask the user which continent they wish to test themselves on. Remember I told you some country names were too long. The continents List serve as indicators on which part of the screen the countries with initials will be printed, based on the continent the user chooses. Also, name your gif images in according to their continents as it will greatly cut down the amount of code you will write.

continents = {"Africa" : [-353, -76], "Americas": [120, 179], "Asia":[-316, -255], "Europe": [-406, 247], "Oceania": [350, -180]}

valid_choice = False

while valid_choice != True:

user_choice = screen.textinput("Choose a Continent", "Which continent do you wish to test your knowledge on: Africa, Americas, Europe, Asia or Oceania").title()

for (key, value) in continents.items():
if key == user_choice:
image = f'./background_images/{user_choice}.gif'
screen.addshape(image)
turtle.shape(image)
data = pandas.read_csv(f"./csv_files/{user_choice}.csv") ## reading the csv file to get the coordinates of each country
abbr_x = value[0]
abbr_y = value[1]
valid_choice = True

(iii) We create some variables that will be useful during this journey.

  countries = data.Country    ## assigning the Country column in the csv file to the variable

guessed_countries = [] ## this list will contain all the countries the user guesses correctly

score = 0 ## keeps track of the number of successful entries.

(iv) Keep asking the user to input country names, check if the name is correct, check if it is in the country initials list, if yes, replace the country name with its initials and print the full name at the side of the map and finally print the country name(or initials).

gameover = False

while gameover != True:

guess = screen.textinput(f"Guessed {score} Countries out of a possible {len(countries)}", "Enter the name of the country. Don't forget to type 'Exit' if you've exhausted your knowledge.").title()

if guess in countries.tolist() and guess not in guessed_countries:

## avoids double counting by adding the guessed country to the list
guessed_countries.append(guess)
score += 1

##gets the x and y coordinates of the country fron the dataframe
country_data = data[data.Country == guess]
x_pos = int(country_data.x)
y_pos = int(country_data.y)


name = turtle.rename(guess) ### checks to see if the the initials
if name is None:
name = guess
else:
turtle.abbreviations(guess, abbr_x, abbr_y) ### If the name in not NONE, it will display the initials at the side of the screen
abbr_y -= 13 ###reduces the value of the y coordinate so that the next name is printed below (Only happens if the initials are used)

turtle.create(name, x_pos, y_pos) ###prints the country name regardless if initials or full names are used.

(v) Still inside the while loop, if the user reaches his/her limit and types "Exit", we will need to get all the countries the user did not guess, and display them on the screen in RED. If you remember, we created a method for this sole purpose.


if guess == "Exit":
unlisted_countries = [country for country in countries if country not in guessed_countries] ##using list comprehension to create a new list

for country in unlisted_countries:
country_data = data[data.Country == country]
x_pos = int(country_data.x)
y_pos = int(country_data.y)
name = turtle.rename(country)

if name is None:
turtle.unlisted_countries(country, x_pos, y_pos)
else:
turtle.unlisted_countries(name, x_pos, y_pos)
turtle.abbreviations(country, abbr_x, abbr_y)
abbr_y -= 13

gameover = True

And it is done. To improve on the user experience, we can put all the code in PHASE III (from step (i) to (v)) and put in in a function called “know_the_world”. This will enable us call the function if the user decides to play again. We can do the following;

def know_the _world():

code from step (i) to (v) enters here


replay = screen.textinput("Try Again", "Do you want to try again? Type 'y' or 'n'").title()

if replay == "Y":
screen.clearscreen()
know_the_world()

screen.mainloop()


know_the _world()

If there is a step or code you do not understand, don’t hesitate to checkout the final code on my Github profile or reach out to me on LinkedIn

--

--

Nekembe Boris
Nekembe Boris

Written by Nekembe Boris

Python Developer | 2x AWS Certified

No responses yet