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

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.backend.TcpServer;
import org.toop.game.*;
import org.toop.game.tictactoe.*;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
@@ -62,11 +65,20 @@ public class Main {
// String serverConnections = future6.get();
// 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() {
new ServerManager();
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.Logger;
@@ -16,14 +18,14 @@ public class MinMaxTicTacToe {
int bestMove = 10; // set bestmove to something impossible
// 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
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;
if (result == State.WIN) {
if (result == GameBase.State.WIN) {
return i; // just return right away if you can win on the next move
}
else {
@@ -56,7 +58,7 @@ public class MinMaxTicTacToe {
else {
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 == ' ') {
empty = true; // if a thing is empty, set to true
break; // break the loop
@@ -69,10 +71,10 @@ public class MinMaxTicTacToe {
if (maximizing) { // it's the maximizing players turn, the AI
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)) {
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
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
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)) {
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
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;
import org.toop.server.backend.tictactoe.game.TicTacToe;
import org.toop.game.tictactoe.*;
import org.toop.server.backend.TcpServer;
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;
}
}