Skip to content

Commit

Permalink
Fix race conditions and code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
germandilio committed Jun 1, 2022
1 parent ea608d7 commit 3605447
Show file tree
Hide file tree
Showing 20 changed files with 87 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void start(Stage stage) throws IOException {
// prompt for registration on start
manager.registration();

} catch(Exception ex) {
} catch (Exception ex) {
System.out.println("Poo-pi-poop. Something went wrong.");
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package ru.hse.germandilio.tetris.client.controllers;

import ru.hse.germandilio.tetris.client.model.ViewGameResult;
import ru.hse.germandilio.tetris.shared.GameResult;

import java.util.List;

public interface ActionProvider {
/**
* Swot to user top list result
*
* @param results list og game session results
*/
void showTopResults(List<ViewGameResult> results);
Expand All @@ -29,6 +29,7 @@ public interface ActionProvider {

/**
* Place brick that was sent by server.
*
* @param brick Brick to place
*/
void placeBrick(boolean[][] brick);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package ru.hse.germandilio.tetris.client.controllers;

import javafx.application.Platform;
import ru.hse.germandilio.tetris.client.model.ViewGameResult;
import ru.hse.germandilio.tetris.client.model.GameSessionStats;
import ru.hse.germandilio.tetris.client.model.ViewGameResult;
import ru.hse.germandilio.tetris.client.model.client.Client;
import ru.hse.germandilio.tetris.client.model.gameboard.GameBoard;
import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;
import ru.hse.germandilio.tetris.server.clienthandling.CommandSender;
import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;

import java.net.UnknownHostException;
import java.util.List;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,7 @@ public void run() {
currentSessionStopwatch.setText(convertTime(seconds));

// send leave game command
String bricksPlaced = Integer.toString(stats.getBricksPlaced());
String sessionTime = Long.toString(stats.getGameSessionDuration());
String command = CommandsAPI.buildCommand(CommandsAPI.LEAVE_GAME,
bricksPlaced,
sessionTime);

gameManager.sendCommand(command);
endGame();
}
};
timer.schedule(closeSession, time * 1000);
Expand Down Expand Up @@ -513,7 +507,7 @@ private void setupWithoutResultsAlert(Alert alertToSetup) {
String clientStats = "Фигур: " + stats.getBricksPlaced() + ". Время в игре: "
+ convertTime(stats.getGameSessionDuration()) + "\n";

alertToSetup.setHeaderText("Вы:\n" + clientStats+ "Победитель: " + stats.getName());
alertToSetup.setHeaderText("Вы:\n" + clientStats + "Победитель: " + stats.getName());
}

private void setupWithResultsAlert(Alert alertToSetup) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,5 +126,7 @@ public void reset() {
opponentGameDuration = 0L;
opponentBricksPlaced = 0;
winnerName = null;

hasEndedGame = false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import ru.hse.germandilio.tetris.client.controllers.ActionProvider;
import ru.hse.germandilio.tetris.client.model.GameSessionStats;
import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;
import ru.hse.germandilio.tetris.server.clienthandling.CommandSender;
import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;

import java.io.*;
import java.net.Socket;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package ru.hse.germandilio.tetris.client.model.client;

import ru.hse.germandilio.tetris.client.controllers.ActionProvider;
import ru.hse.germandilio.tetris.client.model.ViewGameResult;
import ru.hse.germandilio.tetris.client.model.GameSessionStats;
import ru.hse.germandilio.tetris.client.model.ViewGameResult;
import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;

import java.time.*;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
Expand All @@ -22,7 +24,7 @@ public ClientCommandHandler(ActionProvider gameManager, GameSessionStats userSta
}

public void handle(CommandsAPI command, List<String> arguments) {
switch(command) {
switch (command) {
case CONNECTED -> hasConnected();
case WAITING_FOR_NEW_GAME -> waitForNewGame();
case START_GAME -> startGame(arguments);
Expand Down Expand Up @@ -117,6 +119,7 @@ private void waitForNewGame() {

/**
* Convert {@code String} represented brick to boolean matrix.
*
* @param brickString {@code String} represented brick
* @return Matrix 3x3 of booleans.
*/
Expand All @@ -134,6 +137,7 @@ private boolean[][] convertBrick(char[] brickString) {

/**
* Replace all internal symbols to white spaces.
*
* @param string {@code String} where replace.
* @return {@code String} natural view.
*/
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/ru/hse/germandilio/tetris/server/Server.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public Server(int maxClients, long maxTime) throws IOException {

public void launch() {
new Thread(() -> {
try(socket) {
try (socket) {
ForkJoinPool executor = new ForkJoinPool();

// accept all clients
Expand All @@ -51,7 +51,7 @@ public void launch() {
executor.execute(handler);
}
}
} catch(IllegalArgumentException | IOException ex) {
} catch (IllegalArgumentException | IOException ex) {
System.out.println("Cannot accept clients. Server will shut down.");
}
}).start();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,14 @@
public interface Brick {
/**
* Internal matrix that represents 3x3 brick.
*
* @return List of all brick rotations.
*/
List<boolean[][]> getMatrix();

/**
* Number of available rotations.
*
* @return {@code Integer} numbner.
*/
int getRotationsCount();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
package ru.hse.germandilio.tetris.server.clienthandling;

import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;
import ru.hse.germandilio.tetris.server.game.GameManager;
import ru.hse.germandilio.tetris.shared.commands.CommandsAPI;

import java.time.Instant;
import java.time.ZoneOffset;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class CommandHandler {
private static final ReentrantLock ENTRANCE_LOCK = new ReentrantLock();

private final GameManager serverGame;
private final Connection connection;

Expand All @@ -15,7 +20,7 @@ public CommandHandler(GameManager serverGame, Connection clientConnection) {
}

public void handle(CommandsAPI command, List<String> arguments) {
switch(command) {
switch (command) {
case STARTING_GAME -> startingClientGame(arguments);
case GET_NEXT_BRICK -> sendBrick(arguments);
case LEAVE_GAME -> clientLeavingGame(arguments);
Expand Down Expand Up @@ -53,22 +58,31 @@ private void sendBrick(List<String> arguments) {
}

private void clientLeavingGame(List<String> arguments) {
// save client game session configuration
int brickPlaced = Integer.parseInt(arguments.get(0));
connection.setBrickPlaced(brickPlaced);
var endSessionDateTime = Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime();

ENTRANCE_LOCK.lock();
try {
// save client game session configuration
int brickPlaced = Integer.parseInt(arguments.get(0));
connection.setBrickPlaced(brickPlaced);

long duration = Long.parseLong(arguments.get(1));
connection.setGameSessionDuration(duration);

long duration = Long.parseLong(arguments.get(1));
connection.setGameSessionDuration(duration);
connection.setEndTime(endSessionDateTime);

// send waiting for end game
serverGame.sendWaitingEndGame(connection);
// send waiting for end game
serverGame.sendWaitingEndGame(connection);

// save to database game session results
serverGame.saveGameSessionResults(connection);
// save to database game session results
serverGame.saveGameSessionResults(connection);

// if game ready to end send end_game on clients
if (serverGame.readyToEndGame()) {
serverGame.endGame(connection);
// if game ready to end send end_game on clients
if (serverGame.readyToEndGame()) {
serverGame.endGame(connection);
}
} finally {
ENTRANCE_LOCK.unlock();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
public interface CommandSender {
/**
* Send command.
*
* @param command {@code String} represented command.
*/
void sendCommand(String command);

/**
* Close listening socket and/or thread.
*
* @throws Exception on closing
*/
void close() throws Exception;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import ru.hse.germandilio.tetris.client.controllers.IReset;

import java.time.LocalDateTime;

public class Connection implements IReset {
private final int id;

Expand All @@ -10,6 +12,7 @@ public class Connection implements IReset {
private String name;
private long gameSessionDuration;
private int brickPlaced;
private LocalDateTime endTime;

private boolean hasEndedGame = false;

Expand Down Expand Up @@ -57,5 +60,15 @@ public void reset() {
gameSessionDuration = 0L;
brickPlaced = 0;
hasEndedGame = false;

endTime = null;
}

public LocalDateTime getEndTime() {
return endTime;
}

public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ public int getClientsNumber() {

if (scanner.hasNextInt()) {
amount = scanner.nextInt();
}
else if (scanner.hasNext()){
} else if (scanner.hasNext()) {
scanner.next();
amount = -1;
} else {
break;
}
}

return amount; }
return amount;
}

@Override
public long getTimeout() {
Expand All @@ -41,8 +41,7 @@ public long getTimeout() {

if (scanner.hasNextLong()) {
timeout = scanner.nextLong();
}
else if (scanner.hasNext()){
} else if (scanner.hasNext()) {
scanner.next();
timeout = -1;
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
public interface InputHandler {
/**
* Get max number of clients can connect to server.
*
* @return int
*/
int getClientsNumber();

/**
* Get timeout when all clients will be notified with predefined event.
*
* @return long
*/
long getTimeout();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public void launch() {
} catch (IllegalStateException ex) {
System.out.println(ex.getMessage());
return;
} catch(Exception ex) {
} catch (Exception ex) {
System.out.println("Poo-pi-poop. Something went wrong.");
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package ru.hse.germandilio.tetris.server.database;

import ru.hse.germandilio.tetris.shared.GameResult;
import java.sql.SQLException;

import java.sql.SQLException;
import java.util.List;

public interface DataProvider {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
import ru.hse.germandilio.tetris.shared.GameResult;

import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.List;

public class GameSessionsDatabase {
Expand All @@ -24,11 +22,10 @@ public GameSessionsDatabase() {

public void saveSession(Connection client) {
// Creating game result object
var endSessionDateTime = Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime();
var gameDuration = LocalTime.ofSecondOfDay(client.getGameSessionDuration());

try {
var sessionResult = new GameResult(client.getName(), endSessionDateTime, client.getBrickPlaced(), gameDuration);
var sessionResult = new GameResult(client.getName(), client.getEndTime(), client.getBrickPlaced(), gameDuration);
gameSessionsDataProvider.save(sessionResult);
} catch (SQLException e) {
throw new RuntimeException("Cannot save game session result", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,28 @@

public interface GameManager {
Connection playerConnected(CommandSender clientHandler);

void disconnectPlayer(Connection client);

void setName(Connection client, String name);

void sendWaitingStartGame(Connection client);

void sendWaitingEndGame(Connection client);

void sendNextBrick(Connection client, int indexInSequence);

boolean readyToStartGame();

void startGame(Connection client);

boolean readyToEndGame();

void endGame(Connection client);

void sendEndGameWithoutResults(Connection client);

void saveGameSessionResults(Connection client);

void getTopSessions(Connection client, int topNumber);
}
Loading

0 comments on commit 3605447

Please sign in to comment.