73 Commits

Author SHA1 Message Date
cd1a375ed9 update README
All checks were successful
Linux arm64 / Build (push) Successful in 49s
2025-05-26 21:50:51 +02:00
3956f55c59 add screenshots 2025-05-26 21:50:45 +02:00
24e0fbc84c gradle: add deps in jar
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-05-26 21:42:52 +02:00
86ea62614b feat: add app chooser
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-05-26 21:33:02 +02:00
9d65432eff build: auto-detect os
All checks were successful
Linux arm64 / Build (push) Successful in 1m6s
2025-05-26 20:11:12 +02:00
f0efdf4105 Update README.md
All checks were successful
Linux arm64 / Build (push) Successful in 48s
2025-05-19 09:08:50 +00:00
e9a9916d9d add README
All checks were successful
Linux arm64 / Build (push) Successful in 47s
2025-05-19 09:01:44 +00:00
4f2c56a824 remove useless button
All checks were successful
Linux arm64 / Build (push) Successful in 36s
2025-05-19 09:54:45 +02:00
fee2f07232 Merge pull request 'doc' (#17) from doc into main
All checks were successful
Linux arm64 / Build (push) Successful in 45s
Reviewed-on: #17
2025-05-19 07:52:37 +00:00
c741044469 doc, fin
All checks were successful
Linux arm64 / Build (push) Successful in 34s
2025-05-18 23:30:30 +02:00
97950403a5 class documentation - a shitload of it
All checks were successful
Linux arm64 / Build (push) Successful in 33s
2025-05-18 20:08:22 +02:00
523eb094e1 3d promote (Fixes #14)
All checks were successful
Linux arm64 / Build (push) Successful in 35s
2025-05-18 12:18:09 +02:00
fd9aabb6a1 refactor dddview
All checks were successful
Linux arm64 / Build (push) Successful in 46s
2025-05-18 11:45:23 +02:00
1b31643f0b spawn popup at center 2025-05-18 11:45:17 +02:00
fefb826b38 free frame buffer 2025-05-18 11:37:57 +02:00
56f2aa3c56 close window on game end 2025-05-18 11:36:14 +02:00
0e8ee9eacd blocking popups 2025-05-18 11:25:10 +02:00
d3f0de81b1 remove left overs
All checks were successful
Linux arm64 / Build (push) Successful in 46s
2025-05-18 10:34:11 +02:00
70d7d81956 fix warnings
All checks were successful
Linux arm64 / Build (push) Successful in 47s
2025-05-17 18:52:45 +02:00
646eb6492e feat: working castling
All checks were successful
Linux arm64 / Build (push) Successful in 47s
2025-05-17 18:51:23 +02:00
01f0caf672 feat: working pgn simulation
All checks were successful
Linux arm64 / Build (push) Successful in 56s
2025-05-17 17:52:30 +02:00
e52988e511 disable castling buttons
Some checks failed
Linux arm64 / Build (push) Failing after 22s
2025-05-17 17:22:55 +02:00
6bc164937b prevent concurrent modification 2025-05-17 17:22:23 +02:00
e37da34f68 Merge pull request 'dev' (#12) from dev into main
All checks were successful
Linux arm64 / Build (push) Successful in 49s
Reviewed-on: #12
2025-05-17 15:05:23 +00:00
97d11f7105 suppres warning
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-05-17 17:04:40 +02:00
1da185678c test: don't wait on game (when possible)
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-05-17 17:03:30 +02:00
90daf662ea add CommanderSender (Fixes #9)
All checks were successful
Linux arm64 / Build (push) Successful in 36s
2025-05-17 16:48:04 +02:00
b33e333276 merge branch 3dunstable
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-05-17 15:58:36 +02:00
17537e09c6 removes old models
All checks were successful
Linux arm64 / Build (push) Successful in 46s
2025-05-17 15:31:56 +02:00
c80805fc66 refactor: fbo 2025-05-17 12:38:29 +02:00
0a1582cf07 round fps 2025-05-17 12:37:57 +02:00
96945d949a remove redundant interface 2025-05-17 10:22:07 +02:00
fl.du.pr Grens
459e458028 feat: popups 2025-05-16 17:53:01 +02:00
fl.du.pr Grens
6cec5d9e31 feat: spinning turn 2025-05-16 16:20:48 +02:00
l
94870e65c2 imgui (#10)
Co-authored-by: Persson-dev <sim16.prib@gmail.com>
Reviewed-on: #10
2025-05-16 13:35:38 +00:00
9ff433c257 fix null error 2025-05-16 10:44:02 +02:00
dba8e8fb1e feat: add imgui 2025-05-16 10:41:33 +02:00
Janet-Doe
39c7ebefe6 fix coloring bug on double click 2025-05-14 16:46:12 +02:00
Janet-Doe
264391ba81 functional move in 3D view 2025-05-14 15:57:01 +02:00
Janet-Doe
ce977c3b48 debug 2025-05-14 15:56:08 +02:00
Janet-Doe
046f680937 onclick functional 2025-05-14 10:10:14 +02:00
11e6a94ed7 rules package
All checks were successful
Linux arm64 / Build (push) Successful in 47s
2025-05-10 18:09:45 +02:00
c1bf9bcaf9 remove PawnIdentifier 2025-05-10 18:08:55 +02:00
810a0f2159 feat: add ai castling (Fixes #4)
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-05-06 17:15:55 +02:00
58f02f681c rename GameAdapter
All checks were successful
Linux arm64 / Build (push) Successful in 51s
2025-05-06 11:53:26 +02:00
83d5737789 You spin me right 'round, baby, right 'round 2025-05-06 09:55:48 +02:00
ffd77d9777 world: add ejectPiece 2025-04-30 19:16:27 +02:00
ec98b05d61 free opengl resources 2025-04-28 18:23:29 +02:00
0fb24263e0 camel case 2025-04-28 18:08:10 +02:00
533e6260d5 refactor movePiece 2025-04-28 18:06:37 +02:00
0c6ab1df4b add 3d position cache 2025-04-28 17:52:29 +02:00
5f70daea91 board model add constants 2025-04-28 17:32:24 +02:00
dd043794d6 add comment 2025-04-28 17:31:46 +02:00
de4ed869ea feat: change board cells color 2025-04-28 11:04:41 +02:00
b57fa1482b add small example 2025-04-27 20:18:31 +02:00
cbbce43ede raycast cursor 2025-04-27 20:12:38 +02:00
1b61eca58b models: remove uv 2025-04-27 11:02:55 +02:00
9bc09cf812 add world interface 2025-04-27 11:00:14 +02:00
c488f3b4e0 rename PieceModel 2025-04-27 10:14:05 +02:00
9f35bd3c30 opengl package 2025-04-27 10:12:52 +02:00
6ca5d1294f better light 2025-04-26 19:24:52 +02:00
b62dcffcb1 refactor 2025-04-26 18:18:27 +02:00
65c904478f enable face culling 2025-04-26 17:26:27 +02:00
f8ae19fee8 set pieces color 2025-04-26 12:35:37 +02:00
1b22de17d8 change background color 2025-04-26 12:30:29 +02:00
24104fedf5 fix pieces rotation 2025-04-26 12:23:14 +02:00
5b6fce11bc refactor board model 2025-04-26 12:20:00 +02:00
ab309ae48a fix aspectRatio 2025-04-26 12:14:22 +02:00
7af9807127 omg ça marche 2025-04-26 12:00:48 +02:00
cff2d92070 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2025-04-25 17:03:28 +02:00
098b605799 yodaaaaaa 2025-04-24 11:12:53 +02:00
ce0424ff8b osekour 2025-04-22 17:05:26 +02:00
4bd16026e1 begin 3d 2025-04-22 15:02:24 +02:00
132 changed files with 3509 additions and 905 deletions

1
.gitattributes vendored
View File

@@ -6,3 +6,4 @@
# These are Windows script files and should use crlf # These are Windows script files and should use crlf
*.bat text eol=crlf *.bat text eol=crlf
*.glb filter=lfs diff=lfs merge=lfs -text *.glb filter=lfs diff=lfs merge=lfs -text
*.fbx filter=lfs diff=lfs merge=lfs -text

4
.gitignore vendored
View File

@@ -8,5 +8,5 @@ app/bin
.vscode .vscode
audio/*.wav *.wav
app/audio/*.wav imgui.ini

42
README.md Normal file
View File

@@ -0,0 +1,42 @@
# 3DChess ♟
Super chess engine. Outputs to console, Java Swing and 3D (Lwjgl) !
## Features 🌟
- Views:
- Console
- Java Swing
- OpengGL (3D)
- Audio
- Pgn support (import/export)
- Undo moves support
- AIs:
- DumbAI: just makes some random moves
- HungryAI: tries to eat the biggest piece (no depth, no thinking)
- AlphaBetaAI: plays the best move by searching through all possible moves
## Screenshots 🖼
[[screenshots/select_view.png]]
[[screenshots/2d_view.png]]
[[screenshots/3d_view.png]]
## Binaries 📦
Precompiled binaries can be found [here](https://git.ale-pri.com/Crabs/3DChess/releases)
## Run 🏃
```
./gradlew run
```
## Run tests 🗣️🔥
```
./gradlew test
```

View File

@@ -16,21 +16,29 @@ repositories {
mavenCentral() mavenCentral()
} }
def os = "linux"
def lwjgl_version = "3.3.6" def lwjgl_version = "3.3.6"
def lwjgl_natives = "natives-linux" def lwjgl_natives = "natives-$os"
def imgui_version = "1.87.0"
dependencies { dependencies {
// Use JUnit Jupiter for testing. // Use JUnit Jupiter for testing.
testImplementation "org.junit.jupiter:junit-jupiter:5.11.4" testImplementation "org.junit.jupiter:junit-jupiter:5.9.1"
implementation "org.lwjgl:lwjgl:$lwjgl_version" implementation "org.lwjgl:lwjgl:$lwjgl_version"
implementation "org.lwjgl:lwjgl-opengl:$lwjgl_version" implementation "org.lwjgl:lwjgl-opengl:$lwjgl_version"
implementation "org.lwjgl:lwjgl-glfw:$lwjgl_version" implementation "org.lwjgl:lwjgl-glfw:$lwjgl_version"
implementation "org.lwjgl:lwjgl-assimp:$lwjgl_version"
implementation "org.joml:joml:1.10.8" implementation "org.joml:joml:1.10.8"
implementation "org.lwjgl:lwjgl::$lwjgl_natives" implementation "org.lwjgl:lwjgl::$lwjgl_natives"
implementation "org.lwjgl:lwjgl-opengl::$lwjgl_natives" implementation "org.lwjgl:lwjgl-opengl::$lwjgl_natives"
implementation "org.lwjgl:lwjgl-glfw::$lwjgl_natives" implementation "org.lwjgl:lwjgl-glfw::$lwjgl_natives"
implementation "org.lwjgl:lwjgl-assimp::$lwjgl_natives"
implementation "io.github.spair:imgui-java-binding:$imgui_version"
implementation "io.github.spair:imgui-java-natives-$os:$imgui_version"
implementation "io.github.spair:imgui-java-app:$imgui_version"
} }
application { application {
@@ -39,24 +47,24 @@ application {
applicationName = "3DChess" applicationName = "3DChess"
} }
// Add libraries into the final jar
jar {
archiveBaseName = rootProject.getName() + "-" + os
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest {
attributes "Main-Class": application.mainClass
}
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
}
run { run {
standardInput = System.in standardInput = System.in
} }
// Apply a specific Java toolchain to ease working on different environments.
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
jar {
manifest {
attributes 'Main-Class': application.mainClass
}
}
tasks.named('test') { tasks.named('test') {
// Use JUnit Platform for unit tests. // Use JUnit Platform for unit tests.
useJUnitPlatform() useJUnitPlatform()

View File

@@ -1,33 +1,244 @@
package chess; package chess;
import java.util.Scanner; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import chess.view.consolerender.Colors; import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import chess.ai.AI;
import chess.ai.ais.AlphaBetaAI;
import chess.ai.ais.DumbAI;
import chess.ai.ais.HungryAI;
import chess.ai.alphabeta.AlphaBetaConsolePrinter;
import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand;
import chess.controller.event.GameAdapter;
import chess.model.Color;
import chess.model.Game;
import chess.pgn.PgnExport;
import chess.view.GameView;
import chess.view.DDDrender.DDDView;
import chess.view.audio.GameAudio;
import chess.view.consolerender.Console;
import chess.view.simplerender.Window;
/**
* Main class of the chess game. Asks the user for the version to use and runs
* the according main.
*
* @author Grenier Lilas
* @author Pribylski Simon
* @see ConsoleMain
* @see SwingMain
* @see OpenGLMain
*/
public class App { public class App {
public static void main(String[] args) {
System.out.println(Colors.RED + "Credits: Grenier Lilas, Pribylski Simon." + Colors.RESET); private static final String version = "v1.1";
System.out.println("""
Pick the version to use: private final JFrame frame;
1 - Console private final JPanel content;
2 - Window
3 - 3D."""); private ButtonGroup viewSelection;
Scanner scan = new Scanner(System.in); private JRadioButton consoleButton;
String line = scan.nextLine(); private JRadioButton swingButton;
scan.close(); private JRadioButton openglButton;
switch (line) {
case "1", "Console", "console": private final JRadioButton[] manualButtons = new JRadioButton[2];
ConsoleMain.main(args); private final JRadioButton[] dumbButtons = new JRadioButton[2];
break; private final JRadioButton[] hungryButtons = new JRadioButton[2];
case "2", "Window", "window": private final JRadioButton[] alphaButtons = new JRadioButton[2];
SwingMain.main(args);
break; private JCheckBox audioCheck;
case "3", "3D", "3d": private JCheckBox pgnCheck;
OpenGLMain.main(args);
break; private void drawViewSelection() {
default: JPanel viewPanel = new JPanel();
System.out.println("Invalid input");
break; JLabel text = new JLabel("Display mode: ");
viewPanel.add(text);
viewSelection = new ButtonGroup();
consoleButton = new JRadioButton("Console");
viewPanel.add(consoleButton);
viewSelection.add(consoleButton);
swingButton = new JRadioButton("2D Window");
viewPanel.add(swingButton);
viewSelection.add(swingButton);
openglButton = new JRadioButton("3D Window");
viewPanel.add(openglButton);
viewSelection.add(openglButton);
openglButton.setSelected(true);
content.add(viewPanel);
}
private void drawPlayer(Color color) {
JPanel playerContent = new JPanel();
JLabel text = new JLabel(color + ": ");
playerContent.add(text);
ButtonGroup playerSelection = new ButtonGroup();
int playerIndex = color.ordinal();
JRadioButton manualButton = new JRadioButton("Manual");
playerContent.add(manualButton);
playerSelection.add(manualButton);
manualButton.setSelected(true);
JRadioButton dumbButton = new JRadioButton("DumbAI");
playerContent.add(dumbButton);
playerSelection.add(dumbButton);
JRadioButton hungryButton = new JRadioButton("HungryAI");
playerContent.add(hungryButton);
playerSelection.add(hungryButton);
JRadioButton alphaButton = new JRadioButton("AlphaBetaAI");
playerContent.add(alphaButton);
playerSelection.add(alphaButton);
content.add(playerContent);
manualButtons[playerIndex] = manualButton;
dumbButtons[playerIndex] = dumbButton;
hungryButtons[playerIndex] = hungryButton;
alphaButtons[playerIndex] = alphaButton;
}
private void drawFooter() {
JPanel footerArea = new JPanel();
this.audioCheck = new JCheckBox("Audio");
footerArea.add(this.audioCheck);
this.pgnCheck = new JCheckBox("PGN export");
footerArea.add(this.pgnCheck);
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
startGame();
}
});
footerArea.add(startButton);
content.add(footerArea);
}
public App() {
frame = new JFrame();
frame.setTitle("3DChess " + version);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
frame.setContentPane(content);
frame.setLocationRelativeTo(null);
frame.setSize(500, 500);
drawViewSelection();
drawPlayer(Color.White);
drawPlayer(Color.Black);
drawFooter();
frame.setVisible(true);
}
private GameView getViewSelection(CommandExecutor commandExecutor) {
if (consoleButton.isSelected())
return new Console(commandExecutor);
if (swingButton.isSelected())
return new Window(commandExecutor);
return new DDDView(commandExecutor);
}
private AI getAISelection(CommandExecutor commandExecutor, Color color) {
int playerIndex = color.ordinal();
if (dumbButtons[playerIndex].isSelected())
return new DumbAI(commandExecutor, color);
if (hungryButtons[playerIndex].isSelected())
return new HungryAI(commandExecutor, color);
if (alphaButtons[playerIndex].isSelected()) {
AlphaBetaAI ai = new AlphaBetaAI(commandExecutor, color, 5);
AlphaBetaConsolePrinter printer = new AlphaBetaConsolePrinter(ai);
printer.connect();
return ai;
} }
return null;
}
private void addAI(CommandExecutor commandExecutor, Color color) {
AI ai = getAISelection(commandExecutor, color);
if (ai == null)
return;
commandExecutor.addListener(ai);
}
private void addOptionalAudio(CommandExecutor commandExecutor) {
if (this.audioCheck.isSelected())
commandExecutor.addListener(new GameAudio());
}
private void addOptionalPgnExport(CommandExecutor commandExecutor, Game game) {
if (!this.pgnCheck.isSelected())
return;
commandExecutor.addListener(new GameAdapter() {
@Override
public void onGameEnd() {
System.out.println(PgnExport.exportGame(game));
}
});
}
private void addAIs(CommandExecutor commandExecutor) {
addAI(commandExecutor, Color.White);
addAI(commandExecutor, Color.Black);
}
private GameView addView(CommandExecutor commandExecutor) {
GameView view = getViewSelection(commandExecutor);
commandExecutor.addListener(view);
return view;
}
private void startGame() {
Game game = new Game();
CommandExecutor commandExecutor = new CommandExecutor(game);
GameView view = addView(commandExecutor);
addAIs(commandExecutor);
addOptionalAudio(commandExecutor);
addOptionalPgnExport(commandExecutor, game);
commandExecutor.executeCommand(new NewGameCommand());
frame.dispose();
view.run();
}
public static void main(String[] args) {
new App();
} }
} }

View File

@@ -3,6 +3,9 @@
*/ */
package chess; package chess;
/**
* Main class for the console version of the game.
*/
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand; import chess.controller.commands.NewGameCommand;
import chess.model.Game; import chess.model.Game;

View File

@@ -1,9 +1,29 @@
package chess; package chess;
import chess.view.DDDrender.Window; import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand;
import chess.model.Game;
import chess.pgn.PgnFileSimulator;
import chess.view.DDDrender.DDDView;
/**
* Main class for the 3D Window version of the game.
*/
public class OpenGLMain { public class OpenGLMain {
public static void main(String[] args) { public static void main(String[] args) {
new Window().run(); Game game = new Game();
CommandExecutor commandExecutor = new CommandExecutor(game);
PgnFileSimulator fileSimulator = new PgnFileSimulator(commandExecutor, "games/PromoteTest.pgn");
DDDView ddd = new DDDView(commandExecutor);
commandExecutor.addListener(ddd);
commandExecutor.addListener(fileSimulator);
commandExecutor.executeCommand(new NewGameCommand());
ddd.run();
commandExecutor.close();
} }
} }

View File

@@ -1,22 +1,25 @@
package chess; package chess;
import chess.ai.minimax.AlphaBetaAI; import chess.ai.ais.AlphaBetaAI;
import chess.ai.minimax.AlphaBetaConsolePrinter; import chess.ai.alphabeta.AlphaBetaConsolePrinter;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.commands.NewGameCommand; import chess.controller.commands.NewGameCommand;
import chess.controller.event.GameAdaptator; import chess.controller.event.GameAdapter;
import chess.model.Color; import chess.model.Color;
import chess.model.Game; import chess.model.Game;
import chess.pgn.PgnExport; import chess.pgn.PgnExport;
import chess.view.audio.GameAudio; import chess.view.audio.GameAudio;
import chess.view.simplerender.Window; import chess.view.simplerender.Window;
/**
* Main class for the 2D window version of the game.
*/
public class SwingMain { public class SwingMain {
public static void main(String[] args) { public static void main(String[] args) {
Game game = new Game(); Game game = new Game();
CommandExecutor commandExecutor = new CommandExecutor(game); CommandExecutor commandExecutor = new CommandExecutor(game);
Window window = new Window(commandExecutor, true); Window window = new Window(commandExecutor);
commandExecutor.addListener(window); commandExecutor.addListener(window);
AlphaBetaAI ai = new AlphaBetaAI(commandExecutor, Color.Black, 5); AlphaBetaAI ai = new AlphaBetaAI(commandExecutor, Color.Black, 5);
@@ -31,7 +34,7 @@ public class SwingMain {
// Window window2 = new Window(ai2.getSimulation(), false); // Window window2 = new Window(ai2.getSimulation(), false);
// ai2.getSimulation().addListener(window2); // ai2.getSimulation().addListener(window2);
commandExecutor.addListener(new GameAdaptator(){ commandExecutor.addListener(new GameAdapter(){
@Override @Override
public void onGameEnd() { public void onGameEnd() {
System.out.println(PgnExport.exportGame(game)); System.out.println(PgnExport.exportGame(game));

View File

@@ -2,20 +2,18 @@ package chess.ai;
import java.util.List; import java.util.List;
import chess.controller.Command; import chess.ai.actions.AIAction;
import chess.ai.actions.AIActions;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.Command.CommandResult; import chess.controller.event.GameAdapter;
import chess.controller.commands.GetPieceAtCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.controller.commands.GetAllowedCastlingsCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.event.GameAdaptator;
import chess.model.Color; import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece; import chess.model.Piece;
public abstract class AI extends GameAdaptator{ /**
* Abstract class, used to code bots.
*/
public abstract class AI extends GameAdapter implements AIActions {
protected final CommandExecutor commandExecutor; protected final CommandExecutor commandExecutor;
protected final Color color; protected final Color color;
@@ -26,7 +24,6 @@ public abstract class AI extends GameAdaptator{
} }
protected abstract void play(); protected abstract void play();
protected abstract void promote(Coordinate pawnCoords);
@Override @Override
public void onPlayerTurn(Color color, boolean undone) { public void onPlayerTurn(Color color, boolean undone) {
@@ -37,43 +34,12 @@ public abstract class AI extends GameAdaptator{
} }
@Override @Override
public void onPromotePawn(Coordinate pieceCoords) { public CommandExecutor getCommandExecutor() {
Piece pawn = pieceAt(pieceCoords); return this.commandExecutor;
if (pawn.getColor() != this.color)
return;
promote(pieceCoords);
} }
protected Piece pieceAt(Coordinate coordinate) { public Color getColor() {
GetPieceAtCommand command = new GetPieceAtCommand(coordinate); return color;
sendCommand(command);
return command.getPiece();
}
protected List<Move> getAllowedMoves() {
return getAllowedMoves(this.commandExecutor);
}
protected List<Move> getAllowedMoves(CommandExecutor commandExecutor) {
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
sendCommand(cmd, commandExecutor);
return cmd.getMoves();
}
protected CastlingResult getAllowedCastlings() {
GetAllowedCastlingsCommand cmd2 = new GetAllowedCastlingsCommand();
sendCommand(cmd2);
return cmd2.getCastlingResult();
}
protected CommandResult sendCommand(Command command) {
return sendCommand(command, this.commandExecutor);
}
protected CommandResult sendCommand(Command command, CommandExecutor commandExecutor) {
CommandResult result = commandExecutor.executeCommand(command);
assert result != CommandResult.NotAllowed : "Command not allowed!";
return result;
} }
} }

View File

@@ -1,61 +0,0 @@
package chess.ai;
import java.util.List;
import java.util.Random;
import chess.controller.CommandExecutor;
import chess.controller.commands.CastlingCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
public class DumbAI extends AI {
private final Random random = new Random();
public DumbAI(CommandExecutor commandExecutor, Color color) {
super(commandExecutor, color);
}
@Override
protected void play() {
CastlingResult castlings = getAllowedCastlings();
List<Move> moves = getAllowedMoves();
switch (castlings) {
case Both: {
int randomMove = this.random.nextInt(moves.size() + 2);
if (randomMove < moves.size() - 2)
break;
sendCommand(new CastlingCommand(randomMove == moves.size()));
return;
}
case Small:
case Big: {
int randomMove = this.random.nextInt(moves.size() + 1);
if (randomMove != moves.size())
break;
sendCommand(new CastlingCommand(castlings == CastlingResult.Big));
return;
}
default:
break;
}
int randomMove = this.random.nextInt(moves.size());
sendCommand(new MoveCommand(moves.get(randomMove)));
}
@Override
protected void promote(Coordinate pawnCoords) {
int promote = this.random.nextInt(PromoteType.values().length);
sendCommand(new PromoteCommand(PromoteType.values()[promote]));
}
}

View File

@@ -0,0 +1,83 @@
package chess.ai;
import java.util.List;
import chess.ai.actions.AIAction;
import chess.ai.actions.AIActions;
import chess.controller.CommandExecutor;
import chess.controller.CommandSender;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.event.EmptyGameDispatcher;
import chess.controller.event.GameAdapter;
import chess.model.ChessBoard;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Game;
import chess.model.Move;
import chess.model.LightGame;
/**
* Emulates the moves of a bot on a secondary board.
*/
public class GameSimulation extends GameAdapter implements AIActions {
private final CommandExecutor simulation;
private final Game gameSimulation;
public GameSimulation() {
this.gameSimulation = new LightGame();
this.simulation = new CommandExecutor(gameSimulation, new EmptyGameDispatcher());
}
@Override
public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
sendPawnPromotion(promotion);
}
@Override
public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
if (bigCastling)
sendBigCastling();
else
sendCastling();
}
@Override
public void onMove(Move move, boolean captured) {
sendMove(move);
}
@Override
public void onGameStart() {
sendStartGame();
}
@Override
public void onPlayerTurn(Color color, boolean undone) {
if (undone)
sendUndo();
}
@Override
public CommandExecutor getCommandExecutor() {
return simulation;
}
public Game getGame() {
return gameSimulation;
}
public ChessBoard getBoard() {
return this.gameSimulation.getBoard();
}
public Color getPlayerTurn() {
return this.gameSimulation.getPlayerTurn();
}
public void close() {
this.simulation.close();
}
}

View File

@@ -1,61 +0,0 @@
package chess.ai;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import chess.controller.CommandExecutor;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
public class HungryAI extends AI {
private final PieceCost pieceCost;
private final Random random;
public HungryAI(CommandExecutor commandExecutor, Color color) {
super(commandExecutor, color);
this.pieceCost = new PieceCost(color);
this.random = new Random();
}
private int getMoveCost(Move move) {
Piece piece = pieceAt(move.getDeadPieceCoords());
return - (int) pieceCost.getCost(piece);
}
private List<Move> getBestMoves() {
List<Move> moves = getAllowedMoves();
List<Move> bestMoves = new ArrayList<>();
int bestCost = 0;
for (Move move : moves) {
int moveCost = getMoveCost(move);
if (moveCost == bestCost) {
bestMoves.add(move);
} else if (moveCost > bestCost) {
bestMoves.clear();
bestMoves.add(move);
bestCost = moveCost;
}
}
return bestMoves;
}
@Override
protected void play() {
List<Move> bestMoves = getBestMoves();
int randomMove = this.random.nextInt(bestMoves.size());
this.commandExecutor.executeCommand(new MoveCommand(bestMoves.get(randomMove)));
}
@Override
protected void promote(Coordinate pawnCoords) {
sendCommand(new PromoteCommand(PromoteType.Queen));
}
}

View File

@@ -10,6 +10,10 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Evaluate the cost of pieces for AI algorithm.
*/
public class PieceCost implements PieceVisitor<Float> { public class PieceCost implements PieceVisitor<Float> {
private final Color player; private final Color player;

View File

@@ -16,6 +16,10 @@ import chess.model.pieces.Rook;
public class PiecePosCost implements PieceVisitor<List<Float>> { public class PiecePosCost implements PieceVisitor<List<Float>> {
/**
* Evaluate the cost of position for AI algorithm.
*/
private final Color color; private final Color color;
private static final List<Float> BISHOP = Arrays.asList( private static final List<Float> BISHOP = Arrays.asList(

View File

@@ -0,0 +1,36 @@
package chess.ai.actions;
import chess.controller.CommandExecutor;
import chess.controller.CommandSender;
import chess.controller.commands.UndoCommand;
/**
* Abstract class, manage the possible actions of a bot.
*/
public abstract class AIAction implements CommandSender {
private final CommandExecutor commandExecutor;
public AIAction(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor;
}
@Override
public CommandExecutor getCommandExecutor() {
return this.commandExecutor;
}
public void undoAction(CommandExecutor commandExecutor) {
sendCommand(new UndoCommand(), commandExecutor);
}
public void undoAction() {
undoAction(this.commandExecutor);
}
public void applyAction() {
applyAction(this.commandExecutor);
}
public abstract void applyAction(CommandExecutor commandExecutor);
}

View File

@@ -0,0 +1,23 @@
package chess.ai.actions;
import chess.controller.CommandExecutor;
import chess.controller.commands.CastlingCommand;
/**
* Manage the transition between model and bots when it comes to Castling command.
*/
public class AIActionCastling extends AIAction{
private final boolean bigCastling;
public AIActionCastling(CommandExecutor commandExecutor, boolean bigCastling) {
super(commandExecutor);
this.bigCastling = bigCastling;
}
@Override
public void applyAction(CommandExecutor commandExecutor) {
sendCommand(new CastlingCommand(this.bigCastling), commandExecutor);
}
}

View File

@@ -0,0 +1,28 @@
package chess.ai.actions;
import chess.controller.CommandExecutor;
import chess.controller.commands.MoveCommand;
import chess.model.Move;
/**
* Manage the transition between model and bots when it comes to Move command.
*/
public class AIActionMove extends AIAction{
private final Move move;
public AIActionMove(CommandExecutor commandExecutor, Move move) {
super(commandExecutor);
this.move = move;
}
public Move getMove() {
return move;
}
@Override
public void applyAction(CommandExecutor commandExecutor) {
sendCommand(new MoveCommand(move), commandExecutor);
}
}

View File

@@ -0,0 +1,29 @@
package chess.ai.actions;
import chess.controller.CommandExecutor;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Move;
/**
* Manage the transition between model and bots when it comes to Move and Promotion command.
*/
public class AIActionMoveAndPromote extends AIAction{
private final Move move;
private final PromoteType promoteType;
public AIActionMoveAndPromote(CommandExecutor commandExecutor, Move move, PromoteType promoteType) {
super(commandExecutor);
this.move = move;
this.promoteType = promoteType;
}
@Override
public void applyAction(CommandExecutor commandExecutor) {
sendCommand(new MoveCommand(move), commandExecutor);
sendCommand(new PromoteCommand(promoteType), commandExecutor);
}
}

View File

@@ -0,0 +1,69 @@
package chess.ai.actions;
import java.util.ArrayList;
import java.util.List;
import chess.controller.Command;
import chess.controller.CommandSender;
import chess.controller.Command.CommandResult;
import chess.controller.CommandExecutor;
import chess.controller.commands.GetAllowedCastlingsCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.commands.GetPieceAtCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
import chess.model.pieces.Pawn;
/**
* Search and compiles the different actions possible to a bot.
*/
public interface AIActions extends CommandSender {
default List<AIAction> getAllowedActions() {
List<Move> moves = getPlayerMoves();
CastlingResult castlingResult = getAllowedCastlings();
List<AIAction> actions = new ArrayList<>(moves.size() + 10);
for (Move move : moves) {
Piece movingPiece = getPieceAt(move.getStart());
if (movingPiece instanceof Pawn) {
int enemyLineY = movingPiece.getColor() == Color.White ? 0 : 7;
if (move.getFinish().getY() == enemyLineY) {
PromoteType[] promotes = PromoteType.values();
for (PromoteType promote : promotes) {
actions.add(new AIActionMoveAndPromote(getCommandExecutor(), move, promote));
}
continue;
}
}
actions.add(new AIActionMove(getCommandExecutor(), move));
}
switch (castlingResult) {
case Both:
actions.add(new AIActionCastling(getCommandExecutor(), true));
actions.add(new AIActionCastling(getCommandExecutor(), false));
break;
case Small:
actions.add(new AIActionCastling(getCommandExecutor(), false));
break;
case Big:
actions.add(new AIActionCastling(getCommandExecutor(), true));
break;
case None:
break;
}
return actions;
}
}

View File

@@ -1,4 +1,4 @@
package chess.ai.minimax; package chess.ai.ais;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -7,16 +7,17 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
import chess.ai.AI; import chess.ai.*;
import chess.ai.actions.*;
import chess.ai.alphabeta.*;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color; import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import common.Signal1; import common.Signal1;
/**
* Extends AI. Bot based on the alpha-beta method of resolution.
*/
public class AlphaBetaAI extends AI { public class AlphaBetaAI extends AI {
private final int searchDepth; private final int searchDepth;
@@ -38,23 +39,23 @@ public class AlphaBetaAI extends AI {
new AlphaBetaThreadCreator(commandExecutor, color, threadCount)); new AlphaBetaThreadCreator(commandExecutor, color, threadCount));
} }
private Move getBestMove() { private AIAction getBestMove() {
List<Move> moves = getAllowedMoves(); List<AIAction> actions = getAllowedActions();
List<Future<Float>> moveEvaluations = new ArrayList<>(50); List<Future<Float>> moveEvaluations = new ArrayList<>(actions.size());
float bestMoveValue = MIN_FLOAT; float bestMoveValue = MIN_FLOAT;
Move bestMove = null; AIAction bestMove = null;
this.onStartEval.emit(moves.size()); this.onStartEval.emit(actions.size());
for (Move move : moves) { for (AIAction action : actions) {
moveEvaluations.add(this.threadPool.submit(() -> { moveEvaluations.add(this.threadPool.submit(() -> {
return AlphaBetaThreadCreator.getMoveValue(move, this.searchDepth); return AlphaBetaThreadCreator.getMoveValue(action, this.searchDepth);
})); }));
} }
for (int i = 0; i < moves.size(); i++) { for (int i = 0; i < actions.size(); i++) {
this.onProgress.emit((float) i / (float) moves.size()); this.onProgress.emit((float) i / (float) actions.size());
Move move = moves.get(i); AIAction action = actions.get(i);
float value = MIN_FLOAT; float value = MIN_FLOAT;
try { try {
@@ -64,7 +65,7 @@ public class AlphaBetaAI extends AI {
} }
if (value > bestMoveValue) { if (value > bestMoveValue) {
bestMoveValue = value; bestMoveValue = value;
bestMove = move; bestMove = action;
} }
} }
@@ -80,13 +81,13 @@ public class AlphaBetaAI extends AI {
@Override @Override
protected void play() { protected void play() {
Move move = getBestMove(); AIAction move = getBestMove();
sendCommand(new MoveCommand(move)); move.applyAction();
} }
@Override @Override
protected void promote(Coordinate pawnCoords) { public CommandExecutor getCommandExecutor() {
sendCommand(new PromoteCommand(PromoteType.Queen)); return super.getCommandExecutor();
} }
} }

View File

@@ -0,0 +1,32 @@
package chess.ai.ais;
import java.util.List;
import java.util.Random;
import chess.ai.*;
import chess.ai.actions.AIAction;
import chess.controller.CommandExecutor;
import chess.model.Color;
/**
* Bot, takes a random decision among his possible moves.
*/
public class DumbAI extends AI {
private final Random random = new Random();
public DumbAI(CommandExecutor commandExecutor, Color color) {
super(commandExecutor, color);
}
@Override
protected void play() {
List<AIAction> actions = getAllowedActions();
int randomAction = this.random.nextInt(actions.size());
actions.get(randomAction).applyAction();
}
}

View File

@@ -0,0 +1,64 @@
package chess.ai.ais;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import chess.ai.actions.AIAction;
import chess.ai.actions.AIActionMove;
import chess.controller.CommandExecutor;
import chess.model.Color;
import chess.model.Move;
import chess.model.Piece;
import chess.ai.*;
import chess.ai.actions.*;
import chess.ai.actions.AIActions;
/**
* Bot, takes the optimal piece when possible, or make a random move if no piece can be taken during the turn.
* @see PieceCost
* @see PiecePosCost
*/
public class HungryAI extends AI {
private final PieceCost pieceCost;
private final Random random;
public HungryAI(CommandExecutor commandExecutor, Color color) {
super(commandExecutor, color);
this.pieceCost = new PieceCost(color);
this.random = new Random();
}
private int getMoveCost(Move move) {
Piece piece = getPieceAt(move.getDeadPieceCoords());
return -(int) pieceCost.getCost(piece);
}
private List<AIAction> getBestMoves() {
List<AIAction> actions = getAllowedActions();
List<AIAction> bestMoves = new ArrayList<>();
int bestCost = 0;
for (AIAction action : actions) {
if (action instanceof AIActionMove move) {
int moveCost = getMoveCost(move.getMove());
if (moveCost == bestCost) {
bestMoves.add(move);
} else if (moveCost > bestCost) {
bestMoves.clear();
bestMoves.add(move);
bestCost = moveCost;
}
}
}
return bestMoves;
}
@Override
protected void play() {
List<AIAction> bestMoves = getBestMoves();
bestMoves.get(this.random.nextInt(bestMoves.size())).applyAction();
}
}

View File

@@ -1,5 +1,10 @@
package chess.ai.minimax; package chess.ai.alphabeta;
import chess.ai.ais.AlphaBetaAI;
/**
* Print the action of an alpha-beta bot on the console.
* @see AlphaBetaAI
*/
public class AlphaBetaConsolePrinter { public class AlphaBetaConsolePrinter {
private final AlphaBetaAI ai; private final AlphaBetaAI ai;

View File

@@ -1,4 +1,4 @@
package chess.ai.minimax; package chess.ai.alphabeta;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -6,14 +6,20 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import chess.ai.GameSimulation;
import chess.ai.PieceCost; import chess.ai.PieceCost;
import chess.ai.PiecePosCost; import chess.ai.PiecePosCost;
import chess.ai.actions.AIAction;
import chess.model.ChessBoard; import chess.model.ChessBoard;
import chess.model.Color; import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece; import chess.model.Piece;
/**
* Manage the threads for an alpha-beta bot.
* @see AlphaBetaAI
*/
public class AlphaBetaThread extends Thread { public class AlphaBetaThread extends Thread {
private final GameSimulation simulation; private final GameSimulation simulation;
@@ -52,27 +58,27 @@ public class AlphaBetaThread extends Thread {
return result; return result;
} }
public float getMoveValue(Move move, int searchDepth) { public float getMoveValue(AIAction move, int searchDepth) {
this.simulation.tryMove(move); move.applyAction(this.simulation.getCommandExecutor());
float value = -negaMax(searchDepth - 1, MIN_FLOAT, MAX_FLOAT); float value = -negaMax(searchDepth - 1, MIN_FLOAT, MAX_FLOAT);
this.simulation.undoMove(); move.undoAction(this.simulation.getCommandExecutor());
return value; return value;
} }
private float negaMax(int depth, float alpha, float beta) { private float negaMax(int depth, float alpha, float beta) {
float value = MIN_FLOAT; float value = MIN_FLOAT;
List<Move> moves = this.simulation.getAllowedMoves(); List<AIAction> moves = this.simulation.getAllowedActions();
if (moves.isEmpty()) if (moves.isEmpty())
return -getEndGameEvaluation(); return -getEndGameEvaluation();
List<Entry<Move, Float>> movesCost = new ArrayList<>(moves.size()); List<Entry<AIAction, Float>> movesCost = new ArrayList<>(moves.size());
for (Move move : moves) { for (AIAction move : moves) {
this.simulation.tryMove(move); move.applyAction();
movesCost.add(Map.entry(move, -getBoardEvaluation())); movesCost.add(Map.entry(move, -getBoardEvaluation()));
this.simulation.undoMove(); move.undoAction();
} }
Collections.sort(movesCost, (first, second) -> { Collections.sort(movesCost, (first, second) -> {
@@ -83,10 +89,10 @@ public class AlphaBetaThread extends Thread {
return -movesCost.getFirst().getValue(); return -movesCost.getFirst().getValue();
for (var moveEntry : movesCost) { for (var moveEntry : movesCost) {
Move move = moveEntry.getKey(); AIAction move = moveEntry.getKey();
this.simulation.tryMove(move); move.applyAction();
value = Float.max(value, -negaMax(depth - 1, -beta, -alpha)); value = Float.max(value, -negaMax(depth - 1, -beta, -alpha));
this.simulation.undoMove(); move.undoAction();
alpha = Float.max(alpha, value); alpha = Float.max(alpha, value);
if (alpha >= beta) if (alpha >= beta)
return value; return value;

View File

@@ -1,11 +1,16 @@
package chess.ai.minimax; package chess.ai.alphabeta;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import chess.ai.GameSimulation;
import chess.ai.actions.AIAction;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.model.Color; import chess.model.Color;
import chess.model.Move;
/**
* Create the threads for an alpha-beta bot.
* @see AlphaBetaAI
*/
public class AlphaBetaThreadCreator implements ThreadFactory{ public class AlphaBetaThreadCreator implements ThreadFactory{
private final Color color; private final Color color;
@@ -21,7 +26,7 @@ public class AlphaBetaThreadCreator implements ThreadFactory{
} }
} }
public static float getMoveValue(Move move, int searchDepth) { public static float getMoveValue(AIAction move, int searchDepth) {
AlphaBetaThread t = (AlphaBetaThread) Thread.currentThread(); AlphaBetaThread t = (AlphaBetaThread) Thread.currentThread();
return t.getMoveValue(move, searchDepth); return t.getMoveValue(move, searchDepth);
} }

View File

@@ -1,103 +0,0 @@
package chess.ai.minimax;
import java.util.List;
import chess.controller.Command;
import chess.controller.Command.CommandResult;
import chess.controller.CommandExecutor;
import chess.controller.commands.CastlingCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.NewGameCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.UndoCommand;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.event.EmptyGameDispatcher;
import chess.controller.event.GameAdaptator;
import chess.model.ChessBoard;
import chess.model.Color;
import chess.model.Game;
import chess.model.Move;
import chess.model.PermissiveGame;
public class GameSimulation extends GameAdaptator {
private final CommandExecutor simulation;
private final Game gameSimulation;
public GameSimulation() {
this.gameSimulation = new PermissiveGame();
this.simulation = new CommandExecutor(gameSimulation, new EmptyGameDispatcher());
}
protected CommandResult sendCommand(Command command) {
CommandResult result = this.simulation.executeCommand(command);
if (result == CommandResult.NotAllowed) {
System.out.println("eeeeee");
}
return result;
}
public void tryMove(Move move) {
sendCommand(new MoveCommand(move));
if (this.gameSimulation.getBoard().pawnShouldBePromoted())
sendCommand(new PromoteCommand(PromoteType.Queen));
}
public void undoMove() {
sendCommand(new UndoCommand());
}
@Override
public void onPawnPromoted(PromoteType promotion) {
sendCommand(new PromoteCommand(promotion));
}
@Override
public void onCastling(boolean bigCastling) {
sendCommand(new CastlingCommand(bigCastling));
}
@Override
public void onMove(Move move, boolean captured) {
sendCommand(new MoveCommand(move));
}
@Override
public void onGameStart() {
sendCommand(new NewGameCommand());
}
@Override
public void onPlayerTurn(Color color, boolean undone) {
if (undone)
sendCommand(new UndoCommand());
}
public CommandExecutor getCommandExecutor() {
return simulation;
}
public Game getGame() {
return gameSimulation;
}
public ChessBoard getBoard() {
return this.gameSimulation.getBoard();
}
public Color getPlayerTurn() {
return this.gameSimulation.getPlayerTurn();
}
public List<Move> getAllowedMoves() {
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
sendCommand(cmd);
return cmd.getMoves();
}
public void close() {
this.simulation.close();
}
}

View File

@@ -3,18 +3,22 @@ package chess.controller;
import chess.controller.event.GameListener; import chess.controller.event.GameListener;
import chess.model.Game; import chess.model.Game;
/**
* Abstract class, manage the execution and results of commands.
*/
public abstract class Command { public abstract class Command {
public enum CommandResult { public enum CommandResult {
/** /**
* The command was successfull. Should update display and switch player turn. * The command was successful. Should update display and switch player turn.
*/ */
Moved, Moved,
/** The command was successfull. Should not update anything */ /** The command was successful. Should not update anything */
NotMoved, NotMoved,
/** The command was successfull. Should only update display */ /** The command was successful. Should only update display */
ActionNeeded, ActionNeeded,
/** The command was not successfull */ /** The command was not successful */
NotAllowed; NotAllowed;
} }

View File

@@ -10,6 +10,9 @@ import chess.controller.event.GameListener;
import chess.model.Game; import chess.model.Game;
import chess.model.Game.GameStatus; import chess.model.Game.GameStatus;
/**
* Execute commands.
*/
public class CommandExecutor { public class CommandExecutor {
private Game game; private Game game;
@@ -121,4 +124,8 @@ public class CommandExecutor {
public void close() { public void close() {
this.dispatcher.close(); this.dispatcher.close();
} }
public List<GameListener> getListeners() {
return this.dispatcher.getListeners();
}
} }

View File

@@ -0,0 +1,116 @@
package chess.controller;
import java.util.List;
import chess.controller.Command.CommandResult;
import chess.controller.commands.CastlingCommand;
import chess.controller.commands.GetAllowedCastlingsCommand;
import chess.controller.commands.GetAllowedMovesPieceCommand;
import chess.controller.commands.GetPieceAtCommand;
import chess.controller.commands.GetPlayerMovesCommand;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.NewGameCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.SurrenderCommand;
import chess.controller.commands.UndoCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
/**
* Interface for sending commands to the game, make long string of commands easier.
*/
public interface CommandSender {
CommandExecutor getCommandExecutor();
default CommandResult sendCommand(Command cmd, CommandExecutor commandExecutor) {
CommandResult result = commandExecutor.executeCommand(cmd);
if (result == CommandResult.NotAllowed) {
// maybe do something
}
return result;
}
default CommandResult sendCommand(Command cmd) {
return sendCommand(cmd, getCommandExecutor());
}
// inputs
default CastlingResult getAllowedCastlings() {
GetAllowedCastlingsCommand cmd = new GetAllowedCastlingsCommand();
sendCommand(cmd);
return cmd.getCastlingResult();
}
default boolean canDoCastling() {
CastlingResult castlings = getAllowedCastlings();
return castlings == CastlingResult.Both || castlings == CastlingResult.Small;
}
default boolean canDoBigCastling() {
CastlingResult castlings = getAllowedCastlings();
return castlings == CastlingResult.Both || castlings == CastlingResult.Big;
}
default Piece getPieceAt(int x, int y) {
return getPieceAt(new Coordinate(x, y));
}
default Piece getPieceAt(Coordinate coordinate) {
GetPieceAtCommand cmd = new GetPieceAtCommand(coordinate);
sendCommand(cmd);
return cmd.getPiece();
}
default boolean isCellEmpty(int x, int y) {
return getPieceAt(x, y) == null;
}
default List<Move> getPlayerMoves() {
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
sendCommand(cmd);
return cmd.getMoves();
}
default List<Coordinate> getPieceAllowedMoves(Coordinate piecePos) {
GetAllowedMovesPieceCommand cmd = new GetAllowedMovesPieceCommand(piecePos);
sendCommand(cmd);
return cmd.getDestinations();
}
// outputs
default CommandResult sendCastling() {
return sendCommand(new CastlingCommand(false));
}
default CommandResult sendBigCastling() {
return sendCommand(new CastlingCommand(true));
}
default CommandResult sendMove(Move move) {
return sendCommand(new MoveCommand(move));
}
default CommandResult sendStartGame() {
return sendCommand(new NewGameCommand());
}
default CommandResult sendPawnPromotion(PromoteType promote) {
return sendCommand(new PromoteCommand(promote));
}
default CommandResult sendSurrender(Color player) {
return sendCommand(new SurrenderCommand(player));
}
default CommandResult sendUndo() {
return sendCommand(new UndoCommand());
}
}

View File

@@ -3,6 +3,9 @@ package chess.controller;
import chess.controller.event.GameListener; import chess.controller.event.GameListener;
import chess.model.Game; import chess.model.Game;
/**
* Abstract class, manage commands given by the player, which are the commands that can be undone.
*/
public abstract class PlayerCommand extends Command{ public abstract class PlayerCommand extends Command{
public CommandResult undo(Game game, GameListener outputSystem) { public CommandResult undo(Game game, GameListener outputSystem) {

View File

@@ -8,6 +8,9 @@ import chess.model.Coordinate;
import chess.model.Game; import chess.model.Game;
import chess.model.Move; import chess.model.Move;
/**
* Command to execute a Castling or Big Castling.
*/
public class CastlingCommand extends PlayerCommand { public class CastlingCommand extends PlayerCommand {
private Move kingMove; private Move kingMove;
@@ -51,7 +54,7 @@ public class CastlingCommand extends PlayerCommand {
board.setLastMove(this.kingMove); board.setLastMove(this.kingMove);
outputSystem.onCastling(this.bigCastling); outputSystem.onCastling(this.bigCastling, kingMove, rookMove);
return CommandResult.Moved; return CommandResult.Moved;
} }

View File

@@ -4,6 +4,9 @@ import chess.controller.Command;
import chess.controller.event.GameListener; import chess.controller.event.GameListener;
import chess.model.Game; import chess.model.Game;
/**
* Command to check the possible Castling.
*/
public class GetAllowedCastlingsCommand extends Command{ public class GetAllowedCastlingsCommand extends Command{
public enum CastlingResult { public enum CastlingResult {

View File

@@ -10,6 +10,9 @@ import chess.model.Coordinate;
import chess.model.Game; import chess.model.Game;
import chess.model.Piece; import chess.model.Piece;
/**
* Command to check the Castlings that are possible.
*/
public class GetAllowedMovesPieceCommand extends Command { public class GetAllowedMovesPieceCommand extends Command {
private final Coordinate start; private final Coordinate start;
@@ -31,7 +34,7 @@ public class GetAllowedMovesPieceCommand extends Command {
if (piece.getColor() != game.getPlayerTurn()) if (piece.getColor() != game.getPlayerTurn())
return CommandResult.NotAllowed; return CommandResult.NotAllowed;
this.destinations = board.getAllowedMoves(start); this.destinations = board.getPieceAllowedMoves(start);
return CommandResult.NotMoved; return CommandResult.NotMoved;
} }

View File

@@ -6,6 +6,9 @@ import chess.model.Coordinate;
import chess.model.Game; import chess.model.Game;
import chess.model.Piece; import chess.model.Piece;
/**
* Command to check the possible moves for a given piece.
*/
public class GetPieceAtCommand extends Command{ public class GetPieceAtCommand extends Command{
private final Coordinate pieceCoords; private final Coordinate pieceCoords;

View File

@@ -7,6 +7,11 @@ import chess.controller.event.GameListener;
import chess.model.Game; import chess.model.Game;
import chess.model.Move; import chess.model.Move;
/**
* Command to get the possible moves of a player. Castling and Promotion not included.
* @see CastlingCommand
* @see PromoteCommand
*/
public class GetPlayerMovesCommand extends Command { public class GetPlayerMovesCommand extends Command {
private List<Move> moves; private List<Move> moves;

View File

@@ -7,8 +7,13 @@ import chess.model.Coordinate;
import chess.model.Game; import chess.model.Game;
import chess.model.Move; import chess.model.Move;
import chess.model.Piece; import chess.model.Piece;
import chess.model.visitor.PiecePathChecker; import chess.model.rules.PiecePathChecker;
/*
* Command to move a piece. Castling not included.
*
* @see CastlingCommand
*/
public class MoveCommand extends PlayerCommand { public class MoveCommand extends PlayerCommand {
private final Move move; private final Move move;

View File

@@ -13,6 +13,9 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Command to create a new game.
*/
public class NewGameCommand extends Command { public class NewGameCommand extends Command {
public CommandResult execute(Game game, GameListener outputSystem) { public CommandResult execute(Game game, GameListener outputSystem) {
final ChessBoard board = game.getBoard(); final ChessBoard board = game.getBoard();

View File

@@ -9,10 +9,13 @@ import chess.model.Game;
import chess.model.Piece; import chess.model.Piece;
import chess.model.pieces.Bishop; import chess.model.pieces.Bishop;
import chess.model.pieces.Knight; import chess.model.pieces.Knight;
import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
import chess.model.visitor.PawnIdentifier;
/*
* Command to promote a pawn.
*/
public class PromoteCommand extends PlayerCommand { public class PromoteCommand extends PlayerCommand {
public enum PromoteType { public enum PromoteType {
@@ -43,7 +46,7 @@ public class PromoteCommand extends PlayerCommand {
return CommandResult.NotAllowed; return CommandResult.NotAllowed;
Piece pawn = board.pieceAt(this.pieceCoords); Piece pawn = board.pieceAt(this.pieceCoords);
if (!new PawnIdentifier(game.getPlayerTurn()).isPawn(pawn)) if (!(pawn instanceof Pawn))
return CommandResult.NotAllowed; return CommandResult.NotAllowed;
int destY = this.pieceCoords.getY(); int destY = this.pieceCoords.getY();
@@ -56,7 +59,7 @@ public class PromoteCommand extends PlayerCommand {
this.oldPawn = pawn; this.oldPawn = pawn;
board.pieceComes(createPiece(this.promoteType, pawn.getColor()), this.pieceCoords); board.pieceComes(createPiece(this.promoteType, pawn.getColor()), this.pieceCoords);
outputSystem.onPawnPromoted(this.promoteType); outputSystem.onPawnPromoted(this.promoteType, this.pieceCoords);
// invalidate the last move cache // invalidate the last move cache
board.setLastMove(null); board.setLastMove(null);

View File

@@ -5,6 +5,9 @@ import chess.controller.event.GameListener;
import chess.model.Color; import chess.model.Color;
import chess.model.Game; import chess.model.Game;
/**
* Command to surrender a game.
*/
public class SurrenderCommand extends Command { public class SurrenderCommand extends Command {
private final Color player; private final Color player;

View File

@@ -5,6 +5,9 @@ import chess.controller.PlayerCommand;
import chess.controller.event.GameListener; import chess.controller.event.GameListener;
import chess.model.Game; import chess.model.Game;
/**
* Command to undo the last action.
*/
public class UndoCommand extends Command{ public class UndoCommand extends Command{
@Override @Override

View File

@@ -11,6 +11,9 @@ import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
/**
* Create a thread in which the notifications such as Move Not Allowed, Check, Checkmate, Promotion, Surrender, etc. will be sent to update the players.
*/
public class AsyncGameDispatcher extends GameDispatcher { public class AsyncGameDispatcher extends GameDispatcher {
private final List<GameListener> listeners; private final List<GameListener> listeners;
@@ -96,13 +99,13 @@ public class AsyncGameDispatcher extends GameDispatcher {
} }
@Override @Override
public void onCastling(boolean bigCastling) { public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
asyncForEachCall((l) -> l.onCastling(bigCastling)); asyncForEachCall((l) -> l.onCastling(bigCastling, kingMove, rookMove));
} }
@Override @Override
public void onPawnPromoted(PromoteType promotion) { public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
asyncForEachCall((l) -> l.onPawnPromoted(promotion)); asyncForEachCall((l) -> l.onPawnPromoted(promotion, coordinate));
} }
@Override @Override
@@ -110,4 +113,9 @@ public class AsyncGameDispatcher extends GameDispatcher {
this.executor.shutdown(); this.executor.shutdown();
} }
@Override
public List<GameListener> getListeners() {
return this.listeners;
}
} }

View File

@@ -1,10 +1,15 @@
package chess.controller.event; package chess.controller.event;
import java.util.List;
import chess.controller.commands.PromoteCommand.PromoteType; import chess.controller.commands.PromoteCommand.PromoteType;
import chess.model.Color; import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
/**
* Dispatcher for bots, does nothing.
*/
public class EmptyGameDispatcher extends GameDispatcher { public class EmptyGameDispatcher extends GameDispatcher {
@Override @Override
@@ -60,11 +65,11 @@ public class EmptyGameDispatcher extends GameDispatcher {
} }
@Override @Override
public void onCastling(boolean bigCastling) { public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
} }
@Override @Override
public void onPawnPromoted(PromoteType promotion) { public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
} }
@Override @Override
@@ -75,4 +80,9 @@ public class EmptyGameDispatcher extends GameDispatcher {
public void close() { public void close() {
} }
@Override
public List<GameListener> getListeners() {
return List.of();
}
} }

View File

@@ -5,7 +5,11 @@ import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
public abstract class GameAdaptator implements GameListener { /**
* Abstract class, provides default implementation of GameListener methods.
* @see GameListener
*/
public abstract class GameAdapter implements GameListener {
@Override @Override
public void onPlayerTurn(Color color, boolean undone) {} public void onPlayerTurn(Color color, boolean undone) {}
@@ -47,9 +51,9 @@ public abstract class GameAdaptator implements GameListener {
public void onDraw() {} public void onDraw() {}
@Override @Override
public void onCastling(boolean bigCastling) {} public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {}
@Override @Override
public void onPawnPromoted(PromoteType promotion) {} public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {}
} }

View File

@@ -1,9 +1,16 @@
package chess.controller.event; package chess.controller.event;
public abstract class GameDispatcher extends GameAdaptator { import java.util.List;
/**
* Abstract class, provides a dispatcher for game events.
*/
public abstract class GameDispatcher extends GameAdapter {
public abstract void addListener(GameListener listener); public abstract void addListener(GameListener listener);
public abstract List<GameListener> getListeners();
public abstract void close(); public abstract void close();
} }

View File

@@ -5,6 +5,9 @@ import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
/**
* Interface for events to listen.
*/
public interface GameListener { public interface GameListener {
/** /**
@@ -90,15 +93,17 @@ public interface GameListener {
* Invoked when a castling is done * Invoked when a castling is done
* *
* @param bigCastling if it's queen side castling * @param bigCastling if it's queen side castling
* @param kingMove the king's move
* @param rookMove the rook's move
*/ */
void onCastling(boolean bigCastling); void onCastling(boolean bigCastling, Move kingMove, Move rookMove);
/** /**
* Invoked when a pawn is promoted * Invoked when a pawn is promoted
* *
* @param promotion the type of promotion * @param promotion the type of promotion
* @param player the player who promoted the pawns * @param coordinate the coordinate of the old pawn
*/ */
void onPawnPromoted(PromoteType promotion); void onPawnPromoted(PromoteType promotion, Coordinate coordinate);
} }

View File

@@ -5,10 +5,16 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import chess.model.pieces.King; import chess.model.pieces.King;
import chess.model.visitor.PawnIdentifier; import chess.model.pieces.Pawn;
import chess.model.visitor.PiecePathChecker; import chess.model.rules.PiecePathChecker;
/**
* Chess board entity, composed of cells.
*/
public class ChessBoard { public class ChessBoard {
/**
* Cell of the chess board.
*/
public static class Cell { public static class Cell {
private Piece piece; private Piece piece;
@@ -48,6 +54,10 @@ public class ChessBoard {
this.kingPos = new Coordinate[Color.values().length]; this.kingPos = new Coordinate[Color.values().length];
} }
/**
* Apply a move on the board.
* @param move move to apply
*/
public void applyMove(Move move) { public void applyMove(Move move) {
assert move.isValid() : "Invalid move !"; assert move.isValid() : "Invalid move !";
Piece deadPiece = pieceAt(move.getDeadPieceCoords()); Piece deadPiece = pieceAt(move.getDeadPieceCoords());
@@ -64,12 +74,20 @@ public class ChessBoard {
this.lastVirtualMove = move; this.lastVirtualMove = move;
} }
/**
* Undo the last move
*/
public void undoLastMove() { public void undoLastMove() {
assert this.lastVirtualMove != null : "Can't undo at the beginning!"; assert this.lastVirtualMove != null : "Can't undo at the beginning!";
undoMove(this.lastVirtualMove, this.lastEjectedPiece); undoMove(this.lastVirtualMove, this.lastEjectedPiece);
} }
/**
* Undo the specified move
* @param move
* @param deadPiece
*/
public void undoMove(Move move, Piece deadPiece) { public void undoMove(Move move, Piece deadPiece) {
Piece movingPiece = pieceAt(move.getFinish()); Piece movingPiece = pieceAt(move.getFinish());
pieceComes(movingPiece, move.getStart()); pieceComes(movingPiece, move.getStart());
@@ -79,16 +97,29 @@ public class ChessBoard {
movingPiece.unMove(); movingPiece.unMove();
} }
/**
* Check if the cell is empty
* @param coordinate
* @return true if the cell is empty
*/
public boolean isCellEmpty(Coordinate coordinate) { public boolean isCellEmpty(Coordinate coordinate) {
return pieceAt(coordinate) == null; return pieceAt(coordinate) == null;
} }
/**
* Return the piece at the given coordinates
* @param coordinate
* @return piece at the given coordinates, or null if the coordinates are invalid or the cell is empty
*/
public Piece pieceAt(Coordinate coordinate) { public Piece pieceAt(Coordinate coordinate) {
if (!coordinate.isValid()) if (!coordinate.isValid())
return null; return null;
return cellAt(coordinate).getPiece(); return cellAt(coordinate).getPiece();
} }
/**
* Nuke all pieces of the board
*/
public void clearBoard() { public void clearBoard() {
for (int i = 0; i < Coordinate.VALUE_MAX; i++) { for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
for (int j = 0; j < Coordinate.VALUE_MAX; j++) { for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
@@ -97,24 +128,48 @@ public class ChessBoard {
} }
} }
/**
* Get the cell at the given coordinates
* @param coordinate
* @return
*/
private Cell cellAt(Coordinate coordinate) { private Cell cellAt(Coordinate coordinate) {
return this.cells[coordinate.getX()][coordinate.getY()]; return this.cells[coordinate.getX()][coordinate.getY()];
} }
/*
* Set the piece at the given coordinate
*/
public void pieceComes(Piece piece, Coordinate coordinate) { public void pieceComes(Piece piece, Coordinate coordinate) {
cellAt(coordinate).setPiece(piece); cellAt(coordinate).setPiece(piece);
if (piece instanceof King) if (piece instanceof King)
this.kingPos[piece.getColor().ordinal()] = coordinate; this.kingPos[piece.getColor().ordinal()] = coordinate;
} }
/**
* Remove the piece at the given coordiinates
* @param coordinate
*/
public void pieceLeaves(Coordinate coordinate) { public void pieceLeaves(Coordinate coordinate) {
cellAt(coordinate).setPiece(null); cellAt(coordinate).setPiece(null);
} }
/**
* Find the king of the given color on the board
* @param color
* @return the coordinates of the king
*/
public Coordinate findKing(Color color) { public Coordinate findKing(Color color) {
return kingPos[color.ordinal()]; return kingPos[color.ordinal()];
} }
/**
* Get the allowed starting positions for a piece to attack the given Coordinate. Useful for PGN trasnlation.
* @param finish
* @param color
* @return coordinates of the pieces that could attack
*/
public List<Coordinate> getAllowedStarts(Coordinate finish, Color color) { public List<Coordinate> getAllowedStarts(Coordinate finish, Color color) {
List<Coordinate> starts = new ArrayList<>(); List<Coordinate> starts = new ArrayList<>();
for (int i = 0; i < Coordinate.VALUE_MAX; i++) { for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
@@ -139,6 +194,11 @@ public class ChessBoard {
return starts; return starts;
} }
/**
* Check if the king of the given color is in check
* @param color
* @return true if the king is in check
*/
public boolean isKingInCheck(Color color) { public boolean isKingInCheck(Color color) {
Coordinate kingPos = findKing(color); Coordinate kingPos = findKing(color);
assert kingPos.isValid() : "King position is invalid!"; assert kingPos.isValid() : "King position is invalid!";
@@ -158,10 +218,20 @@ public class ChessBoard {
return false; return false;
} }
/**
* Check if the given player has allowed moves
* @param player
* @return true if the player can move
*/
public boolean hasAllowedMoves(Color player) { public boolean hasAllowedMoves(Color player) {
return !getAllowedMoves(player).isEmpty(); return !getAllowedMoves(player).isEmpty();
} }
/**
* Get the allowed moves for the given player
* @param player
* @return
*/
public List<Move> getAllowedMoves(Color player) { public List<Move> getAllowedMoves(Color player) {
if (this.cachedAllowedMoves != null) { if (this.cachedAllowedMoves != null) {
return this.cachedAllowedMoves; return this.cachedAllowedMoves;
@@ -205,7 +275,10 @@ public class ChessBoard {
return result; return result;
} }
public List<Coordinate> getAllowedMoves(Coordinate pieceCoords) { /**
* Get all the end positions possible of a piece
*/
public List<Coordinate> getPieceAllowedMoves(Coordinate pieceCoords) {
Piece piece = pieceAt(pieceCoords); Piece piece = pieceAt(pieceCoords);
if (piece == null) if (piece == null)
return null; return null;
@@ -233,6 +306,13 @@ public class ChessBoard {
return result; return result;
} }
/**
* Check if the given player can castle with the given rook
* @param color
* @param rookX
* @param kingDirection
* @return true if the player can Castle
*/
private boolean canCastle(Color color, int rookX, Direction kingDirection) { private boolean canCastle(Color color, int rookX, Direction kingDirection) {
if (isKingInCheck(color)) if (isKingInCheck(color))
return false; return false;
@@ -267,20 +347,32 @@ public class ChessBoard {
return obstacle == null; return obstacle == null;
} }
/**
* @return wether the player can perform a kingside castling.
*/
public boolean canSmallCastle(Color color) { public boolean canSmallCastle(Color color) {
return canCastle(color, 7, Direction.Right); return canCastle(color, 7, Direction.Right);
} }
/**
* Check if the given player is allowed to execute a queenside castling.
* @param color
* @return
*/
public boolean canBigCastle(Color color) { public boolean canBigCastle(Color color) {
return canCastle(color, 0, Direction.Left); return canCastle(color, 0, Direction.Left);
} }
/**
* Check if there is a pawn to be promoted by the given player.
* @return
*/
public boolean pawnShouldBePromoted() { public boolean pawnShouldBePromoted() {
return pawnPromotePosition() != null; return pawnPromotePosition() != null;
} }
/** /**
* * Check if there's a pawn in the adversary line on the board
* @return Null if there is no pawn to promote * @return Null if there is no pawn to promote
*/ */
public Coordinate pawnPromotePosition() { public Coordinate pawnPromotePosition() {
@@ -291,18 +383,17 @@ public class ChessBoard {
} }
/** /**
* * Check if there's a pawn of the given player in the adversary line on the board
* @return Null if there is no pawn to promote * @return Null if there is no pawn to promote
*/ */
private Coordinate pawnPromotePosition(Color color) { private Coordinate pawnPromotePosition(Color color) {
int enemyLineY = color == Color.White ? 0 : 7; int enemyLineY = color == Color.White ? 0 : 7;
PawnIdentifier identifier = new PawnIdentifier(color);
for (int x = 0; x < Coordinate.VALUE_MAX; x++) { for (int x = 0; x < Coordinate.VALUE_MAX; x++) {
Coordinate pieceCoords = new Coordinate(x, enemyLineY); Coordinate pieceCoords = new Coordinate(x, enemyLineY);
Piece piece = pieceAt(pieceCoords); Piece piece = pieceAt(pieceCoords);
if (identifier.isPawn(piece)) if (piece instanceof Pawn)
return pieceCoords; return pieceCoords;
} }
@@ -310,6 +401,10 @@ public class ChessBoard {
return null; return null;
} }
/**
* Hash according to the pieces position on the board
* @return hash code
*/
@Override @Override
public int hashCode() { public int hashCode() {
int result = 0; int result = 0;
@@ -324,10 +419,16 @@ public class ChessBoard {
return result; return result;
} }
/**
* @return the last played move
*/
public Move getLastMove() { public Move getLastMove() {
return this.lastMove; return this.lastMove;
} }
/**
* Updates the last move of the board and invalidate the allowedMoves cache.
*/
public void setLastMove(Move lastMove) { public void setLastMove(Move lastMove) {
this.lastMove = lastMove; this.lastMove = lastMove;
this.cachedAllowedMoves = null; this.cachedAllowedMoves = null;

View File

@@ -1,5 +1,8 @@
package chess.model; package chess.model;
/**
* Enumeration of colors for player - either black or white
*/
public enum Color { public enum Color {
White, White,
Black; Black;

View File

@@ -2,6 +2,9 @@ package chess.model;
import java.util.Objects; import java.util.Objects;
/**
* Coordinate of a cell on the chess board.
*/
public class Coordinate { public class Coordinate {
private final int x; private final int x;
private final int y; private final int y;

View File

@@ -1,5 +1,9 @@
package chess.model; package chess.model;
/**
* Enumation of the different directions from a cell in a chessboard, and how to navigate the cells.
*/
public enum Direction { public enum Direction {
Unset(65), Unset(65),

View File

@@ -8,6 +8,10 @@ import java.util.Stack;
import chess.controller.PlayerCommand; import chess.controller.PlayerCommand;
import chess.controller.commands.MoveCommand; import chess.controller.commands.MoveCommand;
/**
* Game class that represents a chess game.
*/
public class Game { public class Game {
private final ChessBoard board; private final ChessBoard board;
private Color playerTurn; private Color playerTurn;
@@ -34,19 +38,24 @@ public class Game {
return playerTurn; return playerTurn;
} }
/**
* Reset the game
*/
public void reset() { public void reset() {
resetPlayerTurn(); resetPlayerTurn();
this.traitsPos.clear(); this.traitsPos.clear();
} }
/**
* Reset the player turn.
* Aka: white for the win
*/
public void resetPlayerTurn() { public void resetPlayerTurn() {
this.playerTurn = Color.White; this.playerTurn = Color.White;
} }
/** /**
* * Save the current board configuration
* @param color the current player turn
* @return true if a draw should be declared
*/ */
public void saveTraitPiecesPos() { public void saveTraitPiecesPos() {
int piecesHash = this.board.hashCode(); int piecesHash = this.board.hashCode();
@@ -63,14 +72,16 @@ public class Game {
} }
/** /**
* * Switch player turn
* @return true if a draw should occur
*/ */
public void switchPlayerTurn() { public void switchPlayerTurn() {
playerTurn = Color.getEnemy(playerTurn); playerTurn = Color.getEnemy(playerTurn);
} }
// this is the bottleneck of algorithms using this chess engine /**
* Check the status of the game ofr the specified player
* @return a GameStatus enum
*/
public GameStatus checkGameStatus(Color color) { public GameStatus checkGameStatus(Color color) {
if (checkDraw()) if (checkDraw())
return GameStatus.Draw; return GameStatus.Draw;
@@ -87,20 +98,32 @@ public class Game {
return GameStatus.OnGoing; return GameStatus.OnGoing;
} }
/**
* Check the status of the gamere
*/
public GameStatus checkGameStatus() { public GameStatus checkGameStatus() {
return checkGameStatus(Color.getEnemy(getPlayerTurn())); return checkGameStatus(Color.getEnemy(getPlayerTurn()));
} }
/**
* Add a player move (basic move, castling, ...) to the game history.
*/
public void addAction(PlayerCommand command) { public void addAction(PlayerCommand command) {
this.movesHistory.add(command); this.movesHistory.add(command);
} }
/**
* @return the last player action
*/
public PlayerCommand getLastAction() { public PlayerCommand getLastAction() {
if (this.movesHistory.isEmpty()) if (this.movesHistory.isEmpty())
return null; return null;
return this.movesHistory.pop(); return this.movesHistory.pop();
} }
/**
* Update the last board move ater an undo.
*/
public void updateLastMove() { public void updateLastMove() {
if (this.movesHistory.isEmpty()) if (this.movesHistory.isEmpty())
return; return;
@@ -111,6 +134,9 @@ public class Game {
} }
} }
/**
* Remove the board configuration occurence from the game history
*/
public void undoTraitPiecesPos() { public void undoTraitPiecesPos() {
int piecesHash = this.board.hashCode(); int piecesHash = this.board.hashCode();
Integer count = this.traitsPos.get(piecesHash); Integer count = this.traitsPos.get(piecesHash);
@@ -122,6 +148,9 @@ public class Game {
return this.movesHistory; return this.movesHistory;
} }
/**
* @return wether a pawn should be promoted
*/
public boolean pawnShouldBePromoted() { public boolean pawnShouldBePromoted() {
return this.board.pawnShouldBePromoted(); return this.board.pawnShouldBePromoted();
} }

View File

@@ -1,6 +1,12 @@
package chess.model; package chess.model;
public class PermissiveGame extends Game { /**
* Game where the most ressource-consuming functions are empty.
* Mostly used by bots.
* @see GameSimulation
*/
public class LightGame extends Game {
@Override @Override
public GameStatus checkGameStatus(Color color) { public GameStatus checkGameStatus(Color color) {

View File

@@ -1,5 +1,9 @@
package chess.model; package chess.model;
/**
* Chess move, composed of a starting position, a finishing position and the eventual enemy pieces taken during the move.
*/
public class Move { public class Move {
private final Coordinate start; private final Coordinate start;
private final Coordinate finish; private final Coordinate finish;
@@ -11,6 +15,10 @@ public class Move {
this.deadPieceCoords = finish; this.deadPieceCoords = finish;
} }
/**
*
* @return true if the move is valid, false otherwise
*/
public boolean isValid() { public boolean isValid() {
return this.start.isValid() && this.finish.isValid() && !this.start.equals(this.finish); return this.start.isValid() && this.finish.isValid() && !this.start.equals(this.finish);
} }
@@ -23,6 +31,10 @@ public class Move {
return finish; return finish;
} }
/**
* Returns the number of cells traversed by the move.
* @return int
*/
public int traversedCells() { public int traversedCells() {
assert isValid() : "Move is invalid!"; assert isValid() : "Move is invalid!";
@@ -41,6 +53,9 @@ public class Move {
return 0; return 0;
} }
/**
* @return the coordinates of the cell in the middle of the move
*/
public Coordinate getMiddle() { public Coordinate getMiddle() {
return Coordinate.fromIndex((getStart().toIndex() + getFinish().toIndex()) / 2); return Coordinate.fromIndex((getStart().toIndex() + getFinish().toIndex()) / 2);
} }

View File

@@ -1,5 +1,9 @@
package chess.model; package chess.model;
/**
* Piece of a game. Posesses a color and the number of time it has been moved.
*/
public abstract class Piece { public abstract class Piece {
private final Color color; private final Color color;

View File

@@ -7,6 +7,10 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Visitor interface for pieces.
*/
public interface PieceVisitor<T> { public interface PieceVisitor<T> {
default T visit(Piece piece) { default T visit(Piece piece) {

View File

@@ -4,6 +4,9 @@ import chess.model.Color;
import chess.model.Piece; import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
/**
* Bishop piece.
*/
public class Bishop extends Piece { public class Bishop extends Piece {
public Bishop(Color color) { public Bishop(Color color) {

View File

@@ -4,6 +4,9 @@ import chess.model.Color;
import chess.model.Piece; import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
/**
* King piece.
*/
public class King extends Piece { public class King extends Piece {
public King(Color color) { public King(Color color) {

View File

@@ -4,6 +4,9 @@ import chess.model.Color;
import chess.model.Piece; import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
/**
* Knight piece.
*/
public class Knight extends Piece { public class Knight extends Piece {
public Knight(Color color) { public Knight(Color color) {

View File

@@ -4,6 +4,9 @@ import chess.model.Color;
import chess.model.Piece; import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
/**
* Pawn piece.
*/
public class Pawn extends Piece { public class Pawn extends Piece {
public Pawn(Color color) { public Pawn(Color color) {

View File

@@ -4,6 +4,9 @@ import chess.model.Color;
import chess.model.Piece; import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
/**
* Queen piece.
*/
public class Queen extends Piece { public class Queen extends Piece {
public Queen(Color color) { public Queen(Color color) {

View File

@@ -4,6 +4,9 @@ import chess.model.Color;
import chess.model.Piece; import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
/**
* Rook piece.
*/
public class Rook extends Piece { public class Rook extends Piece {
public Rook(Color color) { public Rook(Color color) {

View File

@@ -1,4 +1,4 @@
package chess.model.visitor; package chess.model.rules;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Direction; import chess.model.Direction;
@@ -12,6 +12,10 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Check if a move can be done.
*/
public class PermissiveRuleChecker implements PieceVisitor<Boolean> { public class PermissiveRuleChecker implements PieceVisitor<Boolean> {
private final Move move; private final Move move;

View File

@@ -1,4 +1,4 @@
package chess.model.visitor; package chess.model.rules;
import chess.model.ChessBoard; import chess.model.ChessBoard;
import chess.model.Color; import chess.model.Color;
@@ -14,6 +14,9 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Check if there are pieces in the path of a move.
*/
public class PiecePathChecker implements PieceVisitor<Boolean> { public class PiecePathChecker implements PieceVisitor<Boolean> {
private final ChessBoard board; private final ChessBoard board;
@@ -104,10 +107,11 @@ public class PiecePathChecker implements PieceVisitor<Boolean> {
Coordinate middle = lastMove.getMiddle(); Coordinate middle = lastMove.getMiddle();
if (middle.equals(this.move.getFinish()) if (middle.equals(this.move.getFinish())
&& new PawnIdentifier(pieceToEat.getColor()).isPawn(pieceToEat)) { && pieceToEat instanceof Pawn) {
this.move.setDeadPieceCoords(lastMove.getFinish()); this.move.setDeadPieceCoords(lastMove.getFinish());
return true; return true;
} }
return false; return false;
} }

View File

@@ -1,52 +0,0 @@
package chess.model.visitor;
import chess.model.Color;
import chess.model.Piece;
import chess.model.PieceVisitor;
import chess.model.pieces.*;
public class PawnIdentifier implements PieceVisitor<Boolean> {
private final Color color;
public PawnIdentifier(Color color) {
this.color = color;
}
public boolean isPawn(Piece piece) {
if (piece == null)
return false;
return visit(piece);
}
@Override
public Boolean visitPiece(Bishop bishop) {
return false;
}
@Override
public Boolean visitPiece(King king) {
return false;
}
@Override
public Boolean visitPiece(Knight knight) {
return false;
}
@Override
public Boolean visitPiece(Pawn pawn) {
return pawn.getColor() == color;
}
@Override
public Boolean visitPiece(Queen queen) {
return false;
}
@Override
public Boolean visitPiece(Rook rook) {
return false;
}
}

View File

@@ -19,29 +19,12 @@ import chess.model.Move;
import chess.model.Piece; import chess.model.Piece;
import chess.model.pieces.Pawn; import chess.model.pieces.Pawn;
/**
* Export a game to PGN format.
*/
public class PgnExport { public class PgnExport {
// public static void main(String[] args) {
// final Game game = new Game();
// final CommandExecutor commandExecutor = new CommandExecutor(game);
// DumbAI ai1 = new DumbAI(commandExecutor, Color.White);
// commandExecutor.addListener(ai1);
// DumbAI ai2 = new DumbAI(commandExecutor, Color.Black);
// commandExecutor.addListener(ai2);
// commandExecutor.addListener(new GameAdaptator() {
// @Override
// public void onGameEnd() {
// System.out.println(exportGame(game));
// commandExecutor.close();
// }
// });
// commandExecutor.executeCommand(new NewGameCommand());
// }
private static final PiecePgnName piecePgnName = new PiecePgnName(); private static final PiecePgnName piecePgnName = new PiecePgnName();
private static Piece pieceAt(CommandExecutor commandExecutor, Coordinate coordinate) { private static Piece pieceAt(CommandExecutor commandExecutor, Coordinate coordinate) {
@@ -72,6 +55,12 @@ public class PgnExport {
} }
} }
/**
* Resolve PGN ambiguity in the case of two pieces of the same type able to move on the same square.
* @param cmdExec the command executor attached to the game
* @param pieceMove move of the piece
* @return the character that solves the eventual ambiguity, empty if no ambiguity to start with
*/
private static String resolveAmbiguity(CommandExecutor cmdExec, Move pieceMove) { private static String resolveAmbiguity(CommandExecutor cmdExec, Move pieceMove) {
Piece movingPiece = pieceAt(cmdExec, pieceMove.getStart()); Piece movingPiece = pieceAt(cmdExec, pieceMove.getStart());
@@ -105,6 +94,12 @@ public class PgnExport {
return ""; return "";
} }
/**
* From a move, get the capture-part of the associated PGN string.
* @param move the move
* @param movingPiece the piece that is moving
* @return the capture string of the PGN move
*/
private static String capture(MoveCommand move, Piece movingPiece) { private static String capture(MoveCommand move, Piece movingPiece) {
String result = ""; String result = "";
if (move.getDeadPiece() != null) { if (move.getDeadPiece() != null) {

View File

@@ -3,6 +3,10 @@ package chess.pgn;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import common.AssetManager; import common.AssetManager;
/**
* Apply moves from a pgn file at the start of a game.
*/
public class PgnFileSimulator extends PgnSimulator{ public class PgnFileSimulator extends PgnSimulator{
public PgnFileSimulator(CommandExecutor commandExecutor, String fileName) { public PgnFileSimulator(CommandExecutor commandExecutor, String fileName) {

View File

@@ -25,6 +25,10 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Import a game from PGN format.
*/
public class PgnImport { public class PgnImport {
private static final Map<String, Class<? extends Piece>> pieceMap = Map.of( private static final Map<String, Class<? extends Piece>> pieceMap = Map.of(
@@ -46,6 +50,13 @@ public class PgnImport {
return getMoves(parts[parts.length - 1]); return getMoves(parts[parts.length - 1]);
} }
private static final int COORDINATE_ANY = -1;
/**
* Parse the moves from a PGN string.
* @param unparsedMoves
* @return
*/
private static List<PlayerCommand> getMoves(String unparsedMoves) { private static List<PlayerCommand> getMoves(String unparsedMoves) {
String[] moves = unparsedMoves.replaceAll("\\{.*?\\}", "") // Remove comments String[] moves = unparsedMoves.replaceAll("\\{.*?\\}", "") // Remove comments
.replaceAll("\\n", " ") // Remove new lines .replaceAll("\\n", " ") // Remove new lines
@@ -75,6 +86,12 @@ public class PgnImport {
return instructions; return instructions;
} }
/**
* Parse a move from the PGN format and plays it in the given game.
* @param move
* @param game
* @return
*/
private static List<PlayerCommand> parseMove(String move, Game game) { private static List<PlayerCommand> parseMove(String move, Game game) {
if (move.equals("O-O-O")) if (move.equals("O-O-O"))
return Arrays.asList(new CastlingCommand(true)); return Arrays.asList(new CastlingCommand(true));
@@ -100,7 +117,7 @@ public class PgnImport {
assert move.length() == 3 || move.length() == 2; assert move.length() == 3 || move.length() == 2;
Coordinate ambiguity = new Coordinate(-1, -1); Coordinate ambiguity = new Coordinate(COORDINATE_ANY, COORDINATE_ANY);
// ambiguity // ambiguity
if (move.length() == 3) { if (move.length() == 3) {
@@ -120,8 +137,17 @@ public class PgnImport {
return cmds; return cmds;
} }
private static Coordinate getStartCoord(Coordinate dest, Class<? extends Piece> pieceType, Coordinate ambiguity, /**
Game game) { * Get the start coordinate of a piece.
* @param dest the end position of the moving piece
* @param pieceType the type of the piece
* @param ambiguity coordinates of the moving piece, indicated with the constant COORDINATE_ANY.
* @param game the game
* @see COORDINATE_ANY
* @see getAmbiguityPattern
* @return the start coordinate of the piece
*/
private static Coordinate getStartCoord(Coordinate dest, Class<? extends Piece> pieceType, Coordinate ambiguity, Game game) {
final ChessBoard board = game.getBoard(); final ChessBoard board = game.getBoard();
List<Coordinate> starts = board.getAllowedStarts(dest, game.getPlayerTurn()); List<Coordinate> starts = board.getAllowedStarts(dest, game.getPlayerTurn());
@@ -148,10 +174,10 @@ public class PgnImport {
} }
private static boolean coordPatternMatch(Coordinate coord, Coordinate pattern) { private static boolean coordPatternMatch(Coordinate coord, Coordinate pattern) {
if (pattern.getX() != -1 && coord.getX() != pattern.getX()) if (pattern.getX() != COORDINATE_ANY && coord.getX() != pattern.getX())
return false; return false;
if (pattern.getY() != -1 && coord.getY() != pattern.getY()) if (pattern.getY() != COORDINATE_ANY && coord.getY() != pattern.getY())
return false; return false;
return true; return true;
@@ -159,8 +185,8 @@ public class PgnImport {
private static Coordinate getAmbiguityPattern(char amb) { private static Coordinate getAmbiguityPattern(char amb) {
if (Character.isDigit(amb)) if (Character.isDigit(amb))
return new Coordinate(-1, getYCoord(amb)); return new Coordinate(COORDINATE_ANY, getYCoord(amb));
return new Coordinate(getXCoord(amb), -1); return new Coordinate(getXCoord(amb), COORDINATE_ANY);
} }
private static Coordinate stringToCoordinate(String coordinates) { private static Coordinate stringToCoordinate(String coordinates) {

View File

@@ -5,10 +5,14 @@ import java.util.List;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.PlayerCommand; import chess.controller.PlayerCommand;
import chess.controller.event.GameAdaptator; import chess.controller.event.GameAdapter;
import common.Signal0; import common.Signal0;
public class PgnSimulator extends GameAdaptator { /**
* Apply moves from a pgn string at the start of a game.
*/
public class PgnSimulator extends GameAdapter {
private final CommandExecutor commandExecutor; private final CommandExecutor commandExecutor;
private final String pgn; private final String pgn;

View File

@@ -8,6 +8,10 @@ import chess.model.pieces.Pawn;
import chess.model.pieces.Queen; import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
/**
* Visitor that returns the PGN name of a piece.
*/
public class PiecePgnName implements PieceVisitor<String> { public class PiecePgnName implements PieceVisitor<String> {
@Override @Override

View File

@@ -1,23 +1,32 @@
package chess.view.DDDrender; package chess.view.DDDrender;
import org.joml.Matrix4f; import org.joml.Matrix4f;
import org.joml.Vector2f;
import org.joml.Vector3f; import org.joml.Vector3f;
import org.joml.Vector4f;
/**
* 3D camera
*/
public class Camera { public class Camera {
public static final float fov = 70.0f; public static final float fov = 70.0f;
// should be changed to match screen
public static final float aspect = 1.0f;
public static final float zNear = 0.01f; public static final float zNear = 0.01f;
public static final float zFar = 100.0f; public static final float zFar = 1000.0f;
private static final Vector3f up = new Vector3f(0.0f, -1.0f, 0.0f);
private static final Vector3f center = new Vector3f(0.0f, 0.0f, 0.0f);
private final float distance = 1.5f;
private final float camHeight = 1.5f;
private float aspectRatio;
private float angle;
private Vector3f pos; private Vector3f pos;
private float yaw = 0.0f;
private float pitch = 0.0f;
public Camera() { public Camera() {
this.pos = new Vector3f(0, 2.0f, 0); this.pos = new Vector3f(0.0f, camHeight, 0.0f);
setRotation(0.0f, -3.14150f / 2.0f); setRotateAngle((float) Math.PI);
} }
public void move(float x, float y) { public void move(float x, float y) {
@@ -25,104 +34,60 @@ public class Camera {
this.pos.y += y; this.pos.y += y;
} }
public void rotate(float yaw, float pitch) { public void setRotateAngle(float angle) {
this.yaw += yaw; this.angle = angle;
this.pitch += pitch; updatePostion();
}
private void updatePostion() {
final float finalX = (float) Math.sin(angle);
final float finalZ = (float) -Math.cos(angle);
this.pos.set(distance * finalX, this.pos.get(1), distance * finalZ);
}
public float getRotateAngle() {
return angle;
} }
public Vector3f getPos() { public Vector3f getPos() {
return pos; return pos;
} }
public float getYaw() {
return yaw;
}
public float getPitch() {
return pitch;
}
public float getFov() { public float getFov() {
return fov; return fov;
} }
public void setX(float x) { public void setAspectRatio(float aspectRatio) {
this.pos.x = x; this.aspectRatio = aspectRatio;
} }
public void setY(float y) { public Matrix4f getPerspectiveMatrix() {
this.pos.y = y; return new Matrix4f().perspective((float) (Math.toRadians(fov)), aspectRatio, zNear, zFar);
} }
public void setZ(float z) { public Matrix4f getViewMatrix() {
this.pos.z = z; return new Matrix4f().lookAt(pos, center, up);
} }
public void setYaw(float yaw) { /**
this.yaw = yaw; * Performs a ray casting to find the selected cell by the cursor
} * @return the position of the cell in world coordinates
*/
public Vector2f getCursorWorldFloorPos(Vector2f screenPos, int windowWidth, int windowHeight) {
float relativeX = (screenPos.x / (float) windowWidth * 2.0f) - 1.0f;
float relativeY = 1.0f - (screenPos.y / (float) windowHeight * 2.0f);
public void setPitch(float pitch) { Vector4f rayClip = new Vector4f(relativeX, relativeY, -1.0f, 1.0f);
this.pitch = pitch;
}
public void reset() { Vector4f rayEye = getPerspectiveMatrix().invert().transform(rayClip);
resetPosition();
resetRotation();
}
public void resetPosition() { rayEye = new Vector4f(rayEye.x, rayEye.y, -1.0f, 0.0f);
pos = new Vector3f(0.0f, 0.0f, 0.0f);
}
public void resetRotation() { Vector4f rayWorld = getViewMatrix().invert().transform(rayEye);
yaw = 0.0f;
pitch = 0.0f;
}
public void moveForward(float distance) { float lambda = -this.pos.y / rayWorld.y;
pos.x += distance * (float) Math.cos(yaw);
pos.y += distance * (float) Math.sin(yaw);
}
public void moveRight(float distance) { return new Vector2f(lambda * rayWorld.x + this.pos.x, lambda *
pos.x += distance * (float) Math.cos(yaw); rayWorld.z + this.pos.z);
pos.y += distance * (float) Math.sin(yaw);
}
public void moveUp(float distance) {
pos.z += distance;
}
public void moveDown(float distance) {
pos.z -= distance;
}
public void addYaw(float angle) {
yaw += angle;
}
public void addPitch(float angle) {
pitch += angle;
}
public void setPosition(Vector3f pos) {
this.pos = pos;
}
public void setRotation(float yaw, float pitch) {
this.yaw = yaw;
this.pitch = pitch;
}
public Matrix4f getMatrix() {
Vector3f forward = new Vector3f(
(float) (Math.cos(yaw) * Math.cos(pitch)),
(float) (Math.sin(pitch)),
(float) (Math.sin(yaw) * Math.cos(pitch)));
return new Matrix4f()
.perspective((float) (Math.toRadians(fov)), aspect, zNear, zFar)
.lookAt(pos, forward, new Vector3f(0.0f, 1.0f, 0.0f));
} }
} }

View File

@@ -0,0 +1,30 @@
package chess.view.DDDrender;
import java.io.Closeable;
import java.io.IOException;
import java.util.List;
import chess.view.DDDrender.opengl.VertexArray;
/**
* OpenGL model.
*/
public class DDDModel implements Closeable {
private final List<VertexArray> vaos;
public DDDModel(List<VertexArray> vaos) {
this.vaos = vaos;
}
public List<VertexArray> getVaos() {
return vaos;
}
@Override
public void close() throws IOException {
for (VertexArray vertexArray : vaos) {
vertexArray.close();
}
}
}

View File

@@ -0,0 +1,24 @@
package chess.view.DDDrender;
import org.joml.Vector2f;
import chess.model.Coordinate;
/**
* Helper functions to convert from 2D to 3D coordinates systems.
*/
public class DDDPlacement {
public static Vector2f coordinatesToVector(Coordinate coo) {
return coordinatesToVector(coo.getX(), coo.getY());
}
public static Vector2f coordinatesToVector(float x, float y) {
return new Vector2f(1.0f - 0.125f - x * 0.250f, 1.0f - 0.125f - y * 0.250f);
}
public static Coordinate vectorToCoordinates(Vector2f pos) {
int x = (int) ((1.0f - pos.x) * 4.0f);
int y = (int) ((1.0f - pos.y) * 4.0f);
return new Coordinate(x, y);
}
}

View File

@@ -0,0 +1,566 @@
package chess.view.DDDrender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import chess.controller.commands.*;
import chess.controller.commands.PromoteCommand.PromoteType;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiCond;
import imgui.flag.ImGuiWindowFlags;
import org.joml.Vector2f;
import org.joml.Vector3f;
import chess.controller.Command.CommandResult;
import chess.controller.CommandExecutor;
import chess.controller.CommandSender;
import chess.controller.event.GameAdapter;
import chess.model.Color;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
import chess.view.GameView;
import chess.view.DDDrender.world.BoardEntity;
import chess.view.DDDrender.world.PieceEntity;
import chess.view.DDDrender.world.World;
public class DDDView extends GameView {
private static final Vector3f BLACK = new Vector3f(0.3f, 0.3f, 0.3f);
private static final Vector3f WHITE = new Vector3f(1.0f, 1.0f, 1.0f);
private static final Vector3f RED = new Vector3f(1.0f, 0.0f, 0.0f);
private static final Vector3f YELLOW = new Vector3f(1.0f, 1.0f, 0.0f);
private static final Vector3f BLUE = new Vector3f(0.0f, 0.0f, 1.0f);
private final CommandExecutor commandExecutor;
private final Window window;
private final World world;
private BoardEntity boardEntity;
private final Camera camera;
private Coordinate click = null;
private static final float animationTime = 0.5f; // in seconds
private static final int animationTurns = 1;
private float moveProgress = 0.0f;
private String waitingPopup = null;
public DDDView(CommandExecutor commandExecutor) {
this.commandExecutor = commandExecutor;
this.world = new World();
this.camera = new Camera();
this.window = new Window(new Renderer(), this.world, this.camera);
}
@Override
public CommandExecutor getCommandExecutor() {
return this.commandExecutor;
}
private void cancelClick() {
this.click = null;
}
private void setClick(Coordinate coordinate) {
this.click = coordinate;
}
/**
* Invoked when a cell is clicked. The first click selects the piece to move, the second click selects the destination.
* @param coordinate
*/
private void onCellClick(Coordinate coordinate) {
if (this.click == null) { // case: first click
List<Coordinate> allowedMoves = getPieceAllowedMoves(coordinate);
if (allowedMoves.isEmpty()) { // case: no movement possible for piece
return;
}
setClick(coordinate);
previewMoves(coordinate);
return;
}
// case: second click
GetAllowedMovesPieceCommand movesCommand = new GetAllowedMovesPieceCommand(this.click);
if (sendCommand(movesCommand) == CommandResult.NotAllowed) { // case: invalid piece to move
cancelPreview(this.click);
cancelClick();
return;
}
List<Coordinate> allowedMoves = movesCommand.getDestinations();
if (allowedMoves.isEmpty()) { // case: no movement possible for piece
cancelPreview(this.click);
cancelClick();
return;
}
if (allowedMoves.contains(coordinate)) { // case: valid attempt to move
cancelPreview(this.click);
sendMove(new Move(click, coordinate));
cancelClick();
return;
}
if (coordinate != this.click) { // cases: invalid move, selecting another piece
cancelPreview(this.click);
previewMoves(coordinate);
setClick(coordinate);
return;
}
cancelClick(); // case: cancelling previous click
}
/**
* Show the possible moves of the piece at the given coordinates: the piece is highlighted in yellow, the allowed moves in red.
* @param coordinate
*/
private void previewMoves(Coordinate coordinate) {
List<Coordinate> allowedMoves = getPieceAllowedMoves(coordinate);
if (allowedMoves.isEmpty())
return;
this.boardEntity.setCellColor(coordinate, RED);
this.world.getPiece(coordinate).setColor(RED);
for (Coordinate destCoord : allowedMoves) {
this.boardEntity.setCellColor(destCoord, YELLOW);
}
}
/**
* Invoked when a cell is hovered. The hovered cell is highlighted in red. If the cell contains a piece, its allowed moves are highlighted in red as well.
* @param coordinate
*/
private void onCellEnter(Coordinate coordinate) {
if (this.click == null) {
// small test turning a cell red when hovered
this.boardEntity.setCellColor(coordinate, RED);
PieceEntity pEntity = this.world.getPiece(coordinate);
if (pEntity == null)
return;
pEntity.setColor(RED);
List<Coordinate> allowedMoves = getPieceAllowedMoves(coordinate);
if (allowedMoves.isEmpty())
return;
for (Coordinate destCoord : allowedMoves) {
this.boardEntity.setCellColor(destCoord, YELLOW);
}
}
}
/**
* Invoked when a cell is not hovered anymore, cancel that cell's preview.
* @param coordinate
*/
private void onCellExit(Coordinate coordinate) {
if (this.click == null) {
this.boardEntity.resetCellColor(coordinate);
Piece p = getPieceAt(coordinate);
if (p == null)
return;
PieceEntity pEntity = this.world.getPiece(coordinate);
if (pEntity == null)
return;
pEntity.setColor(p.getColor() == Color.White ? WHITE : BLACK);
List<Coordinate> allowedMoves = getPieceAllowedMoves(coordinate);
if (allowedMoves.isEmpty())
return;
for (Coordinate destCoord : allowedMoves) {
this.boardEntity.resetCellColor(destCoord);
}
}
}
/**
* Cancel the preview of the moves for the given coordinates.
* @param coordinate
*/
private void cancelPreview(Coordinate coordinate) {
this.boardEntity.resetCellColor(coordinate);
Piece p = getPieceAt(coordinate);
if (p == null)
return;
this.world.getPiece(coordinate).setColor(p.getColor() == Color.White ? WHITE : BLACK);
List<Coordinate> allowedMoves = getPieceAllowedMoves(coordinate);
if (allowedMoves.isEmpty())
return;
for (Coordinate destCoord : allowedMoves) {
this.boardEntity.resetCellColor(destCoord);
}
}
/**
* Start the game by initializing the board, creating the events, and starting the game loop.
*/
@Override
public void onGameStart() {
this.window.scheduleTask(() -> {
try {
initBoard();
} catch (IOException e) {
e.printStackTrace();
}
// start listening to mouse events
this.window.OnCellClick.connect(this::onCellClick);
this.window.OnCellEnter.connect(this::onCellEnter);
this.window.OnCellExit.connect(this::onCellExit);
this.window.OnImGuiTopRender.connect(this::onHeaderRender);
this.window.OnImGuiBottomRender.connect(this::onFooterRender);
synchronized (this) {
notifyAll();
}
});
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void onHeaderRender() {
ImGui.text("FPS : " + (int) ImGui.getIO().getFramerate());
}
/**
* Render the footer of the window.
*/
private void onFooterRender() {
ImGui.beginDisabled(!canDoCastling());
if (ImGui.button("Roque")) {
sendCastling();
}
ImGui.endDisabled();
ImGui.sameLine();
ImGui.beginDisabled(!canDoBigCastling());
if (ImGui.button("Grand Roque")) {
sendBigCastling();
}
ImGui.endDisabled();
ImGui.sameLine();
openPopup();
renderPopups();
}
private void openPopup() {
if (waitingPopup != null) {
ImGui.openPopup(waitingPopup);
waitingPopup = null;
}
}
/**
* Create the 3D piece at the given coordinates
* @param piece the piece to create
* @param coordinate the coordinates of the piece
* @return the piece entity
* @throws IOException
*/
private PieceEntity createDefault(Piece piece, Coordinate coordinate) throws IOException {
Vector2f pieceBoardPos = DDDPlacement.coordinatesToVector(coordinate);
Vector3f pieceWorldPos = new Vector3f(pieceBoardPos.x(), 0, pieceBoardPos.y());
return new PieceEntity(piece, pieceWorldPos,
piece.getColor() == Color.White ? WHITE : BLACK,
piece.getColor() == Color.White ? 0.0f : (float) Math.PI);
}
/**
* Create the 3D board and add the pieces.
* @throws IOException
*/
private void initBoard() throws IOException {
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
Coordinate pos = new Coordinate(i, j);
Piece piece = getPieceAt(pos);
if (piece == null)
continue;
this.world.addPiece(createDefault(piece, pos), pos);
}
}
this.boardEntity = new BoardEntity();
this.world.addEntity(this.boardEntity);
}
/**
* Calculate the position of the point at the t position on a Bezier curve spanning from the begin point to the end point and goign through the control point.
* @param begin begin
* @param middle control point
* @param end end
* @param t between 0 and 1
* @return the point
*/
private Vector3f bezierCurve(Vector3f begin, Vector3f middle, Vector3f end, float t) {
return begin.mul((1.0f - t) * (1.0f - t)).add(middle.mul(2.0f * t * (1.0f - t))).add(end.mul(t * t));
}
/**
* Move the piece on the board according to the given move. Called in a loop to animate the movement.
* @param progress the proportion of the animation already done
* @param piece
* @param move
*/
private void pieceTick(float progress, PieceEntity piece, Move move) {
float height = 1; // how high the piece is raised
Vector2f pieceStartBoard = DDDPlacement.coordinatesToVector(move.getStart());
Vector2f pieceDestinationBoard = DDDPlacement.coordinatesToVector(move.getFinish());
Vector3f start = new Vector3f(pieceStartBoard.x(), 0, pieceStartBoard.y());
Vector3f top = new Vector3f(pieceDestinationBoard.x() - pieceStartBoard.x(), height,
pieceDestinationBoard.y() - pieceStartBoard.y());
Vector3f end = new Vector3f(pieceDestinationBoard.x(), 0, pieceDestinationBoard.y());
piece.setPosition(bezierCurve(start, top, end, progress));
}
/**
* Move the pieces on the board according to the given moves.
* @param moves
*/
private void move3DPieces(List<Move> moves) {
final List<PieceEntity> pEntities = new ArrayList<>(moves.size());
final List<Consumer<Float>> consumers = new ArrayList<>(moves.size());
this.moveProgress = 0.0f;
for (Move move : moves) {
final PieceEntity pEntity = this.world.getPiece(move.getStart());
final Consumer<Float> moveConsumer = (delta) -> {
this.moveProgress += delta / animationTime / (float) moves.size();
pieceTick(this.moveProgress, pEntity, move);
};
pEntities.add(pEntity);
consumers.add(moveConsumer);
this.window.addRegularTask(moveConsumer);
}
try {
Thread.sleep((long) (animationTime * 1000.0f));
} catch (InterruptedException e) {
}
for (int i = 0; i < moves.size(); i++) {
final Move move = moves.get(i);
final Consumer<Float> moveConsumer = consumers.get(i);
final PieceEntity pEntity = pEntities.get(i);
this.window.removeRegularTask(moveConsumer);
Vector2f pieceDestBoardPos = DDDPlacement.coordinatesToVector(move.getFinish());
Vector3f pieceDestWorldPos = new Vector3f(pieceDestBoardPos.x(), 0, pieceDestBoardPos.y());
final PieceEntity pDead = this.world.getPiece(move.getDeadPieceCoords());
this.world.setPieceCoords(null, move.getDeadPieceCoords());
// we must do that on the rendering thread to avoid
// ConcurrentModificationException
this.window.scheduleTask(() -> this.world.ejectPiece(pDead));
pEntity.setPosition(pieceDestWorldPos);
this.world.movePiece(pEntity, move);
}
}
@Override
public void onMove(Move move, boolean captured) {
move3DPieces(List.of(move));
}
/**
* Rotate the camera. Calles in a loop to animate the rotation.
* @param delta the proportion of the animation already done
*/
private void cameraTick(float delta) {
int oddAnimationTurn = (2 * (animationTurns - 1)) + 1;
final float angle = (float) Math.PI;
this.camera.setRotateAngle(this.camera.getRotateAngle() + angle * delta * oddAnimationTurn / animationTime);
}
/**
* Rotate the camera so the current player faces his enemy's pieces.
*/
private void cameraRotate() {
float end = this.camera.getRotateAngle() + (float) Math.PI;
Consumer<Float> rotationConsumer = this::cameraTick;
this.window.addRegularTask(rotationConsumer);
try {
Thread.sleep((long) (animationTime * 1000.0f));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
this.window.removeRegularTask(rotationConsumer);
this.camera.setRotateAngle(end);
}
@Override
public void onPlayerTurn(Color color, boolean undone) {
cameraRotate();
}
/**
* Run the game.
*/
@Override
public void run() {
this.window.run();
this.commandExecutor.close();
// free OpenGL resources
try {
this.window.close();
this.world.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Render a popup with the given title and content.
* @param title
* @param content
*/
private void renderPopup(String title, Runnable content) {
ImVec2 center = ImGui.getMainViewport().getCenter();
ImGui.setNextWindowPos(center, ImGuiCond.Appearing, new ImVec2(0.5f, 0.5f));
if (ImGui.beginPopupModal(title, null, ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoMove)) {
content.run();
if (ImGui.button("Close")) {
closeCurrentPopup();
}
ImGui.endPopup();
}
}
private void closeCurrentPopup() {
ImGui.closeCurrentPopup();
synchronized (this) {
notifyAll();
}
}
private void renderPopup(String title, String text) {
renderPopup(title, () -> ImGui.text(text));
}
/**
* Open the promotion dialog.
*/
private void renderPromoteDialog() {
renderPopup("Promotion", () -> {
ImGui.text("Select the promotion type :");
for (PromoteType promoteType : PromoteType.values()) {
if (ImGui.button(promoteType.toString())) {
sendPawnPromotion(promoteType);
closeCurrentPopup();
}
ImGui.sameLine();
}
ImGui.newLine();
});
}
/**
* List of possible popups.
*/
private void renderPopups() {
renderPopup("Check", "Your king is in check");
renderPopup("Checkmate", "Checkmate, it's a win!");
renderPromoteDialog();
renderPopup("Pat", "It's a pat!");
renderPopup("Tie", "It's a tie!");
renderPopup("White surrender", "The white player has surrendered!");
renderPopup("Black surrender", "The black player has surrendered!");
renderPopup("White victory", "The white player has won !");
renderPopup("Black victory", "The black player has won !");
renderPopup("End", "End of the game, thank you for playing!");
}
/**
* Open the popup identified by the given title and block the current thread until the popup is closed.
* @param title the title of the popup to open
*/
private void openPopup(String title) {
this.waitingPopup = title;
// block the current thread until the popup is closed
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onKingInCheck() {
openPopup("Check");
}
@Override
public void onDraw() {
openPopup("Tie");
}
@Override
public void onKingInMat() {
openPopup("Checkmate");
}
@Override
public void onGameEnd() {
openPopup("End");
this.window.stop();
}
@Override
public void onWin(Color color) {
openPopup(color == Color.White ? "Black victory" : "White victory");
}
@Override
public void onPatSituation() {
openPopup("Pat");
}
@Override
public void onSurrender(Color color) {
openPopup(color == Color.White ? "White surrender" : "Black surrender");
}
@Override
public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
move3DPieces(List.of(kingMove, rookMove));
}
@Override
public void onPromotePawn(Coordinate pieceCoords) {
if (hasAIAttached(getPieceAt(pieceCoords).getColor()))
return;
openPopup("Promotion");
}
/**
* Update the view with the promoted piece
*/
@Override
public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
this.window.scheduleTask(() -> {
this.world.ejectPiece(this.world.getPiece(coordinate));
try {
this.world.addPiece(createDefault(getPieceAt(coordinate), coordinate), coordinate);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}

View File

@@ -2,123 +2,79 @@ package chess.view.DDDrender;
import static org.lwjgl.opengl.GL11.GL_UNSIGNED_INT; import static org.lwjgl.opengl.GL11.GL_UNSIGNED_INT;
import java.io.Closeable;
import java.io.IOException;
import org.joml.Matrix4f;
import org.joml.Vector3f; import org.joml.Vector3f;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
import chess.view.DDDrender.opengl.FrameBuffer;
import chess.view.DDDrender.opengl.VertexArray;
import chess.view.DDDrender.shader.BoardShader; import chess.view.DDDrender.shader.BoardShader;
import chess.view.DDDrender.shader.PieceShader;
import chess.view.DDDrender.shader.ShaderProgram;
public class Renderer { /**
private BoardShader shader; * Basic 3D renderer
private VertexArray vao; */
public class Renderer implements Closeable {
private static int BOARD_WIDTH = 8; private BoardShader boardShader;
private static int BOARD_HEIGHT = 8; private PieceShader pieceShader;
private static int BOARD_SIZE = BOARD_WIDTH * BOARD_HEIGHT; private FrameBuffer frameBuffer;
private static int SQUARE_VERTEX_COUNT = 4;
public Renderer() { public Renderer() {
this.shader = new BoardShader(); this.boardShader = new BoardShader();
this.pieceShader = new PieceShader();
} }
public void Init() { public void Init(float windowWidth, float widowHeight) {
shader.LoadShader(); boardShader.LoadShader();
InitBoard(); pieceShader.LoadShader();
this.frameBuffer = new FrameBuffer((int) windowWidth, (int) (widowHeight * 8.0f / 10.0f));
} }
private float[] GetBoardPositions() { public void Update(Camera cam) {
float[] positions = new float[BOARD_SIZE * SQUARE_VERTEX_COUNT * 3]; this.boardShader.Start();
for (int i = 0; i < BOARD_WIDTH; i++) { this.boardShader.SetCamMatrix(cam);
for (int j = 0; j < BOARD_HEIGHT; j++) { this.pieceShader.Start();
float x = i / (float) BOARD_WIDTH; this.pieceShader.SetCamMatrix(cam);
float dx = (i + 1) / (float) BOARD_WIDTH; }
float z = j / (float) BOARD_HEIGHT;
float dz = (j + 1) / (float) BOARD_HEIGHT;
float trueX = 2 * x - 1; public void Render(DDDModel model, Vector3f color, Matrix4f transform) {
float trueZ = 2 * z - 1; this.pieceShader.Start();
float trueDX = 2 * dx - 1; this.pieceShader.setModelColor(color);
float trueDZ = 2 * dz - 1; this.pieceShader.setModelTransform(transform);
Render(model);
}
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3] = trueX; public void Render(DDDModel model) {
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 1] = 0.0f; for (int i = 0; i < model.getVaos().size(); i++) {
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 2] = trueZ; VertexArray vao = model.getVaos().get(i);
RenderVao(this.pieceShader, vao);
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 3] = trueDX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 4] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 5] = trueZ;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 6] = trueX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 7] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 8] = trueDZ;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 9] = trueDX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 10] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 11] = trueDZ;
}
} }
return positions;
} }
private float[] GetBoardColors() { public void RenderVao(ShaderProgram shader, VertexArray vertexArray) {
float[] colors = new float[BOARD_SIZE * SQUARE_VERTEX_COUNT * 3]; shader.Start();
for (int i = 0; i < BOARD_WIDTH; i++) {
for (int j = 0; j < BOARD_HEIGHT; j++) {
Vector3f color;
if ((i + j) % 2 != 0) {
color = new Vector3f(1.0f, 1.0f, 1.0f);
} else {
color = new Vector3f(0.0f, 0.0f, 0.0f);
}
int squareIndex = i * BOARD_WIDTH + j;
for (int k = 0; k < SQUARE_VERTEX_COUNT; k++) {
colors[squareIndex * SQUARE_VERTEX_COUNT * 3 + k * 3] = color.x;
colors[squareIndex * SQUARE_VERTEX_COUNT * 3 + k * 3 + 1] = color.y;
colors[squareIndex * SQUARE_VERTEX_COUNT * 3 + k * 3 + 2] = color.z;
}
}
}
return colors;
}
private int[] GetBoardIndicies() {
int[] indices = new int[BOARD_SIZE * 6];
for (int i = 0; i < BOARD_SIZE; i++) {
indices[i * 6] = i * 4;
indices[i * 6 + 1] = i * 4 + 1;
indices[i * 6 + 2] = i * 4 + 2;
indices[i * 6 + 3] = i * 4 + 1;
indices[i * 6 + 4] = i * 4 + 2;
indices[i * 6 + 5] = i * 4 + 3;
}
return indices;
}
private void InitBoard() {
ElementBuffer eBuffer = new ElementBuffer(GetBoardIndicies());
this.vao = new VertexArray(eBuffer);
VertexBuffer positionBuffer = new VertexBuffer(GetBoardPositions(), 3);
positionBuffer.AddVertexAttribPointer(0, 3, 0);
VertexBuffer colorBuffer = new VertexBuffer(GetBoardColors(), 3);
colorBuffer.AddVertexAttribPointer(1, 3, 0);
this.vao.Bind();
this.vao.BindVertexBuffer(positionBuffer);
this.vao.BindVertexBuffer(colorBuffer);
this.vao.Unbind();
}
public void Render(Camera cam) {
this.shader.Start();
this.shader.SetCamMatrix(cam.getMatrix());
RenderVao(vao);
}
public void RenderVao(VertexArray vertexArray) {
this.shader.Start();
vertexArray.Bind(); vertexArray.Bind();
GL30.glDrawElements(GL30.GL_TRIANGLES, vertexArray.GetVertexCount(), GL_UNSIGNED_INT, 0); GL30.glDrawElements(GL30.GL_TRIANGLES, vertexArray.GetVertexCount(), GL_UNSIGNED_INT, 0);
vertexArray.Unbind(); vertexArray.Unbind();
} }
public FrameBuffer getFrameBuffer() {
return frameBuffer;
}
public BoardShader getBoardShader() {
return boardShader;
}
@Override
public void close() throws IOException {
this.boardShader.close();
this.pieceShader.close();
this.frameBuffer.close();
}
} }

View File

@@ -1,11 +1,35 @@
package chess.view.DDDrender; package chess.view.DDDrender;
import common.AssetManager;
import common.Signal0;
import org.joml.Vector2f;
import org.lwjgl.*; import org.lwjgl.*;
import org.lwjgl.glfw.*; import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*; import org.lwjgl.opengl.*;
import org.lwjgl.system.*; import org.lwjgl.system.*;
import chess.model.Coordinate;
import chess.view.DDDrender.opengl.FrameBuffer;
import chess.view.DDDrender.world.Entity;
import chess.view.DDDrender.world.World;
import common.Signal1;
import imgui.ImFontConfig;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.flag.ImGuiWindowFlags;
import imgui.gl3.ImGuiImplGl3;
import imgui.glfw.ImGuiImplGlfw;
import imgui.type.ImBoolean;
import imgui.type.ImInt;
import java.io.Closeable;
import java.io.IOException;
import java.nio.*; import java.nio.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.function.Consumer;
import static org.lwjgl.glfw.Callbacks.*; import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.glfw.GLFW.*;
@@ -13,23 +37,79 @@ import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*; import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*; import static org.lwjgl.system.MemoryUtil.*;
public class Window { /**
* GLFW window.
*/
public class Window implements Closeable {
// The window handle // The window handle
private long window; private long window;
private final ImGuiImplGl3 implGl3 = new ImGuiImplGl3();
private final ImGuiImplGlfw implGlfw = new ImGuiImplGlfw();
private Renderer renderer; private Renderer renderer;
private Camera cam; private final Camera cam;
private final World world;
public Window() { private final Queue<Runnable> tasks;
private final List<Consumer<Float>> regularTasks;
private Coordinate lastCell = null;
public final Signal1<Coordinate> OnCellClick = new Signal1<>();
public final Signal1<Coordinate> OnCellEnter = new Signal1<>();
public final Signal1<Coordinate> OnCellExit = new Signal1<>();
public final Signal0 OnImGuiTopRender = new Signal0();
public final Signal0 OnImGuiBottomRender = new Signal0();
private ImInt detailLevel = new ImInt(10);
private ImBoolean pixelatedFrame = new ImBoolean(true);
private boolean shouldBeClosed = false;
public Window(Renderer renderer, World world, Camera camera) {
this.renderer = new Renderer(); this.renderer = new Renderer();
this.cam = new Camera(); this.cam = camera;
this.tasks = new ConcurrentLinkedDeque<>();
this.world = world;
this.regularTasks = new ArrayList<>();
} }
public static void main(String[] args) { /**
new Window().run(); * Add a task to be executed in the next frames.
* @param task
*/
public synchronized void addRegularTask(Consumer<Float> task) {
this.regularTasks.add(task);
} }
/**
* Remove a task that had been set to be executed in the next frames.
* @param task
*/
public synchronized void removeRegularTask(Consumer<Float> task) {this.regularTasks.remove(task);}
/**
* Schedule a task to be executed in the next frame (3d thread).
* @param runnable
*/
public synchronized void scheduleTask(Runnable runnable) {
this.tasks.add(runnable);
}
/**
* Get the next task to be executed.
* @return
*/
private synchronized Runnable getNextTask() {
return this.tasks.poll();
}
/**
* Run the window.
*/
public void run() { public void run() {
System.out.println("LWJGL " + Version.getVersion() + "!"); System.out.println("LWJGL " + Version.getVersion() + "!");
@@ -43,8 +123,35 @@ public class Window {
// Terminate GLFW and free the error callback // Terminate GLFW and free the error callback
glfwTerminate(); glfwTerminate();
glfwSetErrorCallback(null).free(); glfwSetErrorCallback(null).free();
implGl3.shutdown();
implGlfw.shutdown();
ImGui.destroyContext();
} }
/**
* Set the configuration of ImGui
*/
private void initImGui() {
ImGui.setCurrentContext(ImGui.createContext());
implGl3.init("#version 330");
implGlfw.init(window, true);
ImFontConfig config = new ImFontConfig();
config.setFontDataOwnedByAtlas(false);
try {
ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("fonts/comic.ttf").readAllBytes(),
50.0f, config);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initialize the window.
*/
private void init() { private void init() {
// Setup an error callback. The default implementation // Setup an error callback. The default implementation
// will print the error message in System.err. // will print the error message in System.err.
@@ -80,10 +187,19 @@ public class Window {
window, window,
(vidmode.width() - pWidth.get(0)) / 2, (vidmode.width() - pWidth.get(0)) / 2,
(vidmode.height() - pHeight.get(0)) / 2); (vidmode.height() - pHeight.get(0)) / 2);
glfwSetWindowSize(window, vidmode.width(), vidmode.height());
// Make the OpenGL context current
glfwMakeContextCurrent(window);
GL.createCapabilities();
initImGui();
renderer.Init(vidmode.width(), vidmode.height());
} // the stack frame is popped automatically } // the stack frame is popped automatically
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable v-sync // Enable v-sync
glfwSwapInterval(1); glfwSwapInterval(1);
@@ -91,32 +207,131 @@ public class Window {
glfwShowWindow(window); glfwShowWindow(window);
} }
private void render() { private void render(float delta, float aspectRatio) {
cam.rotate(0.01f, 0.01f); final FrameBuffer frameBuffer = this.renderer.getFrameBuffer();
renderer.Render(cam);
cam.setAspectRatio(frameBuffer.getAspectRatio());
frameBuffer.Bind();
frameBuffer.Clear();
renderer.Update(cam);
renderWorld();
frameBuffer.Unbind();
} }
private void loop() { private void renderWorld() {
// This line is critical for LWJGL's interoperation with GLFW's for (Entity entity : this.world.getEntites()) {
// OpenGL context, or any context that is managed externally. entity.render(this.renderer);
// LWJGL detects the context that is current in the current thread, }
// creates the GLCapabilities instance and makes the OpenGL }
// bindings available for use.
GL.createCapabilities();
renderer.Init(); /**
* Execute the tasks in the queue.
* @param delta time since the last frame
*/
private synchronized void executeTasks(float delta) {
Runnable task = getNextTask();
while (task != null) {
task.run();
task = getNextTask();
}
for (Consumer<Float> consumer : regularTasks) {
consumer.accept(delta);
}
}
/**
* Check the cursor position to identify the cell under it.
* @param cursorPosX position of cursor on the x axis
* @param cursorPosY position of cursor on the y axis
* @param windowWidth width of the window
* @param windowHeight height of the window
*/
private void checkCursor(float cursorPosX, float cursorPosY, int windowWidth, int windowHeight) {
Vector2f cursorPos = this.cam.getCursorWorldFloorPos(new Vector2f(cursorPosX, cursorPosY), windowWidth,
windowHeight);
Coordinate selectedCell = DDDPlacement.vectorToCoordinates(cursorPos);
if (this.lastCell == null) {
this.lastCell = selectedCell;
if (selectedCell.isValid())
this.OnCellEnter.emit(selectedCell);
} else if (!this.lastCell.equals(selectedCell)) {
if (this.lastCell.isValid())
this.OnCellExit.emit(this.lastCell);
if (selectedCell.isValid())
this.OnCellEnter.emit(selectedCell);
this.lastCell = selectedCell;
}
if (ImGui.getIO().getMouseClicked(0)) {
if (this.lastCell != null && this.lastCell.isValid())
this.OnCellClick.emit(this.lastCell);
}
}
private void newFrame() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
implGlfw.newFrame();
implGl3.newFrame();
ImGui.newFrame();
}
private void renderWindow() {
ImGui.showDemoWindow();
final FrameBuffer frameBuffer = this.renderer.getFrameBuffer();
final int frameWidth = (int) ImGui.getIO().getDisplaySizeX();
final int frameHeight = (int) (ImGui.getIO().getDisplaySizeY() * 8.0f / 10.0f);
ImGui.setNextWindowSize(ImGui.getIO().getDisplaySize());
ImGui.setNextWindowPos(new ImVec2());
ImGui.begin("Main Window", ImGuiWindowFlags.NoDecoration);
this.OnImGuiTopRender.emit();
ImVec2 mousePos = ImGui.getIO().getMousePos();
ImVec2 framePos = ImGui.getCursorScreenPos();
checkCursor(mousePos.x - framePos.x, frameHeight - (mousePos.y - framePos.y), frameWidth, frameHeight);
ImGui.image(frameBuffer.getRenderTexture(), new ImVec2(frameWidth, frameHeight));
this.OnImGuiBottomRender.emit();
if(ImGui.sliderInt("Niveau de détail", detailLevel.getData(), 1, 10)){
frameBuffer.Resize((int) ((float) frameWidth * detailLevel.get() / 10.0f), (int) ((float) frameHeight * detailLevel.get() / 10.0f));
}
if (ImGui.checkbox("Minecraft", pixelatedFrame)) {
frameBuffer.SetPixelScaling(pixelatedFrame.get());
}
ImGui.end();
}
/**
* Keep on rendering until the user close the window.
*/
private void loop() {
// Set the clear color // Set the clear color
glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearColor(0.4f, 0.4f, 0.6f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glFrontFace(GL_CW);
glColor4f(1.0f, 0.0f, 0.0f, 1.0f); glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
int width[] = new int[1];
int height[] = new int[1];
glfwGetWindowSize(window, width, height);
// Run the rendering loop until the user has attempted to close // Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key. // the window or has pressed the ESCAPE key.
while (!glfwWindowShouldClose(window)) { while (!shouldBeClosed && !glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
render(); newFrame();
render(ImGui.getIO().getDeltaTime(), (float) width[0] / (float) height[0]);
renderWindow();
ImGui.render();
implGl3.renderDrawData(ImGui.getDrawData());
glfwSwapBuffers(window); // swap the color buffers glfwSwapBuffers(window); // swap the color buffers
@@ -124,16 +339,25 @@ public class Window {
// invoked during this call. // invoked during this call.
glfwPollEvents(); glfwPollEvents();
try (MemoryStack stack = stackPush()) { executeTasks(ImGui.getIO().getDeltaTime());
IntBuffer pWidth = stack.mallocInt(1); // int*
IntBuffer pHeight = stack.mallocInt(1); // int*
// Get the window size passed to glfwCreateWindow glfwGetWindowSize(window, width, height);
glfwGetWindowSize(window, pWidth, pHeight); glViewport(0, 0, width[0], height[0]);
glViewport(0, 0, pWidth.get(), pHeight.get());
} // the stack frame is popped automatically
} }
} }
/**
* Closes the window
*/
public void stop() {
shouldBeClosed = true;
}
@Override
public void close() throws IOException {
shouldBeClosed = true;
this.renderer.close();
}
} }

View File

@@ -0,0 +1,118 @@
package chess.view.DDDrender.loader;
import org.joml.Vector3f;
import chess.view.DDDrender.opengl.ElementBuffer;
import chess.view.DDDrender.opengl.VertexArray;
import chess.view.DDDrender.opengl.VertexBuffer;
public class BoardModelLoader {
private static final int BOARD_WIDTH = 8;
private static final int BOARD_HEIGHT = 8;
private static final int BOARD_SIZE = BOARD_WIDTH * BOARD_HEIGHT;
private static final int SQUARE_VERTEX_COUNT = 4;
private static final Vector3f WHITE = new Vector3f(1, 1, 1);
private static final Vector3f BLACK = new Vector3f(0, 0, 0);
/**
* Create the points to make a 3D board.
* Note of developers: "Trust me on this one, bro".
* @return array of 3D points, corressponding to the cells composing the board
*/
private static float[] GetBoardPositions() {
float[] positions = new float[BOARD_SIZE * SQUARE_VERTEX_COUNT * 3];
for (int i = 0; i < BOARD_WIDTH; i++) {
for (int j = 0; j < BOARD_HEIGHT; j++) {
float x = i / (float) BOARD_WIDTH;
float dx = (i + 1) / (float) BOARD_WIDTH;
float z = j / (float) BOARD_HEIGHT;
float dz = (j + 1) / (float) BOARD_HEIGHT;
float trueX = 2 * x - 1;
float trueZ = 2 * z - 1;
float trueDX = 2 * dx - 1;
float trueDZ = 2 * dz - 1;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3] = trueX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 1] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 2] = trueZ;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 3] = trueDX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 4] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 5] = trueZ;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 6] = trueX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 7] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 8] = trueDZ;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 9] = trueDX;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 10] = 0.0f;
positions[(BOARD_WIDTH * i + j) * SQUARE_VERTEX_COUNT * 3 + 11] = trueDZ;
}
}
return positions;
}
/**
* Assign each cell of the bopard to a color.
* Note of developers: "Why are you even reading this ?"
* @return array of colors, corresponding to the cells composing the board
*/
private static float[] GetBoardColors() {
float[] colors = new float[BOARD_SIZE * SQUARE_VERTEX_COUNT * 3];
for (int i = 0; i < BOARD_WIDTH; i++) {
for (int j = 0; j < BOARD_HEIGHT; j++) {
Vector3f color = (i + j) % 2 == 0 ? WHITE : BLACK;
int squareIndex = i * BOARD_WIDTH + j;
for (int k = 0; k < SQUARE_VERTEX_COUNT; k++) {
colors[squareIndex * SQUARE_VERTEX_COUNT * 3 + k * 3] = color.x;
colors[squareIndex * SQUARE_VERTEX_COUNT * 3 + k * 3 + 1] = color.y;
colors[squareIndex * SQUARE_VERTEX_COUNT * 3 + k * 3 + 2] = color.z;
}
}
}
return colors;
}
/**
* Return which points compose each cell.
* Note of developers: "You should stop before you have an heart attack"
* @return array of indicies, corresponding to the cells composing the board
*/
private static int[] GetBoardIndicies() {
int[] indices = new int[BOARD_SIZE * 6];
for (int i = 0; i < BOARD_SIZE; i++) {
indices[i * 6] = i * 4;
indices[i * 6 + 1] = i * 4 + 2;
indices[i * 6 + 2] = i * 4 + 1;
indices[i * 6 + 3] = i * 4 + 1;
indices[i * 6 + 4] = i * 4 + 2;
indices[i * 6 + 5] = i * 4 + 3;
}
return indices;
}
/**
* Create an OpenGL VertexArrayObject (VAO) using all of the functions above for data.
* Note of developers : "Stop annoying me and go read the doc of OpenGL yourself. Please?"
* @return the VAO
*/
public static VertexArray GetBoardModel() {
ElementBuffer eBuffer = new ElementBuffer(GetBoardIndicies());
VertexArray vao = new VertexArray(eBuffer);
VertexBuffer positionBuffer = new VertexBuffer(GetBoardPositions(), 3);
positionBuffer.AddVertexAttribPointer(0, 3, 0);
VertexBuffer colorBuffer = new VertexBuffer(GetBoardColors(), 3);
colorBuffer.AddVertexAttribPointer(1, 3, 0);
vao.Bind();
vao.BindVertexBuffer(positionBuffer);
vao.BindVertexBuffer(colorBuffer);
vao.Unbind();
return vao;
}
}

View File

@@ -0,0 +1,151 @@
package chess.view.DDDrender.loader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.assimp.AIFace.Buffer;
import org.lwjgl.assimp.AIMesh;
import org.lwjgl.assimp.AINode;
import org.lwjgl.assimp.AIScene;
import org.lwjgl.assimp.AIVector3D;
import org.lwjgl.assimp.Assimp;
import org.lwjgl.system.MemoryUtil;
import chess.view.DDDrender.DDDModel;
import chess.view.DDDrender.opengl.ElementBuffer;
import chess.view.DDDrender.opengl.VertexArray;
import chess.view.DDDrender.opengl.VertexBuffer;
import common.AssetManager;
public class ModelLoader {
private static final int VERTEX_SIZE = 3;
private static final int VERTEX_POSITION_INDEX = 0;
private static final int VERTEX_NORMAL_INDEX = 1;
/**
* Note of developers: "Kill me please"
*/
private static float[] toFloatArray(List<Float> list) {
float[] result = new float[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
/**
* Note of developers : "I'd rather write assembly code than watch this again"
*/
private static int[] toIntArray(List<Integer> list) {
int[] result = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
/**
* Process a mesh and create a vertex array object from it.
* @param mesh the mesh to process
* @param scene the model scene
* @return
*/
private static VertexArray processMesh(AIMesh mesh, AIScene scene) {
List<Float> positions = new ArrayList<>();
List<Float> normals = new ArrayList<>();
List<Integer> indicies = new ArrayList<>();
Buffer faces = mesh.mFaces();
int faceNumber = mesh.mNumFaces();
for (int i = 0; i < faceNumber; i++) {
IntBuffer faceIndicies = faces.get(i).mIndices();
for (int j = 0; j < faceIndicies.capacity(); j++) {
indicies.add(faceIndicies.get(j));
}
}
int vertNumber = mesh.mNumVertices();
org.lwjgl.assimp.AIVector3D.Buffer vertecies = mesh.mVertices();
for (int i = 0; i < vertNumber; i++) {
AIVector3D vertex = vertecies.get(i);
positions.add(vertex.x());
positions.add(vertex.y());
positions.add(vertex.z());
}
org.lwjgl.assimp.AIVector3D.Buffer vertexNormals = mesh.mNormals();
for (int i = 0; i < vertNumber; i++) {
AIVector3D normal = vertexNormals.get(i);
normals.add(normal.x());
normals.add(normal.y());
normals.add(normal.z());
}
VertexBuffer positionVBO = new VertexBuffer(toFloatArray(positions), VERTEX_SIZE);
positionVBO.AddVertexAttribPointer(VERTEX_POSITION_INDEX, VERTEX_SIZE, 0);
VertexBuffer normalVBO = new VertexBuffer(toFloatArray(normals), VERTEX_SIZE);
normalVBO.AddVertexAttribPointer(VERTEX_NORMAL_INDEX, VERTEX_SIZE, 0);
VertexArray vao = new VertexArray(new ElementBuffer(toIntArray(indicies)));
vao.Bind();
vao.BindVertexBuffer(positionVBO);
vao.BindVertexBuffer(normalVBO);
vao.Unbind();
return vao;
}
/**
* Recursively process a node and its children.
* @param node
* @param scene
* @param meshes
*/
private static void processNode(AINode node, AIScene scene, List<VertexArray> meshes) {
for (int i = 0; i < node.mNumChildren(); i++) {
AINode child = AINode.create(node.mChildren().get(i));
processNode(child, scene, meshes);
}
for (int i = 0; i < node.mNumMeshes(); i++) {
AIMesh mesh = AIMesh.create(scene.mMeshes().get(node.mMeshes().get(i)));
meshes.add(processMesh(mesh, scene));
}
}
/**
* Load a 3D model from a file (usually .fbx)
*/
public static DDDModel loadModel(String filename) throws IOException {
InputStream input = AssetManager.getResource(filename);
byte[] buffer = input.readAllBytes();
ByteBuffer data = MemoryUtil.memCalloc(buffer.length);
data.put(buffer);
data.flip();
AIScene scene = Assimp.aiImportFileFromMemory(
data,
Assimp.aiProcess_Triangulate | Assimp.aiProcess_PreTransformVertices | Assimp.aiProcess_GlobalScale
| Assimp.aiProcess_ValidateDataStructure,
"");
if (scene == null)
System.err.println(Assimp.aiGetErrorString());
List<VertexArray> vertecies = new ArrayList<>();
processNode(scene.mRootNode(), scene, vertecies);
MemoryUtil.memFree(data);
return new DDDModel(vertecies);
}
}

View File

@@ -0,0 +1,78 @@
package chess.view.DDDrender.loader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import chess.model.Color;
import chess.model.Piece;
import chess.model.PieceVisitor;
import chess.model.pieces.Bishop;
import chess.model.pieces.King;
import chess.model.pieces.Knight;
import chess.model.pieces.Pawn;
import chess.model.pieces.Queen;
import chess.model.pieces.Rook;
import chess.view.DDDrender.DDDModel;
/**
* Visitor that returns the 3d model of a piece.
*/
public class Piece3DModel implements PieceVisitor<String> {
private static final String basePath = "3d/";
private static final Map<String, DDDModel> cache = new HashMap<>();
public DDDModel getModel(Piece piece) throws IOException {
if (piece == null)
return null;
String path = basePath + colorToString(piece.getColor()) + "-" + visit(piece) + ".fbx";
return getModel(path);
}
private DDDModel getModel(String path) throws IOException {
DDDModel model = cache.get(path);
if (model != null)
return model;
model = ModelLoader.loadModel(path);
cache.put(path, model);
return model;
}
private String colorToString(Color color) {
return color == Color.Black ? "black" : "white";
}
@Override
public String visitPiece(Bishop bishop) {
return "bishop";
}
@Override
public String visitPiece(King king) {
return "king";
}
@Override
public String visitPiece(Knight knight) {
return "knight";
}
@Override
public String visitPiece(Pawn pawn) {
return "pawn";
}
@Override
public String visitPiece(Queen queen) {
return "queen";
}
@Override
public String visitPiece(Rook rook) {
return "rook";
}
}

View File

@@ -1,10 +1,13 @@
package chess.view.DDDrender; package chess.view.DDDrender.opengl;
import java.io.Closeable;
import java.io.IOException;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
public class ElementBuffer { public class ElementBuffer implements Closeable {
private int id; private final int id;
private int indiciesCount; private final int indiciesCount;
public ElementBuffer(int[] indicies) { public ElementBuffer(int[] indicies) {
this.indiciesCount = indicies.length; this.indiciesCount = indicies.length;
@@ -15,10 +18,6 @@ public class ElementBuffer {
Unbind(); Unbind();
} }
public void Destroy() {
GL30.glDeleteBuffers(this.id);
}
public void Bind() { public void Bind() {
GL30.glBindBuffer(GL30.GL_ELEMENT_ARRAY_BUFFER, this.id); GL30.glBindBuffer(GL30.GL_ELEMENT_ARRAY_BUFFER, this.id);
} }
@@ -30,4 +29,9 @@ public class ElementBuffer {
public int GetIndiciesCount() { public int GetIndiciesCount() {
return this.indiciesCount; return this.indiciesCount;
} }
@Override
public void close() throws IOException {
GL30.glDeleteBuffers(this.id);
}
} }

View File

@@ -0,0 +1,116 @@
package chess.view.DDDrender.opengl;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DEPTH_COMPONENT;
import static org.lwjgl.opengl.GL11.GL_RGB;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL11.GL_UNSIGNED_BYTE;
import static org.lwjgl.opengl.GL11.glBindTexture;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glTexImage2D;
import static org.lwjgl.opengl.GL11.glViewport;
import java.io.Closeable;
import java.io.IOException;
import org.lwjgl.opengl.GL30;
public class FrameBuffer implements Closeable {
private int fbo;
private int renderTexture;
private int depthBuffer;
private int width;
private int height;
public FrameBuffer(int width, int height) {
this.width = width;
this.height = height;
// The frame buffer
this.fbo = GL30.glGenFramebuffers();
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fbo);
// The texture
this.renderTexture = GL30.glGenTextures();
glBindTexture(GL_TEXTURE_2D, renderTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
GL30.glTexParameteri(GL_TEXTURE_2D, GL30.GL_TEXTURE_MAG_FILTER, GL30.GL_NEAREST);
GL30.glTexParameteri(GL_TEXTURE_2D, GL30.GL_TEXTURE_MIN_FILTER, GL30.GL_NEAREST);
// The depth buffer
this.depthBuffer = GL30.glGenRenderbuffers();
GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, depthBuffer);
GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL_DEPTH_COMPONENT, width, height);
GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL30.GL_RENDERBUFFER,
depthBuffer);
// Set "renderedTexture" as our colour attachement #0
GL30.glFramebufferTexture2D(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTexture, 0);
// Set the list of draw buffers.
int[] drawBuffers = { GL30.GL_COLOR_ATTACHMENT0 };
GL30.glDrawBuffers(drawBuffers);
}
public void Bind() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, this.fbo);
glViewport(0, 0, this.width, this.height);
}
public void Unbind() {
GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
}
public void Clear() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
}
public void Resize(int width, int height) {
this.width = width;
this.height = height;
GL30.glBindTexture(GL_TEXTURE_2D, this.renderTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, this.width, this.height, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, this.depthBuffer);
GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL_DEPTH_COMPONENT, this.width, this.height);
}
public void SetPixelScaling(boolean pixelated) {
glBindTexture(GL_TEXTURE_2D, renderTexture);
int method = pixelated ? GL30.GL_NEAREST : GL30.GL_LINEAR;
GL30.glTexParameteri(GL_TEXTURE_2D, GL30.GL_TEXTURE_MAG_FILTER, method);
GL30.glTexParameteri(GL_TEXTURE_2D, GL30.GL_TEXTURE_MIN_FILTER, method);
}
public float getAspectRatio() {
return (float) width / (float) height;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getRenderTexture() {
return renderTexture;
}
@Override
public void close() throws IOException {
GL30.glDeleteFramebuffers(this.fbo);
GL30.glDeleteRenderbuffers(this.depthBuffer);
GL30.glDeleteTextures(this.renderTexture);
}
}

View File

@@ -1,14 +1,17 @@
package chess.view.DDDrender; package chess.view.DDDrender.opengl;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
public class VertexArray { public class VertexArray implements Closeable {
private int id;
private ElementBuffer elementBuffer; private final int id;
private List<VertexBuffer> vertexBuffers; private final ElementBuffer elementBuffer;
private final List<VertexBuffer> vertexBuffers;
public VertexArray(ElementBuffer elementBuffer) { public VertexArray(ElementBuffer elementBuffer) {
this.id = GL30.glGenVertexArrays(); this.id = GL30.glGenVertexArrays();
@@ -19,10 +22,6 @@ public class VertexArray {
Unbind(); Unbind();
} }
public void Destroy() {
GL30.glDeleteBuffers(this.id);
}
public int GetVertexCount() { public int GetVertexCount() {
return this.elementBuffer.GetIndiciesCount(); return this.elementBuffer.GetIndiciesCount();
} }
@@ -44,4 +43,17 @@ public class VertexArray {
private void BindElementArrayBuffer() { private void BindElementArrayBuffer() {
this.elementBuffer.Bind(); this.elementBuffer.Bind();
} }
public List<VertexBuffer> getVertexBuffers() {
return vertexBuffers;
}
@Override
public void close() throws IOException {
GL30.glDeleteBuffers(this.id);
for (VertexBuffer vertexBuffer : vertexBuffers) {
vertexBuffer.close();
}
elementBuffer.close();
}
} }

View File

@@ -1,4 +1,4 @@
package chess.view.DDDrender; package chess.view.DDDrender.opengl;
public record VertexAttribPointer(int index, int size, int offset) { public record VertexAttribPointer(int index, int size, int offset) {

View File

@@ -1,16 +1,18 @@
package chess.view.DDDrender; package chess.view.DDDrender.opengl;
import static org.lwjgl.opengl.GL11.GL_FLOAT; import static org.lwjgl.opengl.GL11.GL_FLOAT;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
public class VertexBuffer { public class VertexBuffer implements Closeable {
private int id; private final int id;
private int dataStride; private final int dataStride;
List<VertexAttribPointer> vertexAttribs; private final List<VertexAttribPointer> vertexAttribs;
public VertexBuffer(float[] data, int stride) { public VertexBuffer(float[] data, int stride) {
this.id = GL30.glGenBuffers(); this.id = GL30.glGenBuffers();
@@ -22,8 +24,10 @@ public class VertexBuffer {
Unbind(); Unbind();
} }
public void Destroy() { public void UpdateData(int offset, float[] data) {
GL30.glDeleteBuffers(id); Bind();
GL30.glBufferSubData(GL30.GL_ARRAY_BUFFER, offset, data);
Unbind();
} }
public void Bind() { public void Bind() {
@@ -46,4 +50,9 @@ public class VertexBuffer {
this.dataStride * 4, vertexAttribPointer.offset()); this.dataStride * 4, vertexAttribPointer.offset());
} }
} }
@Override
public void close() throws IOException {
GL30.glDeleteBuffers(id);
}
} }

View File

@@ -1,6 +1,6 @@
package chess.view.DDDrender.shader; package chess.view.DDDrender.shader;
import org.joml.Matrix4f; import chess.view.DDDrender.Camera;
public class BoardShader extends ShaderProgram { public class BoardShader extends ShaderProgram {
@@ -10,14 +10,31 @@ public class BoardShader extends ShaderProgram {
layout(location = 0) in vec3 position; layout(location = 0) in vec3 position;
layout(location = 1) in vec3 color; layout(location = 1) in vec3 color;
uniform mat4 camMatrix; uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
uniform vec3 lightPosition = vec3(0, 10, 0);
flat out vec3 pass_color; flat out vec3 pass_color;
out vec3 toLightVector;
out vec3 toCameraVector;
out vec3 surfaceNormal;
void main(void){ void main(void){
gl_Position = camMatrix * vec4(position, 1.0); const vec4 normal = vec4(0.0, 1.0, 0.0, 1.0);
gl_Position = projectionMatrix * viewMatrix * vec4(position, 1.0);
vec3 camPos = (inverse(viewMatrix) * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
toLightVector = lightPosition - position;
toCameraVector = camPos - position;
surfaceNormal = (normal).xyz;
pass_color = color; pass_color = color;
} }
"""; """;
private static String fragmentShader = """ private static String fragmentShader = """
@@ -25,14 +42,44 @@ public class BoardShader extends ShaderProgram {
flat in vec3 pass_color; flat in vec3 pass_color;
out vec4 out_color; in vec3 toLightVector;
in vec3 toCameraVector;
in vec3 surfaceNormal;
layout(location = 0) out vec4 out_color;
void main(void){ void main(void){
out_color = vec4(pass_color, 1.0); const float shineDamper = 10.0;
const float reflectivity = 1.0;
float lightDistance = length(toLightVector);
const vec3 attenuation = vec3(0.2, 0.1, 0.0);
float attenuationFactor = attenuation.x + attenuation.y * lightDistance + attenuation.z * lightDistance * lightDistance;
vec3 unitNormal = normalize(surfaceNormal);
vec3 unitLightVector = normalize(toLightVector);
vec3 unitCamVector = normalize(toCameraVector);
vec3 lightDirection = -unitLightVector;
vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);
float diffuse = max(0.2, dot(unitNormal, unitLightVector));
float specularFactor = max(0.0, dot(reflectedLightDirection, unitCamVector));
float specular = pow(specularFactor, shineDamper) * reflectivity;
float brightness = (diffuse + specular) / attenuationFactor;
out_color = brightness * vec4(pass_color, 1.0);
out_color.w = 1.0;
} }
"""; """;
private int location_CamMatrix = 0; private int location_ProjectionMatrix = 0;
private int location_ViewMatrix = 0;
public BoardShader() { public BoardShader() {
@@ -44,10 +91,12 @@ public class BoardShader extends ShaderProgram {
@Override @Override
protected void GetAllUniformLocation() { protected void GetAllUniformLocation() {
location_CamMatrix = GetUniformLocation("camMatrix"); location_ProjectionMatrix = GetUniformLocation("projectionMatrix");
location_ViewMatrix = GetUniformLocation("viewMatrix");
} }
public void SetCamMatrix(Matrix4f mat) { public void SetCamMatrix(Camera camera) {
LoadMat4(location_CamMatrix, mat); LoadMat4(location_ProjectionMatrix, camera.getPerspectiveMatrix());
LoadMat4(location_ViewMatrix, camera.getViewMatrix());
} }
} }

View File

@@ -0,0 +1,116 @@
package chess.view.DDDrender.shader;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import chess.view.DDDrender.Camera;
public class PieceShader extends ShaderProgram {
private static String vertexShader = """
#version 330
layout(location = 0) in vec3 position;
layout(location = 1) in vec3 normal;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform mat4 modelTransform;
uniform vec3 lightPosition = vec3(0, 10, 0);
out vec3 toLightVector;
out vec3 toCameraVector;
out vec3 surfaceNormal;
void main(void){
vec4 modelPos = modelTransform * vec4(position, 1.0);
vec4 globalNormal = modelTransform * vec4(normal, 1.0);
gl_Position = projectionMatrix * viewMatrix * modelPos;
vec3 camPos = (inverse(viewMatrix) * vec4(0.0, 0.0, 0.0, 1.0)).xyz;
toLightVector = lightPosition - modelPos.xyz;
toCameraVector = camPos - position;
surfaceNormal = normalize(globalNormal.xyz);
}
""";
private static String fragmentShader = """
#version 330
in vec3 toLightVector;
in vec3 toCameraVector;
in vec3 surfaceNormal;
uniform vec3 modelColor;
layout(location = 0) out vec4 out_color;
void main(void){
const float shineDamper = 10.0;
const float reflectivity = 1.0;
float lightDistance = length(toLightVector);
const vec3 attenuation = vec3(0.2, 0.1, 0.0);
float attenuationFactor = attenuation.x + attenuation.y * lightDistance + attenuation.z * lightDistance * lightDistance;
vec3 unitNormal = normalize(surfaceNormal);
vec3 unitLightVector = normalize(toLightVector);
vec3 unitCamVector = normalize(toCameraVector);
vec3 lightDirection = -unitLightVector;
vec3 reflectedLightDirection = reflect(lightDirection, unitNormal);
float diffuse = max(0.2, dot(unitNormal, unitLightVector));
float specularFactor = max(0.0, dot(reflectedLightDirection, unitCamVector));
float specular = pow(specularFactor, shineDamper) * reflectivity;
float brightness = (diffuse + specular) / attenuationFactor;
out_color = brightness * vec4(modelColor, 1.0);
out_color.w = 1.0;
}
""";
private int location_ProjectionMatrix = 0;
private int location_ViewMatrix = 0;
private int location_ModelTransform = 0;
private int location_ModelColor = 0;
public PieceShader() {
}
public void LoadShader() {
super.LoadProgram(vertexShader, fragmentShader);
}
@Override
protected void GetAllUniformLocation() {
location_ProjectionMatrix = GetUniformLocation("projectionMatrix");
location_ViewMatrix = GetUniformLocation("viewMatrix");
location_ModelTransform = GetUniformLocation("modelTransform");
location_ModelColor = GetUniformLocation("modelColor");
}
public void SetCamMatrix(Camera camera) {
LoadMat4(location_ProjectionMatrix, camera.getPerspectiveMatrix());
LoadMat4(location_ViewMatrix, camera.getViewMatrix());
}
public void setModelTransform(Matrix4f mat) {
LoadMat4(location_ModelTransform, mat);
}
public void setModelColor(Vector3f color) {
LoadVector(location_ModelColor, color);
}
}

View File

@@ -1,5 +1,7 @@
package chess.view.DDDrender.shader; package chess.view.DDDrender.shader;
import java.io.Closeable;
import java.io.IOException;
import java.nio.FloatBuffer; import java.nio.FloatBuffer;
import java.nio.IntBuffer; import java.nio.IntBuffer;
@@ -9,7 +11,7 @@ import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GL30;
import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryStack;
public abstract class ShaderProgram { public abstract class ShaderProgram implements Closeable {
private int programId; private int programId;
private int vertexShaderId; private int vertexShaderId;
private int fragmentShaderId; private int fragmentShaderId;
@@ -28,6 +30,11 @@ public abstract class ShaderProgram {
GL30.glUseProgram(0); GL30.glUseProgram(0);
} }
/**
* Load the shader program.
* @param vertexSource the source code of the vertex shader.
* @param fragmentSource the source code of the fragment shader.
*/
public void LoadProgram(String vertexSource, String fragmentSource) { public void LoadProgram(String vertexSource, String fragmentSource) {
this.vertexShaderId = LoadShader(vertexSource, GL30.GL_VERTEX_SHADER); this.vertexShaderId = LoadShader(vertexSource, GL30.GL_VERTEX_SHADER);
this.fragmentShaderId = LoadShader(fragmentSource, GL30.GL_FRAGMENT_SHADER); this.fragmentShaderId = LoadShader(fragmentSource, GL30.GL_FRAGMENT_SHADER);
@@ -45,6 +52,12 @@ public abstract class ShaderProgram {
GetAllUniformLocation(); GetAllUniformLocation();
} }
/**
* Load a shader from source code.
* @param source
* @param type
* @return
*/
private int LoadShader(String source, int type) { private int LoadShader(String source, int type) {
int shaderId = GL30.glCreateShader(type); int shaderId = GL30.glCreateShader(type);
@@ -56,8 +69,8 @@ public abstract class ShaderProgram {
if (compileSuccesful.get() != 1) { if (compileSuccesful.get() != 1) {
System.out.println("Shader did not compile !"); System.out.println("Shader did not compile !");
System.err.println(GL30.glGetShaderInfoLog(shaderId));
return -1; return -1;
} }
return shaderId; return shaderId;
@@ -68,7 +81,7 @@ public abstract class ShaderProgram {
protected int GetUniformLocation(String uniformName) { protected int GetUniformLocation(String uniformName) {
int location = GL30.glGetUniformLocation(programId, uniformName); int location = GL30.glGetUniformLocation(programId, uniformName);
if (location == -1) { if (location == -1) {
System.out.println("Uniform value not found !"); System.out.println("Uniform value \"" + uniformName + "\" not found !");
} }
return location; return location;
} }
@@ -91,4 +104,11 @@ public abstract class ShaderProgram {
GL30.glUniformMatrix4fv(location, false, buffer); GL30.glUniformMatrix4fv(location, false, buffer);
} }
} }
@Override
public void close() throws IOException {
GL30.glDeleteShader(vertexShaderId);
GL30.glDeleteShader(fragmentShaderId);
GL30.glDeleteProgram(programId);
}
} }

View File

@@ -0,0 +1,62 @@
package chess.view.DDDrender.world;
import java.io.IOException;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import chess.model.Coordinate;
import chess.view.DDDrender.Renderer;
import chess.view.DDDrender.loader.BoardModelLoader;
import chess.view.DDDrender.opengl.VertexArray;
import chess.view.DDDrender.opengl.VertexBuffer;
/**
* Abstraction of the 3D model of the board.
*/
public class BoardEntity extends Entity {
private final VertexArray vao;
private final VertexBuffer colorVbo;
private static final Vector3f WHITE = new Vector3f(1, 1, 1);
private static final Vector3f BLACK = new Vector3f(0, 0, 0);
public BoardEntity() {
this.vao = BoardModelLoader.GetBoardModel();
this.colorVbo = this.vao.getVertexBuffers().get(1);
}
/**
* Set the color of a cell.
* @param coord the coordinate of the cell.
* @param color the color of the cell in RGB format.
*/
public void setCellColor(Coordinate coord, Vector3f color) {
float[] data = { color.x, color.y, color.z, color.x, color.y, color.z, color.x, color.y, color.z, color.x,
color.y, color.z};
int cellNumber = (Coordinate.VALUE_MAX - 1 - coord.getX()) * Coordinate.VALUE_MAX + Coordinate.VALUE_MAX - 1 - coord.getY();
int offset = cellNumber * 4 * 4 * 3;
this.colorVbo.UpdateData(offset, data);
}
public void resetCellColor(Coordinate coord) {
setCellColor(coord, (coord.getX() + coord.getY()) % 2 == 0 ? WHITE : BLACK);
}
@Override
public void render(Renderer renderer) {
renderer.RenderVao(renderer.getBoardShader(), vao);
}
@Override
public void close() throws IOException {
vao.close();
}
@Override
public Matrix4f getTransform() {
return null;
}
}

View File

@@ -0,0 +1,18 @@
package chess.view.DDDrender.world;
import java.io.Closeable;
import org.joml.Matrix4f;
import chess.view.DDDrender.Renderer;
/**
* Abstract class for all entities in the 3D view.
*/
public abstract class Entity implements Closeable{
public abstract void render(Renderer renderer);
public abstract Matrix4f getTransform();
}

View File

@@ -0,0 +1,64 @@
package chess.view.DDDrender.world;
import java.io.IOException;
import org.joml.Matrix4f;
import org.joml.Vector3f;
import chess.view.DDDrender.DDDModel;
import chess.view.DDDrender.Renderer;
/**
* Generic type for 3D model that can be rendered.
*/
public class ModelEntity extends Entity {
protected Vector3f position;
protected Vector3f color;
protected float rotation;
protected DDDModel model;
private Matrix4f transform;
public ModelEntity(DDDModel model, Vector3f position, Vector3f color, float rotation) {
this.position = position;
this.color = color;
this.rotation = rotation;
this.model = model;
updateTransform();
}
@Override
public void render(Renderer renderer) {
renderer.Render(model, color, transform);
}
public void setPosition(Vector3f position) {
this.position = position;
updateTransform();
}
public void setColor(Vector3f color) {
this.color = color;
}
public void setRotation(float rotation) {
this.rotation = rotation;
updateTransform();
}
@Override
public void close() throws IOException {
this.model.close();
}
private void updateTransform() {
this.transform = new Matrix4f().translate(this.position).rotate(this.rotation, new Vector3f(0, 1, 0));
}
@Override
public Matrix4f getTransform() {
return transform;
}
}

View File

@@ -0,0 +1,28 @@
package chess.view.DDDrender.world;
import java.io.IOException;
import org.joml.Vector3f;
import chess.model.Piece;
import chess.view.DDDrender.loader.Piece3DModel;
/**
* Model entity of a piece. Loads the correct model of the resources files for the kind of piece.
*/
public class PieceEntity extends ModelEntity {
private static final Piece3DModel modelLoader = new Piece3DModel();
private final Piece piece;
public PieceEntity(Piece piece, Vector3f position, Vector3f color, float rotation) throws IOException {
super(modelLoader.getModel(piece), position, color, rotation);
this.piece = piece;
}
public Piece getPiece() {
return piece;
}
}

View File

@@ -0,0 +1,75 @@
package chess.view.DDDrender.world;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import chess.model.Coordinate;
import chess.model.Move;
import chess.model.Piece;
/**
* Contains all 3D entities.
*/
public class World implements Closeable{
/** Renderable entity list */
private final List<Entity> entites;
/** provides fast access to 3d pieces */
private final PieceEntity[] pieces;
public World() {
this.entites = new ArrayList<>();
this.pieces = new PieceEntity[Coordinate.VALUE_MAX * Coordinate.VALUE_MAX];
}
public PieceEntity getEntity(Piece piece) {
for (Entity entity : entites) {
if (entity instanceof PieceEntity p) {
if (p.getPiece() == piece)
return p;
}
}
return null;
}
public void addPiece(PieceEntity entity, Coordinate coordinate) {
addEntity(entity);
setPieceCoords(entity, coordinate);
}
public void setPieceCoords(PieceEntity entity, Coordinate coordinate) {
pieces[coordinate.toIndex()] = entity;
}
public void movePiece(PieceEntity entity, Move move) {
setPieceCoords(entity, move.getFinish());
setPieceCoords(null, move.getStart());
}
public void ejectPiece(PieceEntity entity) {
if (entity != null)
this.entites.remove(entity);
}
public PieceEntity getPiece(Coordinate coordinate) {
return pieces[coordinate.toIndex()];
}
public void addEntity(Entity entity) {
this.entites.add(entity);
}
public List<Entity> getEntites() {
return entites;
}
@Override
public void close() throws IOException {
for (Entity entity : entites) {
entity.close();
}
}
}

View File

@@ -0,0 +1,21 @@
package chess.view;
import chess.ai.AI;
import chess.controller.CommandSender;
import chess.controller.event.GameAdapter;
import chess.controller.event.GameListener;
import chess.model.Color;
public abstract class GameView extends GameAdapter implements CommandSender{
public abstract void run();
public boolean hasAIAttached(Color color) {
for (GameListener listener : getCommandExecutor().getListeners()) {
if (listener instanceof AI ai) {
if (ai.getColor() == color)
return true;
}
}
return false;
}
}

View File

@@ -10,6 +10,10 @@ import java.net.URISyntaxException;
import common.AssetManager; import common.AssetManager;
/**
* Manage audio files: download, save, and load them.
*/
public class AudioFiles { public class AudioFiles {
private static final String baseURL = "https://images.chesscomfiles.com/chess-themes/sounds/_WAV_/default/"; private static final String baseURL = "https://images.chesscomfiles.com/chess-themes/sounds/_WAV_/default/";

View File

@@ -8,7 +8,15 @@ import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem; import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip; import javax.sound.sampled.Clip;
/**
* Audio player class to play sound files.
*/
public class AudioPlayer { public class AudioPlayer {
/**
* Play a sound file.
* @param audio the audio input stream to play
*/
public static void playSound(InputStream audio) { public static void playSound(InputStream audio) {
new Thread(new Runnable() { new Thread(new Runnable() {
// The wrapper thread is unnecessary, unless it blocks on the // The wrapper thread is unnecessary, unless it blocks on the
@@ -27,6 +35,11 @@ public class AudioPlayer {
}).start(); }).start();
} }
/**
* Convert the given audio input stream to PCM format.
* @param audioInputStream the audio input stream to convert
* @return
*/
private static AudioInputStream convertToPCM(AudioInputStream audioInputStream) { private static AudioInputStream convertToPCM(AudioInputStream audioInputStream) {
AudioFormat m_format = audioInputStream.getFormat(); AudioFormat m_format = audioInputStream.getFormat();

View File

@@ -1,10 +1,14 @@
package chess.view.audio; package chess.view.audio;
import chess.controller.commands.PromoteCommand.PromoteType; import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.event.GameAdaptator; import chess.controller.event.GameAdapter;
import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
public class GameAudio extends GameAdaptator { /**
* Class to handle audio events in the game.
*/
public class GameAudio extends GameAdapter {
private final boolean functional; private final boolean functional;
@@ -51,12 +55,12 @@ public class GameAudio extends GameAdaptator {
} }
@Override @Override
public void onPawnPromoted(PromoteType promotion) { public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
playSound("promote"); playSound("promote");
} }
@Override @Override
public void onCastling(boolean bigCastling) { public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
playSound("castle"); playSound("castle");
} }

View File

@@ -1,5 +1,8 @@
package chess.view.consolerender; package chess.view.consolerender;
/**
* Colors class for console output, contains ANSI escape codes.
*/
public class Colors { public class Colors {
// Reset // Reset
public static final String RESET = "\u001B[0m"; // Text Reset public static final String RESET = "\u001B[0m"; // Text Reset
@@ -15,24 +18,24 @@ public class Colors {
public static final String CYAN = "\033[38;2;0;255;255m"; public static final String CYAN = "\033[38;2;0;255;255m";
// Background // Background
public static final String BLACK_BACKGROUND = "\033[40m"; // BLACK public static final String BLACK_BACKGROUND = "\033[40m";
public static final String LIGHT_GRAY_BACKGROUND = "\033[48;2;180;180;180m"; public static final String LIGHT_GRAY_BACKGROUND = "\033[48;2;180;180;180m";
public static final String DARK_GRAY_BACKGROUND = "\033[48;2;120;120;120m"; public static final String DARK_GRAY_BACKGROUND = "\033[48;2;120;120;120m";
public static final String RED_BACKGROUND = "\033[41m"; // RED public static final String RED_BACKGROUND = "\033[41m";
public static final String GREEN_BACKGROUND = "\033[42m"; // GREEN public static final String GREEN_BACKGROUND = "\033[42m";
public static final String YELLOW_BACKGROUND = "\033[43m"; // YELLOW public static final String YELLOW_BACKGROUND = "\033[43m";
public static final String BLUE_BACKGROUND = "\033[44m"; // BLUE public static final String BLUE_BACKGROUND = "\033[44m";
public static final String PURPLE_BACKGROUND = "\033[45m"; // PURPLE public static final String PURPLE_BACKGROUND = "\033[45m";
public static final String CYAN_BACKGROUND = "\033[46m"; // CYAN public static final String CYAN_BACKGROUND = "\033[46m";
public static final String WHITE_BACKGROUND = "\033[47m"; // WHITE public static final String WHITE_BACKGROUND = "\033[47m";
// High Intensity backgrounds // High Intensity backgrounds
public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";// BLACK public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";
public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";// RED public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";
public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";// GREEN public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";
public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";// YELLOW public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";
public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";// BLUE public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";
public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; // PURPLE public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m";
public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m"; // CYAN public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";
public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m"; // WHITE public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m";
} }

View File

@@ -2,13 +2,15 @@ package chess.view.consolerender;
import chess.controller.Command; import chess.controller.Command;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.CommandSender;
import chess.controller.commands.*; import chess.controller.commands.*;
import chess.controller.commands.PromoteCommand.PromoteType; import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.event.GameListener; import chess.controller.event.GameAdapter;
import chess.model.Color; import chess.model.Color;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
import chess.model.Piece; import chess.model.Piece;
import chess.view.GameView;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -16,7 +18,11 @@ import java.util.Scanner;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
public class Console implements GameListener { /**
* Console renderer.
*/
public class Console extends GameView {
private final Scanner scanner = new Scanner(System.in); private final Scanner scanner = new Scanner(System.in);
private final CommandExecutor commandExecutor; private final CommandExecutor commandExecutor;
private final ConsolePieceName consolePieceName = new ConsolePieceName(); private final ConsolePieceName consolePieceName = new ConsolePieceName();
@@ -33,20 +39,12 @@ public class Console implements GameListener {
this(commandExecutor, true); this(commandExecutor, true);
} }
private Piece pieceAt(int x, int y) { /**
return pieceAt(new Coordinate(x, y)); * Translate a string containing chess coordinates (such as "a1" or "d6") to coordinates.
} * @param coordinates the string to translate
* @return the coordinates of the cell
private Command.CommandResult sendCommand(Command command) { * @throws Exception if the string is not valid
return this.commandExecutor.executeCommand(command); */
}
private Piece pieceAt(Coordinate coordinate) {
GetPieceAtCommand command = new GetPieceAtCommand(coordinate);
sendCommand(command);
return command.getPiece();
}
public Coordinate stringToCoordinate(String coordinates) throws Exception { public Coordinate stringToCoordinate(String coordinates) throws Exception {
char xPos = coordinates.charAt(0); char xPos = coordinates.charAt(0);
char yPos = coordinates.charAt(1); char yPos = coordinates.charAt(1);
@@ -65,6 +63,9 @@ public class Console implements GameListener {
return new Coordinate(x, y); return new Coordinate(x, y);
} }
/**
* Open a dialog so the user can, during their turn, move a piece, show move previews, or surrender.
*/
@Override @Override
public void onPlayerTurn(Color color, boolean undone) { public void onPlayerTurn(Color color, boolean undone) {
if (!captureInput) if (!captureInput)
@@ -95,10 +96,15 @@ public class Console implements GameListener {
} }
private boolean playerPickedSurrender(Color color) { private boolean playerPickedSurrender(Color color) {
sendCommand(new SurrenderCommand(color)); sendSurrender(color);
return true; return true;
} }
/**
* Ask the user to pick a move
* @param color the color of the player
* @return true if there has been a move, false otherwise
*/
public boolean playerPickedMove(Color color) { public boolean playerPickedMove(Color color) {
try { try {
System.out.println("Piece to move, or \"castling\" for a castling"); System.out.println("Piece to move, or \"castling\" for a castling");
@@ -109,7 +115,7 @@ public class Console implements GameListener {
Coordinate start = stringToCoordinate(answer); Coordinate start = stringToCoordinate(answer);
System.out.println("New position: "); System.out.println("New position: ");
Coordinate end = stringToCoordinate(scanner.nextLine()); Coordinate end = stringToCoordinate(scanner.nextLine());
Command.CommandResult result = sendCommand(new MoveCommand(new Move(start, end))); Command.CommandResult result = sendMove(new Move(start, end));
return switch (Objects.requireNonNull(result)) { return switch (Objects.requireNonNull(result)) {
case Command.CommandResult.Moved, Command.CommandResult.ActionNeeded -> true; case Command.CommandResult.Moved, Command.CommandResult.ActionNeeded -> true;
@@ -122,16 +128,16 @@ public class Console implements GameListener {
} }
} }
/**
* Ask the user to pick a piece, and show its potential moves
* @param color
* @return
*/
private boolean playerPickedShowMoves(Color color) { private boolean playerPickedShowMoves(Color color) {
try { try {
System.out.println("Piece to examine: "); System.out.println("Piece to examine: ");
Coordinate piece = stringToCoordinate(scanner.nextLine()); Coordinate piece = stringToCoordinate(scanner.nextLine());
GetAllowedMovesPieceCommand movesCommand = new GetAllowedMovesPieceCommand(piece); List<Coordinate> allowedMoves = getPieceAllowedMoves(piece);
if (sendCommand(movesCommand) == Command.CommandResult.NotAllowed) {
System.out.println("Not allowed.");
return false;
}
List<Coordinate> allowedMoves = movesCommand.getDestinations();
if (allowedMoves.isEmpty()) { if (allowedMoves.isEmpty()) {
System.out.println("No moves allowed for this piece."); System.out.println("No moves allowed for this piece.");
return false; return false;
@@ -182,6 +188,10 @@ public class Console implements GameListener {
this.executor.shutdown(); this.executor.shutdown();
} }
/**
* Open the dialog to promote a pawn.
* @param pieceCoords the coordinates of the pawn to promote
*/
@Override @Override
public void onPromotePawn(Coordinate pieceCoords) { public void onPromotePawn(Coordinate pieceCoords) {
System.out.println("The pawn on the " + pieceCoords + " coordinates needs to be promoted."); System.out.println("The pawn on the " + pieceCoords + " coordinates needs to be promoted.");
@@ -201,7 +211,7 @@ public class Console implements GameListener {
default -> throw new Exception(); default -> throw new Exception();
}; };
valid = true; valid = true;
sendCommand(new PromoteCommand(newPiece)); sendPawnPromotion(newPiece);
} catch (Exception e) { } catch (Exception e) {
System.out.println("Invalid input!"); System.out.println("Invalid input!");
} }
@@ -209,6 +219,9 @@ public class Console implements GameListener {
}); });
} }
/**
* Update and print the board in the console.
*/
@Override @Override
public void onBoardUpdate() { public void onBoardUpdate() {
if (!this.captureInput) if (!this.captureInput)
@@ -218,7 +231,7 @@ public class Console implements GameListener {
for (int i = 0; i < Coordinate.VALUE_MAX; i++) { for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
string.append(8 - i).append(" "); string.append(8 - i).append(" ");
for (int j = 0; j < Coordinate.VALUE_MAX; j++) { for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
Piece p = pieceAt(j, i); Piece p = getPieceAt(new Coordinate(j, i));
if ((i + j) % 2 == 0) { if ((i + j) % 2 == 0) {
string.append(Colors.LIGHT_GRAY_BACKGROUND); string.append(Colors.LIGHT_GRAY_BACKGROUND);
} else { } else {
@@ -236,6 +249,11 @@ public class Console implements GameListener {
System.out.flush(); System.out.flush();
} }
/**
* Display the possible moves of a piece.
* @param piece
* @param moves
*/
public void displayMoves(Coordinate piece, List<Coordinate> moves) { public void displayMoves(Coordinate piece, List<Coordinate> moves) {
StringBuilder string = new StringBuilder(); StringBuilder string = new StringBuilder();
string.append(" a b c d e f g h \n"); string.append(" a b c d e f g h \n");
@@ -243,7 +261,7 @@ public class Console implements GameListener {
string.append(8 - i).append(" "); string.append(8 - i).append(" ");
for (int j = 0; j < Coordinate.VALUE_MAX; j++) { for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
Coordinate currentCell = new Coordinate(j, i); Coordinate currentCell = new Coordinate(j, i);
Piece p = pieceAt(j, i); Piece p = getPieceAt(new Coordinate(j, i));
if (moves.contains(currentCell)) { if (moves.contains(currentCell)) {
string.append(Colors.YELLOW_BACKGROUND); string.append(Colors.YELLOW_BACKGROUND);
} else { } else {
@@ -269,10 +287,6 @@ public class Console implements GameListener {
System.out.println(string); System.out.println(string);
} }
@Override
public void onMove(Move move, boolean captured) {
}
@Override @Override
public void onMoveNotAllowed(Move move) { public void onMoveNotAllowed(Move move) {
System.out.println("Move not allowed."); System.out.println("Move not allowed.");
@@ -283,10 +297,12 @@ public class Console implements GameListener {
System.out.println("Repeated positions!"); System.out.println("Repeated positions!");
} }
/**
* Open different dialogs according to which castling is allowed.
* @return true if a castling was played, false otherwise
*/
private boolean onAskedCastling() { private boolean onAskedCastling() {
GetAllowedCastlingsCommand cmd = new GetAllowedCastlingsCommand(); return switch (getAllowedCastlings()) {
sendCommand(cmd);
return switch (cmd.getCastlingResult()) {
case Small -> onSmallCastling(); case Small -> onSmallCastling();
case Big -> onBigCastling(); case Big -> onBigCastling();
case Both -> onBothCastling(); case Both -> onBothCastling();
@@ -297,6 +313,10 @@ public class Console implements GameListener {
}; };
} }
/**
* Ask the user to confirm a small castling.
* @return true if the castling was played, false otherwise
*/
private boolean onSmallCastling() { private boolean onSmallCastling() {
System.out.println("Small castling allowed. Confirm with \"y\":"); System.out.println("Small castling allowed. Confirm with \"y\":");
String answer = scanner.nextLine(); String answer = scanner.nextLine();
@@ -307,6 +327,10 @@ public class Console implements GameListener {
} }
} }
/**
* Ask the user to confirm a big castling.
* @return true if the castling was played, false otherwise
*/
private boolean onBigCastling() { private boolean onBigCastling() {
System.out.println("Big castling allowed. Confirm with \"y\":"); System.out.println("Big castling allowed. Confirm with \"y\":");
String answer = scanner.nextLine(); String answer = scanner.nextLine();
@@ -317,6 +341,10 @@ public class Console implements GameListener {
} }
} }
/**
* Ask the user to pick a castling when both are allowed.
* @return true if a castling was played, false otherwise
*/
private boolean onBothCastling() { private boolean onBothCastling() {
System.out.println("Both castlings allowed. Pick \"s\" to play a castling, \"b\" to play a big castling."); System.out.println("Both castlings allowed. Pick \"s\" to play a castling, \"b\" to play a big castling.");
String answer = scanner.nextLine(); String answer = scanner.nextLine();
@@ -334,10 +362,13 @@ public class Console implements GameListener {
} }
@Override @Override
public void onCastling(boolean bigCastling) {} public CommandExecutor getCommandExecutor() {
return this.commandExecutor;
}
@Override @Override
public void onPawnPromoted(PromoteType promotion) {} public void run() {
}
} }

View File

@@ -5,6 +5,10 @@ import chess.model.Piece;
import chess.model.PieceVisitor; import chess.model.PieceVisitor;
import chess.model.pieces.*; import chess.model.pieces.*;
/**
* Manage appearance of pieces in the console.
*/
public class ConsolePieceName implements PieceVisitor<String> { public class ConsolePieceName implements PieceVisitor<String> {
public String getString(Piece piece){ public String getString(Piece piece){

View File

@@ -19,11 +19,21 @@ import chess.model.pieces.Queen;
import chess.model.pieces.Rook; import chess.model.pieces.Rook;
import common.AssetManager; import common.AssetManager;
/**
* Visitor that returns the png icon of a piece.
*/
public class PieceIcon implements PieceVisitor<String> { public class PieceIcon implements PieceVisitor<String> {
private static final String basePath = "pieces2D/"; private static final String basePath = "pieces2D/";
private static final Map<String, Icon> cache = new HashMap<>(); private static final Map<String, Icon> cache = new HashMap<>();
/**
* Get icon of the given piece.
* @param piece
* @return icon of the piece
* @throws IOException
*/
public Icon getIcon(Piece piece) throws IOException { public Icon getIcon(Piece piece) throws IOException {
if (piece == null) if (piece == null)
return null; return null;
@@ -31,6 +41,12 @@ public class PieceIcon implements PieceVisitor<String> {
return getIcon(path); return getIcon(path);
} }
/**
* Get icon at the given path.
* @param path
* @return icon at the given path
* @throws IOException
*/
private Icon getIcon(String path) throws IOException { private Icon getIcon(String path) throws IOException {
Icon image = cache.get(path); Icon image = cache.get(path);
if (image != null) if (image != null)

View File

@@ -17,47 +17,42 @@ import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import javax.swing.SwingUtilities; import javax.swing.SwingUtilities;
import chess.controller.Command;
import chess.controller.Command.CommandResult;
import chess.controller.CommandExecutor; import chess.controller.CommandExecutor;
import chess.controller.commands.CastlingCommand; import chess.controller.CommandSender;
import chess.controller.commands.GetAllowedCastlingsCommand;
import chess.controller.commands.GetAllowedMovesPieceCommand;
import chess.controller.commands.GetPieceAtCommand;
import chess.controller.commands.MoveCommand;
import chess.controller.commands.PromoteCommand;
import chess.controller.commands.PromoteCommand.PromoteType; import chess.controller.commands.PromoteCommand.PromoteType;
import chess.controller.commands.UndoCommand;
import chess.controller.commands.GetAllowedCastlingsCommand.CastlingResult;
import chess.controller.event.GameListener; import chess.controller.event.GameListener;
import chess.model.Coordinate; import chess.model.Coordinate;
import chess.model.Move; import chess.model.Move;
import chess.model.Piece; import chess.model.Piece;
import chess.view.GameView;
public class Window extends JFrame implements GameListener { /**
* Window for the 2D chess game.
*/
public class Window extends GameView {
private final CommandExecutor commandExecutor; private final CommandExecutor commandExecutor;
private Coordinate lastClick = null; private Coordinate lastClick = null;
private final JFrame frame;
private final JLabel cells[][]; private final JLabel cells[][];
private final JLabel displayText; private final JLabel displayText;
private final JButton castlingButton = new JButton("Roque"); private final JButton castlingButton = new JButton("Roque");
private final JButton bigCastlingButton = new JButton("Grand Roque"); private final JButton bigCastlingButton = new JButton("Grand Roque");
private final JButton undoButton = new JButton("Annuler le coup précédent"); private final JButton undoButton = new JButton("Annuler le coup précédent");
private final boolean showPopups; public Window(final CommandExecutor commandExecutor) {
this.frame = new JFrame();
public Window(final CommandExecutor commandExecutor, boolean showPopups) {
this.cells = new JLabel[8][8]; this.cells = new JLabel[8][8];
this.displayText = new JLabel(); this.displayText = new JLabel();
this.commandExecutor = commandExecutor; this.commandExecutor = commandExecutor;
this.showPopups = showPopups; this.frame.setSize(800, 910);
setSize(800, 910); this.frame.setVisible(true);
setVisible(true); this.frame.setLocationRelativeTo(null);
setLocationRelativeTo(null); this.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.frame.addWindowListener(new WindowAdapter() {
addWindowListener(new WindowAdapter() {
@Override @Override
public void windowClosed(WindowEvent e) { public void windowClosed(WindowEvent e) {
commandExecutor.close(); commandExecutor.close();
@@ -65,25 +60,26 @@ public class Window extends JFrame implements GameListener {
}); });
} }
private CommandResult sendCommand(Command command) {
return this.commandExecutor.executeCommand(command);
}
private Color getCellColor(int x, int y) { private Color getCellColor(int x, int y) {
return ((x + y) % 2 == 1) ? Color.DARK_GRAY : Color.LIGHT_GRAY; return ((x + y) % 2 == 1) ? Color.DARK_GRAY : Color.LIGHT_GRAY;
} }
/**
* Build and set the buttons of the window.
* @param bottom the Jpanel in which to add the buttons
*/
@SuppressWarnings("unused")
private void buildButtons(JPanel bottom) { private void buildButtons(JPanel bottom) {
castlingButton.addActionListener((event) -> { castlingButton.addActionListener((event) -> {
sendCommand(new CastlingCommand(false)); sendCastling();
}); });
bigCastlingButton.addActionListener((event) -> { bigCastlingButton.addActionListener((event) -> {
sendCommand(new CastlingCommand(true)); sendBigCastling();
}); });
undoButton.addActionListener((event) -> { undoButton.addActionListener((event) -> {
sendCommand(new UndoCommand()); sendUndo();
}); });
bottom.add(castlingButton); bottom.add(castlingButton);
@@ -91,6 +87,9 @@ public class Window extends JFrame implements GameListener {
bottom.add(undoButton); bottom.add(undoButton);
} }
/**
* Build the playable board in the window.
*/
private void buildBoard() { private void buildBoard() {
JPanel content = new JPanel(); JPanel content = new JPanel();
JPanel grid = new JPanel(new GridLayout(8, 8)); JPanel grid = new JPanel(new GridLayout(8, 8));
@@ -102,7 +101,7 @@ public class Window extends JFrame implements GameListener {
content.add(grid); content.add(grid);
content.add(bottom); content.add(bottom);
setContentPane(content); this.frame.setContentPane(content);
for (int y = 0; y < 8; y++) { for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) { for (int x = 0; x < 8; x++) {
@@ -127,23 +126,16 @@ public class Window extends JFrame implements GameListener {
updateBoard(); updateBoard();
} }
private boolean isCellEmpty(int x, int y) { /**
return pieceAt(x, y) == null; * Update the board with the newest pieces' positions.
} */
private Piece pieceAt(int x, int y) {
GetPieceAtCommand command = new GetPieceAtCommand(new Coordinate(x, y));
sendCommand(command);
return command.getPiece();
}
private void updateBoard() { private void updateBoard() {
PieceIcon pieceIcon = new PieceIcon(); PieceIcon pieceIcon = new PieceIcon();
for (int y = 0; y < 8; y++) { for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) { for (int x = 0; x < 8; x++) {
JLabel cell = this.cells[x][y]; JLabel cell = this.cells[x][y];
try { try {
cell.setIcon(pieceIcon.getIcon(pieceAt(x, y))); cell.setIcon(pieceIcon.getIcon(getPieceAt(x, y)));
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -151,12 +143,14 @@ public class Window extends JFrame implements GameListener {
} }
} }
/**
* Show the possible moves of the piece at the given coordinates
* @param x position of the piece on the x axis
* @param y position of the piece on the y axis
* @return true if the piece has possible moves, false otherwise
*/
private boolean previewMoves(int x, int y) { private boolean previewMoves(int x, int y) {
GetAllowedMovesPieceCommand movesCommand = new GetAllowedMovesPieceCommand(new Coordinate(x, y)); List<Coordinate> allowedMoves = getPieceAllowedMoves(new Coordinate(x, y));
if (sendCommand(movesCommand) == CommandResult.NotAllowed)
return false;
List<Coordinate> allowedMoves = movesCommand.getDestinations();
if (allowedMoves.isEmpty()) if (allowedMoves.isEmpty())
return false; return false;
@@ -186,6 +180,11 @@ public class Window extends JFrame implements GameListener {
} }
} }
/**
* Handle the click on a cell. Cancel previous rendering, move the previously selected piece if needed.
* @param x position of the cell on the x axis
* @param y position of the cell on the y axis
*/
private void onCellClicked(int x, int y) { private void onCellClicked(int x, int y) {
clearMoves(); clearMoves();
if (this.lastClick == null) { if (this.lastClick == null) {
@@ -198,18 +197,14 @@ public class Window extends JFrame implements GameListener {
} }
if (!this.lastClick.equals(new Coordinate(x, y))) { if (!this.lastClick.equals(new Coordinate(x, y))) {
Move move = new Move(lastClick, new Coordinate(x, y)); Move move = new Move(lastClick, new Coordinate(x, y));
sendCommand(new MoveCommand(move)); sendMove(move);
} }
this.lastClick = null; this.lastClick = null;
} }
private void updateButtons() { private void updateButtons() {
GetAllowedCastlingsCommand cmd = new GetAllowedCastlingsCommand(); this.castlingButton.setEnabled(canDoCastling());
sendCommand(cmd); this.bigCastlingButton.setEnabled(canDoBigCastling());
this.castlingButton.setEnabled(
cmd.getCastlingResult() == CastlingResult.Small || cmd.getCastlingResult() == CastlingResult.Both);
this.bigCastlingButton.setEnabled(
cmd.getCastlingResult() == CastlingResult.Big || cmd.getCastlingResult() == CastlingResult.Both);
} }
@Override @Override
@@ -220,39 +215,37 @@ public class Window extends JFrame implements GameListener {
@Override @Override
public void onWin(chess.model.Color color) { public void onWin(chess.model.Color color) {
JOptionPane.showMessageDialog(this, "Victory of " + color); JOptionPane.showMessageDialog(this.frame, "Victory of " + color);
} }
@Override @Override
public void onKingInCheck() { public void onKingInCheck() {
if (!showPopups)
return;
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(this, "Check!"); JOptionPane.showMessageDialog(this.frame, "Check!");
}); });
} }
@Override @Override
public void onKingInMat() { public void onKingInMat() {
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(this, "Checkmate!"); JOptionPane.showMessageDialog(this.frame, "Checkmate!");
}); });
} }
@Override @Override
public void onPatSituation() { public void onPatSituation() {
JOptionPane.showMessageDialog(this, "Pat. It's a draw!"); JOptionPane.showMessageDialog(this.frame, "Pat. It's a draw!");
} }
@Override @Override
public void onSurrender(chess.model.Color color) { public void onSurrender(chess.model.Color color) {
JOptionPane.showMessageDialog(this, color + " has surrendered."); JOptionPane.showMessageDialog(this.frame, color + " has surrendered.");
} }
@Override @Override
public void onGameEnd() { public void onGameEnd() {
JOptionPane.showMessageDialog(this, "End of the game"); JOptionPane.showMessageDialog(this.frame, "End of the game");
this.dispose(); this.frame.dispose();
this.commandExecutor.close(); this.commandExecutor.close();
} }
@@ -261,10 +254,18 @@ public class Window extends JFrame implements GameListener {
buildBoard(); buildBoard();
} }
/**
* Open a dialog box when a pawn needs to be promoted
*/
@Override @Override
public void onPromotePawn(Coordinate pieceCoords) { public void onPromotePawn(Coordinate pieceCoords) {
if (!showPopups)
Piece pawn = getPieceAt(pieceCoords);
chess.model.Color player = pawn.getColor();
if (hasAIAttached(player))
return; return;
SwingUtilities.invokeLater(() -> { SwingUtilities.invokeLater(() -> {
String result = null; String result = null;
@@ -277,7 +278,7 @@ public class Window extends JFrame implements GameListener {
while (result == null || result.isEmpty()) { while (result == null || result.isEmpty()) {
result = (String) JOptionPane.showInputDialog( result = (String) JOptionPane.showInputDialog(
this, this.frame,
"Choose the type of piece to upgrade the pawn", "Choose the type of piece to upgrade the pawn",
"Promote Dialog", "Promote Dialog",
JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE,
@@ -296,7 +297,7 @@ public class Window extends JFrame implements GameListener {
} }
if (choosedType != null) if (choosedType != null)
sendCommand(new PromoteCommand(choosedType)); sendPawnPromotion(choosedType);
}); });
} }
@@ -305,9 +306,6 @@ public class Window extends JFrame implements GameListener {
updateBoard(); updateBoard();
} }
@Override
public void onMove(Move move, boolean captured) {}
@Override @Override
public void onMoveNotAllowed(Move move) { public void onMoveNotAllowed(Move move) {
drawInvalid(move); drawInvalid(move);
@@ -315,13 +313,16 @@ public class Window extends JFrame implements GameListener {
@Override @Override
public void onDraw() { public void onDraw() {
JOptionPane.showMessageDialog(this, "Same position was repeated three times. It's a draw!"); JOptionPane.showMessageDialog(this.frame, "Same position was repeated three times. It's a draw!");
} }
@Override @Override
public void onCastling(boolean bigCastling) {} public CommandExecutor getCommandExecutor() {
return this.commandExecutor;
}
@Override @Override
public void onPawnPromoted(PromoteType promotion) {} public void run() {
}
} }

View File

@@ -7,10 +7,18 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
/**
* Manage loading of resources.
*/
public class AssetManager { public class AssetManager {
private static final String gradleBase = "app/src/main/resources/"; private static final String gradleBase = "app/src/main/resources/";
/**
* Get a resource from the classpath or from the file system.
* @param name the name of the resource
* @return the InputStream of the resource
*/
public static InputStream getResource(String name) { public static InputStream getResource(String name) {
// we first search it in files // we first search it in files
InputStream inputStream = getFileInputStream(name); InputStream inputStream = getFileInputStream(name);
@@ -31,6 +39,11 @@ public class AssetManager {
return builder.toString(); return builder.toString();
} }
/**
* Get a resource from the file system.
* @param path the path of the resource
* @return the InputStream of the resource
*/
private static InputStream getFileInputStream(String path) { private static InputStream getFileInputStream(String path) {
File f = new File(path); File f = new File(path);
if (f.exists()) { if (f.exists()) {

Some files were not shown because too many files have changed in this diff Show More