| 13 | |
| 14 | |
| 15 | async function main() { |
| 16 | console.log('Fast Draw, by Al Sweigart al@inventwithpython.com'); |
| 17 | console.log(); |
| 18 | console.log('Time to test your reflexes and see if you are the fastest'); |
| 19 | console.log('draw in the west!'); |
| 20 | console.log('When you see "DRAW", you have 0.3 seconds to press Enter.'); |
| 21 | console.log('But you lose if you press Enter before "DRAW" appears.'); |
| 22 | console.log(); |
| 23 | readlineSync.question('Press Enter to begin...'); |
| 24 | |
| 25 | while (true) { |
| 26 | console.log(); |
| 27 | console.log('It is high noon...'); |
| 28 | await sleep(Math.random() * 3 + 2); |
| 29 | console.log('DRAW!'); |
| 30 | let drawTime = Date.now(); |
| 31 | readlineSync.question(); // This function call doesn't return until Enter is pressed. |
| 32 | let timeElapsed = (Date.now() - drawTime) / 1000; |
| 33 | |
| 34 | if (timeElapsed < 0.01) { |
| 35 | // If the player pressed Enter before DRAW! appeared, the input() |
| 36 | // call returns almost instantly. |
| 37 | console.log('You drew before "DRAW" appeared! You lose.'); |
| 38 | } else if (timeElapsed > 0.3) { |
| 39 | timeElapsed = Math.trunc(timeElapsed * 10000) / 10000; |
| 40 | console.log('You took', timeElapsed, 'seconds to draw. Too slow!'); |
| 41 | } else { |
| 42 | timeElapsed = Math.trunc(timeElapsed * 10000) / 10000; |
| 43 | console.log('You took', timeElapsed, 'seconds to draw.'); |
| 44 | console.log('You are the fastest draw in the west! You win!'); |
| 45 | } |
| 46 | |
| 47 | console.log('Enter QUIT to stop, or press Enter to play again.'); |
| 48 | let response = readlineSync.question('> ').toUpperCase(); |
| 49 | if (response === 'QUIT') { |
| 50 | console.log('Thanks for playing!'); |
| 51 | return; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | main(); |