首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript/HTML猜字游戏:难度级别w/下拉

JavaScript/HTML猜字游戏:难度级别w/下拉
EN

Stack Overflow用户
提问于 2021-12-01 23:42:15
回答 1查看 208关注 0票数 1

我正在做一个随机猜字游戏的项目。到目前为止,大多数代码都是有效的,但我正在尝试实现一些关于显示给用户的单词长度的规则,以衡量游戏的难度(更短的单词=更容易,等等)。我正在使用下拉菜单来获取用户的设置选择,然后在JS标记中有规则来处理这个问题。

在玩了几天之后,我希望一双新的眼睛可能会对我的错误之处有一个建议,以便能够执行我想要执行的规则。

应该处理这个问题的具体函数是setDifficulty(), getSelection(), and randomWord()

代码语言:javascript
复制
<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
        class="btn btn-lg btn-primary m-2"
        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>'''
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-02 00:06:13

让我们首先在下面的变量中保存困难设置:

代码语言:javascript
复制
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
let diff_setting = 'Easy';

然后编辑设置难度函数以更改该变量。

代码语言:javascript
复制
function setDifficulty(difficulty) {
    
  diff_setting = difficulty;
  mistakes = 0;
  guessed = [];
  randomWord();
  guessedWord();
  updateMistakes();
  generateButtons();
}

然后每次更改设置时调用该函数。

代码语言:javascript
复制
<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>

评论这个已经不需要了

代码语言:javascript
复制
// var diff_setting = document.getElementById('difficulty_setting');

并纠正这一点:

代码语言:javascript
复制
let medium_game = random_words.filter((med_words) => {
    if(med_words.length <= 9 && med_words.length>=6){
      return med_words;}});

因为它也选择了中等和简单的词。

此外,randomWord函数用于从未过滤的数组中选择一个单词,而不是您创建的新数组,因此它看起来如下所示:

代码语言:javascript
复制
function randomWord() {
  var arr = getSelection();
  answer = arr[Math.floor(Math.random() * arr.length - 1)];
}

最后,getSelection()应该如下所示:

代码语言:javascript
复制
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;}
}

现在它应该工作得很好:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70192625

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档