JavaScriptでタイピングゲームを作る
2019/06/25

この記事を書いている人 - WRITER -
JavaScriptのミニアプリはドットインストールで学習出来ます。今回はタイピングゲームです。3秒間にどれだけ正確にタイプできるかを測るアプリです。index.html, styles.css, main.jsの3つのソースコードを作ればよく、実装、デバッグのコツはつかめてきました。講座の中では、問題点に対する原因と対策がすぐにわかる事になっているが、自力で作るアプリではバグを見つけ解消することが簡単ではないと思う。そのためにも講義をしっかり聞いて引き出しを増やしていきたい。
【完成時のソースコード】
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Typing Game</title> <link rel="stylesheet" href="css/styles.css"> </head> <body> <p id="target">click to start</p> <p class="info"> Letter count: <span id="score">0</span>, Miss count: <span id="miss">0</span>, Time left: <span id="timer">0</span> </p> <script src="js/main.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
body { padding-top: 40px; font-family: 'Courier New', monospace; text-align: center; } #target { font-size: 48px; letter-spacing: 3px; } .info { color: #ccc; } |
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 |
'use strict'; { const words = [ 'apple', 'sky', 'blue', 'middle', 'set', ]; let word; let loc; let score; let miss; const timeLimit = 3 * 1000; let startTime; let isPlaying = false; const target = document.getElementById('target'); const scoreLabel = document.getElementById('score'); const missLabel = document.getElementById('miss'); const timerLabel = document.getElementById('timer'); function updateTarget() { let placeholder = ''; for (let i = 0; i < loc; i++) { placeholder += '_'; } target.textContent = placeholder + word.substring(loc); } function showResult() { const accuracy = score + miss === 0 ? 0 : score / (score + miss) * 100; alert(`${score} letters, ${miss} misses, ${accuracy.toFixed(2)}% accuracy!`); } function updateTimer() { const timeLeft = startTime + timeLimit - Date.now(); timerLabel.textContent = (timeLeft / 1000).toFixed(2); const timeoutId = setTimeout(() => { updateTimer(); }, 10); if (timeLeft < 0) { isPlaying = false; clearTimeout(timeoutId); setTimeout(() => { showResult(); }, 100); timerLabel.textContent = '0.00'; target.textContent = 'click to replay'; } } window.addEventListener('click', () => { if (isPlaying === true) { return; } isPlaying = true; loc = 0; score = 0; miss = 0; scoreLabel.textContent = score; missLabel.textContent = miss; word = words[Math.floor(Math.random() * words.length)]; updateTarget(); startTime = Date.now(); updateTimer(); }); window.addEventListener('keyup', e => { if (isPlaying !== true) { return; } if (e.key === word[loc]) { loc++; if (loc === word.length) { word = words[Math.floor(Math.random() * words.length)]; loc = 0; } score++; scoreLabel.textContent = score; updateTarget(); } else { miss++; missLabel.textContent = miss; } }); } |
この記事を書いている人 - WRITER -