しりとりゲーム
前回入力された単語の後ろから2文字目と同じ文字から始まる単語を考えて入力してください。
次の単語:
注意: 「ん」で終わる単語は使えません。
<!DOCTYPE html>
<html>
<head>
<title>しりとりゲーム</title>
<script>
function play() {
const word = document.getElementById("inputWord").value;
// ワードチェック
if (word === "") {
alert("単語を入力してください");
return;
}
// 最後の文字チェック
const lastChar = word.charAt(word.length-1);
if (lastChar === "ん" || lastChar === "ン") {
alert(word + "で終わる単語は使えません");
return;
}
// 正しい単語なら次の単語を生成
const nextWord = getNextWord(word);
if (nextWord === "") {
alert("あなたの勝ちです!");
return;
}
// 次の単語を表示
document.getElementById("nextWord").textContent = nextWord;
document.getElementById("inputWord").value = "";
}
function getNextWord(word) {
const lastChar = word.charAt(word.length-2);
const url = "https://api.wordnik.com/v4/words.json/randomWord?hasDictionaryDef=true&minCorpusCount=0&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=-1&includePartOfSpeech=noun%2Cadjective%2Cverb%2Cadverb%2Cinterjection&excludePartOfSpeech=family-name%2Cgiven-name%2Cabbreviation%2Caffix%2Carchaic%2Carticle%2Cauxiliary-verb%2Cconjunction%2Ccontraction%2Cdefinite-article%2Cfamily-name%2Cgiven-name%2Cidiom%2Cimperative%2Cinterrogative%2Cnoun-plural%2Cnoun-posessive%2Cpast-participle%2Cphrasal-prefix%2Cpreposition%2Cpronoun%2Cproper-noun%2Cproper-noun-plural%2Cproper-noun-posessive%2Csuffix%2Cverb-intransitive%2Cverb-transitive%2Cvulgar%2Cword-form&minCorpusFrequency=-1&maxCorpusFrequency=-1&minDictionaryFrequency=-1&maxDictionaryFrequency=-1&orderBy=count&limit=100&api_key=YOUR_API_KEY_HERE";
// APIリクエストを送信して単語を取得
let wordObj;
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
wordObj = JSON.parse(xhttp.responseText);
}
};
xhttp.open("GET", url, false);
xhttp.send();
const nextWord = wordObj.word;
const nextWordLastChar = nextWord.charAt(nextWord.length-2);
// 最後の文字が「ん」なら再帰処理で別の単語を生成
if (nextWordLastChar === "ん" || nextWordLastChar === "ン") {
return getNextWord(word);
}
// 正しい単語なら返す
return nextWord;
}
</script>
</head>
<body>
<h1>しりとりゲーム</h1>
<p>前回入力された単語の後ろから2文字目と同じ文字から始まる単語を考えて入力してください。</p>
<input type="text" id="inputWord">
<button type="button" onclick="play()">次の単語を生成</button>
<p>次の単語: <span id="nextWord"></span></p>
<p>注意: 「ん」で終わる単語は使えません。</p>
</body>
</html>