var target = document.getElementById("startup-target").innerText; var buffer = ""; var successfulAttempts = 0; var failedAttempts = 0; var isGameActive = true; document.body.removeChild(document.getElementById("startup-target")); const field = document.getElementById("spell-field"); const scoreGood = document.getElementById("score-good"); const scoreBad = document.getElementById("score-bad"); const scorePercent = document.getElementById("score-percent"); const image = document.getElementById("word-image"); async function updateTarget() { isGameActive = false; const response = await fetch("/random"); const object = await response.json(); target = object.word; image.src = object.image_url; isGameActive = true; console.log("ready!"); } function isLetter(str) { return str.length === 1 && str.match(/[a-z]/i); } updateSpellField = (text) => { field.innerText = text; field.style.color = ""; } updateScores = () => { scoreGood.innerText = successfulAttempts; scoreBad.innerText = failedAttempts; var total = successfulAttempts + failedAttempts; var percent = (successfulAttempts / total) * 100; scorePercent.innerText = Math.round(percent); } submitBuffer = () => { if(buffer.toLowerCase() !== target.toLowerCase()) { updateSpellField(target); field.style.color = "red"; failedAttempts += 1; } else { updateSpellField(buffer); field.style.color = "green"; successfulAttempts += 1; } updateScores(); buffer = ""; updateTarget(); } document.onkeyup = (ev) => { const key = ev.key; if(isGameActive) { if(key === "Enter") { if(buffer.length != 0) submitBuffer(); } if(isLetter(key)) { buffer += key; updateSpellField(buffer); } } ev.preventDefault(); return false; }