我生成的法语单词重复了吗?什么时候不应该

时间:2014-11-13 06:26:02

标签: javascript html arrays

我已对此进行了排序,但现在又重新开始......我尝试更改for循环,但它似乎仍会生成重复的法语单词。它假设在应用程序运行中没有显示两次法语单词。

我的jsFiddle是一个精确的副本:

http://jsfiddle.net/jamesw1/w8p7b6p3/17/

使用Javascript:

    //James Wainwright's Mobile Apps Assignment
    //Arrays of french and english words.
    var
    RanNumbers = new Array(6),
        foreignWords = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf', 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize', 'dix-sept', 'dix-huit', 'dix-neuf', 'vingt', 'vingt et un', 'vingt-deux', 'vingt-trois', 'vingt-quatre', 'vingt-cinq', 'vingt-six', 'vingt-sept', 'vingt-huit', 'vingt-neuf', 'trente'],
        translate = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty', 'twenty-one', 'twenty-two', 'twenty-three', 'twenty-four', 'twenty-five', 'twenty-six', 'twenty-seven', 'twenty-eight', 'twenty-nine', 'thirty'],
        number = Math.floor((Math.random() * 30)),
        output = '',
        correctAns = translate[number];

    //Generate random numbers and make sure they aren't the same as each other.
    function wordGen() {
    for (var h = 0; h < RanNumbers.length; h++) {
        var temp = 0;
        do {
            temp = Math.floor(Math.random() * 30);
            while(temp==correctAns){
              temp = Math.floor(Math.random() * 30);
            }
        } while (RanNumbers.indexOf(temp) > -1);
        RanNumbers[h] = temp;

    }
} 

        //Call the previous function
        wordGen();

    //Create dynamic select menu using for loop. This loop runs once (on document load)
    document.getElementById('generatedWord').textContent = foreignWords[number];
    var correctAnswerIndex = Math.floor(Math.random() * 6);

        //If it's 0...Change it.
        if(correctAnswerIndex == 0)
        {
            correctAnswerIndex++;   
        }

        //Create a select menu of the options...Add the correct answer randomly into the menu.
        var guess = "<select name='guesses' id='guesses'>";
        for (var i = 1; i < RanNumbers.length; i++) {
            //This randomizes where the correct answer will be.
            if(i == correctAnswerIndex)
                 guess += '<option value="'+i+'">' + correctAns + '</option>';
            else
                 guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";

        }
        guess += "</select>";

    //Output the previous.
    document.getElementById('output').innerHTML = guess;
    numGuessed = document.getElementById('guesses').value;

    function arrayValueIndex(arr, val) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] === val) {
                return i;
            }
        }
        return false;
    }

    //Declare variables 'outside' the onclick function so it ensures they work correctly.
    var numGames = 5;
    var numGuesses = 1;
    var correct = 0;
    var wrong = 0;
    var prevNumber;
    var counter = 0;
    var outputted = '';

    //Create arrays that will hold the options they chose, the correct answer for that particular question, and ofcourse the generated word.
    var guessedList = new Array(6);
    var correctList = new Array(6);
    var wordGenerated = new Array(6);

    //On click, Get new word, Calculate how many they got right/wrong, Show the user what they entered, show them the correct values they should've guessed and more...
    document.getElementById('submitAns').onclick = function () {

    //Declare variables for function.
        prevNumber = number;
        number = Math.floor((Math.random() * 30)),
        output = '',
        correctAns = translate[number];
        document.getElementById('numGuess').innerHTML = "Question #" + numGuesses;

    //Check if guess is right or wrong, if right add 1 to correct pile..Visa versa.
         var
        genWord = document.getElementById('generatedWord').textContent,
            select = document.getElementById('guesses'),
            selectedText = select.options[select.selectedIndex].text;
        prevNumber === arrayValueIndex(translate, selectedText) ? correct++ : wrong++;


    function wordGen() {
    for (var j = 0; j < RanNumbers.length; j++) {
        var temp = 0;
        do {
            temp = Math.floor(Math.random() * 30);
            while(temp==correctAns){
              temp = Math.floor(Math.random() * 30);
            }
        } while (RanNumbers.indexOf(temp) > -1);
        RanNumbers[j] = temp;

    }
}

        //Generate a word here. ( call wordGen() ) 
        wordGen();

        //Create dynamic select menu for options they have to choose from.
        document.getElementById('generatedWord').textContent = foreignWords[number];

        //Generate a random number, so that the 'Correct' answer can be randomly put in a position in the select menu. (It won't always be in the same position...It changes depending on the random number
        var correctAnswerIndex = Math.floor(Math.random() * 6);

        //If it's 0...Change it.
        if(correctAnswerIndex == 0)
        {
            correctAnswerIndex++;   
        }

        //Create a select menu of the options...Add the correct answer randomly into the menu.
        var guess = "<select name='guesses' id='guesses'>";
        for (var i = 1; i < RanNumbers.length; i++) {
            //This randomizes where the correct answer will be.
            if(i == correctAnswerIndex)
                 guess += '<option value="'+i+'">' + correctAns + '</option>';
            else
                 guess += "<option selected='selected' value='" + i + "'>" + translate[RanNumbers[i]] + "</option>";

        }
        guess += "</select>";

        //Outputting to the html page.
        document.getElementById('output').innerHTML = guess;
        numGuessed = document.getElementById('guesses').value;

        function arrayValueIndex(arr, val) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] === val) {
                    return i;
                }
            }
            return false;
        }
        //Checking of the answers below, Accumilating correct and wrong answer. 
        //Count number of guesses
        numGuesses++;
        //Counter for placing guessed, correct and foreign word into there arrays.
        counter++;

        wordGenerated[counter] = foreignWords[number];
        guessedList[counter] = document.getElementById('guesses').options[select.selectedIndex].text;
        correctList[counter] = translate[number];

       //Once the application has finished...It will produce the following output.
        if (numGuesses == 6) {
            document.getElementById('generatedWord').innerHTML = "<span style='font-size:12px;color:red';>Please click for a new game when ready!</span><br /><p>You got " + wrong + " questions wrong " + "<br />You got " + correct + " questions correct";
                $('#submitAns').hide();
                outputted = "<table>";
                for(var d=1;d<wordGenerated.length;d++){
                    outputted += "<tr><td><span id='guessedWord'>Question " + d + ":</td> <td>Generated word: " + wordGenerated[d] + "</td>    <td>Guessed Word: " + guessedList[d] + "</td>   <td><span id='correctWord'>Correct Word: " + correctList[d] + "</span></td></td>";
                }
                outputted += "</table>";
                outputted += "<style type='text/css'>#hint{ display:none; }</style>";
                //Output it to the html page.
                    document.getElementById('details').innerHTML = outputted;
        }
    };
    document.getElementById('hint').onclick = function () {
        alert(correctAns.charAt(0));
    };

HTML:

<div data-role="page" id="page1" data-add-back-btn="true">
    <div data-role="header">
        <h1>James' Translation Guessing Game</h1>
    </div>
    <div data-role="content" class="main">  
        <h2 id="display" style="color:rgba(204,51,204,1);">Guess what the generated french word translates to in English!</h2><br />

        <!-- What question we're upto -->
        <h2 id="numGuess">Question #</h2 >

        <!-- The generated French Word  Aswell as end of app details-->
        <div align="center" class="frenchWord" style="position:">

        <!--Generated french word details-->
             <div style="background-color:rgba(51,51,51,0.5);border-radius:4px 10px 2px;"align="center"  id="generatedWord"></div>
             <br />
             <br />
   <!-- Show the user there guessed answers, correct and foreign word -->
             <div id="details"></div>
        </div>

        <!-- Select menu output -->
        <div align="center" id="output"></div>

        <a href="#" id="hint"><img id="hintImg" style="" src="images/hint.png" alt="Hint" /></a>

        <!-- Buttons, Call Functions -->
        <button type="button" style='opacity:0.5' id="submitAns" onClick="translate();">Check</button>
        <input type="button" value="New Game" onClick="document.location.reload(true)">
             <script>
             //Simple animation
             $(document).ready(function(){
                $("#generatedWord").animate({
                    opacity: 0.8,
                    margin: "40px 0px 100px 0px",
                    width: "20%",
                    padding: "30px",
                }, 1500 );
});
</script>
    </div>
    <div data-role="footer">
        <h4>James Wainwright</h4>
    </div>
</div>

1 个答案:

答案 0 :(得分:0)

这可能会这样做。在为RanNumbers数组分配数字之前,我将其从原始RanNumbers数组中删除,以防止重复。在问题中使用单独的数字数组可能更有意义,但我试图尽可能少地改变。

Updated Fiddle

function wordGen() {
    for (var h = 0; h < RanNumbers.length; h++) {
        var temp = 0;
        do {
            temp = Math.floor(Math.random() * RanNumbers.length);
            while(temp==correctAns){
              temp = Math.floor(Math.random() * RanNumbers.length);
                delete(RanNumbers.indexOf(temp)); // delete it so we can add it down below
            }
        } while (RanNumbers.indexOf(temp) > -1);
        RanNumbers[h] = temp;

    }