vendredi 30 mars 2018

random generator function javascript

I'm making a guessing game for class. I pretty much have it done with the biggest problem I've had was making the string randomize itself after the game ends. It picks a random letter if the page refreshes but the objective is to keep track of stats so refreshing is out.

Here's my javascript code:

var lettersChar = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function randomFunc() {
    var randomMath = lettersChar[Math.floor(Math.random() * 
    lettersChar.length)];
    return randomMath;
}

//variables
var randomChar = randomFunc();

//array where user input will be stored
var userChoices = [];

var wins = 0;

var losses = 0;

var guesses = 9;

//keypress event
document.onkeyup = function (event) {

var userGuess = event.key;

    var userOptions = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", 
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", 
"z"];

//if guess is correct, +1 to win and refresh game and generate new letter
if (userOptions.indexOf(userGuess) > -1) {

    if (userGuess === randomChar) {
        wins++;
        guesses = 9;
        randomFunc();
        console.log(wins);
    }
    //if guess is incorrect, then print wrong guess and -1 to guesses left
    else if (userGuess !== randomChar) {
        guesses--;
        userChoices.push(userGuess);
    }
    //If guess reaches to 0 add +1 to loss and restarts game
    if (guesses === 0) {
        losses++;
        guesses = 9;
        userChoices = [];
        randomChar;
    }
}

I've tried invoking the function and it doesn't appear to work for me at this moment. Any help is appreciated!




Aucun commentaire:

Enregistrer un commentaire