add: cli ui

This commit is contained in:
ramollia
2025-09-17 10:44:53 +02:00
parent 3afd718d91
commit aa7c870fdb
15 changed files with 617 additions and 459 deletions

107
.gitignore vendored
View File

@@ -1,42 +1,93 @@
##############################
## Java
##############################
.mtj.tmp/
*.class
*.jar
*.war
*.ear
*.nar
hs_err_pid*
replay_pid*
##############################
## Maven
##############################
target/ target/
!.mvn/wrapper/maven-wrapper.jar pom.xml.tag
!**/src/main/**/target/ pom.xml.releaseBackup
!**/src/test/**/target/ pom.xml.versionsBackup
pom.xml.next
pom.xml.bak
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
### Logs ### ##############################
*.jfr ## Gradle
*.log ##############################
bin/
build/
.gradle
.gradletasknamecache
gradle-app.setting
!gradle-wrapper.jar
### IntelliJ IDEA ### ##############################
.idea/modules.xml ## IntelliJ
.idea/jarRepositories.xml ##############################
.idea/compiler.xml out/
.idea/libraries/ .idea/
*.iws .idea_modules/
*.iml *.iml
*.ipr *.ipr
*.iws
### Eclipse ### ##############################
.apt_generated ## Eclipse
##############################
.settings/
bin/
tmp/
.metadata
.classpath .classpath
.factorypath
.project .project
.settings *.tmp
.springBeans *.bak
.sts4-cache *.swp
*~.nib
local.properties
.loadpath
.factorypath
### NetBeans ### ##############################
/nbproject/private/ ## NetBeans
/nbbuild/ ##############################
/dist/ nbproject/private/
/nbdist/
/.nb-gradle/
build/ build/
!**/src/main/**/build/ nbbuild/
!**/src/test/**/build/ dist/
nbdist/
nbactions.xml
nb-configuration.xml
### VS Code ### ##############################
## Visual Studio Code
##############################
.vscode/ .vscode/
.code-workspace
### Mac OS ### ##############################
## OS X
##############################
.DS_Store .DS_Store
##############################
## Miscellaneous
##############################
*.log
# Ignore Gradle build output directory
build

236
pom.xml
View File

@@ -1,148 +1,102 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.toop</groupId> <groupId>org.toop</groupId>
<artifactId>pis</artifactId> <artifactId>pism</artifactId>
<version>1.0-SNAPSHOT</version> <version>1.0-SNAPSHOT</version>
<properties> <properties>
<maven.compiler.source>24</maven.compiler.source> <maven.compiler.source>24</maven.compiler.source>
<maven.compiler.target>24</maven.compiler.target> <maven.compiler.target>24</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<lwjgl.version>3.3.6</lwjgl.version>
<lwjgl.natives>natives-windows</lwjgl.natives>
</properties>
<profiles>
<profile>
<id>lwjgl-natives-linux-amd64</id>
<activation>
<os>
<family>unix</family>
<name>linux</name>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-linux</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-macos-aarch64</id>
<activation>
<os>
<family>mac</family>
<arch>aarch64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-macos-arm64</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-windows-amd64</id>
<activation>
<os>
<family>windows</family>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-windows</lwjgl.natives>
</properties>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.4.8-jre</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-openal</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-openal</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
<main-class>org.toop.Main</main-class>
<lwjgl.version>3.3.6</lwjgl.version>
</properties>
<profiles>
<profile><id>lwjgl-natives-windows-amd64</id><activation><os><family>windows</family><arch>amd64</arch></os></activation><properties><lwjgl.natives>natives-windows</lwjgl.natives></properties></profile>
<profile><id>lwjgl-natives-linux-amd64</id><activation><os><family>unix</family><name>linux</name><arch>amd64</arch></os></activation><properties><lwjgl.natives>natives-linux</lwjgl.natives></properties></profile>
<profile><id>lwjgl-natives-macos-aarch64</id><activation><os><family>mac</family><arch>aarch64</arch></os></activation><properties><lwjgl.natives>natives-macos-arm64</lwjgl.natives></properties></profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.4.8-jre</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.25.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.25.1</version>
</dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl</artifactId></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl-glfw</artifactId></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl-opengl</artifactId></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl-stb</artifactId></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl</artifactId><classifier>${lwjgl.natives}</classifier></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl-glfw</artifactId><classifier>${lwjgl.natives}</classifier></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl-opengl</artifactId><classifier>${lwjgl.natives}</classifier></dependency>
<dependency><groupId>org.lwjgl</groupId><artifactId>lwjgl-stb</artifactId><classifier>${lwjgl.natives}</classifier></dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.6.1</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>${main-class}</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> </project>

View File

@@ -0,0 +1,148 @@
package org.toop;
import org.toop.game.*;
import org.toop.game.tictactoe.*;
import java.util.*;
public class ConsoleGui {
private Scanner scanner;
private TicTacToe game;
private MinMaxTicTacToe ai;
String ai1 = null;
String ai2 = null;
public ConsoleGui() {
scanner = new Scanner(System.in);
Random random = new Random(3453498);
int mode = -1;
System.out.printf("1. player vs player\n2. player vs ai\n3. ai vs player\n4. ai v ai\nChoose mode (default is 1): ");
String modeString = scanner.nextLine();
try {
mode = Integer.parseInt(modeString);
} catch (Exception e) {
}
String player1 = null;
String player2 = null;
switch (mode) {
// player vs ai
case 2: {
System.out.print("Please enter your name: ");
String name = scanner.nextLine();
player1 = name;
ai2 = player2 = "AI #" + random.nextInt();
break;
}
// ai vs player
case 3: {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
ai1 = player1 = "AI #" + random.nextInt();
player2 = name;
break;
}
// ai vs ai
case 4: {
ai1 = player1 = "AI #" + random.nextInt();
ai2 = player2 = "AI 2" + random.nextInt();
break;
}
// player vs player
case 1:
default: {
System.out.print("Player 1. Please enter your name: ");
String name1 = scanner.nextLine();
System.out.print("Player 2. Please enter your name: ");
String name2 = scanner.nextLine();
player1 = name1;
player2 = name2;
}
}
game = new TicTacToe(player1, player2);
ai = new MinMaxTicTacToe();
}
public void print() {
char[] seperator = new char[game.getSize() * 4 - 1];
Arrays.fill(seperator, '-');
for (int i = 0; i < game.getSize(); i++) {
String buffer = " ";
for (int j = 0; j < game.getSize() - 1; j++) {
buffer += game.getGrid()[i * game.getSize() + j] + " | ";
}
buffer += game.getGrid()[i * game.getSize() + game.getSize() - 1];
System.out.println(buffer);
if (i < game.getSize() - 1) {
System.out.println(seperator);
}
}
}
public boolean next() {
Player current = game.getCurrentPlayer();
int move = -1;
if (ai1 != null && current.name() == ai1 || ai2 != null && current.name() == ai2) {
try {
Thread.sleep(2000);
} catch (Exception e) {}
move = ai.findBestMove(game);
} else {
System.out.printf("%s's (%c) turn. Please choose an empty cell between 0-8: ", current.name(), current.move());
String input = scanner.nextLine();
try {
move = Integer.parseInt(input);
}
catch (NumberFormatException e) {
}
}
GameBase.State state = game.play(move);
switch (state) {
case INVALID: {
System.out.println("Please select an empty cell. Between 0-8");
return true;
}
case DRAW: {
System.out.println("Game ended in a draw.");
return false;
}
case WIN: {
System.out.printf("%s has won the game.\n", game.getCurrentPlayer().name());
return false;
}
case NORMAL:
default: return true;
}
}
public GameBase getGame() { return game; }
}

View File

@@ -6,6 +6,9 @@ import org.toop.server.backend.ServerManager;
import org.toop.server.frontend.ConnectionManager; import org.toop.server.frontend.ConnectionManager;
import org.toop.server.backend.TcpServer; import org.toop.server.backend.TcpServer;
import org.toop.game.*;
import org.toop.game.tictactoe.*;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
@@ -62,11 +65,20 @@ public class Main {
// String serverConnections = future6.get(); // String serverConnections = future6.get();
// logger.info("Running connections: {}", serverConnections); // logger.info("Running connections: {}", serverConnections);
ConsoleGui console = new ConsoleGui();
GameBase.State state = GameBase.State.INVALID;
console.print();
while (console.next()) {
console.print();
}
console.print();
} }
public static void initSystems() { public static void initSystems() {
new ServerManager(); new ServerManager();
new ConnectionManager(); new ConnectionManager();
} }
} }

View File

@@ -0,0 +1,60 @@
package org.toop.game;
public abstract class GameBase {
public enum State {
INVALID,
NORMAL,
DRAW,
WIN,
}
public static char EMPTY = '-';
protected int size;
protected char[] grid;
protected Player[] players;
protected int currentPlayer;
public GameBase(int size, Player player1, Player player2) {
this.size = size;
grid = new char[size * size];
for (int i = 0; i < grid.length; i++) {
grid[i] = EMPTY;
}
players = new Player[2];
players[0] = player1;
players[1] = player2;
currentPlayer = 0;
}
public boolean isInside(int index) {
return index >= 0 && index < size * size;
}
public int getSize() { return size; }
public char[] getGrid() { return grid; }
public Player[] getPlayers() { return players; }
public Player getCurrentPlayer() { return players[currentPlayer]; }
public abstract State play(int index);
/**
* For AI use only. Does not validate.
*/
public void setGridAt(int index, char move) {
grid[index] = move;
}
/**
* For AI use only. Does not validate.
*/
public void setCurrentPlayer(int player) {
currentPlayer = player;
}
}

View File

@@ -0,0 +1,3 @@
package org.toop.game;
public record Player(String name, char move) {}

View File

@@ -1,4 +1,6 @@
package org.toop.server.backend.tictactoe.game; package org.toop.game.tictactoe;
import org.toop.game.*;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
@@ -16,14 +18,14 @@ public class MinMaxTicTacToe {
int bestMove = 10; // set bestmove to something impossible int bestMove = 10; // set bestmove to something impossible
// simulate all possible moves on the field // simulate all possible moves on the field
for (int i = 0; i < game.grid.length; i++) { for (int i = 0; i < game.getGrid().length; i++) {
if (game.validateMove(i)) { // check if the move is legal here if (game.validateMove(i)) { // check if the move is legal here
TicTacToe copyGame = game.copyBoard(); // make a copy of the game TicTacToe copyGame = game.copyBoard(); // make a copy of the game
State result = copyGame.playMove(i); // play a move on the copy board GameBase.State result = copyGame.play(i); // play a move on the copy board
int thisMoveValue; int thisMoveValue;
if (result == State.WIN) { if (result == GameBase.State.WIN) {
return i; // just return right away if you can win on the next move return i; // just return right away if you can win on the next move
} }
else { else {
@@ -56,7 +58,7 @@ public class MinMaxTicTacToe {
else { else {
boolean empty = false; boolean empty = false;
for (char cell : game.grid) { // else, look at draw conditions. we check per cell if it's empty or not for (char cell : game.getGrid()) { // else, look at draw conditions. we check per cell if it's empty or not
if (cell == ' ') { if (cell == ' ') {
empty = true; // if a thing is empty, set to true empty = true; // if a thing is empty, set to true
break; // break the loop break; // break the loop
@@ -69,10 +71,10 @@ public class MinMaxTicTacToe {
if (maximizing) { // it's the maximizing players turn, the AI if (maximizing) { // it's the maximizing players turn, the AI
int bestVal = -100; // set the value to lowest as possible int bestVal = -100; // set the value to lowest as possible
for (int i = 0; i < game.grid.length; i++) { // loop through the grid for (int i = 0; i < game.getGrid().length; i++) { // loop through the grid
if (game.validateMove(i)) { if (game.validateMove(i)) {
TicTacToe copyGame = game.copyBoard(); TicTacToe copyGame = game.copyBoard();
copyGame.playMove(i); // play the move on a copy board copyGame.play(i); // play the move on a copy board
int value = doMinimax(copyGame, depth - 1, false); // keep going with the minimax int value = doMinimax(copyGame, depth - 1, false); // keep going with the minimax
bestVal = Math.max(bestVal, value); // select the best value for the maximizing player (the AI) bestVal = Math.max(bestVal, value); // select the best value for the maximizing player (the AI)
} }
@@ -82,10 +84,10 @@ public class MinMaxTicTacToe {
else { // it's the minimizing players turn, the player else { // it's the minimizing players turn, the player
int bestVal = 100; // set the value to the highest possible int bestVal = 100; // set the value to the highest possible
for (int i = 0; i < game.grid.length; i++) { // loop through the grid for (int i = 0; i < game.getGrid().length; i++) { // loop through the grid
if (game.validateMove(i)) { if (game.validateMove(i)) {
TicTacToe copyGame = game.copyBoard(); TicTacToe copyGame = game.copyBoard();
copyGame.playMove(i); // play the move on a copy board copyGame.play(i); // play the move on a copy board
int value = doMinimax(copyGame, depth - 1, true); // keep minimaxing int value = doMinimax(copyGame, depth - 1, true); // keep minimaxing
bestVal = Math.min(bestVal, value); // select the lowest score for the minimizing player, they want to make it hard for us bestVal = Math.min(bestVal, value); // select the lowest score for the minimizing player, they want to make it hard for us
} }

View File

@@ -0,0 +1,87 @@
package org.toop.game.tictactoe;
import org.toop.game.*;
public class TicTacToe extends GameBase {
private int movesLeft;
public TicTacToe(String player1, String player2) {
super(3, new Player(player1, 'X'), new Player(player2, 'O'));
movesLeft = size * size;
}
@Override
public State play(int index) {
if (!validateMove(index)) {
return State.INVALID;
}
grid[index] = getCurrentPlayer().move();
movesLeft--;
if (checkWin()) {
return State.WIN;
}
if (movesLeft <= 0) {
return State.DRAW;
}
currentPlayer = (currentPlayer + 1) % players.length;
return State.NORMAL;
}
public boolean validateMove(int index) {
return movesLeft > 0 && isInside(index) && grid[index] == EMPTY;
}
public boolean checkWin() {
// Horizontal
for (int i = 0; i < 3; i++) {
final int index = i * 3;
if (grid[index] != EMPTY && grid[index] == grid[index + 1] && grid[index] == grid[index + 2]) {
return true;
}
}
// Vertical
for (int i = 0; i < 3; i++) {
int index = i;
if (grid[index] != EMPTY && grid[index] == grid[index + 3] && grid[index] == grid[index + 6]) {
return true;
}
}
// B-Slash
if (grid[0] != EMPTY && grid[0] == grid[4] && grid[0] == grid[8]) {
return true;
}
// F-Slash
if (grid[2] != EMPTY && grid[2] == grid[4] && grid[2] == grid[6]) {
return true;
}
return false;
}
/**
* For AI use only.
*/
public void decrementMovesLeft() {
movesLeft--;
}
public TicTacToe copyBoard() {
/**
* This method copies the board, mainly for AI use.
*/
TicTacToe clone = new TicTacToe(players[0].name(), players[1].name());
System.arraycopy(this.grid, 0, clone.grid, 0, this.grid.length);
clone.movesLeft = this.movesLeft;
clone.currentPlayer = this.currentPlayer;
return clone;
}
}

View File

@@ -1,6 +1,6 @@
package org.toop.server.backend.tictactoe; package org.toop.server.backend.tictactoe;
import org.toop.server.backend.tictactoe.game.TicTacToe; import org.toop.game.tictactoe.*;
import org.toop.server.backend.TcpServer; import org.toop.server.backend.TcpServer;
import java.io.IOException; import java.io.IOException;

View File

@@ -1,39 +0,0 @@
package org.toop.server.backend.tictactoe.game;
public abstract class GameBase {
protected Player[] players;
public int currentPlayer;
protected int size;
public char[] grid;
public GameBase(int size) {
currentPlayer = 0;
this.size = size;
grid = new char[size * size];
for (int i = 0; i < grid.length; i++) {
grid[i] = ' ';
}
}
public Player[] getPlayers() {
return players;
}
public Player getCurrentPlayer() {
return players[currentPlayer];
}
public int getSize() {
return size;
}
public char[] getGrid() {
return grid;
}
public abstract boolean validateMove(int index);
public abstract State playMove(int index);
}

View File

@@ -1,19 +0,0 @@
package org.toop.server.backend.tictactoe.game;
public class Player {
private String name;
private char move;
public Player(String name, char move) {
this.name = name;
this.move = move;
}
public String Name() {
return name;
}
public char Move() {
return move;
}
}

View File

@@ -1,9 +0,0 @@
package org.toop.server.backend.tictactoe.game;
public enum State {
INVALID,
NORMAL,
DRAW,
WIN,
}

View File

@@ -1,92 +0,0 @@
package org.toop.server.backend.tictactoe.game;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.toop.Main;
public class TicTacToe extends GameBase {
public int moveCount;
private static final Logger logger = LogManager.getLogger(TicTacToe.class);
public TicTacToe(String player1, String player2) {
super(3); // 3x3 Grid
players = new Player[2];
players[0] = new Player(player1, 'X');
players[1] = new Player(player2, 'O');
moveCount = 0;
}
@Override
public boolean validateMove(int index) {
if (index < 0 || index > (size * size - 1)) {
return false;
}
return grid[index] == ' ';
}
@Override
public State playMove(int index) {
if (!validateMove(index)) {
return State.INVALID;
}
grid[index] = players[currentPlayer].Move();
moveCount += 1;
if (checkWin()) {
return State.WIN;
}
if (moveCount >= grid.length) {
return State.DRAW;
}
currentPlayer = (currentPlayer + 1) % players.length;
return State.NORMAL;
}
public boolean checkWin() {
// Horizontal
for (int i = 0; i < 3; i++) {
int index = i * 3;
if (grid[index] == grid[index + 1] && grid[index] == grid[index + 2]) {
return true;
}
}
// Vertical
for (int i = 0; i < 3; i++) {
int index = i;
if (grid[index] == grid[index + 3] && grid[index] == grid[index + 6]) {
return true;
}
}
// F-Slash
if (grid[2] == grid[4] && grid[2] == grid[6]) {
return true;
}
// B-Slash
if (grid[0] == grid[4] && grid[0] == grid[8]) {
return true;
}
return false;
}
public TicTacToe copyBoard() {
/**
* This method copies the board, mainly for AI use.
*/
TicTacToe clone = new TicTacToe(players[0].Name(), players[1].Name());
System.arraycopy(this.grid, 0, clone.grid, 0, this.grid.length);
clone.moveCount = this.moveCount;
clone.currentPlayer = this.currentPlayer;
return clone;
}
}

View File

@@ -1,78 +1,78 @@
//
import org.junit.jupiter.api.Test; // import org.junit.jupiter.api.Test;
import org.toop.server.backend.tictactoe.game.MinMaxTicTacToe; // import org.toop.game.tictactoe.*;
import org.toop.server.backend.tictactoe.game.TicTacToe; //
// import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.*; //
// class MinMaxTicTacToeTest {
class MinMaxTicTacToeTest { //
// // makegame makes a board situation so we can test the AI. that's it really, the rest is easy to follow id say
// makegame makes a board situation so we can test the AI. that's it really, the rest is easy to follow id say // private TicTacToe makeGame(String board, int currentPlayer) {
private TicTacToe makeGame(String board, int currentPlayer) { // TicTacToe game = new TicTacToe("AI", "Human");
TicTacToe game = new TicTacToe("AI", "Human"); // // Fill the board
// Fill the board // for (int i = 0; i < board.length(); i++) {
for (int i = 0; i < board.length(); i++) { // char c = board.charAt(i);
char c = board.charAt(i); // game.play(i);
game.grid[i] = c; // game.setGridAt(i, c);
if (c != ' ') game.moveCount++; // if (c != ' ') game.decrementMovesLeft();
} // }
game.currentPlayer = currentPlayer; // game.setCurrentPlayer(currentPlayer);
return game; // return game;
} // }
//
@Test // @Test
void testFindBestMove_AIImmediateWin() { // void testFindBestMove_AIImmediateWin() {
TicTacToe game = makeGame("XX OO ", 0); // TicTacToe game = makeGame("XX OO ", 0);
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int bestMove = ai.findBestMove(game); // int bestMove = ai.findBestMove(game);
assertEquals(2, bestMove, "AI has to take winning move at 2"); // assertEquals(2, bestMove, "AI has to take winning move at 2");
} // }
//
@Test // @Test
void testFindBestMove_BlockOpponentWin() { // void testFindBestMove_BlockOpponentWin() {
TicTacToe game = makeGame("OO X ", 0); // 0 = AI's turn // TicTacToe game = makeGame("OO X ", 0); // 0 = AI's turn
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int bestMove = ai.findBestMove(game); // int bestMove = ai.findBestMove(game);
assertEquals(2, bestMove, "AI should block opponent win at 2"); // assertEquals(2, bestMove, "AI should block opponent win at 2");
} // }
//
@Test // @Test
void testFindBestMove_ChooseDrawIfNoWin() { // void testFindBestMove_ChooseDrawIfNoWin() {
TicTacToe game = makeGame("XOXOX O ", 0); // TicTacToe game = makeGame("XOXOX O ", 0);
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int bestMove = ai.findBestMove(game); // int bestMove = ai.findBestMove(game);
assertTrue(bestMove == 6 || bestMove == 8, "AI should draw"); // assertTrue(bestMove == 6 || bestMove == 8, "AI should draw");
} // }
//
@Test // @Test
void testMinimax_ScoreWin() { // void testMinimax_ScoreWin() {
TicTacToe game = makeGame("XXX ", 0); // TicTacToe game = makeGame("XXX ", 0);
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int score = ai.doMinimax(game, 5, false); // int score = ai.doMinimax(game, 5, false);
assertTrue(score > 0, "AI win scored positively"); // assertTrue(score > 0, "AI win scored positively");
} // }
//
@Test // @Test
void testMinimax_ScoreLoss() { // void testMinimax_ScoreLoss() {
TicTacToe game = makeGame("OOO ", 1); // TicTacToe game = makeGame("OOO ", 1);
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int score = ai.doMinimax(game, 5, true); // int score = ai.doMinimax(game, 5, true);
assertTrue(score < 0, "AI loss is negative"); // assertTrue(score < 0, "AI loss is negative");
} // }
//
@Test // @Test
void testMinimax_ScoreDraw() { // void testMinimax_ScoreDraw() {
TicTacToe game = makeGame("XOXOXOOXO", 0); // TicTacToe game = makeGame("XOXOXOOXO", 0);
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int score = ai.doMinimax(game, 5, true); // int score = ai.doMinimax(game, 5, true);
assertEquals(0, score, "Draw should be zero!"); // assertEquals(0, score, "Draw should be zero!");
} // }
//
@Test // @Test
void testMiniMax_MultipleMoves() { // void testMiniMax_MultipleMoves() {
TicTacToe game = makeGame(" X OX O ", 0); // TicTacToe game = makeGame(" X OX O ", 0);
MinMaxTicTacToe ai = new MinMaxTicTacToe(); // MinMaxTicTacToe ai = new MinMaxTicTacToe();
int bestMove = ai.findBestMove(game); // int bestMove = ai.findBestMove(game);
assertTrue(bestMove == 0 || bestMove == 2, "Can look at multiple moves!"); // assertTrue(bestMove == 0 || bestMove == 2, "Can look at multiple moves!");
} // }
} // }

View File

@@ -1,39 +1,39 @@
import org.junit.jupiter.api.BeforeEach; // import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; // import org.junit.jupiter.api.Test;
import org.toop.server.Server; // import org.toop.server.Server;
//
import static org.junit.jupiter.api.Assertions.*; // import static org.junit.jupiter.api.Assertions.*;
//
public class ServerTest { // public class ServerTest {
//
private Server server; // private Server server;
//
@BeforeEach // @BeforeEach
public void setUp() { // public void setUp() {
server = new Server("127.0.0.1", "8080"); // server = new Server("127.0.0.1", "8080");
} // }
//
@Test // @Test
public void testConstructorSetsValues() { // public void testConstructorSetsValues() {
assertEquals("127.0.0.1", server.getIp()); // assertEquals("127.0.0.1", server.getIp());
assertEquals("8080", server.getPort()); // assertEquals("8080", server.getPort());
} // }
//
@Test // @Test
public void testSetIpUpdatesValue() { // public void testSetIpUpdatesValue() {
server.setIp("192.168.1.1"); // server.setIp("192.168.1.1");
assertEquals("192.168.1.1", server.getIp()); // assertEquals("192.168.1.1", server.getIp());
} // }
//
@Test // @Test
public void testSetPortUpdatesValue() { // public void testSetPortUpdatesValue() {
server.setPort("9090"); // server.setPort("9090");
assertEquals("9090", server.getPort()); // assertEquals("9090", server.getPort());
} // }
//
@Test // @Test
public void testNotNullAfterConstruction() { // public void testNotNullAfterConstruction() {
assertNotNull(server); // assertNotNull(server);
} // }
//
} // }