#javascript #html
#язык JavaScript #HTML
Вопрос:
Я работаю над проектом по игре в угадывание случайных слов. До сих пор большая часть кода работает, но я пытаюсь реализовать некоторые правила, касающиеся длины слов, отображаемых пользователю в качестве меры сложности игры (более короткие слова = проще и т. Д.). Я использую выпадающее меню, чтобы выбрать настройки пользователя, а затем в тегах JS есть правила, которые должны обрабатывать это.
Поиграв с этим в течение нескольких дней, я надеялся, что у свежей пары глаз может возникнуть предположение о том, в чем я ошибаюсь, чтобы обеспечить соблюдение правил, которые я пытаюсь обеспечить?
Конкретные функции, которые должны обрабатывать это setDifficulty(), getSelection(), and randomWord()
lt;html lang="en"gt; lt;headgt; lt;stylegt; 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; } lt;/stylegt; lt;meta charset="UTF-8"gt; lt;titlegt;Word Guessing Gamelt;/titlegt; lt;/headgt; lt;bodygt; lt;label for="difficulty"gt;Choose difficulty level:lt;/labelgt; lt;select name="difficulty" id="difficulty_setting"gt; lt;option value="Easy" onclick="setDifficulty()"gt;Easylt;/optiongt; lt;option value="Medium" onclick="setDifficulty()"gt;Mediumlt;/optiongt; lt;option value="Hard" onclick="setDifficulty()"gt;Hardlt;/optiongt; lt;/selectgt; lt;div class="container"gt; lt;h1 class="text-center"gt;Random Word Guessing Gamelt;/h1gt; lt;div class="float-right" style="position: absolute; text-align: left;"gt;Wrong Guesses: lt;span id='mistakes'gt;0lt;/spangt; of lt;span id='maxWrong'gt;lt;/spangt;lt;/divgt; lt;div class="text-center"gt; lt;h3gt;Guess the word:lt;/h3gt; lt;p style="font-size: 56px;" id="wordSpotlight"gt;The word to be guessed goes herelt;/pgt; lt;/divgt; lt;div id="keyboard"gt;lt;/divgt; lt;button class="btn btn-info" onClick="restart()"gt;Restartlt;/buttongt; lt;/divgt; lt;script type="text/javascript"gt; 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) gt;= 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 =gt; (guessed.indexOf(letter) gt;= 0 ? letter : " _ ")).join(''); document.getElementById('wordSpotlight').innerHTML = wordStatus; } function updateMistakes() { document.getElementById('mistakes').innerHTML = mistakes; } function generateButtons() { let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =gt; ` lt;button class="btn btn-lg btn-primary m-2" id='` letter `' onClick="handleGuess('` letter `')" gt; ` letter ` lt;/buttongt; `).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) =gt; { if(easy_words.length lt; 6){ return easy_words;}}); let medium_game = random_words.filter((med_words) =gt; { if(med_words.length lt;= 9){ return med_words;}}); let hard_game = random_words.filter((hard_words) =gt; { if(hard_words.length gt; 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)]; } lt;/scriptgt; lt;/bodygt; lt;/htmlgt;'''
Ответ №1:
Давайте начнем с сохранения параметра сложности в переменной вдоль этих :
let answer = ''; let maxWrong = 8; let mistakes = 0; let guessed = []; let wordStatus = null; let diff_setting = 'Easy';
затем отредактируйте функцию setdifficulty, чтобы изменить эту переменную
function setDifficulty(difficulty) { diff_setting = difficulty; mistakes = 0; guessed = []; randomWord(); guessedWord(); updateMistakes(); generateButtons(); }
затем вызывайте функцию каждый раз при изменении настроек
lt;label for="difficulty"gt;Choose difficulty level:lt;/labelgt; lt;select name="difficulty" id="difficulty_setting" onchange=" setDifficulty(this.value)"gt; lt;option value="Easy" gt;Easylt;/optiongt; lt;option value="Medium"gt;Mediumlt;/optiongt; lt;option value="Hard"gt;Hardlt;/optiongt; lt;/selectgt;
прокомментируйте это, так как в этом больше нет необходимости
// var diff_setting = document.getElementById('difficulty_setting');
и исправьте это :
let medium_game = random_words.filter((med_words) =gt; { if(med_words.length lt;= 9 amp;amp; med_words.lengthgt;=6){ return med_words;}});
как и при выборе слов, которые являются как средними, так и легкими
кроме того, функция randomWord используется для выбора слова из нефильтрованного массива, а не нового, созданного вами, поэтому оно будет выглядеть следующим образом :
function randomWord() { var arr = getSelection(); answer = arr[Math.floor(Math.random() * arr.length - 1)]; }
и, наконец, getSelection() должен выглядеть так :
function getSelection(){ // select difficulty //var selection = diff_setting; let easy_game = random_words.filter((easy_words) =gt; { if(easy_words.length lt; 6){ return easy_words;}}); let medium_game = random_words.filter((med_words) =gt; { if(med_words.length lt;= 9 amp;amp; med_words.lengthgt;6){ return med_words;}}); let hard_game = random_words.filter((hard_words) =gt; { if(hard_words.length gt; 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;} }
теперь это должно работать нормально 🙂
Комментарии:
1. Вы были очень полезны в своих объяснениях, я ценю дополнительную пару глаз и кого-то, у кого больше знаний, чем у меня. Большое спасибо!
2. @McBraunie я изучаю больше javascript, проходя мимо таких постов, как ваш, так что спасибо* ^^