I'm trying to rewrite something I made in Python into Javascript. I'm having trouble with passing variables. It's a word game: in newWord
a random word from the words
-array random
is spoken and shown for 2s, after which an input field pops up in createInputField
and the variable answer
needs to be compared with random
in checkAnswer
The problem I'm having is that checkAnswer
is not working properly. Every answer
is shown as correct. Second, the wordsCorrectCounter
stays at 1, although answer
is tested as correct 3 times.
Lastly, I'm a total noob in coding if there are any stupid mistakes in general build up I would love to hear it, thanks!
<!DOCTYPE html>
<html>
<head>
<title>Aliyah's dictee spel</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="header">
<h1>Hej! Velkommen til Aliyahs diktee!</h1>
</div>
<div id="Random_word">
<h2 id="Empty">Click start to start</h2>
<button id="startGame">Start</button>
</div>
<script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
var words = ["meget", "går", "mor"];
var wordsWrong = [];
var wordsCorrectCounter = 0;
var wordsWrongCounter = 0;
function textToAudio(random)
{
let msg = random;
let speech = new SpeechSynthesisUtterance();
speech.lang = "da-DK";
speech.text = msg;
speech.volume = 1;
speech.rate = 0.5;
speech.pitch = 1;
window.speechSynthesis.speak(speech);
}
async function newWord(words)
{
if (words.length === 0){
endGame();
}
else {
var random = Math.floor(Math.random() * words.length);
document.getElementById("Empty").innerHTML = words[random];
textToAudio(words[random]);
await sleep(2000);
textToAudio(words[random]);
words.splice(random, 1);
document.getElementById("Empty").innerHTML = " ";
createInputField(words[random]);
}
};
function createInputField(random)
{
var answer = document.createElement("input");
answer.setAttribute("type", "text");
answer.id = "inputfield";
document.body.appendChild(answer)
let btn = document.createElement("button");
btn.id = "okBtn"
btn.innerHTML = "ok";
btn.type = "submit";
btn.name = "answerBtn";
document.body.appendChild(btn);
document.getElementById("okBtn").addEventListener("click", () => checkAnswer(answer))
}
function checkAnswer(random, answer)
{
if (answer === words[random]){
console.log("correct");
wordsCorrectCounter = +1;
console.log(wordsCorrectCounter)
document.getElementById("okBtn").remove();
document.getElementById("inputfield").remove();
newWord(words);
}
else{
console.log("wrong");
wordsWrongCounter = +1;
console.log(wordsWrongCounter)
document.getElementById("okBtn").remove();
document.getElementById("inputfield").remove();
newWord(words);
}
};
document.getElementById("startGame").addEventListener("click", () => newWord(words));
function endGame()
{
document.getElementById("Empty").innerHTML = "you are done!" + "Correct: " + wordsCorrectCounter + "Wrong: " + wordsWrongCounter;
};
</script>
</body>
</html>```
Aucun commentaire:
Enregistrer un commentaire