Home
About
Resume
Projects
Links
Blog
Back to Contents
# Mini Web Game - Swimming Start Reaction Time #### Background - On a certain day, my brother and I played a reaction time testing game. He thought this kind of game might be a good tool for training his reaction time for swimming start. (He is like top-10 swimmer at his age in Hong Kong.) - However, there is not much reaction time testing game using sound as the trigger, not to say having the "on your mark" and "beep" sound. - We cannot find one, so we build one. #### Code 1\. Create `audio` tag for playing the *"on your mark"* and *"beep"* sound: ```html
``` 2\. Create the buttons and time display area: ```html
I AM READY
JUMP
NO TIME
``` 3\. Define the game logic ```javascript const readyDuration = 1500; const minTime = 500; const maxTime = 2000; var gameTime = 0; var gameTimeCounter = false; var allowJump = false; var timeHistory = [] function zeroPad(num, places){ return String(num).padStart(places, '0') } function msToHMS(d) { ms = zeroPad(Number(d)*5%1000, 3) d = Number(d)/200 let h = Math.floor(d / 3600) let m = Math.floor(d % 3600 / 60) let s = Math.floor(d % 3600 % 60) let hms = "" if(h*60+m > 0){ hms += `${h*60+m}'` } hms += `${s}.${ms}"` return hms } function getRandomNumber(rangeFrom, rangeTo){ return Math.random()*(rangeTo-rangeFrom)+rangeFrom } function triggerReady(){ if(allowJump){ return } clearInterval(gameTimeCounter); gameTimeCounter = false; gameTime = 0; allowJump = true; document.getElementById('ready-sound').play(); setTimeout(()=>{ triggerStart(); },readyDuration+getRandomNumber(minTime,maxTime)) } function triggerStart(){ document.getElementById('starting-sound').play(); gameTimeCounter = setInterval(()=>{ gameTime++ },5) } function showTime(time){ document.getElementById('time-display').innerHTML = time; } function jump(){ if(!gameTimeCounter || !allowJump){ document.getElementById('time-display').innerHTML = "DSQ" clearInterval(gameTimeCounter); gameTimeCounter = false; allowJump = false; timeHistory.push(msToHMS(0)); }else{ let currTime = msToHMS(gameTime) clearInterval(gameTimeCounter); gameTimeCounter = false; allowJump = false; showTime(currTime); timeHistory.push(currTime); } } ``` #### Demo **Link:** https://lomanhei.com/apps/swimming-reaction/
Previous Post:
Color Ball Sorting
Next Post:
Google Code Jam Qualification Round Q4
Loading