如何从列表中随机分配4个文本框文本?并让其中之一与一个变量随机匹配吗? [英] How would I randomly assign 4 textboxes text from my list? And have one of those randomly match up with a variable?

查看:76
本文介绍了如何从列表中随机分配4个文本框文本?并让其中之一与一个变量随机匹配吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,在code.org上,我有一个项目,您需要从它们的列表中猜测恐龙化石.我的设想是给4个选项和一张图片,但是我不知道如何确保其中一个按钮随机获得正确答案,而其他3个随机按钮则从列表中获得随机名称.我有选择特定变量/正确答案的代码.

Currently, on code.org, I have a project where you need to guess a dinosaur fossil from a list of them. What I have envisioned is to be given 4 options and a picture, however I don't know how to make sure that one of the buttons randomly gets the correct answer, while the other 3 random ones get random names from the list. I have the code that selections the specific variable/correct answer.

var dinosaur = ["T-Rex","Velociraptor","Allosaurus","Spinosaurus","Brachiosaurus","Stegosaurus","Ankylosaurus" Tera,;,"Parasaurolophus","Iguanodon","Diplodocus","Argentinosaurus","Isanosaurus","Styracosaurus","Baryonyx","Carnotaurus","Carnotaurus",代码>

var dinosaur = ["T-Rex", "Velociraptor", "Allosaurus", "Spinosaurus", "Brachiosaurus", "Stegosaurus", "Ankylosaurus", "Triceratops", "Parasaurolophus", "Iguanodon", "Diplodocus", "Argentinosaurus", "Isanosaurus", "Styracosaurus", "Baryonyx", "Carnotaurus", "Europasaurus"];

onEvent("Next", "click", function(nextDinosaur) {
  var dino = dinoPick(dinosaur);
  console.log(dino);
});
function dinoPick(list){
    return (list[(randomNumber(0,list.length-1))]);
}```

推荐答案

TL; DR

在更深入的解决方案中,我编写了两个原型函数,它们随机返回一定数量的元素/属性(默认返回1个元素/属性)并返回这些值.对于该解决方案的TL; DR版本,您只需要我编写的数组函数即可.

TL;DR

In my full solution further down, I wrote two prototype functions that return a certain number of elements/properties (defaults to return 1 element/property) at random and return those value(s). For this TL;DR version of the solution, you only need the array function I wrote.

这应该可以满足您的需求:

This should do what you are looking for:

const dinosaur = ['T-Rex', 'Velociraptor', 'Allosaurus', 'Spinosaurus', 'Brachiosaurus', 'Stegosaurus', 'Ankylosaurus', 'Triceratops', 'Parasaurolophus', 'Iguanodon', 'Diplodocus', 'Argentinosaurus', 'Isanosaurus', 'Styracosaurus', 'Baryonyx', 'Carnotaurus', 'Europasaurus'];

Array.prototype.pickRand = function(count = 1, copy) { return ((copy = [...this]), (count = Math.min(copy.length, count)), Array(count).fill().map(x => copy.splice(Math.floor(Math.random() * copy.length),1)[0])); }

let options = dinosaur.pickRand(4);
let correct = options.pickRand();

console.log(`The four options are ${options.map((e,i) => !i ? `and ${e}` : e).reverse().join(', ')}.\n\nThe correct option is ${correct}.`)

我编写了一个名为 pickRand()的原型函数,该函数具有支持数组和对象的方法,并且本质上是从数组/对象中选择随机数量的项或属性.为了完成您的任务,我将您的选项数组变成了一个键值对象,其中唯一键是种类,值是与每个键关联的图像.

I wrote up a prototype function called pickRand() with methods to support both arrays and objects and essentially picks a random number of items or properties from the array/object. To accomplish your task, I turned your array of options into a key-value object where the unique keys are the species and the values are the images associated with each.

const options = dinosaur.pickRand(4);
const correctSpecies = Object.keys(options.pickRand())[0];

在编写此程序时,我的主要重点是确保这种安全性,即如果有人回答问题要看控制台,将不会有简单或明显的方法来查看所显示的哪个选项.正确答案.为此,我通过引入外部库合并了简单的MD5哈希.我从对象中选择4个随机选项并对其进行迭代,然后随机选择其中之一作为正确答案.当我遍历正确答案时,我对它的ID进行哈希处理并将其设置为父表单上的数据属性值,并且还将问题的图像URL设置为其 imageURL 属性的值./p>

As I programmed this, one key focus I had was to make this secure in such a way where if someone answering the questions were to look at the console, there would be no simple or obvious way of seeing which option presented is the correct answer. To do this, I incorporated simple MD5 hashing by pulling in an external library. I pick 4 random options from the object and iterate through them, picking one of them randomly as the correct answer. As I iterate over the correct answer, I hash its ID and set it as a data-attribute value on the parent form, and I also set the question's image URL to the value of its imageURL property.

const options = dinosaur.pickRand(4);
const correctSpecies = Object.keys(options.pickRand())[0]; // -> "T-Rex"
Object.entries(options).forEach(([species, imageURL]) => {
    const speciesKey = keyify(species);
    // ...
    if (species === correctSpecies) {
        form.dataset.hash = md5(speciesKey);
        questionImage.style.backgroundImage = `url(${imageURL})`;
    }
});

然后,当有人单击答案时,我将他们所选答案的哈希ID与我们先前存储在表单数据属性中的哈希值进行比较.如果它们相等,我们将通过输入的关联标签上的数据属性将答案标记为正确.否则,我们将其标记为不正确.这种正确状态"指的是:影响样式和按钮中的单词生成新问题.

Then, when someone clicks an answer, I compare the hashed ID of their selected answer with the hash value we previously stored in the form's data-attribute. If they are equal, we mark the answer as correct via a data-attribute on the input's associated label. Otherwise, we mark it as incorrect. This "correct status" affects styling as well as verbiage in the button to generate a new question.

在这里,全部放在一起.点击运行代码段"请参阅下面的测验.就本例而言,我使用的占位符图像均带有正确答案的文本,因此您可以轻松测试真值和假值.

Here it is, all put together. Click "Run Snippet" below to see the quiz in action. For the sake of this example, I am using placeholder images with the correct answer's text for each so you can easily test true and false values.

const form = document.getElementById('questions');

var dinosaur = {
    'T-Rex': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=T-Rex',
    'Velociraptor': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Velociraptor',
    'Allosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Allosaurus',
    'Spinosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Spinosaurus',
    'Brachiosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Brachiosaurus',
    'Stegosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Stegosaurus',
    'Ankylosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Ankylosaurus',
    'Triceratops': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Triceratops',
    'Parasaurolophus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Parasaurolophus',
    'Iguanodon': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Iguanodon',
    'Diplodocus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Diplodocus',
    'Argentinosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Argentinosaurus',
    'Isanosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Isanosaurus',
    'Styracosaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Styracosaurus',
    'Baryonyx': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Baryonyx',
    'Carnotaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Carnotaurus',
    'Europasaurus': 'https://via.placeholder.com/600x400/6d4c41/efebe9/?text=Europasaurus'
};

Array.prototype.pickRand = function(count = 1, copy) { return ((copy = [...this]), (count = Math.min(copy.length, count)), Array(count).fill().map(x => copy.splice(Math.floor(Math.random() * copy.length),1)[0])); }

Object.prototype.pickRand = function(count = 1, copy) { return ((copy = Object.entries({...this})), (count = Math.min(copy.length, count)), Object.fromEntries(Array(count).fill().map(x => copy.splice(Math.floor(Math.random() * copy.length),1)[0]))); }

const keyify = term => term.toLowerCase().replace(/[-\s]/g, '');

const generateQuestion = () => {
    const options = dinosaur.pickRand(4);
    const correctSpecies = Object.keys(options.pickRand(1))[0];
    form.innerHTML = '';
    form.dataset.hash = '';
    form.insertAdjacentHTML('afterbegin', `<div id="question-image"></div>`);
    const questionImage = form.querySelector('#question-image');
    Object.entries(options).forEach(([species, imageURL]) => {
        const speciesKey = keyify(species);
        form.insertAdjacentHTML('beforeend', `<input type="radio" name="dinosaur" value="${speciesKey}" id="${speciesKey}" required><label for="${speciesKey}">${species}</label>`);
        if (species === correctSpecies) {
            form.dataset.hash = md5(speciesKey);
            questionImage.style.backgroundImage = `url(${imageURL})`;
        }
    });
};

const validateAnswer = () => {
    const inputs = Array.from(form.querySelectorAll('input'));
    const selected = inputs.filter(e => e.checked)[0];
    const correctStatus = md5(selected.id) === form.dataset.hash;
    inputs.forEach(input => input.disabled = true);
    selected.nextElementSibling.setAttribute('data-correct', correctStatus);
    form.dataset.hash = '';
    form.insertAdjacentHTML('beforeend', `<button class="${correctStatus ? 'correct' : 'incorrect'}">${correctStatus ? 'Great job! Next question' : 'Try again'}</button>`);
};

document.addEventListener('click', e => e.target?.matches('form button') && generateQuestion());

document.addEventListener('change', e => e.target?.matches('form input') && validateAnswer());

form.addEventListener('submit', e => e.preventDefault());

generateQuestion();

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&display=swap');
@charset "UTF-8";
html {
  margin: 0;
  padding: 0;
}
body {
  margin: 0;
  padding: 20px;
  font-family: "Roboto", sans-serif;
  font-size: 16px;
  color: #37474f;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
#questions {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-self: flex-start;
}
#questions > :nth-child(n+2) {
  margin-top: 10px;
}
#question-image {
  width: 300px;
  height: 200px;
  background-size: cover;
  background-position: center;
  margin-bottom: 10px;
  align-self: center;
}
input {
  display: none;
}
input + label {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  position: relative;
  padding: 20px;
  background-color: #eceff1;
  border-radius: 500px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.15s ease-out;
}
input + label::after {
  content: "";
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  background-color: transparent;
  box-shadow: inset 0 0 0 5px rgba(55, 71, 79, 0.25);
  border-radius: 50%;
  font-family: "Font Awesome 5 Pro";
  font-weight: 900;
  font-size: 18px;
  font-style: normal;
  font-variant: normal;
  text-rendering: auto;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #fff;
  transition: inherit;
}
input + label[data-correct] {
  font-weight: 500;
}
input + label[data-correct=false] {
  background-color: #ffcdd2;
  color: #b71c1c;
}
input + label[data-correct=false]::after {
  content: "";
  box-shadow: inset 0 0 0 16px #f44336;
}
input + label[data-correct=true] {
  background-color: #c8e6c9;
  color: #1b5e20;
}
input + label[data-correct=true]::after {
  content: "";
  box-shadow: inset 0 0 0 16px #4caf50;
}
button {
  -webkit-appearance: none;
     -moz-appearance: none;
          appearance: none;
  padding: 20px;
  background-color: #2196f3;
  border: none;
  border-radius: 500px;
  font-family: inherit;
  font-size: 20px;
  font-weight: 700;
  color: #fff;
  cursor: pointer;
}
button::after {
  content: "";
  margin-left: 10px;
  font-family: "Font Awesome 5 Pro";
}
button:focus {
  outline: 0;
  box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.5);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/blueimp-md5/2.18.0/js/md5.min.js"></script>
<script src="https://kit.fontawesome.com/07afc061fe.js"></script>
<form id="questions" data-hash=""></form>

我在这里看到的一个可能的改进是,当用户正确猜出问题时,将原始对象的值拼接起来,这样,一旦他们正确回答了问题,就不会再对相同的问题进行提问了.这样,用户将继续回答,直到他们正确猜出所有问题为止.如果剩下的选项数量太少,我们可以退回到使用已经被猜到的随机项目来填补空白,直到正确选择每个选项为止.

One possible improvement I see here is splicing values from the original object as the user guesses questions correctly so they aren't quizzed on the same question again once they answer it correctly. This way, the user will keep answering until they guess all questions correctly. When there are too few choices left from the number of options left, we can fall back to using random items that were already guessed to fill in the gaps until every option is correctly selected.

这篇关于如何从列表中随机分配4个文本框文本?并让其中之一与一个变量随机匹配吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆