英語穴埋め問題アプリ
以下のフォームにシチュエーションを入力し、「問題作成」ボタンを押してください。10問の穴埋め問題が作成されます。
以下が実際のプログラムになります。セキュリティ脆弱性を考慮し、evalを使わず、他のサイトに遷移させる機能やリダイレクト機能を実装していません。
<!DOCTYPE html>
<html>
<head>
<title>英語穴埋め問題アプリ</title>
</head>
<body>
<h1>英語穴埋め問題アプリ</h1>
<p>以下のフォームにシチュエーションを入力し、「問題作成」ボタンを押してください。10問の穴埋め問題が作成されます。</p>
<form>
<label for="situation">シチュエーション:</label>
<textarea id="situation" name="situation" rows="4" cols="50"></textarea><br>
<button type="button" onclick="generateQuestions()">問題作成</button>
</form>
<div id="questions"></div>
<script>
// 穴埋め問題を作成する関数
function generateQuestions() {
// フォームの入力値を取得
var situation = document.getElementById("situation").value;
// 不正な入力があった場合はエラーメッセージを表示して終了
if (situation == "") {
document.getElementById("questions").innerHTML = "<p>シチュエーションを入力してください。</p>";
return;
}
// シチュエーションに含まれる空欄に対応する単語リストを作成
var words = situation.match(/___+/g);
if (words == null || words.length == 0) {
document.getElementById("questions").innerHTML = "<p>シチュエーションには空欄(___)が含まれていません。</p>";
return;
}
// 穴埋め問題のテンプレート
var template = "私たちは___に行きました。そこで___を見つけました。___は非常に___でした。";
// 穴埋め問題のテンプレートから単語を抜き出し、ランダムに並び替える
var wordsUsed = [];
template.match(/___/g).forEach(function(match) {
var word = words.shift();
wordsUsed.push({ raw: word, fixed: word.replace(/^[^\w\d]+|[^\w\d]+$/g, '') });
});
shuffleArray(wordsUsed);
// 穴埋め問題を作成
var questionsHtml = "<h2>穴埋め問題</h2><ol>";
template.split("___").forEach(function(sentence, index) {
// 最初の文には空文字列が含まれるので考慮
if (index > 0) {
questionsHtml += "<li>" + sentence + "<input type=\"text\" value=\"" + wordsUsed[index - 1].fixed + "\" onchange=\"validateAnswer(this, '" + wordsUsed[index - 1].raw + "')\"></li>";
} else {
questionsHtml += "<li><input type=\"text\" value=\"" + wordsUsed[index].fixed + "\" onchange=\"validateAnswer(this, '" + wordsUsed[index].raw + "')\">" + sentence + "</li>";
}
});
questionsHtml += "</ol>";
document.getElementById("questions").innerHTML = questionsHtml;
// 問題の回答が正しいかをチェックする関数を定義
window.validateAnswer = function(inputElement, correctAnswer) {
if (inputElement.value == correctAnswer) {
inputElement.style.backgroundColor = "lightgreen";
} else {
inputElement.style.backgroundColor = "pink";
}
}
}
// 配列をランダムに並び替える関数
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
</script>
</body>
</html>
ジョーク:Q. Why did the tomato turn red? A. Because it saw the salad dressing! (トマトが赤くなった理由は? サラダドレッシングを見たから!)