Skip to content

Commit

Permalink
from scynchronization to event driven
Browse files Browse the repository at this point in the history
  • Loading branch information
Antenehden authored Aug 10, 2024
1 parent 8ac671a commit 598eeda
Show file tree
Hide file tree
Showing 5 changed files with 192 additions and 157 deletions.
70 changes: 49 additions & 21 deletions src/main/java/uta/cse3310/App.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.java_websocket.WebSocket;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_6455;
Expand All @@ -21,6 +25,7 @@ public class App extends WebSocketServer {
private Vector<Game> activeGames = new Vector<>();
private int gameId = 1;
private int connectionId = 0;
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private Statistics stats;
private HttpServer httpServer;

Expand Down Expand Up @@ -49,43 +54,50 @@ public void onOpen(WebSocket conn, ClientHandshake handshake) {
Game game = null;

for (Game g : activeGames) {
if (g.getPlayers().size() < 4) { // Assuming a maximum of 4 players per game
if (g.getPlayers().size() < 4) { // Assuming a maximum of 4 players per game
game = g;
System.out.println("Found a match");
break;
}
}

Player newPlayer = new Player("Player" + connectionId, PlayerType.HUMAN);

if (game == null) {
List<Player> players = new ArrayList<>();
players.add(new Player("Player" + connectionId, PlayerType.HUMAN)); // Initialize at least one player
players.add(newPlayer); // Initialize at least one player

try {
game = new Game(players, "src/main/resources/words.txt", "src/main/resources/stakes.txt", new Statistics(), new Scanner(System.in));
game = new Game(players, "src/main/resources/words.txt", "src/main/resources/stakes.txt",
new Statistics());
} catch (IOException e) {
e.printStackTrace();
return;
}
game.setGameId(gameId++);
activeGames.add(game);

System.out.println("Creating a new Game");
} else {
game.addPlayer(new Player("Player" + connectionId, PlayerType.HUMAN));
game.addPlayer(newPlayer);
System.out.println("Joining an existing game");
}


conn.setAttachment(game); // Attach the game to the connection


conn.setAttachment(game); // Attach the game to the connection
Gson gson = new Gson();
String jsonString = gson.toJson(event);
conn.send(jsonString);
System.out.println("> " + jsonString);

jsonString = gson.toJson(game);
System.out.println("< " + jsonString);
broadcastToGame(game, jsonString); // Broadcast to the specific game
String playerJson = gson.toJson(newPlayer.getId());
conn.send(playerJson);
System.out.println("> Player ID" + playerJson);

String gameJson = gson.toJson(event);
conn.send(gameJson);
System.out.println("> " + gameJson);

gameJson = gson.toJson(game);
// System.out.println("< " + gameJson);
broadcastToGame(game, gameJson); // Broadcast to the specific game

if (game.getPlayers().size() == 2) {
game.startGame();
Expand All @@ -106,21 +118,37 @@ public void onClose(WebSocket conn, int code, String reason, boolean remote) {

@Override
public void onMessage(WebSocket conn, String message) {
System.out.println("< " + message);
Gson gson = new GsonBuilder().create();
UserEvent event = gson.fromJson(message, UserEvent.class);

Game game = conn.getAttachment();
if (game != null) {
Player currentPlayer = game.getCurrentRound().getCurrentPlayer();

if (!event.getPlayerId().equals(currentPlayer.getId())) {
System.out.println("It's not this player's turn.");
return; // Ignore the action if it's not the current player's turn
}

System.out.println("Received message from player ID: " + event.getPlayerId() + " with action: " + event.getAction());

game.update(event);
String jsonString = gson.toJson(game);
System.out.println("> " + jsonString);
broadcastToGame(game, jsonString); // Broadcast to the specific game
if (game.playerActionComplete) {
game.getCurrentRound().playerActionTaken();
game.playerActionComplete = false;

// After processing the input, determine if the turn should continue or advance
if (!game.getCurrentRound().isRoundActive()) {
game.moveToNextRoundOrEndGame();
} else if (!game.correctGuess){
// Advance to the next turn
game.getCurrentRound().advanceTurn();
}

String jsonString = gson.toJson(game);
broadcastToGame(game, jsonString);
} else {
System.out.println("No game attached to the WebSocket connection.");
}
System.out.println("Finished onMessage for player ID: " + event.getPlayerId());

}

@Override
Expand Down
84 changes: 51 additions & 33 deletions src/main/java/uta/cse3310/Game.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,20 @@
public class Game {
private static final int MAX_PLAYERS = 4;
private List<Player> players;
private List<Round> rounds;
List<Round> rounds;
private int currentRoundIndex;
public boolean isGameActive;
private Statistics stats;
private int gameId;
private boolean inTestingMode;
public boolean playerActionComplete;
private transient Scanner scanner; // Marked as transient
//private transient Scanner scanner; // Marked as transient
boolean correctGuess;
//private TurnStartListener turnStartListener;

public Game(List<Player> players, String wordFilePath, String stakeFilePath, Statistics stats, Scanner scanner) throws IOException {
public Game(List<Player> players, String wordFilePath, String stakeFilePath, Statistics stats) throws IOException {
this.players = players;
this.rounds = new ArrayList<>();
this.scanner = scanner;
this.currentRoundIndex = 0;
this.isGameActive = false;
this.stats = stats; // Keep the passed stats
Expand All @@ -33,23 +34,20 @@ public Game(List<Player> players, String wordFilePath, String stakeFilePath, Sta
this.playerActionComplete = false;

for (int i = 0; i < 3; i++) {
rounds.add(new Round(players, wordFilePath, stakeFilePath, scanner));
rounds.add(new Round(players, wordFilePath, stakeFilePath));
}
}

public Game(List<Player> players, String wordFilePath, String stakeFilePath, Statistics stats, WordList wordlist, Scanner scanner) throws IOException {
public Game(List<Player> players, List<Round> rounds, int currentRoundIndex, boolean isGameActive, int gameId, boolean playerActionComplete, boolean correctGuess) {
this.players = players;
this.scanner = scanner;
this.rounds = new ArrayList<>();
this.currentRoundIndex = 0;
this.isGameActive = true;
this.stats = stats; // Keep the passed stats
this.gameId = 0;
this.inTestingMode = false;

for (int i = 0; i < 3; i++) {
rounds.add(new Round(players, wordlist, stakeFilePath, scanner));//error with this function
}
this.rounds = rounds;
this.currentRoundIndex = currentRoundIndex;
this.isGameActive = isGameActive;
this.gameId = gameId;
this.playerActionComplete = playerActionComplete;
this.correctGuess = correctGuess;
// Initialize transient fields or any other required fields as needed
//this.scanner = new Scanner(System.in); // or set it to null if it should be handled differently
}

public void setTestingMode(boolean inTestingMode) {
Expand All @@ -60,6 +58,10 @@ public List<Player> getPlayers() {
return players;
}

public List<Round> getRounds() {
return rounds;
}

public void setGameId(int gameId) {
this.gameId = gameId;
}
Expand Down Expand Up @@ -87,36 +89,39 @@ public void update(UserEvent event) {
System.err.println("Received null event");
return;
}

String action = event.getAction();
if (action == null) {
System.err.println("Event action is null");
return;
}

Round currentRound = rounds.get(currentRoundIndex);
Player currentPlayer = currentRound.getCurrentPlayer();



switch (action) {
case "BUY_VOWEL":
currentRound.buyVowel(currentPlayer, event.getValue().charAt(0));
playerActionComplete = true;
correctGuess = currentRound.buyVowel(currentPlayer, event.getValue().charAt(0));
break;
case "SELECT_CONSONANT":
currentRound.selectConsonant(currentPlayer, event.getValue().charAt(0));
correctGuess = currentRound.selectConsonant(currentPlayer, event.getValue().charAt(0));
System.out.println("Consonant selected by " + currentPlayer.getName());
break;
case "SOLVE_PUZZLE":
currentRound.solvePuzzle(currentPlayer, event.getValue());
correctGuess = currentRound.solvePuzzle(currentPlayer, event.getValue());
break;
default:
System.out.println("Unknown action: " + action);
}

//currentRound.playerActionTaken();

// Debugging log
System.out.println("Updated game state: " + new Gson().toJson(this));

if (playerActionComplete) {
System.out.println("Player " + currentPlayer.getName() + " action complete.");
}
}




Expand All @@ -128,11 +133,12 @@ public void startGame() {
return;
}
System.out.println("Game started with " + players.size() + " players.");
isGameActive = true;

/*
if (!inTestingMode) {
for(int i =0; i < 3; i++){
System.out.println("back in game");
isGameActive = true;
startNextRound();
System.out.println("finished start next round method");
Expand All @@ -142,14 +148,24 @@ public void startGame() {
System.out.println("All round complete");
}
}
}
//startNextRound();
} */
startNextRound();
}

public void startNextRound() {
public void moveToNextRoundOrEndGame() {
if (currentRoundIndex < rounds.size() - 1) {
System.out.println("Round is over. Moving to the next round.");
currentRoundIndex++; // Move to the next round
startNextRound(); // Start the next round
} else {
System.out.println("All rounds complete. Ending the game.");
endGame(determineWinner()); // End the game and declare the winner
}
}

public void startNextRound(){
Round currentRound = rounds.get(currentRoundIndex);
currentRound.startRound();
currentRoundIndex++;
}

public void playRound() {
Expand Down Expand Up @@ -190,7 +206,7 @@ public Round getCurrentRound() {
return rounds.get(currentRoundIndex);
}

public void determineWinner() {
public Player determineWinner() {
Player winner = null;
int highestScore = 0;
for (Player player : players) {
Expand All @@ -207,6 +223,8 @@ public void determineWinner() {
} else {
System.out.println("No winner determined.");
}

return winner;
}

public void resetGame() {
Expand Down
22 changes: 15 additions & 7 deletions src/main/java/uta/cse3310/GameTimer.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
import java.util.TimerTask;

public class GameTimer {
private transient Timer timer;
private transient Timer timer;
private long startTime;
private long elapsedTime;
private boolean isRunning;
//private TimerTask timerTask;
private final long timeLimit;

public GameTimer() {
public GameTimer(long timeLimit) {
this.timer = new Timer();
this.timeLimit = timeLimit; // Time limit in milliseconds
this.elapsedTime = 0;
this.isRunning = false;
}
Expand All @@ -22,15 +23,18 @@ public void start() {
}
this.startTime = System.currentTimeMillis();
this.isRunning = true;

// Create a new TimerTask instance each time the timer is started

TimerTask timerTask = new TimerTask() {
@Override
public void run() {
elapsedTime = System.currentTimeMillis() - startTime;
if (getRemainingTime() <= 0) {
stop();
// Handle timer expiration (e.g., advance the turn)
}
}
};

timer.scheduleAtFixedRate(timerTask, 0, 1000); // Update elapsed time every second
}

Expand All @@ -51,7 +55,11 @@ public void reset() {
}

public long getElapsedTime() {
return elapsedTime / 1000; // Return elapsed time in seconds
return elapsedTime; // Elapsed time in milliseconds
}

public long getRemainingTime() {
return timeLimit - getElapsedTime(); // Remaining time in milliseconds
}

public boolean isRunning() {
Expand Down
10 changes: 3 additions & 7 deletions src/main/java/uta/cse3310/Player.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ public class Player {
private List<Character> guessedConsonants;
private PlayerType playerType;

private static final int TURN_TIME_LIMIT = 1000000;

public Player(String name, PlayerType playerType) {
this.id = UUID.randomUUID().toString();
this.name = name;
this.score = 1000;
this.timer = new GameTimer();
this.timer = new GameTimer(TURN_TIME_LIMIT);
this.boughtVowels = new ArrayList<>();
this.guessedConsonants = new ArrayList<>();
this.playerType = playerType;
Expand Down Expand Up @@ -92,9 +94,3 @@ public void setPlayerType(PlayerType playerType) {
this.playerType = playerType;
}
}






Loading

0 comments on commit 598eeda

Please sign in to comment.