From 62cd43fa60052525cbfe7fc39337375564ff9ea6 Mon Sep 17 00:00:00 2001 From: Diganta Regmi Date: Wed, 1 May 2024 23:02:40 -0500 Subject: [PATCH] Added functionality for timer --- html/game.js | 38 +++++++++++++++++++++++++++++ html/index.html | 10 ++++++++ src/main/java/uta/cse3310/Game.java | 3 +++ 3 files changed, 51 insertions(+) diff --git a/html/game.js b/html/game.js index 97ef7eb..fc5322b 100644 --- a/html/game.js +++ b/html/game.js @@ -9,6 +9,9 @@ class Game { this.playersList = document.querySelector(".players-list"); this.preGameLobby = this.gamePageDiv.querySelector(".pre-game-lobby"); this.selectedCells = []; + this.timerDisplay = document.getElementById("timerDisplay"); + this.timer = null; + this.gameDuration = 180; // Event listeners for game actions this.startButton.addEventListener("click", () => this.startGameClicked()); @@ -20,8 +23,43 @@ class Game { gameId: this.gameId, }; this.app.websocket.send(JSON.stringify(startGameMessage)); + this.startTimer(this.gameDuration); + } + startTimer(duration) { + let timer = duration, minutes, seconds; + this.timer = setInterval(() => { + minutes = parseInt(timer / 60, 10); + seconds = parseInt(timer % 60, 10); + + minutes = minutes < 10 ? "0" + minutes : minutes; + seconds = seconds < 10 ? "0" + seconds : seconds; + + this.timerDisplay.textContent = minutes + ":" + seconds; + + if (--timer < 0) { + clearInterval(this.timer); + this.timerEnded(); + } + }, 1000); + } + + timerEnded() { + console.log("Timer ended. Game over."); + this.endGame(); + const timeUpMessage = { + action: "timeUp", + gameId: this.gameId + }; + this.app.websocket.send(JSON.stringify(timeUpMessage)); + } + + endGame() { + console.log("End the game on the client side."); + clearInterval(this.timer); // Make sure the timer stops when the game ends + } + updateGamePage(data) { this.gameGrid.classList.remove("hidden"); this.preGameLobby.classList.add("hidden"); diff --git a/html/index.html b/html/index.html index 1590ef9..a34c8a4 100644 --- a/html/index.html +++ b/html/index.html @@ -59,6 +59,16 @@

Available Games

+
+ +
+

Time Remaining:

+ 03:00 +
+ +
+ +

Global Chat

diff --git a/src/main/java/uta/cse3310/Game.java b/src/main/java/uta/cse3310/Game.java index a8f30c5..9890247 100644 --- a/src/main/java/uta/cse3310/Game.java +++ b/src/main/java/uta/cse3310/Game.java @@ -100,6 +100,8 @@ public boolean isGameActive() { private void endGame() { this.gameActive = false; this.listener.onGameEnded(this); + System.out.println("Game ended: " + name); + timer.shutdown(); } @@ -107,5 +109,6 @@ public void startGame() { this.gameActive = true; timer = Executors.newSingleThreadScheduledExecutor(); timer.schedule(this::endGame, gameDuration, TimeUnit.SECONDS); + System.out.println("Game started: " + name + ". It will end in " + gameDuration + " seconds."); } }