-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathGameTimer.java
More file actions
71 lines (54 loc) · 2.42 KB
/
GameTimer.java
File metadata and controls
71 lines (54 loc) · 2.42 KB
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
package co.ppg2.services;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.Map;
public class GameTimer implements Runnable {
private final Map<String, Long> playerTotalTime; // Total time spent by each player
private final Map<String, Integer> playerMoves; // Number of moves made by each player
private String currentPlayer; // Current player whose time is being tracked
private long startTime; // Start time of the current player's move
private boolean running; // Timer state
public GameTimer() {
playerTotalTime = new HashMap<>();
playerMoves = new HashMap<>();
running = false;
}
// Starts the timer for the current player
public synchronized void startTimer(String playerName) {
if (running) cancelTimer();
currentPlayer = playerName;
startTime = System.currentTimeMillis();
running = true;
new Thread(this).start(); // Start the timer thread
}
// Stops the timer and records the elapsed time
public synchronized void cancelTimer() {
if (!running) return;
long elapsedTime = System.currentTimeMillis() - startTime;
playerTotalTime.put(currentPlayer, playerTotalTime.getOrDefault(currentPlayer, 0L) + elapsedTime);
playerMoves.put(currentPlayer, playerMoves.getOrDefault(currentPlayer, 0) + 1);
running = false;
}
// Computes the average time per move for a player
public synchronized double getAverageTimePerMove(String playerName) {
long totalTime = playerTotalTime.getOrDefault(playerName, 0L);
int moves = playerMoves.getOrDefault(playerName, 0);
return moves == 0 ? 0.0 : (totalTime / (double) moves) / 1000.0; // Convert to seconds
}
//TODO: Could add a pause button to pause the timer and resume once the button is pressed again. Would need to add the button in GameView
@Override
public void run() {
while (running) {
try {
Thread.sleep(500); // Update every half second if needed
Platform.runLater(() -> {
// Update GUI components if needed in future
});
// simple add to log loop status
System.out.println("Timer is running..."); // log message in each iteration
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}