【问题标题】:How do I adjust the code so that the image appears when the website loads and the guess is guessing what I want it to guess?如何调整代码,以便在网站加载时出现图像并且猜测是猜测我希望它猜测的内容?
【发布时间】:2021-07-20 03:59:11
【问题描述】:
<!DOCTYPE html>
<html>
    <body>
        <p id="Image"></p>

基本上我想做什么

【问题讨论】:

  • 请edit您的问题删除多余的空白。您还可以通过使用 Stack Snippets(图标在编辑器工具栏中看起来像 &lt;&gt;)来生成可以在问题中运行的 minimal reproducible example 来帮助其他人。
  • @BrandonMcConnell 不抱歉,没有
  • @Chad1212323232 有什么不同?我的解决方案从数组中获取选项列表及其相关图像,随机选择其中的一些,用一个正确的选项显示这些选项。如果用户选择了正确的值,它会将其标记为正确并跟踪他们的进度。在游戏结束时,它会显示他们的结果。
  • @BrandonMcConnell 我明白了,但我不想做同样的事情。我在选择随机图像时没有问题。我目前的问题是,当我运行页面时,我只想显示图像。我不太擅长编码,所以很难解释。你能运行我的代码以便明白我的意思吗?我真的很感激。

标签: javascript arrays image loops if-statement


【解决方案1】:

我建议的一种解决方法是将您的逻辑拆分为两个函数,一个是用户单击以检查其答案,另一个是用户单击以查看下一个问题。这将允许您在屏幕上而不是在警报中显示祝贺消息。以下是实际操作:

let score = 0;
let questionsAsked = 0;
const button = document.querySelector('button');
const input = document.getElementById('userInput');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const checkMessage = document.getElementById('check-message');
checkMessage.set = message => checkMessage.innerHTML = message;
checkMessage.clear = message => checkMessage.innerHTML = '';
const options = {
  chad: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Chad',
  bob: 'https://via.placeholder.com/600x400/000000/efebe9/?text=Bob',
  john: 'https://via.placeholder.com/600x400/000000/efebe9/?text=John'
}
function askQuestion() {
  checkMessage.clear();
  input.value = '';
  const optionsNames = Object.values(options);
  const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
  document.getElementById('image').innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
  button.setAttribute('onclick','checkAnswer()');
  button.textContent = 'Check Your Answer!';
}
function checkAnswer() {
  const userGuess = options[input.value.toLowerCase()];
  const correctAnswer = document.getElementById('question-image').getAttribute('src');
  if (options[input.value.toLowerCase()] === correctAnswer) {
    checkMessage.set('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
    gameScore.add();
  } else {
    checkMessage.set('SORRY, IT WAS INCORRECT');
    gameScore.subtract();
  }
  questionsAsked++;
  button.setAttribute('onclick','askQuestion()');
  button.textContent = 'Next Question';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="checkAnswer()">Start Game!</button>
<input id="userInput" type="text" />
<p id="check-message"></p>

如果您希望将所有内容保存在一个函数中并使用警报来发送祝贺消息,您可以通过跟踪当时提出的问题数量来做到这一点,而不是在第一次加载时立即检查答案,如下所示:

let score = 0;
let questionsAnswered = -1;
const imageContainer = document.getElementById('image');
const button = document.querySelector('button');
const input = document.getElementById('user-input');
const gameScore = document.getElementById('game-score-inner');
gameScore.add = (pts = 1) => gameScore.innerHTML = parseInt(gameScore.textContent) + 1;
gameScore.subtract = (pts = 1) => gameScore.innerHTML = Math.max(parseInt(gameScore.textContent) - 1, 0);
const options = {
  chad: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Chad',
  bob: 'https://via.placeholder.com/250x250/000000/efebe9/?text=Bob',
  john: 'https://via.placeholder.com/250x250/000000/efebe9/?text=John'
}
function askQuestion() {
  questionsAnswered++;
  const optionsNames = Object.values(options);
  const randomPhoto = optionsNames[Math.floor(Math.random() * optionsNames.length)];
  if (questionsAnswered) {
    const userGuess = options[input.value.toLowerCase()];
    const correctAnswer = document.getElementById('question-image').getAttribute('src');
    if (options[input.value.toLowerCase()] === correctAnswer) {
      gameScore.add();
      alert('CONGRATULATIONS!!! YOU GUESSED IT RIGHT');
    } else {
      gameScore.subtract();
      alert('SORRY, IT WAS INCORRECT');
    }
    questionsAnswered++;
  }
  imageContainer.innerHTML = `<img src="${randomPhoto}" id="question-image" width="250" height="250" />`;
  input.value = '';
}
askQuestion();
<p id="image"></p>
<p id="game-score">Score: <span id="game-score-inner">0</span></p>
<button onclick="askQuestion()">Check Answer!</button>
<input id="user-input" type="text" />

两种解决方案都可以很好地处理警报,但第一个解决方案为您希望在两个问题之间执行的任何功能提供了更大的灵活性。这里要做的另一个主要修复是在检查答案之后检查更改图像,并确保在这种情况下使用askQuestion() 在开始时实际使用该功能。我还添加了几个方便的函数gameScore.add() 和gameScore.subtract() 以方便将来使用。

如果您每个人都想有双重加权问题,您可以传入其他整数,例如 gameScore.add(2)。我还添加了Math.max() 行以确保分数永远不会低于 0。如果您希望玩家的分数变为负数,可以将其删除。

【讨论】:

  • 优秀的答案!希望再次穿越。
【解决方案2】:
Here is a working version of your game. To begin: <br>
1.Your code was not modifying the src of the image (thus no image appears) <br>
1a. I am modifying the src attribute associated with the `img` tag now. <br>
1b. `document.getElementById("Image").src = randomPhoto;` <br>
2. `theArrayArray` does not exist. I updated the variable to `theArray` <br>
3. To display an image when the game begins you need a handler. <br>
3a. I added the `button` to handle that <br>
4. Unless you want the user to type out `.jpg` you need to remove .jpg <br>
4a. `randomPhoto = randomPhoto.replace(".jpg", "");` <br>
   

     <img id="Image" src="#" width="250" height="250">
        <br>
        <br>
        <input id="userInput" type="text">
        <br>
        <br>
        <button type="button" id="btn" onclick="startGame()">Start Game</button>
        <span id="GameScore">Score:</span> 
    
    
        <script>
          
          let score = 10;
          var Chad = "Chad.jpg";
        
          let begin = 1;
          let thePhoto;
          var someArray = [ Chad, Bob
];
          function startGame() {
            if (start == 0) {
              for (var l = 2; i < 3; i--) {
                randomPhoto = theArray[Math.floor(Math.random()*theArray.length)];
                document.getElementById("Image").src = randomPhoto;
                document.getElementById("btn").innerHTML = "Submit";
                start = 1;
              }
            } else {
    
    
              
              randomPhoto = randomPhoto.replace(".jpg", "Insert");
                
                 }
                else {
    for (var x = 0; i < 3; i++) {
                  TheName = theArray[Math.floor(Math.random()*theArray.length)];
                  document.getElementById("Image").src = theName;
                  alert("No");
                  scorex = score-1;
                }
                document.getElementById("theScore").innerHTML="Score: "+score;
    
               
          
        </script>
        </body>
        </html>
    
    

【讨论】:

  • @J 代码 非常感谢!你认为这里有什么地方可以插入参数吗?
  • 您要为什么插入参数?
  • @J Code 有没有办法让您更新您的答案,以便使用数字?我想制作完全相同的游戏,但只是为了数字。所以基本上会显示 1-10 之间的数字,用户必须在文本框中输入数字是什么。我还是有点困惑。
  • 为此,您只需使用数字表示图像。您可以使用对象将图像与数字相关联。
  • @J Code 非常感谢你的帮助。但我并不是说将图像与数字相关联。我的意思是我如何才能让这个人在他们看到的屏幕上写下数字?例如,如果数字 5 出现在我设置的数组中,则该人必须写 5。如果您知道如何执行此操作,您能否通过更新代码来帮助我?
猜你喜欢
  • 2013-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多