xxxxxxxxxx
98
// Auto clicks on the canvas :)
this.focus();
let countries;
let chosenOne = "";
let flag;
let list = [];
let correct = false;
let guessed = 0;
let wrong = 0;
async function preload() {
let url = "https://restcountries.com/v3.1/all?fields=name,flags";
let response = await fetch(url);
countries = await response.json();
selectCountries();
}
function setup() {
createCanvas(600, 400);
textAlign(CENTER);
background(200);
describe('A game to help learn the flags of all the countries in the world. It uses the https://restcountries.com API ');
}
function draw() {
image(flag, 0, 0, width, height * 0.75);
fill(0, 200);
rect(0, 0, width, height * 0.75);
showFlagAndCountries();
}
function mousePressed() {
selectCountries();
}
function showFlagAndCountries() {
noStroke();
fill(255, 60);
rect(width / 2 - 160, height / 2 - 140, 320, 220, 5);
if (flag) {
image(flag, width / 2 - 150, height / 2 - 130, 300, 200);
fill(50);
rect(0, 300, 600, 100);
fill(255);
textSize(10);
text(`1. ${list[0]} - 2.${list[1]} - 3.${list[2]}`, width / 2, 350);
}
scoreAndContinue();
drawCorrectIncorrect();
}
function getRandomCountry() {
let randy = floor(random(countries.length));
let chosenCountry = countries[randy];
return chosenCountry;
}
function selectCountries() {
list = [];
chosenOne = getRandomCountry();
flag = loadImage(chosenOne.flags.png);
let name = chosenOne.name.common;
list.push(name);
list.push(getRandomCountry().name.common);
list.push(getRandomCountry().name.common);
list.sort();
}
function keyPressed() {
if (list[key - 1] === chosenOne.name.common) {
correct = true;
guessed++;
} else {
wrong++;
}
}
function drawCorrectIncorrect(){
fill(0,200,0);
textSize(30);
text(guessed,20,30);
fill(200,0,0);
text(wrong, width-20,30);
}
function scoreAndContinue() {
if (correct) {
setTimeout(() => (correct = false), 500);
setTimeout(() => selectCountries(), 5);
}
}