打字游戲是一種有趣的小游戲,而HTML是網頁開發中非?;A的技術。那么,如何使用HTML來開發一個簡單的打字游戲呢?
<!DOCTYPE html> <html> <head> <title>打字游戲</title> </head> <body> <h1>打字游戲</h1> <p>請在文本框中輸入下面的文字:</p> <p>瑪麗亞?謝爾蓋耶夫娜?屠格涅夫</p> <input type="text" id="input-box"> <br><br> <p>已輸入文字:</p> <p id="words"></p> <p>正確率:<span id="accuracy">0</span>%</p> <p>用時:<span id="time">0</span>秒</p> <button onclick="start()">開始</button> <button onclick="reset()">重置</button> <script> var words = "瑪麗亞?謝爾蓋耶夫娜?屠格涅夫"; var inputBox = document.getElementById("input-box"); var wordsArea = document.getElementById("words"); var accuracyArea = document.getElementById("accuracy"); var timeArea = document.getElementById("time"); var timer, startTime, endTime; function start() { inputBox.focus(); inputBox.addEventListener("input", check); startTime = new Date(); timer = setInterval(updateTime, 1000); } function check() { var inputText = inputBox.value; var correctWords = getCorrectWords(inputText); wordsArea.innerHTML = correctWords; var accuracy = getAccuracy(words, correctWords); accuracyArea.innerHTML = accuracy; } function getCorrectWords(inputText) { var correctWords = ""; for (var i = 0; i< inputText.length; i++) { if (inputText[i] === words[i]) { correctWords += inputText[i]; } else { correctWords += "<span style='color:red'>" + inputText[i] + "</span>"; } } return correctWords; } function getAccuracy(words, correctWords) { var accuracy = (correctWords.length / words.length * 100).toFixed(2); return accuracy; } function updateTime() { var currentTime = new Date(); var time = (currentTime - startTime) / 1000; timeArea.innerHTML = time.toFixed(1); } function reset() { inputBox.value = ""; wordsArea.innerHTML = ""; accuracyArea.innerHTML = "0.00%"; timeArea.innerHTML = "0"; clearInterval(timer); } </script> </body> </html>
通過上述代碼,我們可以實現一個簡單的打字游戲。玩家需要在文本框中輸入指定的文字,程序會自動計算出已輸入的文字和正確率等信息,并實時更新在頁面上。同時,通過JavaScript的時間函數,我們還能實現一個倒計時功能,讓游戲更具挑戰性。這里我們使用了HTML、CSS和JavaScript三種語言,為開發一些有趣的小游戲提供了很好的入門方式。