App下載

如何用 JavaScript 制作猜謎游戲

港城寶藏女孩 2021-08-25 11:46:43 瀏覽數(shù) (2537)
反饋

在本教程中,我們將制作一個簡單的猜數(shù)字游戲,它將生成一個 0 - 10 之間的隨機(jī)數(shù)(你可以將最大數(shù)字設(shè)置為你想要的任何數(shù)字),然后如果用戶猜到正確的數(shù)字,它將顯示或其他將顯示錯誤答案。

實例代碼

<input type="text" placeholder="Your Guess" id="inputfield">
<button id="inputsubmit">Submit</button>
<!-- The results will be shown here -->
<div id="result"></div>
const inputfield = document.getElementById('inputfield')
const inputsubmit = document.getElementById('inputsubmit')
const result = document.getElementById('result')

const random = Math.floor(Math.random() * 10)

inputsubmit.addEventListener('click', () => {
    const inputvalue = inputfield.value
    const input = parseInt(inputvalue)
    if ( random === input ) {
        result.innerText = "Correct answer"
    } else {
        result.innerText = "Wrong answer"
    }
})

實現(xiàn)內(nèi)容

在HTML中,只制作了一個用于猜測數(shù)字的輸入字段(input),一個用于提交猜測的按鈕(button)以及一個用來顯示結(jié)果的div。

在JavaScript中,我們使用 getElementById 獲取在 HTML 中所需要的這些內(nèi)容。然后再通過 Math.random() 生成一個隨機(jī)數(shù),并將其乘以10(這是最大數(shù)字,你也可以將它改為任何你想要的數(shù)值。)

接著,我們再添加一個事件監(jiān)聽器,創(chuàng)建一個名為 inputvalue 的常量并在其中傳遞 inputfield.value,然后我們使用 parseInt 來獲取 inputvalue 的整數(shù)值。在我們只使用 if 語句,所以如果隨機(jī) === 輸入,那么我們將在結(jié)果 div 中寫入“正確答案”,否則我們將在結(jié)果 div 中寫入“錯誤答案”。

總結(jié)

本篇文章介紹到此就結(jié)束了,感謝各位的觀看。

0 人點贊