File size: 9,623 Bytes
f1aa5b2
6ef6ef2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Find the Neighboring Countries!</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link rel="icon" type="image/png" href="favicon.png">
    <script src="helpers.js"></script>

    <script>
        const allCountries = new Object();
        countryObjects.forEach((item) => { // countryObjects is loaded from helpers.js
            var tempObject = {code2: item.code, name: item.name};
            allCountries[item.code3] = tempObject;
        })


        document.addEventListener("DOMContentLoaded", () => {
            //start a new Game
            let gameRound = 1;
            let gameScore = 0;
            let rightChoises = 0;
            let wrongChoises = 0;
            const theNeighbours = [];
            const restUrl = "https://restcountries.com/v2/alpha/";
            //const restUrl = "https://restcountries.com/v3.1/alpha/";
            const myCountryName = document.querySelector("#my-country-name");
            const myCountryFlag = document.querySelector("#my-country-flag");
            const displayRound = document.querySelector("#round");
            const displayScore = document.querySelector("#score");
            const neighboursPanel = document.querySelector("#neighbours-panel");


            function findBorders(code3) {
                return fetch(restUrl + code3)
                .then((response) => {
                    if (response.status === 200) {
                        return response.json();
                    }
                    else throw new Error(response.status);
                })
                .then((data) => {
                    if (data.borders == null) {
                        console.log("No Borders!");
                    } else {
                        data.borders.forEach((item) =>{
                            theNeighbours.push(item);
                        })
                    }
                })
            }


            function makeCountryChoises(borders) {
                const totalCountries = borders.length * 3;
                const choises = [...theNeighbours];
                while (choises.length < totalCountries) {
                    var c = countryObjects[Math.floor(Math.random() * 249) + 1].code3;
                        if (!choises.includes(c)) {
                            choises.push(c);
                        }
                }
                return choises;
            }


            async function buildGamePanel() {
                document.querySelector("html").style.cursor = "wait"; // cursor turns into a spinning wheel 
                                                                      // until the game panel is built
                do { // Loop until a random country with borders is found
                    await findBorders(shuffleArray(countryObjects)[0].code3);
                } while (theNeighbours.length == 0);

                // Display the right choises to the console
                const tmpArr = [];
                theNeighbours.forEach(item => {
                    tmpArr.push(allCountries[item].name);
                });
                console.log(allCountries[countryObjects[0].code3].name, tmpArr);

                const choises = makeCountryChoises(theNeighbours);
                shuffleArray(choises);
                choises.forEach((item) => {
                    if (theNeighbours.includes(item)) {
                        neighboursPanel.innerHTML += `<div class="neighbour-is-valid"><div id="flag">${getFlagEmoji(allCountries[item].code2)}</div> <div id="name">${allCountries[item].name}</div></div>`;
                    } else {
                        neighboursPanel.innerHTML += `<div class="neighbour-is-invalid"><div id="flag">${getFlagEmoji(allCountries[item].code2)}</div> <div id="name">${allCountries[item].name}</div></div>`;
                    }
                })
                document.querySelector("html").style.cursor = "default"; // cursor back to a normal pointer


                // Build the game panel...
                displayRound.innerHTML = `<div>Round:</div> <div>${gameRound}</div>`;
                displayScore.innerHTML = `<div>Total Score:</div> <div>${gameScore}</div>`;
                myCountryFlag.innerHTML = getFlagEmoji(countryObjects[0].code);
                myCountryName.innerHTML = countryObjects[0].name;


                // event listener to selecting a right country
                document.querySelectorAll(".neighbour-is-valid").forEach(item => {
                    item.addEventListener("click", () => {
                        var txt = item.querySelector("#flag").textContent;
                        gameScore +=5;
                        displayScore.innerHTML = `<div>Total Score:</div> <div>${gameScore}</div>`;
                        item.className += " was-clicked";
                        rightChoises += 1;
                        document.querySelector("#bar").style.width = rightChoises/theNeighbours.length*100 + "%"
                        if (rightChoises == theNeighbours.length) {
                            endOfGame("win");
                        }

                    }, {once: true}) // use each eventListener just once

                })


                // event listener to selecting a wrong country
                document.querySelectorAll(".neighbour-is-invalid").forEach(item => {
                    item.addEventListener("click", () => {
                        var txt = item.querySelector("#flag").textContent;
                        gameScore -= 3;
                        displayScore.innerHTML = `<div>Total Score:</div> <div>${gameScore}</div>`;
                        item.className += " was-clicked";
                        wrongChoises += 1;
                        if (wrongChoises == theNeighbours.length) {
                            endOfGame("lose");
                        }

                    }, {once: true}) // use each eventListener just once

                })


                function endOfGame(status) {
                    if (status == "win") {
                        document.querySelector("#next-round-panel").style.display = "flex";
                        document.querySelector("#next-round-panel").style.color = "blue";
                        document.querySelector("#next-round-panel").innerHTML = "You've found them all!";
                        document.querySelector("#btn-next-round").disabled = false;

                    } else {
                        document.querySelector("#next-round-panel").style.display = "flex";
                        document.querySelector("#next-round-panel").style.color = "#921308";
                        document.querySelector("#next-round-panel").innerHTML = "Sorry, you lose!";
                        document.querySelector("#btn-next-round").disabled = false;
                    }

                    if (gameRound == 10) {
                        setTimeout(() => {
                            alert(`Congratulations!!!\nThe game is over after 10 rounds!\nFinal Score: ${gameScore} points\n\nClick OK to play again.`);
                            location.reload();
                        }
                        ,500)
                    }

                }

            }


            buildGamePanel();


            // event listener to new game button
            document.querySelector("#btn-new-game").addEventListener("click", () => {
                let wc = confirm("Are you sure? Your score will be purged!");
                if (wc == true) {
                    location.reload();
                }
            })

            // event listener to next round button
            document.querySelector("#btn-next-round").addEventListener("click", () => {
                gameRound += 1
                rightChoises = 0;
                wrongChoises = 0;
                theNeighbours.length = 0;
                neighboursPanel.innerHTML = `<div id="next-round-panel"></div>`
                document.querySelector("#next-round-panel").style.display = "none";
                document.querySelector("#bar").style.width = 0 + "%"
                document.querySelector("#btn-next-round").disabled = true;
                buildGamePanel();
            })

        });
    </script>

</head>

<body>
    <div class="game-panel">

        <div id="sidebar">
            <div id="game-title">Find the Neighboring Countries!</div>
            <hr>
            <div id="round"></div>
            <div id="score"></div>
            <div id="buttons">
                <button id="btn-next-round" disabled>Next Round</button>
                <button id="btn-new-game">New Game</button>
        </div>
    </div>
        <div id="countries">
            <div id="my-country">
                <div id="my-country-flag"></div>
                <div id="my-country-name"></div>
            </div>
            <div id="progress">
                <div id="bar"></div>
            </div>
            <div id="neighbours-panel">
                <div id="next-round-panel"></div>
            </div>
        </div>
    </div>

</body>

<script>
    // The following applies only to macOS users.
    if (navigator.appVersion.indexOf("Macintosh") > 0) {
        document.body.style.fontFamily = '"Open Sans"';
    }
</script>

</html>