soundbirder/public/javascripts/game.js
2023-07-29 18:21:40 +02:00

86 lines
2.9 KiB
JavaScript
Executable File

import { geolocationHandler, getCoordinates } from './map.js';
import client from './api-client.js';
const API_VERSION = "0";
function geolocationStep() {
if (document.getElementById('map') != undefined)
geolocationHandler();
let start_button = document.querySelector('.game .start-button');
if (start_button != undefined)
start_button.addEventListener('click', quizzStep);
}
function quizzStep() {
// Start by disallowing geolocation step
document.querySelector('.game-map-step').classList.toggle('none');
// Then allow the quizz step
document.querySelector('.game-quizz-step').classList.remove('none');
// Retrieve coordinates from former done geolocation (TODO: fix the need of cookie)
const coordinates = getCoordinates();
const [lat, lng] = coordinates;
console.log("Coordinates: " + `${lat}, ${lng}`);
client.getQuizz(lat, lng)
.then(quizz => {
// Display the quizz
displayQuizz(quizz);
}).catch(error => {
console.log(error);
});
}
function displayQuizz(quizz) {
let audio = document.querySelector('.game-quizz-step audio');
audio.src = quizz.audio;
audio.play();
let proposals = document.querySelector('.game-quizz-step .proposals');
quizz.species.forEach(sp => {
let proposal = document.createElement('li');
proposal.classList.add('proposal');
let button = document.createElement('button');
button.classList.add('proposal-button');
button.classList.add('button');
button.value = sp.speciesCode;
button.innerText = sp.comName;
proposal.appendChild(button);
proposals.appendChild(proposal);
button.addEventListener('click', verifyAnswer);
});
}
function verifyAnswer(event) {
let answer = event.target.value;
client.checkAnswer(answer)
.then(data => {
let message_class;
if (data.correct)
message_class = 'success';
else
message_class = 'error';
displayResult(message_class, data.message, data.answer);
}).catch(error => {
console.log(error);
});
}
function displayResult(message_class, message, species) {
let result = document.querySelector('.game-results-step .message');
document.querySelector('.game-quizz-step').classList.toggle('none');
result.classList.remove('success', 'error');
result.classList.add(message_class);
result.innerText = message;
document.querySelector('.game-results-step').classList.remove('none');
document.querySelector('.game-results-step .restart-button').addEventListener('click', restart);
document.querySelector('.game-results-step .species .com').innerText = species.comName;
document.querySelector('.game-results-step .species .sci').innerText = species.sciName;
}
function restart() {
window.location.reload();
}
function game() {
geolocationStep();
}
game();