簡単なHTML+JS+CSSでも、タイピングゲームは作れる!わりとシンプルなCSS/JSで実装出来るもんだな~。
ブラウザだけで実行できるので、ローカルのデスクトップでも動作する。
動作デモ
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 |
<!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"> 正解の文字数: <span id="score">0</span>, ミスした文字数: <span id="miss">0</span>, 残り時間: <span id="timer">0.00</span> </p> <script src="js/main.js"></script> </body> <style> body { /* 上から少し離して、中央に文字を置く */ padding-top: 40px; text-align: center; /* 等幅フォントにして文字の横幅を統一する */ font-family: 'Courier New', monospace; } #target { /* タイプする英単語は大きく! */ font-size: 48px; /* 1文字ずつの間隔を少し開ける */ letter-spacing: 3px; } .info { /* 正解の文字数・ミスした文字数・残り時間の色 */ color: #444; } </style> <script> 'use strict'; { // 中学で習う英単語(1500弱)。意外と難しいのもある! const words = ["a","able","about","above","abroad","absent","accept","accident","according","across","act","add","address","aerobics","afraid","africa","after","afternoon","again","against","age","ago","agree","ahead","air","airplane","airport","album","all","almost","alone","along","already","also","always","am","ambulance","america","american","among","an","and","angry","animal","another","answer","any","anybody","anyone","anything","apartment","appear","apple","apricot","april","apron","arch","are","arm","around","arrive","art","artist","as","asia","ask","at","attention","august","aunt","australia","australian","autumn","away","awful","axe","baby","back","backward","bad","badly","bag","bald","ball","bank","barber","baseball","basket","basketball","bat","bat","bath","bathroom","be","bestuck","beach","beachvolleyball","bear","beautiful","beauty","because","become","bed","bedroom","before","begin","behind","believe","bell","belong","below","bench","berry","beside","best","better","between","bicycle","big","billion","bird","birthday","bite","black","blink","blow","blue","boardwalk","boat","body","book","bored","borrow","both","bottle","bottom","bough","box","boy","brave","bread","break","breakfast","breathe","breeze","bridge","bright","bring","british","broom","brother","brown","brush","bud","buggy","build","building","bull","bumpy","bun","burn","bus","busy","but","butter","butterfly","button","buy","by","cake","calendar","call","camel","camp","can","canopener","can't","canada","canadian","cap","capital","captain","car","card","care","careful","carefully","careless","carpet","carry","case","cat","catch","cause","cent","center","centimeter","central","century","certain","chair","chalk","chance","change","cheap","cherry","chicken","child","children","chimney","chin","china","chinese","chocolate","choose","christmas","church","circle","city","class","classmate","classroom","clean","clear","clever","climb","clock","close","closet","cloth","clothes","cloud","cloudy","club","coast","coat","coffee","coffeetable","coin","cold","collect","college","color","come","comfortable","common","complain","computer","concert","condition","contact","contest","continent","continue","cook","cookie","cool","cord","corner","correct","cost","cough","count","countries","country","couple","course","cousin","cover","cow","crash","cream","create","cross","crowd","crush","cry","cucumber","culture","cup","curly","custom","cut","cute","dad","damage","dance","danger","dangerous","dark","darkness","date","daughter","day","dead","dear","death","december","decide","deep","deer","delicious","deliver","departmentstore","deposit","desert","design","desire","desk","destroy","diary","dictionary","die","different","difficult","dime","diningroom","dinner","dirty","disappear","discover","discuss","dish","distance","do","doctor","does","dog","doll","dollar","door","dot","down","downstairs","draw","dream","dress","drink","drive","drop","dry","during","duty","each","ear","early","earth","earthquake","easily","east","easter","easy","eat","egg","eggplant","eight","eighteen","eighteenth","eighth","eighty","either","elbow","electric","elephant","eleven","eleventh","else","empty","end","energy","engine","england","english","englishman","enjoy","enough","enter","entrance","entrancehall","eraser","escalator","europe","european","even","evening","event","ever","every","everybody","everyday","everyone","everything","examination","examine","example","except","excited","exciting","excuse","exercise","exist","exit","expect","expensive","explain","export","eye","face","factory","fail","fair","fall","family","famous","fan","far","farm","farmer","fast","fat","father","father'sday","fault","favor","favorite","february","feel","feet","fence","ferry","few","field","fifteen","fifth","fifty","fight","fill","final","finally","find","fine","finger","finish","fire","fireengine","firefighter","first","fish","fit","five","fix","flag","flamingo","flat","float","floor","flow","flower","flowershop","flute","fly","fold","follow","fond","food","foolish","foot","for","forehead","foreign","foreigner","forest","forever","forget","fork","form","forty","forward","four","fourteen","fourth","fox","france","free","freedom","freeway","french","fresh","friday","friend","friendly","from","front","fruit","full","fun","funny","future","game","garage","garden","gate","geese","gentleman","german","germany","get","getchanged","getoff","geton","getup","ghost","gift","girl","give","glad","glass","glove","go","gotoschool","goal","goat","god","gold","golf","good","good-by","goose","government","grade","graduation","grammar","grandfather","grandmother","grass","gray","great","green","greenpepper","ground","group","grow","guess","guest","guide","guitar","gun","hair","half","hall","halloween","hand","handkerchief","hang","happen","happiness","happy","hard","harmony","has","hat","have","he","head","headache","hear","heart","heat","heavy","height","hello","help","hen","her","here","hers","herself","hi","hide","high","hill","him","himself","his","history","hit","hobby","hockey","hold","holiday","home","homework","honest","honesty","honor","hop","hope","horse","hospital","hot","hotel","hour","house","how","however","human","humor","hundred","hungry","hurry","hurt","husband","i","ice","icecream","idea","if","ill","imagination","imagine","important","impossible","impress","impression","in","inch","independence","independenceday","independent","india","indian","information","ink","inside","interest","interested","interesting","international","intersection","into","introduce","invite","iron","is","island","it","italian","italy","itch","its","itself","january","japan","japanese","jeans","jetski","job","jogging","join","journey","judge","juggle","juice","july","jump","june","junior","just","keep","kenya","key","kick","kill","kilometre","kind","kindness","king","kiss","kitchen","knee","kneel","knife","knit","knock","know","korea","ladder","lady","lake","lamp","land","language","large","last","late","lately","later","laugh","law","lead","leaf","lean","learn","least","leave","leaves","lecture","left","leg","lend","less","lesson","let","let's","letter","lettuce","library","lie","lie","life","lift","light","like","likely","line","listen","litter","little","live","livingroom","local","lonely","long","look","lose","lot","loud","loudly","love","low","lucky","luggage","lunch","machine","mad","magazine","mail","mailbox","make","man","manage","mango","manner","many","map","march","mark","market","marry","mask","master","mat","mathematics","matter","may","may","maybe","me","meal","mean","meat","medicine","meet","meeting","member","memorial","men","mention","merry","message","messy","metre","middle","midnight","mile","milk","million","mind","mine","minute","mirror","miss","mistake","mitt","modern","mom","moment","monday","money","monkey","monorail","month","moon","more","morning","most","mother","mother'sday","motorbike","mountain","mouse","mouth","move","movie","mr.","mrs.","much","museum","music","musical","must","my","myself","nail","name","napkin","narrow","natural","nature","near","nearly","necessary","neck","need","neighbor","never","new","newyear","newzealand","news","newspaper","newspaperstand","next","nice","nickel","night","nine","nineteen","ninety","ninth","no","nobody","nod","noise","noisy","none","noon","north","nose","not","notyet","notebook","nothing","notice","november","now","number","nurse","o'clock","october","of","ofcourse","off","office","official","often","oil","ok","old","on","once","one","onion","only","open","opinion","or","orange","order","origin","other","ouch","our","ours","ourselves","out","outside","over","owl","own","page","paint","painter","pair","paper","pardon","parent","park","parkinglot","parliament","part","party","pass","past","paste","pat","pause","pay","peace","pen","pencil","pencilsharpener","penny","people","perhaps","person","pet","phone","piano","pick","pickup","picnic","picture","pie","piece","pier","pig","pineapple","place","plan","plane","plate","play","player","please","pleasure","plenty","plug","plum","pocket","poem","point","police","policeofficer","policeman","polite","pond","pool","poor","popular","possible","post","potato","power","practice","prepare","present","present","president","pretty","prevent","price","principal","print","private","problem","professional","program","promise","protect","proud","public","pull","pupil","pure","purple","push","put","quarter","quarterto3","quartertoten","queen","question","quickly","quiet","quite","quiz","rabbit","race","race","racket","radio","railroad","rain","rainbow","rainy","raise","rat","reach","read","ready","real","really","reason","receive","record","red","refrigerator","refuse","remain","remember","repeat","report","rest","restaurant","return","rice","rich","ride","right","ring","ring","rise","river","road","rock","rockgarden","roll","roof","room","round","row","rub","rug","rule","run","rush","sad","safe","safely","sail","sailor","salt","salty","same","sand","sandwich","saturday","save","saw","saxophone","say","scared","scarf","scary","scene","school","schoolbus","science","scientist","scissors","sea","season","seat","second","secret","see","seed","seem","sell","send","sense","sentence","september","serious","seriously","serve","service","set","seven","seventhirty","seventeen","seventeenth","seventh","seventy","several","sh!","shake","shall","shallow","share","shawl","she","sheep","shine","ship","shirt","shoe","shoot","shop","shoppingmall","short","should","shoulder","shout","show","shower","shut","sick","sickness","side","sight","sign","signal","silent","silver","simple","since","sing","sink","siren","sister","sit","six","sixteen","sixth","sixty","size","skate","skateboard","ski","skunk","sky","sleep","sleepy","slide","slow","slowly","small","smell","smile","smoke","snow","so","soccer","sock","soda","sofa","soft","some","somebody","someone","something","sometimes","son","song","soon","sorry","sort","sound","sour","south","space","spain","spanish","speak","special","speech","speed","spend","spoon","sport","spring","square","stair","stamp","stand","star","start","state","station","stay","steal","step","stick","stickon","still","stir","stomachache","stone","stop","store","story","straight","strange","stranger","street","streetcar","stretch","strike","strong","student","study","subject","subtract","suburb","success","such","suddenly","sugar","summer","summerholiday","sun","sunday","sunny","sunrise","sunset","support","suppose","sure","surfing","surprise","sweater","sweet","swim","swimming","table","tail","take","tale","talk","tall","taste","tea","teach","teacher","team","tear","tear","teeth","tell","temple","ten","tennis","tenth","terrible","test","than","thank","thanksgiving","that","the","theater","their","theirs","them","themselves","then","there","these","they","thin","thing","think","third","thirsty","thirteen","thirteenth","thirty","this","those","though","thousand","three","through","throw","thursday","tie","tight","till","time","tire","tired","to","today","toe","together","tomato","tomorrow","tonight","too","tooth","toothache","toothbrush","toothpaste","top","touch","tough","toward","towel","tower","town","toy","traffic","train","travel","tree","trip","trouble","truck","true","truth","try","tuesday","turn","turnoff","turnon","turtle","tv","twelfth","twelve","twenty","twice","two","ugly","umbrella","uncle","under","understand","unitedstates","universe","university","until","up","upsidedown","upstairs","us","use","useful","usual","usually","vacation","valentine'sday","valley","variety","vase","vat","vegetable","very","village","violin","visit","voice","volleyball","wait","wake","wakeup","walk","wall","wallet","want","war","warm","wash","watch","water","waterski","waterfall","wave","wavy","way","we","weak","wear","weather","wednesday","week","weight","welcome","well","west","wet","what","when","where","which","while","whistle","white","who","whole","whose","why","wide","wife","wild","will","win","wind","window","wink","winter","wipe","wise","wish","with","without","woman","women","wonder","wonderful","wood","word","work","workout","world","worry","worse","worst","would","write","wrong","yachtharbor","yard","year","yellow","yes","yesterday","yet","you","young","your","yours","yourself","yourselves","zoo" ]; let word; // タイプする英単語 let loc; // 文字位置 let score; // 正解した文字数 let miss; // ミスした文字数 const timeLimit = 30 * 1000; // 制限時間。ミリ秒なので×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 updateTimer() { // 開始時間は取得日時を保持しているので、現在時刻との差分で計算する const timeLeft = startTime + timeLimit - Date.now(); timerLabel.textContent = (timeLeft / 1000).toFixed(2); // ピッタリに終わらないので、ちょっとだけ(10ミリ秒)を遊びでもたせる const timeoutId = setTimeout(() => { updateTimer(); }, 10); // 残り時間が無くなったら、クリア処理 if (timeLeft < 0) { isPlaying = false; clearTimeout(timeoutId); timerLabel.textContent = '0.00'; setTimeout(() => { showResult(); }, 100); target.textContent = 'click to replay'; } } // 結果表示 function showResult() { const accuracy = score + miss === 0 ? 0 : score / (score + miss) * 100; alert(`正解した文字数: ${score} , ミスした文字数${miss} , 正答率: ${accuracy.toFixed(2)}% !`); } // スターボタン(click to start)を押されたら 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)]; target.textContent = word; startTime = Date.now(); updateTimer(); }); // キーボードを押された時の処理 window.addEventListener('keydown', 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; } updateTarget(); score++; // 1アルファベット文字=1点 scoreLabel.textContent = score; } else { miss++; missLabel.textContent = miss; } }); } </script> </html> |