Home > Net >  JavaScript/HTML Word Guessing Game: difficulty levels w/drop-down
JavaScript/HTML Word Guessing Game: difficulty levels w/drop-down

Time:12-02

I am working on a project to have a random word guessing game. So far most of the code is working but I am trying to implement some rules on the length of words displayed to the user as a measure of game difficulty (shorter words = easier, etc). I am using a drop-down menu to get the user's setting selection, and then have rules in the JS tags that are supposed to be handling this.

After toying around with this for several days, I was hoping that a fresh pair of eyes might have a suggestion about where I am going wrong to be able to enforce the rules I am trying to enforce?

The specific functions that should be handling this are setDifficulty(), getSelection(), and randomWord()

<html lang="en">
<head>
  <style>

    body {
      background-color: rgb(231, 223, 223);
      align-content: center;
      margin: 2px;
      padding: auto;
    }
    
    h1 {
      text-align: center;
      font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
      border: rgb(187, 212, 235);
      margin: auto;
    }

    h4 {
      text-align: center;
      font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
      margin: auto;
    }

    div {
      text-align: center;
      font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
      background-color: rgb(231, 223, 223);
    }

    button {
      background-color: rgba(65, 127, 207, 0.781);
      color: rgb(255, 255, 255);
      padding: 1%;
      margin-bottom: 2%;
      flex-wrap: wrap;
      font-size: xx-large;
      border: 3px;
      border-radius: 5px;
    }
    button:disabled {
      background-color: rgba(65, 127, 207, 0.363);
    }

    label {
      text-align: center;
      font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
      border: 3px;
      border-radius: 5px;
    }

  </style>
  <meta charset="UTF-8">
  <title>Word Guessing Game</title>
</head>
<body>

  <label for="difficulty">Choose difficulty level:</label>
  <select name="difficulty" id="difficulty_setting">
    <option value="Easy" onclick="setDifficulty()">Easy</option>
    <option value="Medium" onclick="setDifficulty()">Medium</option>
    <option value="Hard" onclick="setDifficulty()">Hard</option>
  </select>
  <div class="container">
  <h1 class="text-center">Random Word Guessing Game</h1>
  <div class="float-right" style="position: absolute; text-align: left;">Wrong Guesses: <span id='mistakes'>0</span> of <span id='maxWrong'></span></div>
  <div class="text-center">
    <h3>Guess the word:</h3>
    <p style="font-size: 56px;" id="wordSpotlight">The word to be guessed goes here</p>
  </div> 
  <div id="keyboard"></div>
  <button class="btn btn-info" onClick="restart()">Restart</button>
</div>
<script type="text/javascript">
  
  let random_words = [
    "plankton",
    "pitman",
    "dexamethasone",
    "marabout",
    "wintertime",
    "trencherman",
    "subtilize",
    "cursorial",
    "asterism",
    "jam",
    "bacteriostat",
    "unworn",
    "nonuniformity",
    "subpart",
    "groats",
    "quintette",
    "blowtube",
    "ethnographical",
    "bulbous",
    "cataphoretic",
    "difficult",
    "opacify",
    "credence",
    "sextette",
    "mot",
    "prosthodontics",
    "whippletree",
    "life",
    "cook",
    "toxic",
    "quadrature",
    "tawdrily",
    "escalader",
    "clincher",
    "ataxia",
    "chiton",
    "pains",
    "straining",
    "tenderize",
    "circadian",
    "wreak",
    "foam",
    "artemisia",
    "pietistic",
    "commemoration",
    "excise",
    "phalanger",
    "decidua",
    "cinematography",
    "supportable",
    "unspoilt",
    "hermeneutics",
    "whipsaw",
    "quartan",
    "transportable",
    "imbrue",
    "oxtongue",
    "flogging",
    "intramolecular",
    "mechanism",
    "busted",
    "talker",
    "sedum",
    "glial",
    "youthful",
    "deviationist",
    "headpin",
    "realise",
    "hygiene",
    "worst",
    "isosmotic",
    "narcoleptic",
    "confidently",
    "boneset",
    "tugboat",
    "bimanual",
    "daredeviltry",
    "bris",
    "trip",
    "notably",
    "repartee",
    "suckling",
    "hymnody",
    "pleating",
    "graffiti",
    "assuredly",
    "moment",
    "isotropic",
    "absconder",
    "microspore",
    "adobe",
    "photoconductivity",
    "stray",
    "stalk",
    "squelch",
    "animistic",
    "pretentiousness",
    "unsmoothed",
    "goalmouth",
    "exclusiveness",
    "bullpen",
    "unasked",
    "dilettantish",
    "dedication",
    "happily",
    "squealer",
    "perineurium",
    "whatchamacallit",
    "appreciativeness",
    "topographically",
    "conjuncture",
    "resurvey",
    "vaned",
    "homo",
    "upcurved",
    "houseful",
    "microdot",
    "hated",
    "literature",
    "hydrophilic",
    "collie",
    "phycoerythrin",
    "canine",
    "unmanful",
    "scrim",
    "wanted",
    "enantiomorphism",
    "theologian",
    "gastronomical",
    "bura",
    "malocclusion",
    "superincumbent",
    "circumferential",
    "interrelated",
    "calamine",
    "subsidizer",
    "sarcoplasm",
    "eagerly",
    "incautiously",
    "priorship",
    "gooseneck",
    "wearisome",
    "preciously",
    "lust",
    "liger",
    "ovary",
    "garganey",
    "slather",
    "hisser",
    "counterfoil",
    "divisible",
    "hypochondria",
    "statute",
    "education",
    "byword",
    "damp",
    "hornbeam",
    "levity",
    "nucha",
    "fauteuil",
    "rho",
    "soothsaying",
    "decreased",
    "faze",
    "lamia",
    "above",
    "artful",
    "schmuck",
    "stocked",
    "carabiner",
    "incomparably",
    "unfaithfully",
    "parturient",
    "erotism",
    "menu",
    "pall",
    "technical",
    "stile",
    "expulsion",
    "spitball",
    "doubting",
    "wheelchair",
    "aptly",
    "aedes",
    "successfulness",
    "abductor",
    "offerer",
    "bloody",
    "tenderheartedness",
    "amusive",
    "streptococci",
    "gnaw",
    "curiousness",
    "hemorrhage",
    "theologise",
    "uninhabited",
    "strep",
    "unadoptable",
    "prophetic",
    "somite",
    "pythoness",
    "governable",
    "churlish",
    "craniate",
    "confusion",
    "smilingly",
    "accruement",
    "oftener",
    "coho",
    "scripture",
    "unprovoked",
    "adenohypophysis",
    "fitter",
    "pronouncement",
    "replacing",
    "custodial",
    "dynamiter",
    "vespers",
    "hostility",
    "knoll",
    "vendor",
    "sprig",
    "stave",
    "raphia",
    "canfield",
    "paint",
    "data",
    "teleconference",
    "tractability",
    "knit",
    "amazement",
    "airfield",
    "cesium",
    "galactic",
    "axial",
    "buffalo",
    "unsaddled",
    "pygmy",
    "brewer",
    "hazel",
    "inauthentic",
    "herrenvolk",
    "uncommercialized",
    "exasperatingly",
    "irony",
    "solan",
    "subsequence",
    "outclass",
    "etch",
    "regalia",
    "unanswered",
    "prospective",
    "rumormonger",
    "forecastle",
    "mineralogy",
    "adorability",
    "photogravure",
    "pronucleus",
    "underpopulated",
    "disgrace",
    "smutch",
    "ohmage",
    "cabomba",
    "emptying",
    "wordsmith",
    "charitable",
    "sadomasochism",
    "web",
    "railroader",
    "allow",
    "pennon",
    "preservation",
    "mollah",
    "prematurity",
    "puzzlement",
    "megaloblast",
    "adulterating",
    "dowager",
    "shirtfront",
    "exchequer",
    "transplanter",
    "turntable",
    "heedlessness",
    "escapist",
    "calf",
    "aortic",
    "rumored",
    "sagamore",
    "form",
    "settle",
    "persuasiveness",
    "ineptitude",
    "trembles",
    "navigator",
    "gabbro",
    "disappear",
    "thermocouple",
    "spay",
    "frisking",
    "haft"
]

let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;



function handleGuess(chosenLetter) {
  guessed.indexOf(chosenLetter) === -1 ? guessed.push(chosenLetter) : null;
  document.getElementById(chosenLetter).setAttribute('disabled', true);

  if (answer.indexOf(chosenLetter) >= 0) {
    guessedWord();
    checkIfGameWon();
  } else if (answer.indexOf(chosenLetter) === -1) {
    mistakes  ;
    updateMistakes();
    checkIfGameLost();
    updateHangmanPicture();
  }
}

function checkIfGameWon() {
  if (wordStatus === answer) {
    document.getElementById('keyboard').innerHTML = 'You Won!!!';
  }
}

function checkIfGameLost() {
  if (mistakes === maxWrong) {
    document.getElementById('wordSpotlight').innerHTML = 'The answer was: '   answer;
    document.getElementById('keyboard').innerHTML = 'You Lost!!!';
  }
}

function guessedWord() {
  wordStatus = answer.split('').map(letter => (guessed.indexOf(letter) >= 0 ? letter : " _ ")).join('');
  document.getElementById('wordSpotlight').innerHTML = wordStatus;
}

function updateMistakes() {
  document.getElementById('mistakes').innerHTML = mistakes;
}

function generateButtons() {
  let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
    `
      <button
        
        id='`   letter   `'
        onClick="handleGuess('`   letter   `')"
      >
        `   letter   `
      </button>
    `).join('');

  document.getElementById('keyboard').innerHTML = buttonsHTML;
}

function restart() {
  mistakes = 0;
  guessed = [];
  randomWord();
  guessedWord();
  updateMistakes();
  generateButtons();
}

function setDifficulty() {
  mistakes = 0;
  guessed = [];
  randomWord();
  guessedWord();
  updateMistakes();
  generateButtons();
}

document.getElementById('maxWrong').innerHTML = maxWrong;
var diff_setting = document.getElementById('difficulty_setting');

randomWord();
generateButtons();
guessedWord();

function getSelection(){
    // select difficulty
  //var selection = diff_setting;
  let easy_game = random_words.filter((easy_words) => {
    if(easy_words.length < 6){
      return easy_words;}});
    
  let medium_game = random_words.filter((med_words) => {
    if(med_words.length <= 9){
      return med_words;}});
  
  let hard_game = random_words.filter((hard_words) => {
    if(hard_words.length > 9){
      return hard_words;}});

  alert(diff_setting.value);
  if(diff_setting.value == 'Easy'){
    return easy_game;
  } else if (diff_setting.value == 'Medium'){
    return medium_game;
  } else {
      return hard_game;}
}


function randomWord() {
  var arr = getSelection();
  answer = random_words[Math.floor(Math.random() * arr.length - 1)];
}

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

CodePudding user response:

Let's start by saving the difficulty setting in a variable along these :

let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
let diff_setting = 'Easy';

then edit the setdifficulty function to change that variable

function setDifficulty(difficulty) {
    
  diff_setting = difficulty;
  mistakes = 0;
  guessed = [];
  randomWord();
  guessedWord();
  updateMistakes();
  generateButtons();
}

then call the function each time the setting is changed

<label for="difficulty">Choose difficulty level:</label>
  <select name="difficulty" id="difficulty_setting" onchange=" setDifficulty(this.value)">
    <option value="Easy" >Easy</option>
    <option value="Medium">Medium</option>
    <option value="Hard">Hard</option>
  </select>

comment this as its not needed anymore

// var diff_setting = document.getElementById('difficulty_setting');

and correct this :

let medium_game = random_words.filter((med_words) => {
    if(med_words.length <= 9 && med_words.length>=6){
      return med_words;}});

as it was also selecting words that are both medium and easy

also the randomWord function used to select a word from the unfiltered array not the new one you created so it would look like this :

function randomWord() {
  var arr = getSelection();
  answer = arr[Math.floor(Math.random() * arr.length - 1)];
}

and finally getSelection() should look like this :

function getSelection(){
    // select difficulty
  //var selection = diff_setting;
  let easy_game = random_words.filter((easy_words) => {
    if(easy_words.length < 6){
      return easy_words;}});
    
  let medium_game = random_words.filter((med_words) => {
    if(med_words.length <= 9 && med_words.length>6){
      return med_words;}});
  
  let hard_game = random_words.filter((hard_words) => {
    if(hard_words.length > 9){
      return hard_words;}});

  alert(diff_setting);
  if(diff_setting == 'Easy'){
    return easy_game;
  } else if (diff_setting == 'Medium'){
    return medium_game;
  } else if(diff_setting == 'Hard'){
      return hard_game;}
}

now it should work fine :)

  • Related