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!"); } const levenshteinDistance = (str1, str2) => { const track = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null)); for (let i = 0; i <= str1.length; i += 1) { track[0][i] = i; } for (let j = 0; j <= str2.length; j += 1) { track[j][0] = j; } for (let j = 1; j <= str2.length; j += 1) { for (let i = 1; i <= str1.length; i += 1) { const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1; track[j][i] = Math.min( track[j][i - 1] + 1, // deletion track[j - 1][i] + 1, // insertion track[j - 1][i - 1] + indicator, // substitution ); } } return track[str2.length][str1.length]; }; function isLetter(str) { return str.length === 1 && str.match(/[a-z]/i); } updateSpellField = (text) => { field.innerText = text; field.style.color = ""; if(text.length == 0) { field.innerText = "escribe algo..."; field.style.color = "gray"; } } updateScores = () => { scoreGood.innerText = successfulAttempts; scoreBad.innerText = failedAttempts; var total = successfulAttempts + failedAttempts; var percent = (successfulAttempts / total) * 100; scorePercent.innerText = Math.round(percent); } submitBuffer = () => { let distance = levenshteinDistance(buffer.toLowerCase(), target.toLowerCase()); if(distance > 1) { updateSpellField(target); field.style.color = "red"; failedAttempts += 1; } else if(distance > 0) { updateSpellField(target); field.style.color = "yellow"; } 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(key === "Backspace") { buffer = buffer.slice(0, buffer.length - 1); updateSpellField(buffer); } if(isLetter(key)) { buffer += key; updateSpellField(buffer); } } ev.preventDefault(); return false; }