しりとり地名アプリ
以下のテキストボックスに「しりとり」で使える日本の地名を入力してください。
以下が、ユーザーの要望に合わせたアプリです。
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>しりとり地名アプリ</title>
</head>
<body>
<h1>しりとり地名アプリ</h1>
<p>以下のテキストボックスに「しりとり」で使える日本の地名を入力してください。</p>
<input type="text" id="cityname" onkeyup="searchCityName()" autofocus>
<br>
<p id="result"></p>
<script>
function searchCityName() {
const inputCity = document.getElementById("cityname").value.trim().toLowerCase();
const url = "https://www.tt.rim.or.jp/~ishato/tiri/cities/cities.txt";
fetch(url)
.then(response => {
if (response.ok) {
return response.text();
} else {
throw new Error("Network response was not ok.");
}
})
.then(data => {
const cityList = data.split("\n");
const lastAlphabet = inputCity.charAt(inputCity.length - 1);
const lastIndex = cityList.findIndex(element => element.trim().toLowerCase().startsWith(lastAlphabet));
let searchResult = "";
if (lastIndex !== -1) {
let i = lastIndex;
while (i < cityList.length) {
const cityName = cityList[i].trim();
const firstAlphabet = cityName.charAt(0);
if (firstAlphabet === lastAlphabet && cityName !== inputCity && cityName.length >= 2) {
searchResult = cityName;
break;
}
i++;
}
if (searchResult === "") {
searchResult = "あなたの勝ちです!";
}
} else {
searchResult = "すべての地名にしりとりできる語尾の都市名は存在しません。";
}
document.getElementById("result").innerHTML = searchResult;
})
.catch(error => {
console.error("There was a problem with fetch operation:", error);
document.getElementById("result").innerHTML = "エラーが発生しました。";
});
}
</script>
</body>
</html>
```
このアプリは、Fetch APIを使って指定されたサイトから日本の地名のリストを取得し、ユーザーが入力した地名をしりとりで続けることができるかどうかチェックし、適切な応答を返します。入力した地名の語尾から始まる日本の地名が見つかれば、その地名を返し、見つからなければ「あなたの勝ちです!」という応答を返します。語尾から始まる地名がない場合、「すべての地名にしりとりできる語尾の都市名は存在しません。」という応答を返します。
プログラムの最後にエラー処理を追加しました。もしFetch APIでエラーが発生した場合、「エラーが発生しました。」という応答を返します。
注意点として、Fetch APIを使っているため、このアプリはクロスドメイン制限に遭遇する可能性があることに注意してください。これは、同一オリジンポリシーに違反している可能性があるためです。もしクロスドメイン制限が問題となる場合は、別の方法で地名のリストを取得する必要があります。