From 718734f048ea7db2c1eb4dd83cb2c122bca1857a Mon Sep 17 00:00:00 2001 From: Chris Kozlowski Date: Thu, 13 Jun 2019 16:50:16 -0700 Subject: [PATCH] refactor timer to run independantly client-side --- src/lib/game.js | 49 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/src/lib/game.js b/src/lib/game.js index b7118e8..0f02eef 100644 --- a/src/lib/game.js +++ b/src/lib/game.js @@ -22,8 +22,33 @@ class Game { //Morgana - use deployed link this.socket = client.connect(SOCKET_SERVER_URL); this.count = 1; + this.timeLeft = 20; + this.countdown = null; + this.decrement = this.decrement.bind(this); } + decrement() { + this.timeLeft--; + this.drawTimer(this.timeLeft); + } + + drawTimer(timeLeft) { + process.stdout.write(ansiEscapes.cursorSavePosition); + process.stdout.write(ansiEscapes.cursorPrevLine); + process.stdout.write(ansiEscapes.cursorPrevLine); + process.stdout.clearLine(); + process.stdout.write('Your Turn!'); + process.stdout.write(ansiEscapes.cursorNextLine); + process.stdout.clearLine(); + if (timeLeft >= 0) { + process.stdout.write('Time left: '); + process.stdout.write(timeLeft.toString()); + if (timeLeft < 10) { + process.stdout.write(' <-- Time\'s almost up, hurry!'); + } + } + process.stdout.write(ansiEscapes.cursorRestorePosition); + } /** * Start listening for events from the server */ @@ -38,24 +63,12 @@ class Game { this.socket.on('turn', payload => { // process.stdout.write(ansiEscapes.clearScreen); this.showPrompt(payload); + this.countdown = setInterval(this.decrement, 1000, this.timeLeft); }); - this.socket.on('countdown', payload => { - process.stdout.write(ansiEscapes.cursorSavePosition); - process.stdout.write(ansiEscapes.cursorPrevLine); - if (this.count === 2) { - process.stdout.write(ansiEscapes.cursorPrevLine); - } - process.stdout.clearLine(); - if (payload >= 0) { - process.stdout.write('Time left: '); - process.stdout.write(payload.toString()); - if (payload < 10) { - process.stdout.write(' <-- Time\'s almost up, hurry!'); - } - } - process.stdout.write(ansiEscapes.cursorRestorePosition); - }); + // this.socket.on('countdown', payload => { + // this.timeLeft = payload; + // }); this.socket.on('game over', payload => { console.log('Game Over!'); @@ -82,7 +95,7 @@ class Game { //Morgana - payload at 0 is the game id, payload at 1 is the message console.log(payload[1]); console.log('Your Turn!'); - console.log('Time left: ', 20); + console.log('Time left: 20'); const gameID = payload[0]; const questions = [ { @@ -104,6 +117,8 @@ class Game { this.socket.close(); }); if (this.checkChoices(response.stack, response.amount, payload[1])) { + clearInterval(this.countdown); + this.timeLeft = 20; this.socket.emit('move', [gameID, response.stack, response.amount]); this.count = 1; } else {