<html lang="ja">
<head>
<title>神経衰弱</title>
</head>
<script src="main.js"></script>
<body>
<style>
.omote {
width: 100px;
height: 140px;
border: 1px solid red;
border-radius: 5px;
text-align: center;
font-size: 36px;
box-shadow: rgb(100, 100, 100) 2px 2px;
}
.ura {
background-color: black;
border: 0px solid black;
}
</style>
<table id="field"></table>
<h2><span id="time">0</span>秒経過</h2>
</body>
</html>
let timer = NaN; // クリアまでの時間計測用タイマー
let start = null; // ゲーム開始時刻
let modosuTime = NaN; // 裏に戻すためのタイマー
let itimaimeCard = null; // 1枚目に裏返したカード
let score = 0;
// 初期化関数
function init() {
let table = document.getElementById("field");
let cards = []; // カード格納用配列
for (let a = 1; a <= 10; a++) {
cards.push(a);
cards.push(a);
}
cards.shuffle(); // カードをシャッフル
for (let i = 0; i < 4; i++) {
let itiretu = document.createElement("tr");
for (let j = 0; j < 5; j++) {
let itimai = document.createElement("td");
itimai.className = "omote ura";
itimai.number = cards[i * 5 + j];
itiretu.appendChild(itimai);
itimai.onclick = uragaesu;
}
table.appendChild(itiretu);
}
start = new Date(); // ゲーム開始時刻を保存
timer = setInterval(kousin, 1000); // タイマー開始
}
//経過時間計測用タイマー(1秒ごとに実行)
function kousin() {
let now = new Date();
let keika = Math.floor((now.getTime() - start.getTime()) / 1000);
document.getElementById("time").textContent = keika; // 経過時刻を表示
}
// 配列シャッフル
Array.prototype.shuffle = function () {
let i = this.length;
while (i) {
let j = Math.floor(Math.random() * i);
let t = this[--i];
this[i] = this[j];
this[j] = t;
}
return this;
};
// カード裏返し
function uragaesu(e) {
let clicked = e.target;
if (modosuTime || clicked.textContent !== "") {
return;
}
let nowNumber = clicked.number;
clicked.className = "omote";
clicked.textContent = nowNumber;
if (itimaimeCard == null) {
itimaimeCard = clicked;
return;
}
if (itimaimeCard.number === nowNumber) {
if (++score === 10) {
clearInterval(timer);
}
itimaimeCard = null;
clearTimeout(modosuTime);
} else {
modosuTime = setTimeout(function () {
itimaimeCard.textContent = "";
itimaimeCard.className = "omote ura";
clicked.textContent = "";
clicked.className = "omote ura";
modosuTime = NaN;
itimaimeCard = null;
}, 1000);
}
}
window.addEventListener("load", init);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.