File size: 9,918 Bytes
6a7997c
 
 
 
 
 
ed2ca9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a7997c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed2ca9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a7997c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed2ca9d
 
 
 
 
 
 
 
 
 
 
 
 
6a7997c
 
 
 
 
ed2ca9d
 
 
6a7997c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed2ca9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3b3029
ed2ca9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a7997c
 
 
 
 
 
 
 
 
 
 
e3b3029
ed2ca9d
 
 
 
 
 
 
 
6a7997c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
(function(){
  const canvas = document.getElementById('gameCanvas');
  const ctx = canvas.getContext('2d');
  const targetSpan = document.getElementById('target');
  const startBtn = document.getElementById('startBtn');
  const messageDiv = document.getElementById('message');
  const modeRadios = document.querySelectorAll('input[name="mode"]');
  const difficultyDiv = document.getElementById('difficultySelect');
  const difficultyRadios = document.querySelectorAll('input[name="difficulty"]');
  modeRadios.forEach(radio => {
    radio.addEventListener('change', () => {
      if (document.querySelector('input[name="mode"]:checked').value === 'vsAI') {
        difficultyDiv.style.display = 'block';
      } else {
        difficultyDiv.style.display = 'none';
      }
    });
  });
  const scoresDiv = document.getElementById('scores');
  const playerScoreSpan = document.getElementById('playerScore');
  const aiScoreSpan = document.getElementById('aiScore');
  let gameMode = 'single';
  let playerScore = 0;
  let aiScore = 0;
  let aiTimeout = null;
  let aiAccuracy;
  const AI_EASY_ACCURACY = 0.3;
  const AI_HARD_ACCURACY = 0.7;
  const aiMinDelay = 500;
  const aiMaxDelay = 2000;
  let items = [];
  let remaining = [];
  let currentTarget = null;
  const count = 30;
  const fontSize = 24;
  ctx.textBaseline = 'alphabetic';
  ctx.font = fontSize + 'px sans-serif';

  function isOverlapping(x, y, w, h, arr) {
    return arr.some(item => {
      return x < item.x + item.width &&
             x + w > item.x &&
             y - h < item.y &&
             y > item.y - item.height;
    });
  }

  function initGame() {
    items = [];
    messageDiv.textContent = '';
    messageDiv.className = '';
    targetSpan.textContent = '--';
    gameMode = document.querySelector('input[name="mode"]:checked').value;
    if (gameMode === 'vsAI') {
      const difficulty = document.querySelector('input[name="difficulty"]:checked').value;
      aiAccuracy = difficulty === 'easy' ? AI_EASY_ACCURACY : AI_HARD_ACCURACY;
      playerScore = 0;
      aiScore = 0;
      playerScoreSpan.textContent = playerScore;
      aiScoreSpan.textContent = aiScore;
      scoresDiv.style.display = 'block';
    } else {
      scoresDiv.style.display = 'none';
    }
    if (aiTimeout) {
      clearTimeout(aiTimeout);
      aiTimeout = null;
    }
    for (let i = 1; i <= count; i++) {
      const text = i.toString();
      const metrics = ctx.measureText(text);
      const width = metrics.width;
      const height = fontSize;
      let x, y, attempts = 0;
      do {
        x = Math.random() * (canvas.width - width);
        y = Math.random() * (canvas.height - height) + height;
        attempts++;
        if (attempts > 1000) break;
      } while (isOverlapping(x, y, width, height, items));
      const angle = Math.random() * 2 * Math.PI;
      items.push({ num: i, x, y, width, height, angle });
    }
    remaining = items.slice();
    drawAll();
    pickNext();
  }

  function drawAll() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#000';
    remaining.forEach(item => {
      ctx.save();
      const cx = item.x + item.width / 2;
      const cy = item.y - item.height / 2;
      ctx.translate(cx, cy);
      ctx.rotate(item.angle);
      ctx.fillText(item.num, -item.width / 2, item.height / 2);
      ctx.restore();
    });
  }

  function pickNext() {
    if (remaining.length === 0) {
      currentTarget = null;
      targetSpan.textContent = '--';
      messageDiv.className = 'clear';
      if (gameMode === 'vsAI') {
        if (aiTimeout) {
          clearTimeout(aiTimeout);
          aiTimeout = null;
        }
        let resultText = '';
        if (playerScore > aiScore) resultText = 'あなたの勝ち!';
        else if (playerScore < aiScore) resultText = 'AIの勝ち!';
        else resultText = '引き分け!';
        messageDiv.textContent = 'ゲームクリア!結果: あなた ' + playerScore + ' - AI ' + aiScore + ' ' + resultText;
      } else {
        messageDiv.textContent = 'ゲームクリア!';
      }
      return;
    }
    const idx = Math.floor(Math.random() * remaining.length);
    currentTarget = remaining[idx].num;
    targetSpan.textContent = currentTarget;
    if (gameMode === 'vsAI') {
      scheduleAIAttempt();
    }
  }

  function repositionItems() {
    const newItems = [];
    remaining.forEach(orig => {
      const { num, width, height } = orig;
      let x, y, attempts = 0;
      do {
        x = Math.random() * (canvas.width - width);
        y = Math.random() * (canvas.height - height) + height;
        attempts++;
        if (attempts > 1000) break;
      } while (isOverlapping(x, y, width, height, newItems));
      const angle = Math.random() * 2 * Math.PI;
      newItems.push({ num, x, y, width, height, angle });
    });
    return newItems;
  }

  function animateReposition(oldItems, newItems, duration, callback) {
    const startTime = performance.now();
    function animate(time) {
      const t = Math.min((time - startTime) / duration, 1);
      remaining = oldItems.map((oldItem, i) => {
        const newItem = newItems[i];
        return {
          num: oldItem.num,
          width: oldItem.width,
          height: oldItem.height,
          x: oldItem.x + (newItem.x - oldItem.x) * t,
          y: oldItem.y + (newItem.y - oldItem.y) * t,
          angle: oldItem.angle + (newItem.angle - oldItem.angle) * t
        };
      });
      drawAll();
      if (t < 1) requestAnimationFrame(animate);
      else callback();
    }
    requestAnimationFrame(animate);
  }

  function drawRedCircle(item) {
    const cx = item.x + item.width / 2;
    const cy = item.y - item.height / 2;
    const r = Math.max(item.width, item.height) / 2 + 5;
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.stroke();
  }

  function drawRedCross(item) {
    const x1 = item.x;
    const y1 = item.y - item.height;
    const x2 = item.x + item.width;
    const y2 = item.y;
    ctx.strokeStyle = 'red';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.moveTo(x1, y2);
    ctx.lineTo(x2, y1);
    ctx.stroke();
  }
  function drawBlueCircle(item) {
    const cx = item.x + item.width / 2;
    const cy = item.y - item.height / 2;
    const r = Math.max(item.width, item.height) / 2 + 5;
    ctx.strokeStyle = 'blue';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.stroke();
  }
  function drawBlueCross(item) {
    const x1 = item.x;
    const y1 = item.y - item.height;
    const x2 = item.x + item.width;
    const y2 = item.y;
    ctx.strokeStyle = 'blue';
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.moveTo(x1, y2);
    ctx.lineTo(x2, y1);
    ctx.stroke();
  }

  function scheduleAIAttempt() {
    if (aiTimeout) clearTimeout(aiTimeout);
    const delay = aiMinDelay + Math.random() * (aiMaxDelay - aiMinDelay);
    aiTimeout = setTimeout(doAIAttempt, delay);
  }

  function doAIAttempt() {
    aiTimeout = null;
    if (gameMode !== 'vsAI' || currentTarget === null) return;
    const correct = Math.random() < aiAccuracy;
    if (correct) {
      const idx = remaining.findIndex(item => item.num === currentTarget);
      currentTarget = null;
      if (idx === -1) return;
      const item = remaining[idx];
      aiScore++;
      aiScoreSpan.textContent = aiScore;
      messageDiv.className = 'correct';
      messageDiv.textContent = 'AIが正解!';
      drawAll();
      drawBlueCircle(item);
      setTimeout(() => {
        remaining.splice(idx, 1);
        const oldItems = remaining.map(it => ({ ...it }));
        const newItems = repositionItems();
        animateReposition(oldItems, newItems, 1000, () => {
          remaining = newItems;
          pickNext();
        });
      }, 500);
    } else {
      if (remaining.length > 1) {
        const wrongItems = remaining.filter(item => item.num !== currentTarget);
        const wrongItem = wrongItems[Math.floor(Math.random() * wrongItems.length)];
        messageDiv.className = 'wrong';
        messageDiv.textContent = 'AIが間違えた!';
        drawAll();
        drawBlueCross(wrongItem);
        setTimeout(drawAll, 500);
      }
      scheduleAIAttempt();
    }
  }

  canvas.addEventListener('click', e => {
    if (currentTarget === null) return;
    const rect = canvas.getBoundingClientRect();
    const clickX = e.clientX - rect.left;
    const clickY = e.clientY - rect.top;
    for (let i = 0; i < remaining.length; i++) {
      const item = remaining[i];
      if (clickX >= item.x && clickX <= item.x + item.width &&
          clickY <= item.y && clickY >= item.y - item.height) {
        if (item.num === currentTarget) {
          currentTarget = null;
          if (gameMode === 'vsAI') {
            if (aiTimeout) {
              clearTimeout(aiTimeout);
              aiTimeout = null;
            }
            playerScore++;
            playerScoreSpan.textContent = playerScore;
          }
          messageDiv.className = 'correct';
          messageDiv.textContent = '正解!';
          drawAll();
          drawRedCircle(item);
          setTimeout(() => {
            remaining.splice(i, 1);
            const oldItems = remaining.map(it => ({ ...it }));
            const newItems = repositionItems();
            animateReposition(oldItems, newItems, 1000, () => {
              remaining = newItems;
              pickNext();
            });
          }, 500);
        } else {
          messageDiv.className = 'wrong';
          messageDiv.textContent = '違うよ!';
          drawAll();
          drawRedCross(item);
          setTimeout(drawAll, 500);
        }
        return;
      }
    }
  });

  startBtn.addEventListener('click', initGame);
})();