vendredi 14 mai 2021

Deleting dictionary items possibly result in different behaviour of program

I just started learning Javascript this week to write a wordgame to help my kid. The idea is that it should show and play a random word from a dictionary, she writes it the entry is checked and random gets deleted from the dictionary. The game continues until the dictionary length===0, and the wrong words are summarised if there are any. Somehow, the program is unpredictable, it literally works 1 in 7 times, and I can't understand why. Giving the following error:

Uncaught (in promise) TypeError: Cannot read property 'word' of undefined

I do think it has something the do with the way I delete random, or check if the dictonary is empty. Underneath the code is pasted links to screenshots of the console.log; 1 is the result of the program completely finishing, the other of one that doesn't. The interesting thing is that the error also is unpredictable, sometimes after just 1 word, sometimes 2. The only thing I do is refresh the page and the program behaves differently. I also tried running it on different browsers.

Being a total noob, I was quite surprised that I get different results while trying to do the same thing. It was quite frustrating to find out what was happening :-)

<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>
        <button id="editList">Edit word list</button>
        <h3 id="correctWord"></h3>

    </div>
    <script>
    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    var dictionary = [
        {   word: "apple",
            audio: 'apple.mp3',
        },
        {
            word: "baby",
            audio: 'baby.mp3',
        },
        {
            word: "car",
            audio: 'car.mp3'
        }

    ];

    var wordsWrong = [];
    var wordsCorrectCounter = 0;
    var wordsWrongCounter = 0;
    //var cheer = new Audio('correct.mp3');
    //var boo = new Audio('wrong.mp3');

    function editWords(){
        console.log("under construction");
    };

    function startGame(){
        document.getElementById("startGame").remove();
        document.getElementById("editList").remove();
        newWord(dictionary);
    };
    
    async function newWord(dictionary)
    {
        if (Object.entries(dictionary).length === 0){
            endGame();
        }
            else {
                var random = Math.floor(Math.random() * dictionary.length);
                document.getElementById("Empty").innerHTML = dictionary[random].word;
                console.log(dictionary[random].word);
                console.log(dictionary);
                await sleep(2000);
                document.getElementById("Empty").innerHTML = "       ";
                createInputField(random);
            }
    };

    function createInputField(random)
    {
        var entry = document.createElement("input");
        entry.setAttribute("type", "text");
        entry.id = "inputfield";
        document.body.appendChild(entry);
        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(random, entry.value));
    };

    function checkAnswer(random, entry)
        {var answer = entry.toLowerCase();
    
        if (dictionary[random].word == answer){
            //cheer.play();
            wordsCorrectCounter += 1;
            document.getElementById("okBtn").remove();
            document.getElementById("inputfield").remove();
            delete dictionary[random];
            console.log(dictionary);
            newWord(dictionary);
        }
            else{
                wordsWrong.push(dictionary[random].word);
                wordsWrongCounter += 1;
                document.getElementById("okBtn").remove();
                document.getElementById("inputfield").remove();
                //boo.play();
                document.body.style.backgroundColor = "red";
                document.getElementById("correctWord").innerHTML = dictionary[random].word;
                let btn = document.createElement("button");
                btn.id = "contBtn";
                btn.innerHTML = "Continue";
                btn.type = "submit";
                btn.name = "continueBtn";
                document.body.appendChild(btn);
                document.getElementById("contBtn").addEventListener("click", () => wrongAnswer(random));
            }
    };

    function wrongAnswer(random){
        document.getElementById("contBtn").remove();
        document.getElementById("correctWord").innerHTML = "    "
        delete dictionary[random];
        newWord(dictionary);
    };

    function endGame()
    {
        document.getElementById("Empty").innerHTML = "you are done!" + "Correct: " + wordsCorrectCounter + "Wrong: " + wordsWrongCounter 
        + "These words were wrong: " + wordsWrong;
        

    };

    function Refresh() {
        window.parent.location = window.parent.location.href;
    };
 
    document.getElementById("startGame").addEventListener("click", () => startGame());



    

    </script>
</body>
</html>

Console.log when program is able to finish

Console.log when program gets stuck




Aucun commentaire:

Enregistrer un commentaire