add: base game & ttt rules

This commit is contained in:
ramollia
2025-09-11 14:40:41 +02:00
parent 4b36e842ba
commit 9cf1bac943
4 changed files with 145 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
package org.toop.game;
public abstract class GameBase {
protected Player[] players;
protected int currentPlayer;
protected int size;
protected char[] grid;
public GameBase(Player[] players, int size) {
this.players = players;
currentPlayer = 0;
this.size = size;
grid = new char[size * size];
for (int i = 0; i < grid.length; i++) {
grid[i] = ' ';
}
}
public Player[] Players() {
return players;
}
public Player CurrentPlayer() {
return players[currentPlayer];
}
public int Size() {
return size;
}
public char[] Grid() {
return grid;
}
public abstract boolean ValidateMove(int index);
public abstract State PlayMove(int index);
}

View File

@@ -0,0 +1,19 @@
package org.toop.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

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

View File

@@ -0,0 +1,77 @@
package org.toop.game;
public class TTT extends GameBase {
private int moveCount;
public TTT(String player1, String player2) {
Player[] players = new Player[2];
players[0] = new Player(player1, 'X');
players[1] = new Player(player2, 'O');
super(players, 9);
moveCount = 0;
}
@Override
public boolean ValidateMove(int index) {
if (index < 0 || index > (size * size - 1)) {
return false;
}
return (grid[index] == ' ') ? true : false;
}
@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;
}
private 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;
}
}