Compare commits
7 Commits
main
...
decorateur
| Author | SHA1 | Date | |
|---|---|---|---|
| fa3c6672e4 | |||
| b920c4fbb3 | |||
|
|
f4b5e10e5b | ||
|
|
747bc62596 | ||
|
|
d60e66fd09 | ||
|
|
c8c6019b15 | ||
|
|
d720e16de0 |
4
.gitattributes
vendored
4
.gitattributes
vendored
@@ -3,7 +3,7 @@
|
|||||||
#
|
#
|
||||||
# Linux start script should use lf
|
# Linux start script should use lf
|
||||||
/gradlew text eol=lf
|
/gradlew text eol=lf
|
||||||
|
|
||||||
# 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
|
|
||||||
*.fbx filter=lfs diff=lfs merge=lfs -text
|
|
||||||
|
|||||||
25
.github/workflows/build.yml
vendored
25
.github/workflows/build.yml
vendored
@@ -1,25 +0,0 @@
|
|||||||
name: Linux arm64
|
|
||||||
run-name: Build And Test
|
|
||||||
|
|
||||||
on: [push]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
Build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Check out repository code
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
|
|
||||||
- uses: actions/setup-java@v4
|
|
||||||
with:
|
|
||||||
distribution: 'temurin'
|
|
||||||
java-version: '21'
|
|
||||||
|
|
||||||
- name: Setup Gradle
|
|
||||||
uses: gradle/actions/setup-gradle@v4
|
|
||||||
|
|
||||||
- name: Build with Gradle
|
|
||||||
run: ./gradlew assemble
|
|
||||||
|
|
||||||
- name: Test
|
|
||||||
run: ./gradlew test
|
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@@ -4,9 +4,4 @@
|
|||||||
# Ignore Gradle build output directory
|
# Ignore Gradle build output directory
|
||||||
build
|
build
|
||||||
|
|
||||||
app/bin
|
app/bin
|
||||||
|
|
||||||
.vscode
|
|
||||||
|
|
||||||
*.wav
|
|
||||||
imgui.ini
|
|
||||||
42
README.md
42
README.md
@@ -1,42 +0,0 @@
|
|||||||
# 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
|
|
||||||
```
|
|
||||||
@@ -16,10 +16,8 @@ repositories {
|
|||||||
mavenCentral()
|
mavenCentral()
|
||||||
}
|
}
|
||||||
|
|
||||||
def os = "linux"
|
|
||||||
def lwjgl_version = "3.3.6"
|
def lwjgl_version = "3.3.6"
|
||||||
def lwjgl_natives = "natives-$os"
|
def lwjgl_natives = "natives-windows"
|
||||||
def imgui_version = "1.87.0"
|
|
||||||
|
|
||||||
dependencies {
|
dependencies {
|
||||||
// Use JUnit Jupiter for testing.
|
// Use JUnit Jupiter for testing.
|
||||||
@@ -28,41 +26,16 @@ dependencies {
|
|||||||
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 {
|
||||||
// Define the main class for the application.
|
// Define the main class for the application.
|
||||||
mainClass = "chess.App"
|
mainClass = "chess.App"
|
||||||
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 {
|
|
||||||
standardInput = System.in
|
|
||||||
}
|
}
|
||||||
|
|
||||||
tasks.named('test') {
|
tasks.named('test') {
|
||||||
|
|||||||
@@ -1,244 +1,16 @@
|
|||||||
|
/*
|
||||||
|
* This Java source file was generated by the Gradle 'init' task.
|
||||||
|
*/
|
||||||
package chess;
|
package chess;
|
||||||
|
|
||||||
import java.awt.event.ActionEvent;
|
import chess.view.render2D.Window;
|
||||||
import java.awt.event.ActionListener;
|
|
||||||
|
|
||||||
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 String getGreeting() {
|
||||||
private static final String version = "v1.1";
|
return "Hello World!";
|
||||||
|
|
||||||
private final JFrame frame;
|
|
||||||
private final JPanel content;
|
|
||||||
|
|
||||||
private ButtonGroup viewSelection;
|
|
||||||
private JRadioButton consoleButton;
|
|
||||||
private JRadioButton swingButton;
|
|
||||||
private JRadioButton openglButton;
|
|
||||||
|
|
||||||
private final JRadioButton[] manualButtons = new JRadioButton[2];
|
|
||||||
private final JRadioButton[] dumbButtons = new JRadioButton[2];
|
|
||||||
private final JRadioButton[] hungryButtons = new JRadioButton[2];
|
|
||||||
private final JRadioButton[] alphaButtons = new JRadioButton[2];
|
|
||||||
|
|
||||||
private JCheckBox audioCheck;
|
|
||||||
private JCheckBox pgnCheck;
|
|
||||||
|
|
||||||
private void drawViewSelection() {
|
|
||||||
JPanel viewPanel = new JPanel();
|
|
||||||
|
|
||||||
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) {
|
public static void main(String[] args) {
|
||||||
new App();
|
Window.main(args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
/*
|
|
||||||
* This Java source file was generated by the Gradle 'init' task.
|
|
||||||
*/
|
|
||||||
package chess;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main class for the console version of the game.
|
|
||||||
*/
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.controller.commands.NewGameCommand;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.view.consolerender.Console;
|
|
||||||
|
|
||||||
public class ConsoleMain {
|
|
||||||
public static void main(String[] args) {
|
|
||||||
Game game = new Game();
|
|
||||||
CommandExecutor commandExecutor = new CommandExecutor(game);
|
|
||||||
|
|
||||||
Console console = new Console(commandExecutor);
|
|
||||||
commandExecutor.addListener(console);
|
|
||||||
|
|
||||||
commandExecutor.executeCommand(new NewGameCommand());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
package chess;
|
|
||||||
|
|
||||||
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 static void main(String[] args) {
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package chess;
|
|
||||||
|
|
||||||
import chess.ai.ais.AlphaBetaAI;
|
|
||||||
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.audio.GameAudio;
|
|
||||||
import chess.view.simplerender.Window;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Main class for the 2D window version of the game.
|
|
||||||
*/
|
|
||||||
public class SwingMain {
|
|
||||||
public static void main(String[] args) {
|
|
||||||
Game game = new Game();
|
|
||||||
CommandExecutor commandExecutor = new CommandExecutor(game);
|
|
||||||
|
|
||||||
Window window = new Window(commandExecutor);
|
|
||||||
commandExecutor.addListener(window);
|
|
||||||
|
|
||||||
AlphaBetaAI ai = new AlphaBetaAI(commandExecutor, Color.Black, 5);
|
|
||||||
commandExecutor.addListener(ai);
|
|
||||||
|
|
||||||
AlphaBetaConsolePrinter aiResults = new AlphaBetaConsolePrinter(ai);
|
|
||||||
aiResults.connect();
|
|
||||||
|
|
||||||
// AI ai2 = new AlphaBetaAI(commandExecutor, Color.White, 5);
|
|
||||||
// commandExecutor.addListener(ai2);
|
|
||||||
|
|
||||||
// Window window2 = new Window(ai2.getSimulation(), false);
|
|
||||||
// ai2.getSimulation().addListener(window2);
|
|
||||||
|
|
||||||
commandExecutor.addListener(new GameAdapter(){
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {
|
|
||||||
System.out.println(PgnExport.exportGame(game));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
commandExecutor.addListener(new GameAudio());
|
|
||||||
|
|
||||||
commandExecutor.executeCommand(new NewGameCommand());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package chess.ai;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.ai.actions.AIAction;
|
|
||||||
import chess.ai.actions.AIActions;
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.controller.event.GameAdapter;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Piece;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Abstract class, used to code bots.
|
|
||||||
*/
|
|
||||||
public abstract class AI extends GameAdapter implements AIActions {
|
|
||||||
|
|
||||||
protected final CommandExecutor commandExecutor;
|
|
||||||
protected final Color color;
|
|
||||||
|
|
||||||
public AI(CommandExecutor commandExecutor, Color color) {
|
|
||||||
this.commandExecutor = commandExecutor;
|
|
||||||
this.color = color;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected abstract void play();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPlayerTurn(Color color, boolean undone) {
|
|
||||||
if (this.color != color || undone)
|
|
||||||
return;
|
|
||||||
|
|
||||||
play();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandExecutor getCommandExecutor() {
|
|
||||||
return this.commandExecutor;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Color getColor() {
|
|
||||||
return color;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
package chess.ai;
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Evaluate the cost of pieces for AI algorithm.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PieceCost implements PieceVisitor<Float> {
|
|
||||||
|
|
||||||
private final Color player;
|
|
||||||
|
|
||||||
public static final float BISHOP = 30;
|
|
||||||
public static final float KING = 900;
|
|
||||||
public static final float KNIGHT = 30;
|
|
||||||
public static final float PAWN = 10;
|
|
||||||
public static final float QUEEN = 90;
|
|
||||||
public static final float ROOK = 50;
|
|
||||||
|
|
||||||
public PieceCost(Color color) {
|
|
||||||
this.player = color;
|
|
||||||
}
|
|
||||||
|
|
||||||
public float getCost(Piece piece) {
|
|
||||||
if (piece == null)
|
|
||||||
return 0;
|
|
||||||
float cost = visit(piece);
|
|
||||||
if (piece.getColor() != player)
|
|
||||||
cost = -cost;
|
|
||||||
return cost;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Float visitPiece(Bishop bishop) {
|
|
||||||
return BISHOP;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Float visitPiece(King king) {
|
|
||||||
return KING;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Float visitPiece(Knight knight) {
|
|
||||||
return KNIGHT;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Float visitPiece(Pawn pawn) {
|
|
||||||
return PAWN;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Float visitPiece(Queen queen) {
|
|
||||||
return QUEEN;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Float visitPiece(Rook rook) {
|
|
||||||
return ROOK;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
package chess.ai;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
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;
|
|
||||||
|
|
||||||
public class PiecePosCost implements PieceVisitor<List<Float>> {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Evaluate the cost of position for AI algorithm.
|
|
||||||
*/
|
|
||||||
|
|
||||||
private final Color color;
|
|
||||||
|
|
||||||
private static final List<Float> BISHOP = Arrays.asList(
|
|
||||||
-2.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -2.0f,
|
|
||||||
-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
|
|
||||||
-1.0f, 0.0f, 0.5f, 1.0f, 1.0f, 0.5f, 0.0f, -1.0f,
|
|
||||||
-1.0f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -1.0f,
|
|
||||||
-1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f,
|
|
||||||
-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
|
|
||||||
-1.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -1.0f,
|
|
||||||
-2.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -2.0f);
|
|
||||||
|
|
||||||
private static final List<Float> KING = Arrays.asList(
|
|
||||||
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
|
|
||||||
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
|
|
||||||
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
|
|
||||||
-3.0f, -4.0f, -4.0f, -5.0f, -5.0f, -4.0f, -4.0f, -3.0f,
|
|
||||||
-2.0f, -3.0f, -3.0f, -4.0f, -4.0f, -3.0f, -3.0f, -2.0f,
|
|
||||||
-1.0f, -2.0f, -2.0f, -2.0f, -2.0f, -2.0f, -2.0f, -1.0f,
|
|
||||||
2.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 2.0f,
|
|
||||||
2.0f, 3.0f, 1.0f, 0.0f, 0.0f, 1.0f, 3.0f, 2.0f);
|
|
||||||
|
|
||||||
private static final List<Float> KNIGHT = Arrays.asList(
|
|
||||||
-5.0f, -4.0f, -3.0f, -3.0f, -3.0f, -3.0f, -4.0f, -5.0f,
|
|
||||||
-4.0f, -2.0f, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f, -4.0f,
|
|
||||||
-3.0f, 0.0f, 1.0f, 1.5f, 1.5f, 1.0f, 0.0f, -3.0f,
|
|
||||||
-3.0f, 0.5f, 1.5f, 2.0f, 2.0f, 1.5f, 0.5f, -3.0f,
|
|
||||||
-3.0f, 0.0f, 1.5f, 2.0f, 2.0f, 1.5f, 0.0f, -3.0f,
|
|
||||||
-3.0f, 0.5f, 1.0f, 1.5f, 1.5f, 1.0f, 0.5f, -3.0f,
|
|
||||||
-4.0f, -2.0f, 0.0f, 0.5f, 0.5f, 0.0f, -2.0f, -4.0f,
|
|
||||||
-5.0f, -4.0f, -3.0f, -3.0f, -3.0f, -3.0f, -4.0f, -5.0f);
|
|
||||||
|
|
||||||
private static final List<Float> PAWN = Arrays.asList(
|
|
||||||
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
|
|
||||||
5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f, 5.0f,
|
|
||||||
1.0f, 1.0f, 2.0f, 3.0f, 3.0f, 2.0f, 1.0f, 1.0f,
|
|
||||||
0.5f, 0.5f, 1.0f, 2.5f, 2.5f, 1.0f, 0.5f, 0.5f,
|
|
||||||
0.0f, 0.0f, 1.0f, 2.0f, 2.0f, 1.0f, 0.0f, 0.0f,
|
|
||||||
0.5f, -0.5f, -1.0f, 0.0f, 0.0f, -1.0f, -0.5f, 0.5f,
|
|
||||||
0.5f, 1.0f, 1.0f, -2.0f, -2.0f, 1.0f, 1.0f, 0.5f,
|
|
||||||
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
|
|
||||||
|
|
||||||
private static final List<Float> QUEEN = Arrays.asList(
|
|
||||||
-2.0f, -1.0f, -1.0f, -0.5f, -0.5f, -1.0f, -1.0f, -2.0f,
|
|
||||||
-1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
|
|
||||||
-1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -1.0f,
|
|
||||||
-0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -0.5f,
|
|
||||||
0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -0.5f,
|
|
||||||
-1.0f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.0f, -1.0f,
|
|
||||||
-1.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f,
|
|
||||||
-2.0f, -1.0f, -1.0f, -0.5f, -0.5f, -1.0f, -1.0f, -2.0f);
|
|
||||||
|
|
||||||
private static final List<Float> ROOK = Arrays.asList(
|
|
||||||
0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f,
|
|
||||||
0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.5f,
|
|
||||||
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
|
|
||||||
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
|
|
||||||
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
|
|
||||||
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
|
|
||||||
-0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f,
|
|
||||||
0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f);
|
|
||||||
|
|
||||||
public PiecePosCost(Color color) {
|
|
||||||
this.color = color;
|
|
||||||
}
|
|
||||||
|
|
||||||
public float getEvaluation(Piece piece, Coordinate coordinate) {
|
|
||||||
if (piece == null)
|
|
||||||
return 0;
|
|
||||||
List<Float> positions = visit(piece);
|
|
||||||
int x = piece.getColor() == Color.Black ? (Coordinate.VALUE_MAX - 1 - coordinate.getX()) : coordinate.getX();
|
|
||||||
int y = piece.getColor() == Color.Black ? (Coordinate.VALUE_MAX - 1 - coordinate.getY()) : coordinate.getY();
|
|
||||||
Coordinate newCoords = new Coordinate(x, y);
|
|
||||||
assert newCoords.isValid();
|
|
||||||
float result = positions.get(newCoords.toIndex());
|
|
||||||
if (piece.getColor() != color)
|
|
||||||
return -result;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Float> visitPiece(Bishop bishop) {
|
|
||||||
return BISHOP;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Float> visitPiece(King king) {
|
|
||||||
return KING;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Float> visitPiece(Knight knight) {
|
|
||||||
return KNIGHT;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Float> visitPiece(Pawn pawn) {
|
|
||||||
return PAWN;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Float> visitPiece(Queen queen) {
|
|
||||||
return QUEEN;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<Float> visitPiece(Rook rook) {
|
|
||||||
return ROOK;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
package chess.ai.ais;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.ExecutionException;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.concurrent.Future;
|
|
||||||
|
|
||||||
import chess.ai.*;
|
|
||||||
import chess.ai.actions.*;
|
|
||||||
import chess.ai.alphabeta.*;
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.model.Color;
|
|
||||||
import common.Signal1;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extends AI. Bot based on the alpha-beta method of resolution.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class AlphaBetaAI extends AI {
|
|
||||||
|
|
||||||
private final int searchDepth;
|
|
||||||
|
|
||||||
private static final float MAX_FLOAT = Float.MAX_VALUE;
|
|
||||||
private static final float MIN_FLOAT = -MAX_FLOAT;
|
|
||||||
|
|
||||||
private final ExecutorService threadPool;
|
|
||||||
|
|
||||||
public final Signal1<Integer> onStartEval = new Signal1<>();
|
|
||||||
public final Signal1<Float> onCompleteEval = new Signal1<>();
|
|
||||||
public final Signal1<Float> onProgress = new Signal1<>();
|
|
||||||
|
|
||||||
public AlphaBetaAI(CommandExecutor commandExecutor, Color color, int searchDepth) {
|
|
||||||
super(commandExecutor, color);
|
|
||||||
this.searchDepth = searchDepth;
|
|
||||||
int threadCount = Runtime.getRuntime().availableProcessors();
|
|
||||||
this.threadPool = Executors.newFixedThreadPool(threadCount,
|
|
||||||
new AlphaBetaThreadCreator(commandExecutor, color, threadCount));
|
|
||||||
}
|
|
||||||
|
|
||||||
private AIAction getBestMove() {
|
|
||||||
List<AIAction> actions = getAllowedActions();
|
|
||||||
List<Future<Float>> moveEvaluations = new ArrayList<>(actions.size());
|
|
||||||
float bestMoveValue = MIN_FLOAT;
|
|
||||||
AIAction bestMove = null;
|
|
||||||
|
|
||||||
this.onStartEval.emit(actions.size());
|
|
||||||
|
|
||||||
for (AIAction action : actions) {
|
|
||||||
moveEvaluations.add(this.threadPool.submit(() -> {
|
|
||||||
return AlphaBetaThreadCreator.getMoveValue(action, this.searchDepth);
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < actions.size(); i++) {
|
|
||||||
this.onProgress.emit((float) i / (float) actions.size());
|
|
||||||
AIAction action = actions.get(i);
|
|
||||||
|
|
||||||
float value = MIN_FLOAT;
|
|
||||||
try {
|
|
||||||
value = moveEvaluations.get(i).get();
|
|
||||||
} catch (InterruptedException | ExecutionException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
if (value > bestMoveValue) {
|
|
||||||
bestMoveValue = value;
|
|
||||||
bestMove = action;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.onCompleteEval.emit(bestMoveValue);
|
|
||||||
|
|
||||||
return bestMove;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {
|
|
||||||
this.threadPool.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void play() {
|
|
||||||
AIAction move = getBestMove();
|
|
||||||
move.applyAction();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandExecutor getCommandExecutor() {
|
|
||||||
return super.getCommandExecutor();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
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 {
|
|
||||||
|
|
||||||
private final AlphaBetaAI ai;
|
|
||||||
private long lastTime;
|
|
||||||
|
|
||||||
public void connect() {
|
|
||||||
ai.onStartEval.connect((moveCount) -> {
|
|
||||||
this.lastTime = System.currentTimeMillis();
|
|
||||||
System.out.println("Evaluating " + moveCount + " moves ...");
|
|
||||||
});
|
|
||||||
|
|
||||||
ai.onProgress.connect((progress) -> {
|
|
||||||
System.out.printf("Progress : %.2f %% \r", progress * 100.0f);
|
|
||||||
});
|
|
||||||
|
|
||||||
ai.onCompleteEval.connect((bestMove) -> {
|
|
||||||
System.out.println("Best move : " + bestMove + " ");
|
|
||||||
System.out.println("Took " + (System.currentTimeMillis() - this.lastTime) + "ms");
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public AlphaBetaConsolePrinter(AlphaBetaAI ai) {
|
|
||||||
this.ai = ai;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,107 +0,0 @@
|
|||||||
package chess.ai.alphabeta;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Map.Entry;
|
|
||||||
|
|
||||||
import chess.ai.GameSimulation;
|
|
||||||
import chess.ai.PieceCost;
|
|
||||||
import chess.ai.PiecePosCost;
|
|
||||||
import chess.ai.actions.AIAction;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Piece;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manage the threads for an alpha-beta bot.
|
|
||||||
* @see AlphaBetaAI
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class AlphaBetaThread extends Thread {
|
|
||||||
|
|
||||||
private final GameSimulation simulation;
|
|
||||||
private final PieceCost pieceCost;
|
|
||||||
private final PiecePosCost piecePosCost;
|
|
||||||
|
|
||||||
private static final int GREAT_MOVE = 9999;
|
|
||||||
|
|
||||||
private static final float MAX_FLOAT = Float.MAX_VALUE;
|
|
||||||
private static final float MIN_FLOAT = -MAX_FLOAT;
|
|
||||||
|
|
||||||
public AlphaBetaThread(Runnable task, GameSimulation simulation, Color color) {
|
|
||||||
super(task);
|
|
||||||
this.simulation = simulation;
|
|
||||||
this.pieceCost = new PieceCost(color);
|
|
||||||
this.piecePosCost = new PiecePosCost(color);
|
|
||||||
}
|
|
||||||
|
|
||||||
private float getEndGameEvaluation() {
|
|
||||||
Color currentTurn = this.simulation.getPlayerTurn();
|
|
||||||
if (this.simulation.getBoard().isKingInCheck(currentTurn))
|
|
||||||
return GREAT_MOVE;
|
|
||||||
return getBoardEvaluation() - PieceCost.PAWN;
|
|
||||||
}
|
|
||||||
|
|
||||||
private float getBoardEvaluation() {
|
|
||||||
final ChessBoard board = this.simulation.getBoard();
|
|
||||||
float result = 0;
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Coordinate coordinate = new Coordinate(i, j);
|
|
||||||
Piece piece = board.pieceAt(coordinate);
|
|
||||||
result += pieceCost.getCost(piece) + piecePosCost.getEvaluation(piece, coordinate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public float getMoveValue(AIAction move, int searchDepth) {
|
|
||||||
move.applyAction(this.simulation.getCommandExecutor());
|
|
||||||
float value = -negaMax(searchDepth - 1, MIN_FLOAT, MAX_FLOAT);
|
|
||||||
move.undoAction(this.simulation.getCommandExecutor());
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
private float negaMax(int depth, float alpha, float beta) {
|
|
||||||
float value = MIN_FLOAT;
|
|
||||||
|
|
||||||
List<AIAction> moves = this.simulation.getAllowedActions();
|
|
||||||
|
|
||||||
if (moves.isEmpty())
|
|
||||||
return -getEndGameEvaluation();
|
|
||||||
|
|
||||||
List<Entry<AIAction, Float>> movesCost = new ArrayList<>(moves.size());
|
|
||||||
|
|
||||||
for (AIAction move : moves) {
|
|
||||||
move.applyAction();
|
|
||||||
movesCost.add(Map.entry(move, -getBoardEvaluation()));
|
|
||||||
move.undoAction();
|
|
||||||
}
|
|
||||||
|
|
||||||
Collections.sort(movesCost, (first, second) -> {
|
|
||||||
return Float.compare(first.getValue(), second.getValue());
|
|
||||||
});
|
|
||||||
|
|
||||||
if (depth == 1)
|
|
||||||
return -movesCost.getFirst().getValue();
|
|
||||||
|
|
||||||
for (var moveEntry : movesCost) {
|
|
||||||
AIAction move = moveEntry.getKey();
|
|
||||||
move.applyAction();
|
|
||||||
value = Float.max(value, -negaMax(depth - 1, -beta, -alpha));
|
|
||||||
move.undoAction();
|
|
||||||
alpha = Float.max(alpha, value);
|
|
||||||
if (alpha >= beta)
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public GameSimulation getSimulation() {
|
|
||||||
return simulation;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package chess.ai.alphabeta;
|
|
||||||
|
|
||||||
import java.util.concurrent.ThreadFactory;
|
|
||||||
|
|
||||||
import chess.ai.GameSimulation;
|
|
||||||
import chess.ai.actions.AIAction;
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.model.Color;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Create the threads for an alpha-beta bot.
|
|
||||||
* @see AlphaBetaAI
|
|
||||||
*/
|
|
||||||
public class AlphaBetaThreadCreator implements ThreadFactory{
|
|
||||||
|
|
||||||
private final Color color;
|
|
||||||
private final GameSimulation simulations[];
|
|
||||||
private int currentThread = 0;
|
|
||||||
|
|
||||||
public AlphaBetaThreadCreator(CommandExecutor commandExecutor, Color color, int threadCount) {
|
|
||||||
this.color = color;
|
|
||||||
simulations = new GameSimulation[threadCount];
|
|
||||||
for (int i = 0; i < threadCount; i++) {
|
|
||||||
simulations[i] = new GameSimulation();
|
|
||||||
commandExecutor.addListener(simulations[i]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public static float getMoveValue(AIAction move, int searchDepth) {
|
|
||||||
AlphaBetaThread t = (AlphaBetaThread) Thread.currentThread();
|
|
||||||
return t.getMoveValue(move, searchDepth);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Thread newThread(Runnable r) {
|
|
||||||
AlphaBetaThread t = new AlphaBetaThread(r, simulations[currentThread], color);
|
|
||||||
currentThread++;
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
package chess.controller;
|
|
||||||
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Game;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Abstract class, manage the execution and results of commands.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public abstract class Command {
|
|
||||||
|
|
||||||
public enum CommandResult {
|
|
||||||
/**
|
|
||||||
* The command was successful. Should update display and switch player turn.
|
|
||||||
*/
|
|
||||||
Moved,
|
|
||||||
/** The command was successful. Should not update anything */
|
|
||||||
NotMoved,
|
|
||||||
/** The command was successful. Should only update display */
|
|
||||||
ActionNeeded,
|
|
||||||
/** The command was not successful */
|
|
||||||
NotAllowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract CommandResult execute(Game game, GameListener outputSystem);
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
package chess.controller;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.controller.Command.CommandResult;
|
|
||||||
import chess.controller.commands.UndoCommand;
|
|
||||||
import chess.controller.event.AsyncGameDispatcher;
|
|
||||||
import chess.controller.event.GameDispatcher;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Game.GameStatus;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute commands.
|
|
||||||
*/
|
|
||||||
public class CommandExecutor {
|
|
||||||
|
|
||||||
private Game game;
|
|
||||||
private final GameDispatcher dispatcher;
|
|
||||||
|
|
||||||
public CommandExecutor() {
|
|
||||||
this(null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public CommandExecutor(Game game) {
|
|
||||||
this(game, new AsyncGameDispatcher());
|
|
||||||
}
|
|
||||||
|
|
||||||
public CommandExecutor(Game game, GameDispatcher dispatcher) {
|
|
||||||
this.game = game;
|
|
||||||
this.dispatcher = dispatcher;
|
|
||||||
}
|
|
||||||
|
|
||||||
public synchronized CommandResult executeCommand(Command command) {
|
|
||||||
assert this.game != null : "No input game specified !";
|
|
||||||
|
|
||||||
CommandResult result = command.execute(this.game, this.dispatcher);
|
|
||||||
|
|
||||||
// non player commands are not supposed to return move result
|
|
||||||
assert result != CommandResult.Moved || command instanceof PlayerCommand || command instanceof UndoCommand;
|
|
||||||
|
|
||||||
processResult(command, result);
|
|
||||||
|
|
||||||
if (command instanceof PlayerCommand playerCommand && result != CommandResult.NotAllowed)
|
|
||||||
this.game.addAction(playerCommand);
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void executeCommands(List<? extends Command> commands) {
|
|
||||||
for (Command command : commands) {
|
|
||||||
CommandResult result = executeCommand(command);
|
|
||||||
assert result != CommandResult.NotAllowed;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processResult(Command command, CommandResult result) {
|
|
||||||
switch (result) {
|
|
||||||
case NotAllowed:
|
|
||||||
case NotMoved:
|
|
||||||
return;
|
|
||||||
|
|
||||||
case ActionNeeded:
|
|
||||||
this.dispatcher.onBoardUpdate();
|
|
||||||
return;
|
|
||||||
|
|
||||||
case Moved:
|
|
||||||
boolean notifyPlayerTurn = true;
|
|
||||||
this.dispatcher.onBoardUpdate();
|
|
||||||
if (!(command instanceof UndoCommand) && checkGameStatus()) {
|
|
||||||
this.dispatcher.onGameEnd();
|
|
||||||
notifyPlayerTurn = false;
|
|
||||||
}
|
|
||||||
switchPlayerTurn(command instanceof UndoCommand, notifyPlayerTurn);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void switchPlayerTurn(boolean undone, boolean notifyPlayerTurn) {
|
|
||||||
this.game.switchPlayerTurn();
|
|
||||||
if (notifyPlayerTurn)
|
|
||||||
this.dispatcher.onPlayerTurn(this.game.getPlayerTurn(), undone);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
*
|
|
||||||
* @return True if the game is over
|
|
||||||
*/
|
|
||||||
private boolean checkGameStatus() {
|
|
||||||
GameStatus gameStatus = this.game.checkGameStatus();
|
|
||||||
|
|
||||||
switch (gameStatus) {
|
|
||||||
case Draw:
|
|
||||||
this.dispatcher.onDraw();
|
|
||||||
return true;
|
|
||||||
case Check:
|
|
||||||
this.dispatcher.onKingInCheck();
|
|
||||||
return false;
|
|
||||||
|
|
||||||
case CheckMate:
|
|
||||||
this.dispatcher.onKingInMat();
|
|
||||||
this.dispatcher.onWin(this.game.getPlayerTurn());
|
|
||||||
return true;
|
|
||||||
|
|
||||||
case OnGoing:
|
|
||||||
return false;
|
|
||||||
|
|
||||||
case Pat:
|
|
||||||
this.dispatcher.onPatSituation();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void addListener(GameListener listener) {
|
|
||||||
this.dispatcher.addListener(listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setGame(Game game) {
|
|
||||||
this.game = game;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void close() {
|
|
||||||
this.dispatcher.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<GameListener> getListeners() {
|
|
||||||
return this.dispatcher.getListeners();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
29
app/src/main/java/chess/controller/Controller.java
Normal file
29
app/src/main/java/chess/controller/Controller.java
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
package chess.controller;
|
||||||
|
|
||||||
|
import chess.model.Coordinates;
|
||||||
|
import chess.model.Game;
|
||||||
|
import chess.model.Move;
|
||||||
|
import chess.view.render2D.Window;
|
||||||
|
|
||||||
|
public class Controller {
|
||||||
|
private final Game game;
|
||||||
|
private final Window view;
|
||||||
|
|
||||||
|
public Controller(Game game, Window view) {
|
||||||
|
this.game = game;
|
||||||
|
this.view = view;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param from Coordinates: old coordinates
|
||||||
|
* @param to Coordinates: new coordinates
|
||||||
|
*/
|
||||||
|
public void sendMove(Coordinates from, Coordinates to) {
|
||||||
|
System.out.println("New move: " + from + " to " + to);
|
||||||
|
game.setMove(new Move(from, to));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
package chess.controller;
|
|
||||||
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
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 CommandResult undo(Game game, GameListener outputSystem) {
|
|
||||||
CommandResult result = undoImpl(game, outputSystem);
|
|
||||||
game.updateLastMove();
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected abstract CommandResult undoImpl(Game game, GameListener outputSystem);
|
|
||||||
}
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Move;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to execute a Castling or Big Castling.
|
|
||||||
*/
|
|
||||||
public class CastlingCommand extends PlayerCommand {
|
|
||||||
|
|
||||||
private Move kingMove;
|
|
||||||
private Move rookMove;
|
|
||||||
private final boolean bigCastling;
|
|
||||||
|
|
||||||
public CastlingCommand(boolean bigCastling) {
|
|
||||||
this.bigCastling = bigCastling;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
|
|
||||||
// we must promote the pending pawn before
|
|
||||||
if (board.pawnShouldBePromoted())
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
if (bigCastling && !board.canBigCastle(game.getPlayerTurn()))
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
if (!bigCastling && !board.canSmallCastle(game.getPlayerTurn()))
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
int rookBeginX = bigCastling ? 0 : 7;
|
|
||||||
int rookEndX = bigCastling ? 3 : 5;
|
|
||||||
|
|
||||||
int kingBeginX = 4;
|
|
||||||
int kingEndX = bigCastling ? 2 : 6;
|
|
||||||
|
|
||||||
int colorLine = game.getPlayerTurn() == Color.White ? 7 : 0;
|
|
||||||
|
|
||||||
Coordinate kingCoords = new Coordinate(kingBeginX, colorLine);
|
|
||||||
Coordinate rookCoords = new Coordinate(rookBeginX, colorLine);
|
|
||||||
|
|
||||||
this.kingMove = new Move(kingCoords, new Coordinate(kingEndX, colorLine));
|
|
||||||
this.rookMove = new Move(rookCoords, new Coordinate(rookEndX, colorLine));
|
|
||||||
|
|
||||||
board.applyMove(this.kingMove);
|
|
||||||
board.applyMove(this.rookMove);
|
|
||||||
|
|
||||||
board.setLastMove(this.kingMove);
|
|
||||||
|
|
||||||
outputSystem.onCastling(this.bigCastling, kingMove, rookMove);
|
|
||||||
|
|
||||||
return CommandResult.Moved;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isBigCastling() {
|
|
||||||
return bigCastling;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected CommandResult undoImpl(Game game, GameListener outputSystem) {
|
|
||||||
game.getBoard().undoMove(this.kingMove, null);
|
|
||||||
game.getBoard().undoMove(this.rookMove, null);
|
|
||||||
|
|
||||||
return CommandResult.Moved;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Game;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to check the possible Castling.
|
|
||||||
*/
|
|
||||||
public class GetAllowedCastlingsCommand extends Command{
|
|
||||||
|
|
||||||
public enum CastlingResult {
|
|
||||||
None, Small, Big, Both;
|
|
||||||
}
|
|
||||||
|
|
||||||
private CastlingResult castlingResult;
|
|
||||||
|
|
||||||
public GetAllowedCastlingsCommand() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
boolean canSmallCastle = game.getBoard().canSmallCastle(game.getPlayerTurn());
|
|
||||||
boolean canBigCastle = game.getBoard().canBigCastle(game.getPlayerTurn());
|
|
||||||
|
|
||||||
int result = 0;
|
|
||||||
if (canSmallCastle)
|
|
||||||
result += 1;
|
|
||||||
if (canBigCastle)
|
|
||||||
result += 2;
|
|
||||||
|
|
||||||
this.castlingResult = CastlingResult.values()[result];
|
|
||||||
|
|
||||||
return CommandResult.NotMoved;
|
|
||||||
}
|
|
||||||
|
|
||||||
public CastlingResult getCastlingResult() {
|
|
||||||
return castlingResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Piece;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to check the Castlings that are possible.
|
|
||||||
*/
|
|
||||||
public class GetAllowedMovesPieceCommand extends Command {
|
|
||||||
|
|
||||||
private final Coordinate start;
|
|
||||||
private List<Coordinate> destinations;
|
|
||||||
|
|
||||||
public GetAllowedMovesPieceCommand(Coordinate start) {
|
|
||||||
this.start = start;
|
|
||||||
this.destinations = new ArrayList<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
Piece piece = board.pieceAt(start);
|
|
||||||
|
|
||||||
if (piece == null)
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
if (piece.getColor() != game.getPlayerTurn())
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
this.destinations = board.getPieceAllowedMoves(start);
|
|
||||||
return CommandResult.NotMoved;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Coordinate> getDestinations() {
|
|
||||||
return destinations;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Piece;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to check the possible moves for a given piece.
|
|
||||||
*/
|
|
||||||
public class GetPieceAtCommand extends Command{
|
|
||||||
|
|
||||||
private final Coordinate pieceCoords;
|
|
||||||
private Piece piece;
|
|
||||||
|
|
||||||
public GetPieceAtCommand(Coordinate pieceCoords) {
|
|
||||||
this.pieceCoords = pieceCoords;
|
|
||||||
this.piece = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
if (!pieceCoords.isValid())
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
this.piece = game.getBoard().pieceAt(pieceCoords);
|
|
||||||
|
|
||||||
return CommandResult.NotMoved;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Piece getPiece() {
|
|
||||||
return piece;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Game;
|
|
||||||
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 {
|
|
||||||
|
|
||||||
private List<Move> moves;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
this.moves = game.getBoard().getAllowedMoves(game.getPlayerTurn());
|
|
||||||
return CommandResult.NotMoved;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Move> getMoves() {
|
|
||||||
return moves;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Move;
|
|
||||||
import chess.model.Piece;
|
|
||||||
import chess.model.rules.PiecePathChecker;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Command to move a piece. Castling not included.
|
|
||||||
*
|
|
||||||
* @see CastlingCommand
|
|
||||||
*/
|
|
||||||
public class MoveCommand extends PlayerCommand {
|
|
||||||
|
|
||||||
private final Move move;
|
|
||||||
private Piece deadPiece;
|
|
||||||
|
|
||||||
public MoveCommand(Move move) {
|
|
||||||
this.move = move;
|
|
||||||
this.deadPiece = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Move getMove() {
|
|
||||||
return move;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Piece getDeadPiece() {
|
|
||||||
return deadPiece;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
CommandResult result = processMove(game, outputSystem);
|
|
||||||
|
|
||||||
switch (result) {
|
|
||||||
case NotAllowed:
|
|
||||||
outputSystem.onMoveNotAllowed(this.move);
|
|
||||||
return result;
|
|
||||||
|
|
||||||
case Moved:
|
|
||||||
game.saveTraitPiecesPos();
|
|
||||||
return result;
|
|
||||||
|
|
||||||
case ActionNeeded:
|
|
||||||
case NotMoved:
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private CommandResult processMove(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
|
|
||||||
// we must promote the pending pawn before
|
|
||||||
if (game.pawnShouldBePromoted())
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
Piece piece = board.pieceAt(move.getStart());
|
|
||||||
if (piece == null)
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
if (piece.getColor() != game.getPlayerTurn())
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
boolean valid = new PiecePathChecker(board, move).isValid();
|
|
||||||
if (!valid)
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
this.deadPiece = board.pieceAt(move.getDeadPieceCoords());
|
|
||||||
board.applyMove(move);
|
|
||||||
|
|
||||||
if (board.isKingInCheck(game.getPlayerTurn())) {
|
|
||||||
board.undoLastMove();
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tryPromote(game, outputSystem)) {
|
|
||||||
outputSystem.onMove(this.move, this.deadPiece != null);
|
|
||||||
return CommandResult.ActionNeeded;
|
|
||||||
}
|
|
||||||
|
|
||||||
board.setLastMove(this.move);
|
|
||||||
|
|
||||||
outputSystem.onMove(this.move, this.deadPiece != null);
|
|
||||||
|
|
||||||
return CommandResult.Moved;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected CommandResult undoImpl(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
|
|
||||||
game.undoTraitPiecesPos();
|
|
||||||
board.undoMove(move, deadPiece);
|
|
||||||
return CommandResult.Moved;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean tryPromote(Game game, GameListener outputSystem) {
|
|
||||||
Coordinate pawnPos = game.getBoard().pawnPromotePosition();
|
|
||||||
|
|
||||||
if (pawnPos == null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
outputSystem.onPromotePawn(pawnPos);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
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;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to create a new game.
|
|
||||||
*/
|
|
||||||
public class NewGameCommand extends Command {
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
|
|
||||||
board.clearBoard();
|
|
||||||
|
|
||||||
for (int i = 0; i < 8; i++) {
|
|
||||||
board.pieceComes(new Pawn(Color.Black), new Coordinate(i, 1));
|
|
||||||
board.pieceComes(new Pawn(Color.White), new Coordinate(i, Coordinate.VALUE_MAX - 2));
|
|
||||||
}
|
|
||||||
|
|
||||||
board.pieceComes(new Rook(Color.Black), new Coordinate(0, 0));
|
|
||||||
board.pieceComes(new Rook(Color.Black), new Coordinate(Coordinate.VALUE_MAX - 1, 0));
|
|
||||||
|
|
||||||
board.pieceComes(new Rook(Color.White), new Coordinate(0, Coordinate.VALUE_MAX - 1));
|
|
||||||
board.pieceComes(new Rook(Color.White), new Coordinate(Coordinate.VALUE_MAX - 1, Coordinate.VALUE_MAX - 1));
|
|
||||||
|
|
||||||
board.pieceComes(new Knight(Color.Black), new Coordinate(1, 0));
|
|
||||||
board.pieceComes(new Knight(Color.Black), new Coordinate(Coordinate.VALUE_MAX - 2, 0));
|
|
||||||
|
|
||||||
board.pieceComes(new Knight(Color.White), new Coordinate(1, Coordinate.VALUE_MAX - 1));
|
|
||||||
board.pieceComes(new Knight(Color.White), new Coordinate(Coordinate.VALUE_MAX - 2, Coordinate.VALUE_MAX - 1));
|
|
||||||
|
|
||||||
board.pieceComes(new Bishop(Color.Black), new Coordinate(2, 0));
|
|
||||||
board.pieceComes(new Bishop(Color.Black), new Coordinate(Coordinate.VALUE_MAX - 3, 0));
|
|
||||||
|
|
||||||
board.pieceComes(new Bishop(Color.White), new Coordinate(2, Coordinate.VALUE_MAX - 1));
|
|
||||||
board.pieceComes(new Bishop(Color.White), new Coordinate(Coordinate.VALUE_MAX - 3, Coordinate.VALUE_MAX - 1));
|
|
||||||
|
|
||||||
board.pieceComes(new Queen(Color.Black), new Coordinate(3, 0));
|
|
||||||
board.pieceComes(new King(Color.Black), new Coordinate(4, 0));
|
|
||||||
|
|
||||||
board.pieceComes(new Queen(Color.White), new Coordinate(3, Coordinate.VALUE_MAX - 1));
|
|
||||||
board.pieceComes(new King(Color.White), new Coordinate(4, Coordinate.VALUE_MAX - 1));
|
|
||||||
|
|
||||||
game.reset();
|
|
||||||
|
|
||||||
outputSystem.onGameStart();
|
|
||||||
outputSystem.onPlayerTurn(game.getPlayerTurn(), false);
|
|
||||||
|
|
||||||
return CommandResult.NotMoved;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Piece;
|
|
||||||
import chess.model.pieces.Bishop;
|
|
||||||
import chess.model.pieces.Knight;
|
|
||||||
import chess.model.pieces.Pawn;
|
|
||||||
import chess.model.pieces.Queen;
|
|
||||||
import chess.model.pieces.Rook;
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Command to promote a pawn.
|
|
||||||
*/
|
|
||||||
public class PromoteCommand extends PlayerCommand {
|
|
||||||
|
|
||||||
public enum PromoteType {
|
|
||||||
Queen,
|
|
||||||
Rook,
|
|
||||||
Bishop,
|
|
||||||
Knight
|
|
||||||
}
|
|
||||||
|
|
||||||
private final PromoteType promoteType;
|
|
||||||
private Coordinate pieceCoords;
|
|
||||||
private Piece oldPawn;
|
|
||||||
|
|
||||||
public PromoteCommand(PromoteType promoteType) {
|
|
||||||
this.promoteType = promoteType;
|
|
||||||
assert this.promoteType != null;
|
|
||||||
this.pieceCoords = null;
|
|
||||||
this.oldPawn = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
|
|
||||||
this.pieceCoords = board.pawnPromotePosition();
|
|
||||||
|
|
||||||
if (this.pieceCoords == null)
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
Piece pawn = board.pieceAt(this.pieceCoords);
|
|
||||||
if (!(pawn instanceof Pawn))
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
int destY = this.pieceCoords.getY();
|
|
||||||
|
|
||||||
int enemyLine = pawn.getColor() == Color.White ? 0 : 7;
|
|
||||||
|
|
||||||
if (destY != enemyLine)
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
this.oldPawn = pawn;
|
|
||||||
board.pieceComes(createPiece(this.promoteType, pawn.getColor()), this.pieceCoords);
|
|
||||||
|
|
||||||
outputSystem.onPawnPromoted(this.promoteType, this.pieceCoords);
|
|
||||||
|
|
||||||
// invalidate the last move cache
|
|
||||||
board.setLastMove(null);
|
|
||||||
|
|
||||||
return CommandResult.Moved;
|
|
||||||
}
|
|
||||||
|
|
||||||
private Piece createPiece(PromoteType promoteType, Color color) {
|
|
||||||
switch (promoteType) {
|
|
||||||
case Queen:
|
|
||||||
return new Queen(color);
|
|
||||||
|
|
||||||
case Bishop:
|
|
||||||
return new Bishop(color);
|
|
||||||
|
|
||||||
case Knight:
|
|
||||||
return new Knight(color);
|
|
||||||
|
|
||||||
case Rook:
|
|
||||||
return new Rook(color);
|
|
||||||
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected CommandResult undoImpl(Game game, GameListener outputSystem) {
|
|
||||||
final ChessBoard board = game.getBoard();
|
|
||||||
|
|
||||||
Piece promoted = board.pieceAt(this.pieceCoords);
|
|
||||||
|
|
||||||
assert promoted != null;
|
|
||||||
|
|
||||||
game.undoTraitPiecesPos();
|
|
||||||
|
|
||||||
board.pieceComes(this.oldPawn, this.pieceCoords);
|
|
||||||
|
|
||||||
game.getLastAction().undo(game, outputSystem);
|
|
||||||
|
|
||||||
return CommandResult.Moved;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PromoteType getPromoteType() {
|
|
||||||
return promoteType;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Game;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to surrender a game.
|
|
||||||
*/
|
|
||||||
public class SurrenderCommand extends Command {
|
|
||||||
|
|
||||||
private final Color player;
|
|
||||||
|
|
||||||
public SurrenderCommand(Color player) {
|
|
||||||
this.player = player;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
outputSystem.onSurrender(player);
|
|
||||||
outputSystem.onWin(Color.getEnemy(player));
|
|
||||||
outputSystem.onGameEnd();
|
|
||||||
return CommandResult.NotMoved;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
package chess.controller.commands;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.event.GameListener;
|
|
||||||
import chess.model.Game;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Command to undo the last action.
|
|
||||||
*/
|
|
||||||
public class UndoCommand extends Command{
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandResult execute(Game game, GameListener outputSystem) {
|
|
||||||
PlayerCommand lastAction = game.getLastAction();
|
|
||||||
if (lastAction == null)
|
|
||||||
return CommandResult.NotAllowed;
|
|
||||||
|
|
||||||
return lastAction.undo(game, outputSystem);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
package chess.controller.event;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
import java.util.function.Consumer;
|
|
||||||
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
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 {
|
|
||||||
|
|
||||||
private final List<GameListener> listeners;
|
|
||||||
private final ExecutorService executor;
|
|
||||||
|
|
||||||
public AsyncGameDispatcher() {
|
|
||||||
this.listeners = new ArrayList<>();
|
|
||||||
this.executor = Executors.newSingleThreadExecutor();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void addListener(GameListener listener) {
|
|
||||||
this.listeners.add(listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void asyncForEachCall(Consumer<GameListener> func) {
|
|
||||||
this.executor.execute(() -> this.listeners.forEach(func));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPlayerTurn(Color color, boolean undone) {
|
|
||||||
asyncForEachCall((l) -> l.onPlayerTurn(color, undone));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onWin(Color color) {
|
|
||||||
asyncForEachCall((l) -> l.onWin(color));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInCheck() {
|
|
||||||
asyncForEachCall((l) -> l.onKingInCheck());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInMat() {
|
|
||||||
asyncForEachCall((l) -> l.onKingInMat());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPatSituation() {
|
|
||||||
asyncForEachCall((l) -> l.onPatSituation());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onSurrender(Color color) {
|
|
||||||
asyncForEachCall((l) -> l.onSurrender(color));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameStart() {
|
|
||||||
asyncForEachCall((l) -> l.onGameStart());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPromotePawn(Coordinate pieceCoords) {
|
|
||||||
asyncForEachCall((l) -> l.onPromotePawn(pieceCoords));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onBoardUpdate() {
|
|
||||||
asyncForEachCall((l) -> l.onBoardUpdate());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {
|
|
||||||
asyncForEachCall((l) -> l.onGameEnd());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMove(Move move, boolean captured) {
|
|
||||||
asyncForEachCall((l) -> l.onMove(move, captured));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMoveNotAllowed(Move move) {
|
|
||||||
asyncForEachCall((l) -> l.onMoveNotAllowed(move));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onDraw() {
|
|
||||||
asyncForEachCall((l) -> l.onDraw());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
|
|
||||||
asyncForEachCall((l) -> l.onCastling(bigCastling, kingMove, rookMove));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
|
|
||||||
asyncForEachCall((l) -> l.onPawnPromoted(promotion, coordinate));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void close() {
|
|
||||||
this.executor.shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<GameListener> getListeners() {
|
|
||||||
return this.listeners;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
package chess.controller.event;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Move;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Dispatcher for bots, does nothing.
|
|
||||||
*/
|
|
||||||
public class EmptyGameDispatcher extends GameDispatcher {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onBoardUpdate() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onDraw() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameStart() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInCheck() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInMat() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMove(Move move, boolean captured) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMoveNotAllowed(Move move) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPatSituation() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPlayerTurn(Color color, boolean undone) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPromotePawn(Coordinate pieceCoords) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onSurrender(Color coward) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onWin(Color winner) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void addListener(GameListener listener) {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void close() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public List<GameListener> getListeners() {
|
|
||||||
return List.of();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package chess.controller.event;
|
|
||||||
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Move;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Abstract class, provides default implementation of GameListener methods.
|
|
||||||
* @see GameListener
|
|
||||||
*/
|
|
||||||
public abstract class GameAdapter implements GameListener {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPlayerTurn(Color color, boolean undone) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onWin(Color color) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInCheck() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInMat() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPatSituation() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onSurrender(Color color) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameStart() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPromotePawn(Coordinate pieceCoords) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onBoardUpdate() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMove(Move move, boolean captured) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMoveNotAllowed(Move move) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onDraw() {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package chess.controller.event;
|
|
||||||
|
|
||||||
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 List<GameListener> getListeners();
|
|
||||||
|
|
||||||
public abstract void close();
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,109 +0,0 @@
|
|||||||
package chess.controller.event;
|
|
||||||
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Move;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Interface for events to listen.
|
|
||||||
*/
|
|
||||||
public interface GameListener {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when the display of the board should be updated
|
|
||||||
*/
|
|
||||||
void onBoardUpdate();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a draw occurs (same position is repeated three times)
|
|
||||||
*/
|
|
||||||
void onDraw();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when the game has ended (by a win or a draw)
|
|
||||||
*/
|
|
||||||
void onGameEnd();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when the game has started
|
|
||||||
*/
|
|
||||||
void onGameStart();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a king is in check
|
|
||||||
*/
|
|
||||||
void onKingInCheck();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a checkmate occurs
|
|
||||||
*/
|
|
||||||
void onKingInMat();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a valid move on the board occurs
|
|
||||||
*
|
|
||||||
* @param move the move to be processed
|
|
||||||
* @param captured whether the move is a result of a capture
|
|
||||||
*/
|
|
||||||
void onMove(Move move, boolean captured);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a sent move is not allowed
|
|
||||||
*
|
|
||||||
* @param move the move to be processed
|
|
||||||
*/
|
|
||||||
void onMoveNotAllowed(Move move);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a pat situation occurs
|
|
||||||
*/
|
|
||||||
void onPatSituation();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when it's the player turn
|
|
||||||
*
|
|
||||||
* @param color the color of the player who should play
|
|
||||||
* @param undone true if it's a result of an undo command
|
|
||||||
*/
|
|
||||||
void onPlayerTurn(Color color, boolean undone);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a pawn should be promoted
|
|
||||||
*
|
|
||||||
* @param pieceCoords the coordinates of the pawn
|
|
||||||
*/
|
|
||||||
void onPromotePawn(Coordinate pieceCoords);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a players surrenders
|
|
||||||
*
|
|
||||||
* @param coward the player who gave up
|
|
||||||
*/
|
|
||||||
void onSurrender(Color coward);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a player wins (by checkmate or if the other one surrenders)
|
|
||||||
*
|
|
||||||
* @param winner
|
|
||||||
*/
|
|
||||||
void onWin(Color winner);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a castling is done
|
|
||||||
*
|
|
||||||
* @param bigCastling if it's queen side castling
|
|
||||||
* @param kingMove the king's move
|
|
||||||
* @param rookMove the rook's move
|
|
||||||
*/
|
|
||||||
void onCastling(boolean bigCastling, Move kingMove, Move rookMove);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Invoked when a pawn is promoted
|
|
||||||
*
|
|
||||||
* @param promotion the type of promotion
|
|
||||||
* @param coordinate the coordinate of the old pawn
|
|
||||||
*/
|
|
||||||
void onPawnPromoted(PromoteType promotion, Coordinate coordinate);
|
|
||||||
|
|
||||||
}
|
|
||||||
17
app/src/main/java/chess/model/AccessibleCellsDecorator.java
Normal file
17
app/src/main/java/chess/model/AccessibleCellsDecorator.java
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
package chess.model;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
public abstract class AccessibleCellsDecorator {
|
||||||
|
public AccessibleCellsDecorator base;
|
||||||
|
public ArrayList<Cell> cells;
|
||||||
|
protected abstract ArrayList<Cell> getAccessibleCells();
|
||||||
|
public AccessibleCellsDecorator(AccessibleCellsDecorator base) {
|
||||||
|
this.base = base;
|
||||||
|
}
|
||||||
|
public AccessibleCellsDecorator() {
|
||||||
|
this(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
81
app/src/main/java/chess/model/Board.java
Normal file
81
app/src/main/java/chess/model/Board.java
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
package chess.model;
|
||||||
|
|
||||||
|
import chess.model.pieces.*;
|
||||||
|
|
||||||
|
public class Board {
|
||||||
|
private final Cell[][] cells;
|
||||||
|
private static final int WHITE = 0;
|
||||||
|
private static final int BLACK = 1;
|
||||||
|
|
||||||
|
public Board(int size) {
|
||||||
|
cells = new Cell[size][size];
|
||||||
|
for (int y = 0; y < size; y++) {
|
||||||
|
for (int x = 0; x < size; x++) {
|
||||||
|
cells[y][x] = new Cell();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setPieces();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Board() {
|
||||||
|
this(8);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Cell getCell(Coordinates coordinates) {
|
||||||
|
return cells[coordinates.getX()][coordinates.getY()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSize() {
|
||||||
|
return cells.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPieces() throws Error {
|
||||||
|
if (this.getSize() == 8) {
|
||||||
|
setPiecesSize8();
|
||||||
|
} else {
|
||||||
|
throw new Error("Oops. This isn't implemented yet.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPiecesSize8() {
|
||||||
|
for (int i = 0; i < 8; i++) {
|
||||||
|
cells[i][1].setPiece(new Pawn(BLACK, this, cells[i][1]));
|
||||||
|
cells[i][6].setPiece(new Pawn(WHITE, this, cells[i][6]));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i <= 7; i += 7) {
|
||||||
|
cells[i][0].setPiece(new Rook(BLACK, this, cells[i][0]));
|
||||||
|
cells[i][7].setPiece(new Rook(WHITE, this, cells[i][7]));
|
||||||
|
}
|
||||||
|
for (int i = 1; i <= 6; i += 5) {
|
||||||
|
cells[i][0].setPiece(new Knight(BLACK, this, cells[i][0]));
|
||||||
|
cells[i][7].setPiece(new Knight(WHITE, this, cells[i][7]));
|
||||||
|
}
|
||||||
|
for (int i = 2; i <= 5; i += 3) {
|
||||||
|
cells[i][0].setPiece(new Bishop(BLACK, this, cells[i][0]));
|
||||||
|
cells[i][7].setPiece(new Bishop(WHITE, this, cells[i][7]));
|
||||||
|
}
|
||||||
|
cells[3][0].setPiece(new Queen(BLACK, this, cells[3][0]));
|
||||||
|
cells[3][7].setPiece(new Queen(WHITE, this, cells[3][7]));
|
||||||
|
cells[4][0].setPiece(new King(BLACK, this, cells[4][0]));
|
||||||
|
cells[4][7].setPiece(new King(WHITE, this, cells[4][7]));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Piece getPiece(Coordinates coordinates) {
|
||||||
|
return getCell(coordinates).getPiece();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void movePiece(Move move) throws Error {
|
||||||
|
Piece movingPiece = getPiece(move.getStart());
|
||||||
|
Cell arrivalCell = getCell(move.getEnd());
|
||||||
|
getCell(move.getStart()).deletePiece();
|
||||||
|
arrivalCell.setPiece(movingPiece);
|
||||||
|
movingPiece.setPosition(arrivalCell);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Cell getRelativePosition(Coordinates coordinates) {
|
||||||
|
// todo
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
25
app/src/main/java/chess/model/Cell.java
Normal file
25
app/src/main/java/chess/model/Cell.java
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
package chess.model;
|
||||||
|
|
||||||
|
public class Cell {
|
||||||
|
private Piece piece = null;
|
||||||
|
|
||||||
|
public Cell(Piece piece) {
|
||||||
|
this.piece = piece;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Cell(){
|
||||||
|
this.piece = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPiece(Piece piece) {
|
||||||
|
this.piece = piece;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void deletePiece() {
|
||||||
|
this.piece = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Piece getPiece() {
|
||||||
|
return piece;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,444 +0,0 @@
|
|||||||
package chess.model;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
import chess.model.pieces.King;
|
|
||||||
import chess.model.pieces.Pawn;
|
|
||||||
import chess.model.rules.PiecePathChecker;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Chess board entity, composed of cells.
|
|
||||||
*/
|
|
||||||
public class ChessBoard {
|
|
||||||
/**
|
|
||||||
* Cell of the chess board.
|
|
||||||
*/
|
|
||||||
public static class Cell {
|
|
||||||
private Piece piece;
|
|
||||||
|
|
||||||
public Cell() {
|
|
||||||
this.piece = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Piece getPiece() {
|
|
||||||
return piece;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPiece(Piece piece) {
|
|
||||||
this.piece = piece;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private final Cell[][] cells;
|
|
||||||
private Move lastVirtualMove;
|
|
||||||
private Move lastMove;
|
|
||||||
private Piece lastEjectedPiece;
|
|
||||||
|
|
||||||
private List<Move> cachedAllowedMoves = null;
|
|
||||||
|
|
||||||
private final Coordinate kingPos[];
|
|
||||||
|
|
||||||
public ChessBoard() {
|
|
||||||
this.cells = new Cell[Coordinate.VALUE_MAX][Coordinate.VALUE_MAX];
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
this.cells[i][j] = new Cell();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.lastVirtualMove = null;
|
|
||||||
this.lastMove = null;
|
|
||||||
this.lastEjectedPiece = null;
|
|
||||||
this.kingPos = new Coordinate[Color.values().length];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply a move on the board.
|
|
||||||
* @param move move to apply
|
|
||||||
*/
|
|
||||||
public void applyMove(Move move) {
|
|
||||||
assert move.isValid() : "Invalid move !";
|
|
||||||
Piece deadPiece = pieceAt(move.getDeadPieceCoords());
|
|
||||||
if (deadPiece != null) {
|
|
||||||
this.lastEjectedPiece = deadPiece;
|
|
||||||
} else {
|
|
||||||
this.lastEjectedPiece = null;
|
|
||||||
}
|
|
||||||
Piece movingPiece = pieceAt(move.getStart());
|
|
||||||
pieceLeaves(move.getDeadPieceCoords());
|
|
||||||
pieceLeaves(move.getStart());
|
|
||||||
pieceComes(movingPiece, move.getFinish());
|
|
||||||
movingPiece.move();
|
|
||||||
this.lastVirtualMove = move;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Undo the last move
|
|
||||||
*/
|
|
||||||
public void undoLastMove() {
|
|
||||||
assert this.lastVirtualMove != null : "Can't undo at the beginning!";
|
|
||||||
|
|
||||||
undoMove(this.lastVirtualMove, this.lastEjectedPiece);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Undo the specified move
|
|
||||||
* @param move
|
|
||||||
* @param deadPiece
|
|
||||||
*/
|
|
||||||
public void undoMove(Move move, Piece deadPiece) {
|
|
||||||
Piece movingPiece = pieceAt(move.getFinish());
|
|
||||||
pieceComes(movingPiece, move.getStart());
|
|
||||||
pieceLeaves(move.getFinish());
|
|
||||||
pieceComes(deadPiece, move.getDeadPieceCoords());
|
|
||||||
assert movingPiece != null;
|
|
||||||
movingPiece.unMove();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the cell is empty
|
|
||||||
* @param coordinate
|
|
||||||
* @return true if the cell is empty
|
|
||||||
*/
|
|
||||||
public boolean isCellEmpty(Coordinate coordinate) {
|
|
||||||
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) {
|
|
||||||
if (!coordinate.isValid())
|
|
||||||
return null;
|
|
||||||
return cellAt(coordinate).getPiece();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Nuke all pieces of the board
|
|
||||||
*/
|
|
||||||
public void clearBoard() {
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
pieceLeaves(new Coordinate(i, j));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the cell at the given coordinates
|
|
||||||
* @param coordinate
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
private Cell cellAt(Coordinate coordinate) {
|
|
||||||
return this.cells[coordinate.getX()][coordinate.getY()];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Set the piece at the given coordinate
|
|
||||||
*/
|
|
||||||
public void pieceComes(Piece piece, Coordinate coordinate) {
|
|
||||||
cellAt(coordinate).setPiece(piece);
|
|
||||||
if (piece instanceof King)
|
|
||||||
this.kingPos[piece.getColor().ordinal()] = coordinate;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove the piece at the given coordiinates
|
|
||||||
* @param coordinate
|
|
||||||
*/
|
|
||||||
public void pieceLeaves(Coordinate coordinate) {
|
|
||||||
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) {
|
|
||||||
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) {
|
|
||||||
List<Coordinate> starts = new ArrayList<>();
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Coordinate attackCoords = new Coordinate(i, j);
|
|
||||||
Piece attackPiece = pieceAt(attackCoords);
|
|
||||||
if (attackPiece == null || attackPiece.getColor() != color)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
Move move = new Move(attackCoords, finish);
|
|
||||||
PiecePathChecker piecePathChecker = new PiecePathChecker(this,
|
|
||||||
move);
|
|
||||||
if (!piecePathChecker.isValid())
|
|
||||||
continue;
|
|
||||||
|
|
||||||
applyMove(move);
|
|
||||||
if (!isKingInCheck(color))
|
|
||||||
starts.add(attackCoords);
|
|
||||||
undoLastMove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
Coordinate kingPos = findKing(color);
|
|
||||||
assert kingPos.isValid() : "King position is invalid!";
|
|
||||||
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Coordinate attackCoords = new Coordinate(i, j);
|
|
||||||
Piece attackPiece = pieceAt(attackCoords);
|
|
||||||
if (attackPiece == null || attackPiece.getColor() == color)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
PiecePathChecker checker = new PiecePathChecker(this, new Move(attackCoords, kingPos));
|
|
||||||
if (checker.isValid())
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the given player has allowed moves
|
|
||||||
* @param player
|
|
||||||
* @return true if the player can move
|
|
||||||
*/
|
|
||||||
public boolean hasAllowedMoves(Color player) {
|
|
||||||
return !getAllowedMoves(player).isEmpty();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the allowed moves for the given player
|
|
||||||
* @param player
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public List<Move> getAllowedMoves(Color player) {
|
|
||||||
if (this.cachedAllowedMoves != null) {
|
|
||||||
return this.cachedAllowedMoves;
|
|
||||||
}
|
|
||||||
|
|
||||||
List<Move> result = new ArrayList<>();
|
|
||||||
|
|
||||||
for (int x = 0; x < Coordinate.VALUE_MAX; x++) {
|
|
||||||
for (int y = 0; y < Coordinate.VALUE_MAX; y++) {
|
|
||||||
|
|
||||||
Coordinate start = new Coordinate(x, y);
|
|
||||||
|
|
||||||
Piece piece = pieceAt(start);
|
|
||||||
if (piece == null || piece.getColor() != player)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Coordinate destination = new Coordinate(i, j);
|
|
||||||
Move move = new Move(start, destination);
|
|
||||||
|
|
||||||
Piece destPiece = pieceAt(destination);
|
|
||||||
|
|
||||||
if (destPiece != null && destPiece.getColor() == player)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
PiecePathChecker piecePathChecker = new PiecePathChecker(this,
|
|
||||||
move);
|
|
||||||
if (!piecePathChecker.isValid())
|
|
||||||
continue;
|
|
||||||
|
|
||||||
applyMove(move);
|
|
||||||
if (!isKingInCheck(player))
|
|
||||||
result.add(move);
|
|
||||||
undoLastMove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.cachedAllowedMoves = result;
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all the end positions possible of a piece
|
|
||||||
*/
|
|
||||||
public List<Coordinate> getPieceAllowedMoves(Coordinate pieceCoords) {
|
|
||||||
Piece piece = pieceAt(pieceCoords);
|
|
||||||
if (piece == null)
|
|
||||||
return null;
|
|
||||||
|
|
||||||
Color player = piece.getColor();
|
|
||||||
|
|
||||||
List<Coordinate> result = new ArrayList<>();
|
|
||||||
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Coordinate destination = new Coordinate(i, j);
|
|
||||||
Move move = new Move(pieceCoords, destination);
|
|
||||||
|
|
||||||
PiecePathChecker piecePathChecker = new PiecePathChecker(this,
|
|
||||||
move);
|
|
||||||
if (!piecePathChecker.isValid())
|
|
||||||
continue;
|
|
||||||
|
|
||||||
applyMove(move);
|
|
||||||
if (!isKingInCheck(player))
|
|
||||||
result.add(destination);
|
|
||||||
undoLastMove();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
if (isKingInCheck(color))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
int colorLine = color == Color.White ? 7 : 0;
|
|
||||||
|
|
||||||
Coordinate kingCoords = new Coordinate(4, colorLine);
|
|
||||||
Coordinate rookCoords = new Coordinate(rookX, colorLine);
|
|
||||||
Piece king = pieceAt(kingCoords);
|
|
||||||
Piece rook = pieceAt(rookCoords);
|
|
||||||
|
|
||||||
if (king == null || rook == null || king.hasMoved() || rook.hasMoved())
|
|
||||||
return false;
|
|
||||||
|
|
||||||
for (int step = 1; step <= 2; step++) {
|
|
||||||
Coordinate dest = Coordinate.fromIndex(kingCoords.toIndex() + step * kingDirection.getIndexOffset());
|
|
||||||
Piece obstacle = pieceAt(dest);
|
|
||||||
if (obstacle != null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
applyMove(new Move(kingCoords, dest));
|
|
||||||
if (isKingInCheck(color)) {
|
|
||||||
undoLastMove();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
undoLastMove();
|
|
||||||
}
|
|
||||||
|
|
||||||
Coordinate rookObstacleCoords = Coordinate.fromIndex(rookCoords.toIndex() - kingDirection.getIndexOffset());
|
|
||||||
Piece obstacle = pieceAt(rookObstacleCoords);
|
|
||||||
|
|
||||||
return obstacle == null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return wether the player can perform a kingside castling.
|
|
||||||
*/
|
|
||||||
public boolean canSmallCastle(Color color) {
|
|
||||||
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) {
|
|
||||||
return canCastle(color, 0, Direction.Left);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if there is a pawn to be promoted by the given player.
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
public boolean pawnShouldBePromoted() {
|
|
||||||
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
|
|
||||||
*/
|
|
||||||
public Coordinate pawnPromotePosition() {
|
|
||||||
Coordinate piecePos = pawnPromotePosition(Color.White);
|
|
||||||
if (piecePos != null)
|
|
||||||
return piecePos;
|
|
||||||
return pawnPromotePosition(Color.Black);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
*/
|
|
||||||
private Coordinate pawnPromotePosition(Color color) {
|
|
||||||
int enemyLineY = color == Color.White ? 0 : 7;
|
|
||||||
|
|
||||||
for (int x = 0; x < Coordinate.VALUE_MAX; x++) {
|
|
||||||
Coordinate pieceCoords = new Coordinate(x, enemyLineY);
|
|
||||||
Piece piece = pieceAt(pieceCoords);
|
|
||||||
|
|
||||||
if (piece instanceof Pawn)
|
|
||||||
return pieceCoords;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Hash according to the pieces position on the board
|
|
||||||
* @return hash code
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
int result = 0;
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Piece piece = pieceAt(new Coordinate(i, j));
|
|
||||||
if (piece == null)
|
|
||||||
continue;
|
|
||||||
result = Objects.hash(result, piece.getColor(), new Coordinate(i, j), piece);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return the last played move
|
|
||||||
*/
|
|
||||||
public Move getLastMove() {
|
|
||||||
return this.lastMove;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Updates the last move of the board and invalidate the allowedMoves cache.
|
|
||||||
*/
|
|
||||||
public void setLastMove(Move lastMove) {
|
|
||||||
this.lastMove = lastMove;
|
|
||||||
this.cachedAllowedMoves = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (obj instanceof ChessBoard board)
|
|
||||||
return board.hashCode() == this.hashCode();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
package chess.model;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enumeration of colors for player - either black or white
|
|
||||||
*/
|
|
||||||
public enum Color {
|
|
||||||
White,
|
|
||||||
Black;
|
|
||||||
|
|
||||||
public static Color getEnemy(Color color) {
|
|
||||||
return color == White ? Black : White;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
package chess.model;
|
|
||||||
|
|
||||||
import java.util.Objects;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Coordinate of a cell on the chess board.
|
|
||||||
*/
|
|
||||||
public class Coordinate {
|
|
||||||
private final int x;
|
|
||||||
private final int y;
|
|
||||||
|
|
||||||
public static int VALUE_MAX = 8;
|
|
||||||
|
|
||||||
public Coordinate(int x, int y) {
|
|
||||||
this.x = x;
|
|
||||||
this.y = y;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getX() {
|
|
||||||
return x;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getY() {
|
|
||||||
return y;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isValid() {
|
|
||||||
return 0 <= this.x && this.x < VALUE_MAX && 0 <= this.y && this.y < VALUE_MAX;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Coordinate fromIndex(int index) {
|
|
||||||
return new Coordinate(index % VALUE_MAX, index / VALUE_MAX);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int toIndex() {
|
|
||||||
return this.y * VALUE_MAX + this.x;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (obj instanceof Coordinate coo) {
|
|
||||||
return this.x == coo.x && this.y == coo.y;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String toString() {
|
|
||||||
return "(" + this.x + ", " + this.y + ")";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
return Objects.hash(this.x, this.y);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
22
app/src/main/java/chess/model/Coordinates.java
Normal file
22
app/src/main/java/chess/model/Coordinates.java
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package chess.model;
|
||||||
|
|
||||||
|
public class Coordinates {
|
||||||
|
private int x;
|
||||||
|
private int y;
|
||||||
|
|
||||||
|
public Coordinates(int x, int y) {
|
||||||
|
this.x = x;
|
||||||
|
this.y = y;
|
||||||
|
}
|
||||||
|
public int getX() {
|
||||||
|
return this.x;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getY() {
|
||||||
|
return this.y;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString() {
|
||||||
|
return "(" + this.x + ", " + this.y + ")";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
package chess.model;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Enumation of the different directions from a cell in a chessboard, and how to navigate the cells.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public enum Direction {
|
|
||||||
|
|
||||||
Unset(65),
|
|
||||||
Front(-8), Back(8), Left(-1), Right(1),
|
|
||||||
FrontLeft(-9), FrontRight(-7), BackLeft(7), BackRight(9);
|
|
||||||
|
|
||||||
private final int indexOffset;
|
|
||||||
|
|
||||||
Direction(int indexOffset) {
|
|
||||||
this.indexOffset = indexOffset;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIndexOffset() {
|
|
||||||
return indexOffset;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Direction fromInt(int direction) {
|
|
||||||
for (Direction dir : Direction.values()) {
|
|
||||||
if (dir.getIndexOffset() == direction)
|
|
||||||
return dir;
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static Direction findDirection(Move move) {
|
|
||||||
assert move.isValid() : "Move is invalid!";
|
|
||||||
int diffX = move.getFinish().getX() - move.getStart().getX();
|
|
||||||
int diffY = move.getFinish().getY() - move.getStart().getY();
|
|
||||||
|
|
||||||
if (diffX == 0 && diffY < 0)
|
|
||||||
return Direction.Front;
|
|
||||||
if (diffX == 0 && diffY > 0)
|
|
||||||
return Direction.Back;
|
|
||||||
|
|
||||||
if (diffX < 0 && diffY == 0)
|
|
||||||
return Direction.Left;
|
|
||||||
if (diffX > 0 && diffY == 0)
|
|
||||||
return Direction.Right;
|
|
||||||
|
|
||||||
if (diffX < 0 && -diffX == diffY)
|
|
||||||
return Direction.BackLeft;
|
|
||||||
if (diffX > 0 && diffX == diffY)
|
|
||||||
return Direction.BackRight;
|
|
||||||
|
|
||||||
if (diffY < 0 && diffX == diffY)
|
|
||||||
return Direction.FrontLeft;
|
|
||||||
if (diffX > 0 && diffX == -diffY)
|
|
||||||
return Direction.FrontRight;
|
|
||||||
|
|
||||||
return Direction.Unset;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,158 +1,87 @@
|
|||||||
package chess.model;
|
package chess.model;
|
||||||
|
|
||||||
import java.util.HashMap;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.Observable;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Stack;
|
|
||||||
|
|
||||||
import chess.controller.PlayerCommand;
|
public class Game extends Observable implements Runnable {
|
||||||
import chess.controller.commands.MoveCommand;
|
private final Board board;
|
||||||
|
private Move move;
|
||||||
|
private final ArrayList<Player> players = new ArrayList<>();
|
||||||
|
|
||||||
/**
|
public Game(int size) {
|
||||||
* Game class that represents a chess game.
|
this.board = new Board(size);
|
||||||
*/
|
this.setChanged();
|
||||||
|
this.notifyObservers();
|
||||||
|
}
|
||||||
|
public Game() {
|
||||||
|
this(8);
|
||||||
|
}
|
||||||
|
|
||||||
public class Game {
|
public int getSize(){
|
||||||
private final ChessBoard board;
|
return board.getSize();
|
||||||
private Color playerTurn;
|
}
|
||||||
private final Stack<PlayerCommand> movesHistory;
|
public Board getBoard() {
|
||||||
private final Map<Integer, Integer> traitsPos;
|
return board;
|
||||||
|
}
|
||||||
|
public Move getMove() {
|
||||||
|
return move;
|
||||||
|
}
|
||||||
|
|
||||||
private static final int DRAW_REPETITONS = 3;
|
public void setMove(Move m){
|
||||||
|
this.move = m;
|
||||||
|
synchronized (this) {
|
||||||
|
this.notify();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public enum GameStatus {
|
public boolean gameDone(){
|
||||||
Draw, Check, CheckMate, OnGoing, Pat;
|
// todo
|
||||||
}
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
public Game() {
|
public Player getNextPlayer(){
|
||||||
this.board = new ChessBoard();
|
return players.getFirst();
|
||||||
this.movesHistory = new Stack<>();
|
}
|
||||||
this.traitsPos = new HashMap<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
public ChessBoard getBoard() {
|
public void updatePlayersList(){
|
||||||
return board;
|
Player player = players.getFirst();
|
||||||
}
|
players.remove(player);
|
||||||
|
players.add(player);
|
||||||
|
}
|
||||||
|
|
||||||
public Color getPlayerTurn() {
|
public void playGame() {
|
||||||
return playerTurn;
|
players.add(new Player(this));
|
||||||
}
|
players.add(new Player(this));
|
||||||
|
while (!gameDone()){
|
||||||
|
Move m = getNextPlayer().getMove();
|
||||||
|
while (!applyMove(m)){
|
||||||
|
m = getNextPlayer().getMove();
|
||||||
|
}
|
||||||
|
updatePlayersList();
|
||||||
|
setChanged();
|
||||||
|
notifyObservers();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
@Override
|
||||||
* Reset the game
|
public void run(){
|
||||||
*/
|
playGame();
|
||||||
public void reset() {
|
}
|
||||||
resetPlayerTurn();
|
|
||||||
this.traitsPos.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
public boolean applyMove(Move m){
|
||||||
* Reset the player turn.
|
if (board.getCell(m.getStart()).getPiece() == null){
|
||||||
* Aka: white for the win
|
return false;
|
||||||
*/
|
}
|
||||||
public void resetPlayerTurn() {
|
try {
|
||||||
this.playerTurn = Color.White;
|
move(m);
|
||||||
}
|
}
|
||||||
|
catch (Exception e) {
|
||||||
/**
|
return false;
|
||||||
* Save the current board configuration
|
}
|
||||||
*/
|
return true;
|
||||||
public void saveTraitPiecesPos() {
|
}
|
||||||
int piecesHash = this.board.hashCode();
|
|
||||||
Integer count = this.traitsPos.get(piecesHash);
|
|
||||||
this.traitsPos.put(piecesHash, count == null ? 1 : count + 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return whether the game is in a draw situation
|
|
||||||
*/
|
|
||||||
private boolean checkDraw() {
|
|
||||||
return this.traitsPos.containsValue(DRAW_REPETITONS);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Switch player turn
|
|
||||||
*/
|
|
||||||
public void switchPlayerTurn() {
|
|
||||||
playerTurn = Color.getEnemy(playerTurn);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check the status of the game ofr the specified player
|
|
||||||
* @return a GameStatus enum
|
|
||||||
*/
|
|
||||||
public GameStatus checkGameStatus(Color color) {
|
|
||||||
if (checkDraw())
|
|
||||||
return GameStatus.Draw;
|
|
||||||
|
|
||||||
if (this.board.isKingInCheck(color))
|
|
||||||
if (this.board.hasAllowedMoves(color))
|
|
||||||
return GameStatus.Check;
|
|
||||||
else
|
|
||||||
return GameStatus.CheckMate;
|
|
||||||
|
|
||||||
if (!board.hasAllowedMoves(color))
|
|
||||||
return GameStatus.Pat;
|
|
||||||
|
|
||||||
return GameStatus.OnGoing;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check the status of the gamere
|
|
||||||
*/
|
|
||||||
public GameStatus checkGameStatus() {
|
|
||||||
return checkGameStatus(Color.getEnemy(getPlayerTurn()));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a player move (basic move, castling, ...) to the game history.
|
|
||||||
*/
|
|
||||||
public void addAction(PlayerCommand command) {
|
|
||||||
this.movesHistory.add(command);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return the last player action
|
|
||||||
*/
|
|
||||||
public PlayerCommand getLastAction() {
|
|
||||||
if (this.movesHistory.isEmpty())
|
|
||||||
return null;
|
|
||||||
return this.movesHistory.pop();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update the last board move ater an undo.
|
|
||||||
*/
|
|
||||||
public void updateLastMove() {
|
|
||||||
if (this.movesHistory.isEmpty())
|
|
||||||
return;
|
|
||||||
|
|
||||||
PlayerCommand last = this.movesHistory.getLast();
|
|
||||||
if (last instanceof MoveCommand move) {
|
|
||||||
this.board.setLastMove(move.getMove());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove the board configuration occurence from the game history
|
|
||||||
*/
|
|
||||||
public void undoTraitPiecesPos() {
|
|
||||||
int piecesHash = this.board.hashCode();
|
|
||||||
Integer count = this.traitsPos.get(piecesHash);
|
|
||||||
if (count != null)
|
|
||||||
this.traitsPos.put(piecesHash, count - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<PlayerCommand> getMoves() {
|
|
||||||
return this.movesHistory;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return wether a pawn should be promoted
|
|
||||||
*/
|
|
||||||
public boolean pawnShouldBePromoted() {
|
|
||||||
return this.board.pawnShouldBePromoted();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
public void move(Move move) throws Exception{
|
||||||
|
board.movePiece(move);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
package chess.model;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Game where the most ressource-consuming functions are empty.
|
|
||||||
* Mostly used by bots.
|
|
||||||
* @see GameSimulation
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class LightGame extends Game {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public GameStatus checkGameStatus(Color color) {
|
|
||||||
return GameStatus.OnGoing;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void undoTraitPiecesPos() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void saveTraitPiecesPos() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
15
app/src/main/java/chess/model/Model2D.java
Normal file
15
app/src/main/java/chess/model/Model2D.java
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package chess.model;
|
||||||
|
|
||||||
|
import java.util.Observable;
|
||||||
|
|
||||||
|
public class Model2D extends Observable {
|
||||||
|
public int x;
|
||||||
|
public int y;
|
||||||
|
|
||||||
|
public void set(int i, int j){
|
||||||
|
this.x = i;
|
||||||
|
this.y = j;
|
||||||
|
setChanged();
|
||||||
|
notifyObservers();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,78 +1,26 @@
|
|||||||
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 Coordinates start;
|
||||||
private final Coordinate finish;
|
private Coordinates end;
|
||||||
private Coordinate deadPieceCoords;
|
|
||||||
|
|
||||||
public Move(Coordinate start, Coordinate finish) {
|
public Move(Coordinates start, Coordinates end) {
|
||||||
this.start = start;
|
this.start = start;
|
||||||
this.finish = finish;
|
this.end = end;
|
||||||
this.deadPieceCoords = finish;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
public Coordinates getEnd() {
|
||||||
*
|
return end;
|
||||||
* @return true if the move is valid, false otherwise
|
}
|
||||||
*/
|
|
||||||
public boolean isValid() {
|
|
||||||
return this.start.isValid() && this.finish.isValid() && !this.start.equals(this.finish);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Coordinate getStart() {
|
public Coordinates getStart() {
|
||||||
return start;
|
return start;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Coordinate getFinish() {
|
public void updateMove(Coordinates start, Coordinates end) {
|
||||||
return finish;
|
this.start = start;
|
||||||
}
|
this.end = end;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns the number of cells traversed by the move.
|
|
||||||
* @return int
|
|
||||||
*/
|
|
||||||
public int traversedCells() {
|
|
||||||
assert isValid() : "Move is invalid!";
|
|
||||||
|
|
||||||
int diffX = getFinish().getX() - getStart().getX();
|
|
||||||
int diffY = getFinish().getY() - getStart().getY();
|
|
||||||
|
|
||||||
assert Math.abs(diffX) < Coordinate.VALUE_MAX : "Move is too big!";
|
|
||||||
assert Math.abs(diffY) < Coordinate.VALUE_MAX : "Move is too big!";
|
|
||||||
|
|
||||||
if (diffX == 0)
|
|
||||||
return Math.abs(diffY);
|
|
||||||
if (diffY == 0)
|
|
||||||
return Math.abs(diffX);
|
|
||||||
if (Math.abs(diffX) == Math.abs(diffY))
|
|
||||||
return Math.abs(diffX);
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @return the coordinates of the cell in the middle of the move
|
|
||||||
*/
|
|
||||||
public Coordinate getMiddle() {
|
|
||||||
return Coordinate.fromIndex((getStart().toIndex() + getFinish().toIndex()) / 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setDeadPieceCoords(Coordinate deadCoords) {
|
|
||||||
this.deadPieceCoords = deadCoords;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Coordinate getDeadPieceCoords() {
|
|
||||||
return deadPieceCoords;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (obj instanceof Move other)
|
|
||||||
return this.start.equals(other.start) && this.finish.equals(other.finish);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,35 +1,27 @@
|
|||||||
package chess.model;
|
package chess.model;
|
||||||
|
|
||||||
/**
|
import chess.view.render2D.Pieces;
|
||||||
* Piece of a game. Posesses a color and the number of time it has been moved.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public abstract class Piece {
|
public abstract class Piece {
|
||||||
|
public final int color;
|
||||||
|
public AccessibleCellsDecorator decorator;
|
||||||
|
public final Board board;
|
||||||
|
public Cell position;
|
||||||
|
|
||||||
private final Color color;
|
public Piece(int color, Board board, Cell position) {
|
||||||
private int moved;
|
this.color = color;
|
||||||
|
this.board = board;
|
||||||
|
this.position = position;
|
||||||
|
}
|
||||||
|
|
||||||
public Piece(Color color) {
|
public int getColor() {
|
||||||
this.color = color;
|
return color;
|
||||||
this.moved = 0;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public void move() {
|
public void setPosition(Cell cell) {
|
||||||
this.moved++;
|
this.position = cell;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Color getColor() {
|
public abstract void accept(PieceVisitor pv);
|
||||||
return color;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean hasMoved() {
|
|
||||||
return moved > 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void unMove() {
|
|
||||||
this.moved--;
|
|
||||||
}
|
|
||||||
|
|
||||||
public abstract <T> T accept(PieceVisitor<T> visitor);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,32 +1,17 @@
|
|||||||
package chess.model;
|
package chess.model;
|
||||||
|
|
||||||
import chess.model.pieces.Bishop;
|
import chess.model.pieces.*;
|
||||||
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;
|
|
||||||
|
|
||||||
/**
|
public interface PieceVisitor{
|
||||||
* Visitor interface for pieces.
|
default void visit(Piece p) {
|
||||||
*/
|
p.accept(this);
|
||||||
|
}
|
||||||
|
|
||||||
public interface PieceVisitor<T> {
|
void visitPiece(Bishop p);
|
||||||
|
void visitPiece(Knight p);
|
||||||
default T visit(Piece piece) {
|
void visitPiece(Pawn p);
|
||||||
return piece.accept(this);
|
void visitPiece(Queen p);
|
||||||
}
|
void visitPiece(King p);
|
||||||
|
void visitPiece(Rook p);
|
||||||
T visitPiece(Bishop bishop);
|
|
||||||
|
|
||||||
T visitPiece(King king);
|
|
||||||
|
|
||||||
T visitPiece(Knight knight);
|
|
||||||
|
|
||||||
T visitPiece(Pawn pawn);
|
|
||||||
|
|
||||||
T visitPiece(Queen queen);
|
|
||||||
|
|
||||||
T visitPiece(Rook rook);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
21
app/src/main/java/chess/model/Player.java
Normal file
21
app/src/main/java/chess/model/Player.java
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
package chess.model;
|
||||||
|
|
||||||
|
public class Player {
|
||||||
|
private final Game game;
|
||||||
|
|
||||||
|
public Player(Game game) {
|
||||||
|
this.game = game;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Move getMove(){
|
||||||
|
synchronized(game){
|
||||||
|
try {
|
||||||
|
game.wait();
|
||||||
|
}
|
||||||
|
catch (Exception e) {
|
||||||
|
System.out.println(e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return game.getMove();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package chess.model.decorators;
|
||||||
|
|
||||||
|
import chess.model.AccessibleCellsDecorator;
|
||||||
|
import chess.model.Cell;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
public class DiagonalDecorator extends AccessibleCellsDecorator {
|
||||||
|
public DiagonalDecorator(AccessibleCellsDecorator base) {
|
||||||
|
super(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DiagonalDecorator(){
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected ArrayList<Cell> getAccessibleCells() {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
22
app/src/main/java/chess/model/decorators/LineDecorator.java
Normal file
22
app/src/main/java/chess/model/decorators/LineDecorator.java
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package chess.model.decorators;
|
||||||
|
|
||||||
|
import chess.model.AccessibleCellsDecorator;
|
||||||
|
import chess.model.Cell;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
public class LineDecorator extends AccessibleCellsDecorator {
|
||||||
|
public LineDecorator(AccessibleCellsDecorator base) {
|
||||||
|
super(base);
|
||||||
|
}
|
||||||
|
|
||||||
|
public LineDecorator(){
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected ArrayList<Cell> getAccessibleCells() {
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,17 @@
|
|||||||
package chess.model.pieces;
|
package chess.model.pieces;
|
||||||
|
|
||||||
import chess.model.Color;
|
import chess.model.Board;
|
||||||
|
import chess.model.Cell;
|
||||||
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(final int color, Board board, Cell cell) {
|
||||||
|
super(color, board, cell);
|
||||||
|
}
|
||||||
|
|
||||||
public Bishop(Color color) {
|
@Override
|
||||||
super(color);
|
public void accept(PieceVisitor pv) {
|
||||||
}
|
pv.visitPiece(this);
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public <T> T accept(PieceVisitor<T> visitor) {
|
|
||||||
return visitor.visitPiece(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,17 @@
|
|||||||
package chess.model.pieces;
|
package chess.model.pieces;
|
||||||
|
|
||||||
import chess.model.Color;
|
import chess.model.Board;
|
||||||
|
import chess.model.Cell;
|
||||||
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(final int color, Board board, Cell cell) {
|
||||||
|
super(color, board, cell);
|
||||||
|
}
|
||||||
|
|
||||||
public King(Color color) {
|
@Override
|
||||||
super(color);
|
public void accept(PieceVisitor pv) {
|
||||||
}
|
pv.visitPiece(this);
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public <T> T accept(PieceVisitor<T> visitor) {
|
|
||||||
return visitor.visitPiece(this);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,17 @@
|
|||||||
package chess.model.pieces;
|
package chess.model.pieces;
|
||||||
|
|
||||||
import chess.model.Color;
|
import chess.model.Board;
|
||||||
|
import chess.model.Cell;
|
||||||
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(final int color, Board board, Cell cell) {
|
||||||
|
super(color, board, cell);
|
||||||
|
}
|
||||||
|
|
||||||
public Knight(Color color) {
|
@Override
|
||||||
super(color);
|
public void accept(PieceVisitor pv) {
|
||||||
}
|
pv.visitPiece(this);
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public <T> T accept(PieceVisitor<T> visitor) {
|
|
||||||
return visitor.visitPiece(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,17 @@
|
|||||||
package chess.model.pieces;
|
package chess.model.pieces;
|
||||||
|
|
||||||
import chess.model.Color;
|
import chess.model.Board;
|
||||||
|
import chess.model.Cell;
|
||||||
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(final int color, Board board, Cell cell) {
|
||||||
|
super(color, board, cell);
|
||||||
|
}
|
||||||
|
|
||||||
public Pawn(Color color) {
|
@Override
|
||||||
super(color);
|
public void accept(PieceVisitor pv) {
|
||||||
}
|
pv.visitPiece(this);
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public <T> T accept(PieceVisitor<T> visitor) {
|
|
||||||
return visitor.visitPiece(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
public int multiplier() {
|
|
||||||
return getColor() == Color.White ? 1 : -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,16 @@
|
|||||||
package chess.model.pieces;
|
package chess.model.pieces;
|
||||||
|
|
||||||
import chess.model.Color;
|
import chess.model.*;
|
||||||
import chess.model.Piece;
|
import chess.model.decorators.DiagonalDecorator;
|
||||||
import chess.model.PieceVisitor;
|
import chess.model.decorators.LineDecorator;
|
||||||
|
|
||||||
/**
|
|
||||||
* Queen piece.
|
|
||||||
*/
|
|
||||||
public class Queen extends Piece {
|
public class Queen extends Piece {
|
||||||
|
public Queen(final int color, Board board, Cell cell) {
|
||||||
|
super(color, board, cell);
|
||||||
|
}
|
||||||
|
|
||||||
public Queen(Color color) {
|
@Override
|
||||||
super(color);
|
public void accept(PieceVisitor pv) {
|
||||||
}
|
pv.visitPiece(this);
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public <T> T accept(PieceVisitor<T> visitor) {
|
|
||||||
return visitor.visitPiece(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
package chess.model.pieces;
|
package chess.model.pieces;
|
||||||
|
|
||||||
import chess.model.Color;
|
import chess.model.Board;
|
||||||
|
import chess.model.Cell;
|
||||||
import chess.model.Piece;
|
import chess.model.Piece;
|
||||||
import chess.model.PieceVisitor;
|
import chess.model.PieceVisitor;
|
||||||
|
import chess.model.decorators.DiagonalDecorator;
|
||||||
|
import chess.model.decorators.LineDecorator;
|
||||||
|
|
||||||
/**
|
|
||||||
* Rook piece.
|
|
||||||
*/
|
|
||||||
public class Rook extends Piece {
|
public class Rook extends Piece {
|
||||||
|
public Rook(final int color, Board board, Cell cell) {
|
||||||
|
super(color, board, cell);
|
||||||
|
this.decorator = new LineDecorator();
|
||||||
|
// todo
|
||||||
|
}
|
||||||
|
|
||||||
public Rook(Color color) {
|
@Override
|
||||||
super(color);
|
public void accept(PieceVisitor pv) {
|
||||||
}
|
pv.visitPiece(this);
|
||||||
|
}
|
||||||
@Override
|
|
||||||
public <T> T accept(PieceVisitor<T> visitor) {
|
|
||||||
return visitor.visitPiece(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,123 +0,0 @@
|
|||||||
package chess.model.rules;
|
|
||||||
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Direction;
|
|
||||||
import chess.model.Move;
|
|
||||||
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;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if a move can be done.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PermissiveRuleChecker implements PieceVisitor<Boolean> {
|
|
||||||
|
|
||||||
private final Move move;
|
|
||||||
|
|
||||||
public PermissiveRuleChecker(Move move) {
|
|
||||||
this.move = move;
|
|
||||||
assert move.isValid() : "Move is invalid!";
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isValidFor(Piece piece) {
|
|
||||||
return visit(piece);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Bishop bishop) {
|
|
||||||
Direction moveDirection = Direction.findDirection(this.move);
|
|
||||||
|
|
||||||
switch (moveDirection) {
|
|
||||||
case FrontLeft:
|
|
||||||
case BackLeft:
|
|
||||||
case FrontRight:
|
|
||||||
case BackRight:
|
|
||||||
return true;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(King king) {
|
|
||||||
return this.move.traversedCells() == 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Knight knight) {
|
|
||||||
Coordinate piecePos = move.getStart();
|
|
||||||
final Coordinate[] positions = {
|
|
||||||
new Coordinate(piecePos.getX() - 1, piecePos.getY() - 2),
|
|
||||||
new Coordinate(piecePos.getX() - 1, piecePos.getY() + 2),
|
|
||||||
new Coordinate(piecePos.getX() + 1, piecePos.getY() - 2),
|
|
||||||
new Coordinate(piecePos.getX() + 1, piecePos.getY() + 2),
|
|
||||||
new Coordinate(piecePos.getX() + 2, piecePos.getY() - 1),
|
|
||||||
new Coordinate(piecePos.getX() + 2, piecePos.getY() + 1),
|
|
||||||
new Coordinate(piecePos.getX() - 2, piecePos.getY() - 1),
|
|
||||||
new Coordinate(piecePos.getX() - 2, piecePos.getY() + 1),
|
|
||||||
};
|
|
||||||
|
|
||||||
for (int i = 0; i < positions.length; i++) {
|
|
||||||
if (this.move.getFinish().equals(positions[i]))
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Pawn pawn) {
|
|
||||||
Direction moveDirection = Direction.findDirection(this.move);
|
|
||||||
int directionIndexOffset = moveDirection.getIndexOffset();
|
|
||||||
int distance = this.move.traversedCells();
|
|
||||||
|
|
||||||
// Revoke moving backwards
|
|
||||||
if (directionIndexOffset * pawn.multiplier() > 0)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
// Allowing straight moves
|
|
||||||
if (Math.abs(directionIndexOffset) == Math.abs(Direction.Front.getIndexOffset())) {
|
|
||||||
if (pawn.hasMoved())
|
|
||||||
return distance == 1;
|
|
||||||
return distance == 1 || distance == 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allowing small diagonal moves
|
|
||||||
if (directionIndexOffset * pawn.multiplier() == Direction.FrontLeft.getIndexOffset()
|
|
||||||
|| directionIndexOffset * pawn.multiplier() == Direction.FrontRight.getIndexOffset()) {
|
|
||||||
return distance == 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Queen queen) {
|
|
||||||
Direction moveDirection = Direction.findDirection(this.move);
|
|
||||||
return moveDirection != Direction.Unset;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Rook rook) {
|
|
||||||
Direction moveDirection = Direction.findDirection(this.move);
|
|
||||||
|
|
||||||
switch (moveDirection) {
|
|
||||||
case Front:
|
|
||||||
case Back:
|
|
||||||
case Left:
|
|
||||||
case Right:
|
|
||||||
return true;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,155 +0,0 @@
|
|||||||
package chess.model.rules;
|
|
||||||
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Direction;
|
|
||||||
import chess.model.Move;
|
|
||||||
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;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if there are pieces in the path of a move.
|
|
||||||
*/
|
|
||||||
public class PiecePathChecker implements PieceVisitor<Boolean> {
|
|
||||||
|
|
||||||
private final ChessBoard board;
|
|
||||||
private final Move move;
|
|
||||||
|
|
||||||
public PiecePathChecker(ChessBoard board, Move move) {
|
|
||||||
this.move = move;
|
|
||||||
this.board = board;
|
|
||||||
}
|
|
||||||
|
|
||||||
public boolean isValid() {
|
|
||||||
if (this.move.getStart().equals(this.move.getFinish()))
|
|
||||||
return false;
|
|
||||||
Piece piece = this.board.pieceAt(move.getStart());
|
|
||||||
if (piece == null)
|
|
||||||
return false;
|
|
||||||
return visit(piece);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Bishop bishop) {
|
|
||||||
return basicCheck(bishop);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(King king) {
|
|
||||||
return destCheck(king);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Knight knight) {
|
|
||||||
return destCheck(knight);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Queen queen) {
|
|
||||||
return basicCheck(queen);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Rook rook) {
|
|
||||||
return basicCheck(rook);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Boolean visitPiece(Pawn pawn) {
|
|
||||||
if (!new PermissiveRuleChecker(this.move).isValidFor(pawn))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
Direction moveDirection = Direction.fromInt(Direction.findDirection(move).getIndexOffset() * pawn.multiplier());
|
|
||||||
|
|
||||||
if (moveDirection == Direction.Front)
|
|
||||||
return testPath(pawn.getColor()) && this.board.pieceAt(this.move.getFinish()) == null;
|
|
||||||
|
|
||||||
assert moveDirection == Direction.FrontLeft || moveDirection == Direction.FrontRight;
|
|
||||||
|
|
||||||
if (checkEnPassant())
|
|
||||||
return true;
|
|
||||||
|
|
||||||
Piece destPiece = this.board.pieceAt(this.move.getFinish());
|
|
||||||
if (destPiece == null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
return destPiece.getColor() != pawn.getColor();
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean checkEnPassant() {
|
|
||||||
Move lastMove = this.board.getLastMove();
|
|
||||||
|
|
||||||
if (lastMove == null)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
Piece pieceToEat = this.board.pieceAt(lastMove.getFinish());
|
|
||||||
|
|
||||||
if (pieceToEat == null || !(pieceToEat instanceof Pawn))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
Piece pawn = this.board.pieceAt(this.move.getStart());
|
|
||||||
|
|
||||||
if (pieceToEat.getColor() == pawn.getColor())
|
|
||||||
return false;
|
|
||||||
|
|
||||||
Direction lastMoveDir = Direction.findDirection(lastMove);
|
|
||||||
|
|
||||||
if ((lastMoveDir != Direction.Front && lastMoveDir != Direction.Back) || lastMove.traversedCells() != 2)
|
|
||||||
return false;
|
|
||||||
|
|
||||||
Coordinate middle = lastMove.getMiddle();
|
|
||||||
|
|
||||||
if (middle.equals(this.move.getFinish())
|
|
||||||
&& pieceToEat instanceof Pawn) {
|
|
||||||
this.move.setDeadPieceCoords(lastMove.getFinish());
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean destCheck(Piece piece) {
|
|
||||||
if (!new PermissiveRuleChecker(this.move).isValidFor(piece))
|
|
||||||
return false;
|
|
||||||
|
|
||||||
Piece destPiece = board.pieceAt(this.move.getFinish());
|
|
||||||
if (destPiece == null)
|
|
||||||
return true;
|
|
||||||
return destPiece.getColor() != piece.getColor();
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean basicCheck(Piece piece) {
|
|
||||||
if (!new PermissiveRuleChecker(this.move).isValidFor(piece))
|
|
||||||
return false;
|
|
||||||
return testPath(piece.getColor());
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean testPath(Color color) {
|
|
||||||
Direction moveDirection = Direction.findDirection(this.move);
|
|
||||||
int distance = this.move.traversedCells();
|
|
||||||
int stepIndex = move.getStart().toIndex();
|
|
||||||
|
|
||||||
for (int step = 0; step < distance; step++) {
|
|
||||||
stepIndex += moveDirection.getIndexOffset();
|
|
||||||
|
|
||||||
if (Coordinate.fromIndex(stepIndex).equals(move.getFinish())) {
|
|
||||||
Piece pieceDest = this.board.pieceAt(move.getFinish());
|
|
||||||
if (pieceDest == null)
|
|
||||||
return true;
|
|
||||||
return pieceDest.getColor() != color;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!this.board.isCellEmpty(Coordinate.fromIndex(stepIndex)))
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,237 +0,0 @@
|
|||||||
package chess.pgn;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.Command.CommandResult;
|
|
||||||
import chess.controller.commands.CastlingCommand;
|
|
||||||
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.event.EmptyGameDispatcher;
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Move;
|
|
||||||
import chess.model.Piece;
|
|
||||||
import chess.model.pieces.Pawn;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Export a game to PGN format.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PgnExport {
|
|
||||||
|
|
||||||
private static final PiecePgnName piecePgnName = new PiecePgnName();
|
|
||||||
|
|
||||||
private static Piece pieceAt(CommandExecutor commandExecutor, Coordinate coordinate) {
|
|
||||||
GetPieceAtCommand cmd = new GetPieceAtCommand(coordinate);
|
|
||||||
commandExecutor.executeCommand(cmd);
|
|
||||||
return cmd.getPiece();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<Move> playerMoves(CommandExecutor commandExecutor) {
|
|
||||||
GetPlayerMovesCommand cmd = new GetPlayerMovesCommand();
|
|
||||||
commandExecutor.executeCommand(cmd);
|
|
||||||
return cmd.getMoves();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String gameEnd(Game game) {
|
|
||||||
switch (game.checkGameStatus(game.getPlayerTurn())) {
|
|
||||||
case Draw:
|
|
||||||
case Pat:
|
|
||||||
return "1/2-1/2";
|
|
||||||
|
|
||||||
case CheckMate:
|
|
||||||
if (game.getPlayerTurn() == Color.White)
|
|
||||||
return "0-1";
|
|
||||||
return "1-0";
|
|
||||||
|
|
||||||
default:
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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) {
|
|
||||||
Piece movingPiece = pieceAt(cmdExec, pieceMove.getStart());
|
|
||||||
|
|
||||||
assert movingPiece != null;
|
|
||||||
|
|
||||||
if (movingPiece instanceof Pawn)
|
|
||||||
return "";
|
|
||||||
|
|
||||||
List<Move> moves = playerMoves(cmdExec);
|
|
||||||
|
|
||||||
for (Move move : moves) {
|
|
||||||
if (move.equals(pieceMove) || !move.getFinish().equals(pieceMove.getFinish()))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
Piece otherPiece = pieceAt(cmdExec, move.getStart());
|
|
||||||
|
|
||||||
// checking type of piece
|
|
||||||
if (!otherPiece.getClass().equals(movingPiece.getClass()))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
String startPos = toString(pieceMove.getStart());
|
|
||||||
|
|
||||||
if (move.getStart().getX() != pieceMove.getStart().getX())
|
|
||||||
// not on the same column
|
|
||||||
return Character.toString(startPos.charAt(0));
|
|
||||||
else
|
|
||||||
return Character.toString(startPos.charAt(1));
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
|
||||||
String result = "";
|
|
||||||
if (move.getDeadPiece() != null) {
|
|
||||||
if (movingPiece instanceof Pawn) {
|
|
||||||
result += toString(move.getMove().getStart()).charAt(0);
|
|
||||||
}
|
|
||||||
result += "x";
|
|
||||||
}
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String promote(PlayerCommand nextCommand) {
|
|
||||||
if (nextCommand != null && nextCommand instanceof PromoteCommand promoteCommand) {
|
|
||||||
String result = "=";
|
|
||||||
result += switch (promoteCommand.getPromoteType()) {
|
|
||||||
case Bishop -> "B";
|
|
||||||
case Knight -> "N";
|
|
||||||
case Queen -> "Q";
|
|
||||||
case Rook -> "R";
|
|
||||||
};
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String castling(CastlingCommand castlingCommand) {
|
|
||||||
String result = "O-O";
|
|
||||||
if (castlingCommand.isBigCastling())
|
|
||||||
result += "-O";
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static String checkCheckMate(Game game) {
|
|
||||||
switch (game.checkGameStatus(game.getPlayerTurn())) {
|
|
||||||
case CheckMate:
|
|
||||||
return "#";
|
|
||||||
|
|
||||||
case Check:
|
|
||||||
return "+";
|
|
||||||
|
|
||||||
default:
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private record MoveResult(String move, CommandResult commandResult) {
|
|
||||||
}
|
|
||||||
|
|
||||||
private static MoveResult printMove(PlayerCommand cmd, PlayerCommand nextCommand, Game virtualGame,
|
|
||||||
CommandExecutor executor) {
|
|
||||||
String result = "";
|
|
||||||
if (cmd instanceof MoveCommand move) {
|
|
||||||
|
|
||||||
Piece movingPiece = virtualGame.getBoard().pieceAt(move.getMove().getStart());
|
|
||||||
|
|
||||||
assert movingPiece != null;
|
|
||||||
|
|
||||||
// piece name
|
|
||||||
result += piecePgnName.visit(movingPiece);
|
|
||||||
|
|
||||||
// ambiguious start
|
|
||||||
result += resolveAmbiguity(executor, move.getMove());
|
|
||||||
|
|
||||||
// capture
|
|
||||||
result += capture(move, movingPiece);
|
|
||||||
|
|
||||||
// end cell
|
|
||||||
result += toString(move.getMove().getFinish());
|
|
||||||
|
|
||||||
// promote
|
|
||||||
result += promote(nextCommand);
|
|
||||||
|
|
||||||
} else if (cmd instanceof CastlingCommand castlingCommand) {
|
|
||||||
result += castling(castlingCommand);
|
|
||||||
}
|
|
||||||
|
|
||||||
CommandResult commandResult = executor.executeCommand(cmd);
|
|
||||||
|
|
||||||
// check or checkmate
|
|
||||||
result += checkCheckMate(virtualGame);
|
|
||||||
|
|
||||||
result += " ";
|
|
||||||
|
|
||||||
return new MoveResult(result, commandResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String exportGame(Game game) {
|
|
||||||
|
|
||||||
Game virtualGame = new Game();
|
|
||||||
|
|
||||||
CommandExecutor executor = new CommandExecutor(virtualGame, new EmptyGameDispatcher());
|
|
||||||
executor.executeCommand(new NewGameCommand());
|
|
||||||
|
|
||||||
List<PlayerCommand> commands = game.getMoves();
|
|
||||||
String result = "";
|
|
||||||
|
|
||||||
int tour = 1;
|
|
||||||
|
|
||||||
String lastMove = null;
|
|
||||||
|
|
||||||
for (int i = 0; i < commands.size(); i++) {
|
|
||||||
PlayerCommand cmd = commands.get(i);
|
|
||||||
PlayerCommand nextCommand = null;
|
|
||||||
|
|
||||||
if (i != commands.size() - 1) {
|
|
||||||
nextCommand = commands.get(i + 1);
|
|
||||||
}
|
|
||||||
MoveResult moveResult = printMove(cmd, nextCommand, virtualGame, executor);
|
|
||||||
if (moveResult.commandResult() == CommandResult.Moved && virtualGame.getPlayerTurn() == Color.Black) {
|
|
||||||
result += tour + ".";
|
|
||||||
tour++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (moveResult.commandResult() == CommandResult.ActionNeeded) {
|
|
||||||
lastMove = moveResult.move();
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (lastMove != null && moveResult.commandResult() == CommandResult.Moved){
|
|
||||||
result += lastMove;
|
|
||||||
lastMove = null;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
result += moveResult.move();
|
|
||||||
|
|
||||||
}
|
|
||||||
return result + " " + gameEnd(virtualGame);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static String toString(Coordinate coordinate) {
|
|
||||||
String letters = "abcdefgh";
|
|
||||||
String numbers = "87654321";
|
|
||||||
return Character.toString(letters.charAt(coordinate.getX())) + numbers.charAt(coordinate.getY());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
package chess.pgn;
|
|
||||||
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import common.AssetManager;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply moves from a pgn file at the start of a game.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PgnFileSimulator extends PgnSimulator{
|
|
||||||
|
|
||||||
public PgnFileSimulator(CommandExecutor commandExecutor, String fileName) {
|
|
||||||
super(commandExecutor, AssetManager.getResourceAsString(fileName));
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,198 +0,0 @@
|
|||||||
package chess.pgn;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.commands.CastlingCommand;
|
|
||||||
import chess.controller.commands.MoveCommand;
|
|
||||||
import chess.controller.commands.NewGameCommand;
|
|
||||||
import chess.controller.commands.PromoteCommand;
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
import chess.controller.event.EmptyGameDispatcher;
|
|
||||||
import chess.model.ChessBoard;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Game;
|
|
||||||
import chess.model.Move;
|
|
||||||
import chess.model.Piece;
|
|
||||||
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 a game from PGN format.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PgnImport {
|
|
||||||
|
|
||||||
private static final Map<String, Class<? extends Piece>> pieceMap = Map.of(
|
|
||||||
"K", King.class,
|
|
||||||
"Q", Queen.class,
|
|
||||||
"R", Rook.class,
|
|
||||||
"B", Bishop.class,
|
|
||||||
"N", Knight.class);
|
|
||||||
|
|
||||||
private static final Map<String, PromoteType> promoteMap = Map.of(
|
|
||||||
"Q", PromoteType.Queen,
|
|
||||||
"R", PromoteType.Rook,
|
|
||||||
"B", PromoteType.Bishop,
|
|
||||||
"N", PromoteType.Knight);
|
|
||||||
|
|
||||||
public static List<PlayerCommand> importGame(String pgnContent) {
|
|
||||||
String[] parts = pgnContent.split("\n\n");
|
|
||||||
// we just ignore headers
|
|
||||||
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) {
|
|
||||||
String[] moves = unparsedMoves.replaceAll("\\{.*?\\}", "") // Remove comments
|
|
||||||
.replaceAll("\\n", " ") // Remove new lines
|
|
||||||
.split("[\\s.]+"); // Split by whitespace and dots (trimming it also)
|
|
||||||
|
|
||||||
Game virtualGame = new Game();
|
|
||||||
CommandExecutor commandExecutor = new CommandExecutor(virtualGame, new EmptyGameDispatcher());
|
|
||||||
List<PlayerCommand> instructions = new ArrayList<>();
|
|
||||||
|
|
||||||
commandExecutor.executeCommand(new NewGameCommand());
|
|
||||||
|
|
||||||
for (int i = 0; i < moves.length; i++) {
|
|
||||||
if (i % 3 == 0)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
String move = moves[i];
|
|
||||||
|
|
||||||
if (move.equals("1-0") || move.equals("0-1") || move.equals("1/2-1/2")) {
|
|
||||||
break; // End of the game
|
|
||||||
}
|
|
||||||
|
|
||||||
List<PlayerCommand> cmds = parseMove(move, virtualGame);
|
|
||||||
commandExecutor.executeCommands(cmds);
|
|
||||||
|
|
||||||
instructions.addAll(cmds);
|
|
||||||
}
|
|
||||||
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) {
|
|
||||||
if (move.equals("O-O-O"))
|
|
||||||
return Arrays.asList(new CastlingCommand(true));
|
|
||||||
if (move.equals("O-O"))
|
|
||||||
return Arrays.asList(new CastlingCommand(false));
|
|
||||||
|
|
||||||
move = move.replaceAll("[x|#|\\+]", "");
|
|
||||||
|
|
||||||
PromoteCommand promoteCommand = null;
|
|
||||||
|
|
||||||
if (move.contains("=")) {
|
|
||||||
String promoteString = move.substring(move.length() - 1);
|
|
||||||
promoteCommand = new PromoteCommand(promoteMap.get(promoteString));
|
|
||||||
move = move.substring(0, move.length() - 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
Class<? extends Piece> pieceType = pieceMap.get(move.substring(0, 1));
|
|
||||||
|
|
||||||
if (pieceType == null)
|
|
||||||
pieceType = Pawn.class;
|
|
||||||
else
|
|
||||||
move = move.substring(1);
|
|
||||||
|
|
||||||
assert move.length() == 3 || move.length() == 2;
|
|
||||||
|
|
||||||
Coordinate ambiguity = new Coordinate(COORDINATE_ANY, COORDINATE_ANY);
|
|
||||||
|
|
||||||
// ambiguity
|
|
||||||
if (move.length() == 3) {
|
|
||||||
ambiguity = getAmbiguityPattern(move.charAt(0));
|
|
||||||
move = move.substring(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
Coordinate dest = stringToCoordinate(move);
|
|
||||||
|
|
||||||
Coordinate start = getStartCoord(dest, pieceType, ambiguity, game);
|
|
||||||
|
|
||||||
List<PlayerCommand> cmds = new ArrayList<>();
|
|
||||||
cmds.add(new MoveCommand(new Move(start, dest)));
|
|
||||||
if (promoteCommand != null)
|
|
||||||
cmds.add(promoteCommand);
|
|
||||||
|
|
||||||
return cmds;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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();
|
|
||||||
|
|
||||||
List<Coordinate> starts = board.getAllowedStarts(dest, game.getPlayerTurn());
|
|
||||||
|
|
||||||
assert !starts.isEmpty() : "No moves allowed!";
|
|
||||||
|
|
||||||
for (Coordinate start : starts) {
|
|
||||||
Piece piece = board.pieceAt(start);
|
|
||||||
if (piece.getClass().equals(pieceType) && coordPatternMatch(start, ambiguity))
|
|
||||||
return start;
|
|
||||||
}
|
|
||||||
|
|
||||||
assert false : "There is a small problem ...";
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int getXCoord(char xPos) {
|
|
||||||
return xPos - 'a';
|
|
||||||
}
|
|
||||||
|
|
||||||
private static int getYCoord(char yPos) {
|
|
||||||
return Coordinate.VALUE_MAX - 1 - (yPos - '1');
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean coordPatternMatch(Coordinate coord, Coordinate pattern) {
|
|
||||||
if (pattern.getX() != COORDINATE_ANY && coord.getX() != pattern.getX())
|
|
||||||
return false;
|
|
||||||
|
|
||||||
if (pattern.getY() != COORDINATE_ANY && coord.getY() != pattern.getY())
|
|
||||||
return false;
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Coordinate getAmbiguityPattern(char amb) {
|
|
||||||
if (Character.isDigit(amb))
|
|
||||||
return new Coordinate(COORDINATE_ANY, getYCoord(amb));
|
|
||||||
return new Coordinate(getXCoord(amb), COORDINATE_ANY);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static Coordinate stringToCoordinate(String coordinates) {
|
|
||||||
char xPos = coordinates.charAt(0);
|
|
||||||
char yPos = coordinates.charAt(1);
|
|
||||||
|
|
||||||
return new Coordinate(getXCoord(xPos), getYCoord(yPos));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package chess.pgn;
|
|
||||||
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.controller.PlayerCommand;
|
|
||||||
import chess.controller.event.GameAdapter;
|
|
||||||
import common.Signal0;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Apply moves from a pgn string at the start of a game.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PgnSimulator extends GameAdapter {
|
|
||||||
|
|
||||||
private final CommandExecutor commandExecutor;
|
|
||||||
private final String pgn;
|
|
||||||
|
|
||||||
public final Signal0 onComplete = new Signal0();
|
|
||||||
|
|
||||||
public PgnSimulator(CommandExecutor commandExecutor, String pgn) {
|
|
||||||
this.commandExecutor = commandExecutor;
|
|
||||||
this.pgn = pgn;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameStart() {
|
|
||||||
List<PlayerCommand> cmds = PgnImport.importGame(this.pgn);
|
|
||||||
this.commandExecutor.executeCommands(cmds);
|
|
||||||
this.onComplete.emit();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,47 +0,0 @@
|
|||||||
package chess.pgn;
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Visitor that returns the PGN name of a piece.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class PiecePgnName implements PieceVisitor<String> {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Bishop bishop) {
|
|
||||||
return "B";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(King king) {
|
|
||||||
return "K";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Knight knight) {
|
|
||||||
return "N";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Pawn pawn) {
|
|
||||||
return "";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Queen queen) {
|
|
||||||
return "Q";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Rook rook) {
|
|
||||||
return "R";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
package chess.view.DDDrender;
|
|
||||||
|
|
||||||
import org.joml.Matrix4f;
|
|
||||||
import org.joml.Vector2f;
|
|
||||||
import org.joml.Vector3f;
|
|
||||||
import org.joml.Vector4f;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 3D camera
|
|
||||||
*/
|
|
||||||
public class Camera {
|
|
||||||
public static final float fov = 70.0f;
|
|
||||||
public static final float zNear = 0.01f;
|
|
||||||
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;
|
|
||||||
|
|
||||||
public Camera() {
|
|
||||||
this.pos = new Vector3f(0.0f, camHeight, 0.0f);
|
|
||||||
setRotateAngle((float) Math.PI);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void move(float x, float y) {
|
|
||||||
this.pos.x += x;
|
|
||||||
this.pos.y += y;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setRotateAngle(float angle) {
|
|
||||||
this.angle = angle;
|
|
||||||
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() {
|
|
||||||
return pos;
|
|
||||||
}
|
|
||||||
|
|
||||||
public float getFov() {
|
|
||||||
return fov;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAspectRatio(float aspectRatio) {
|
|
||||||
this.aspectRatio = aspectRatio;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Matrix4f getPerspectiveMatrix() {
|
|
||||||
return new Matrix4f().perspective((float) (Math.toRadians(fov)), aspectRatio, zNear, zFar);
|
|
||||||
}
|
|
||||||
|
|
||||||
public Matrix4f getViewMatrix() {
|
|
||||||
return new Matrix4f().lookAt(pos, center, up);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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);
|
|
||||||
|
|
||||||
Vector4f rayClip = new Vector4f(relativeX, relativeY, -1.0f, 1.0f);
|
|
||||||
|
|
||||||
Vector4f rayEye = getPerspectiveMatrix().invert().transform(rayClip);
|
|
||||||
|
|
||||||
rayEye = new Vector4f(rayEye.x, rayEye.y, -1.0f, 0.0f);
|
|
||||||
|
|
||||||
Vector4f rayWorld = getViewMatrix().invert().transform(rayEye);
|
|
||||||
|
|
||||||
float lambda = -this.pos.y / rayWorld.y;
|
|
||||||
|
|
||||||
return new Vector2f(lambda * rayWorld.x + this.pos.x, lambda *
|
|
||||||
rayWorld.z + this.pos.z);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,566 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
package chess.view.DDDrender;
|
|
||||||
|
|
||||||
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.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.PieceShader;
|
|
||||||
import chess.view.DDDrender.shader.ShaderProgram;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Basic 3D renderer
|
|
||||||
*/
|
|
||||||
public class Renderer implements Closeable {
|
|
||||||
private BoardShader boardShader;
|
|
||||||
private PieceShader pieceShader;
|
|
||||||
private FrameBuffer frameBuffer;
|
|
||||||
|
|
||||||
public Renderer() {
|
|
||||||
this.boardShader = new BoardShader();
|
|
||||||
this.pieceShader = new PieceShader();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Init(float windowWidth, float widowHeight) {
|
|
||||||
boardShader.LoadShader();
|
|
||||||
pieceShader.LoadShader();
|
|
||||||
|
|
||||||
this.frameBuffer = new FrameBuffer((int) windowWidth, (int) (widowHeight * 8.0f / 10.0f));
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Update(Camera cam) {
|
|
||||||
this.boardShader.Start();
|
|
||||||
this.boardShader.SetCamMatrix(cam);
|
|
||||||
this.pieceShader.Start();
|
|
||||||
this.pieceShader.SetCamMatrix(cam);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Render(DDDModel model, Vector3f color, Matrix4f transform) {
|
|
||||||
this.pieceShader.Start();
|
|
||||||
this.pieceShader.setModelColor(color);
|
|
||||||
this.pieceShader.setModelTransform(transform);
|
|
||||||
Render(model);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Render(DDDModel model) {
|
|
||||||
for (int i = 0; i < model.getVaos().size(); i++) {
|
|
||||||
VertexArray vao = model.getVaos().get(i);
|
|
||||||
RenderVao(this.pieceShader, vao);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void RenderVao(ShaderProgram shader, VertexArray vertexArray) {
|
|
||||||
shader.Start();
|
|
||||||
vertexArray.Bind();
|
|
||||||
GL30.glDrawElements(GL30.GL_TRIANGLES, vertexArray.GetVertexCount(), GL_UNSIGNED_INT, 0);
|
|
||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,363 +0,0 @@
|
|||||||
package chess.view.DDDrender;
|
|
||||||
|
|
||||||
import common.AssetManager;
|
|
||||||
import common.Signal0;
|
|
||||||
import org.joml.Vector2f;
|
|
||||||
import org.lwjgl.*;
|
|
||||||
import org.lwjgl.glfw.*;
|
|
||||||
import org.lwjgl.opengl.*;
|
|
||||||
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.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.GLFW.*;
|
|
||||||
import static org.lwjgl.opengl.GL11.*;
|
|
||||||
import static org.lwjgl.system.MemoryStack.*;
|
|
||||||
import static org.lwjgl.system.MemoryUtil.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GLFW window.
|
|
||||||
*/
|
|
||||||
public class Window implements Closeable {
|
|
||||||
|
|
||||||
// The window handle
|
|
||||||
private long window;
|
|
||||||
|
|
||||||
private final ImGuiImplGl3 implGl3 = new ImGuiImplGl3();
|
|
||||||
private final ImGuiImplGlfw implGlfw = new ImGuiImplGlfw();
|
|
||||||
|
|
||||||
private Renderer renderer;
|
|
||||||
private final Camera cam;
|
|
||||||
private final World world;
|
|
||||||
|
|
||||||
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.cam = camera;
|
|
||||||
this.tasks = new ConcurrentLinkedDeque<>();
|
|
||||||
this.world = world;
|
|
||||||
this.regularTasks = new ArrayList<>();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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() {
|
|
||||||
System.out.println("LWJGL " + Version.getVersion() + "!");
|
|
||||||
|
|
||||||
init();
|
|
||||||
loop();
|
|
||||||
|
|
||||||
// Free the window callbacks and destroy the window
|
|
||||||
glfwFreeCallbacks(window);
|
|
||||||
glfwDestroyWindow(window);
|
|
||||||
|
|
||||||
// Terminate GLFW and free the error callback
|
|
||||||
glfwTerminate();
|
|
||||||
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() {
|
|
||||||
// Setup an error callback. The default implementation
|
|
||||||
// will print the error message in System.err.
|
|
||||||
GLFWErrorCallback.createPrint(System.err).set();
|
|
||||||
|
|
||||||
// Initialize GLFW. Most GLFW functions will not work before doing this.
|
|
||||||
if (!glfwInit())
|
|
||||||
throw new IllegalStateException("Unable to initialize GLFW");
|
|
||||||
|
|
||||||
// Configure GLFW
|
|
||||||
glfwDefaultWindowHints(); // optional, the current window hints are already the default
|
|
||||||
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
|
|
||||||
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable
|
|
||||||
|
|
||||||
// Create the window
|
|
||||||
window = glfwCreateWindow(1000, 1000, "3DChess", NULL, NULL);
|
|
||||||
if (window == NULL)
|
|
||||||
throw new RuntimeException("Failed to create the GLFW window");
|
|
||||||
|
|
||||||
// Get the thread stack and push a new frame
|
|
||||||
try (MemoryStack stack = stackPush()) {
|
|
||||||
IntBuffer pWidth = stack.mallocInt(1); // int*
|
|
||||||
IntBuffer pHeight = stack.mallocInt(1); // int*
|
|
||||||
|
|
||||||
// Get the window size passed to glfwCreateWindow
|
|
||||||
glfwGetWindowSize(window, pWidth, pHeight);
|
|
||||||
|
|
||||||
// Get the resolution of the primary monitor
|
|
||||||
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
|
|
||||||
|
|
||||||
// Center the window
|
|
||||||
glfwSetWindowPos(
|
|
||||||
window,
|
|
||||||
(vidmode.width() - pWidth.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
|
|
||||||
|
|
||||||
// Enable v-sync
|
|
||||||
glfwSwapInterval(1);
|
|
||||||
|
|
||||||
// Make the window visible
|
|
||||||
glfwShowWindow(window);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void render(float delta, float aspectRatio) {
|
|
||||||
final FrameBuffer frameBuffer = this.renderer.getFrameBuffer();
|
|
||||||
|
|
||||||
cam.setAspectRatio(frameBuffer.getAspectRatio());
|
|
||||||
frameBuffer.Bind();
|
|
||||||
frameBuffer.Clear();
|
|
||||||
renderer.Update(cam);
|
|
||||||
renderWorld();
|
|
||||||
frameBuffer.Unbind();
|
|
||||||
}
|
|
||||||
|
|
||||||
private void renderWorld() {
|
|
||||||
for (Entity entity : this.world.getEntites()) {
|
|
||||||
entity.render(this.renderer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
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);
|
|
||||||
|
|
||||||
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
|
|
||||||
// the window or has pressed the ESCAPE key.
|
|
||||||
while (!shouldBeClosed && !glfwWindowShouldClose(window)) {
|
|
||||||
|
|
||||||
newFrame();
|
|
||||||
|
|
||||||
render(ImGui.getIO().getDeltaTime(), (float) width[0] / (float) height[0]);
|
|
||||||
|
|
||||||
renderWindow();
|
|
||||||
ImGui.render();
|
|
||||||
implGl3.renderDrawData(ImGui.getDrawData());
|
|
||||||
|
|
||||||
glfwSwapBuffers(window); // swap the color buffers
|
|
||||||
|
|
||||||
// Poll for window events. The key callback above will only be
|
|
||||||
// invoked during this call.
|
|
||||||
glfwPollEvents();
|
|
||||||
|
|
||||||
executeTasks(ImGui.getIO().getDeltaTime());
|
|
||||||
|
|
||||||
glfwGetWindowSize(window, width, height);
|
|
||||||
glViewport(0, 0, width[0], height[0]);
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Closes the window
|
|
||||||
*/
|
|
||||||
public void stop() {
|
|
||||||
shouldBeClosed = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void close() throws IOException {
|
|
||||||
shouldBeClosed = true;
|
|
||||||
this.renderer.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
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);
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
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";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
package chess.view.DDDrender.opengl;
|
|
||||||
|
|
||||||
public record VertexAttribPointer(int index, int size, int offset) {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,102 +0,0 @@
|
|||||||
package chess.view.DDDrender.shader;
|
|
||||||
|
|
||||||
import chess.view.DDDrender.Camera;
|
|
||||||
|
|
||||||
public class BoardShader extends ShaderProgram {
|
|
||||||
|
|
||||||
private static String vertexShader = """
|
|
||||||
#version 330
|
|
||||||
|
|
||||||
layout(location = 0) in vec3 position;
|
|
||||||
layout(location = 1) in vec3 color;
|
|
||||||
|
|
||||||
uniform mat4 viewMatrix;
|
|
||||||
uniform mat4 projectionMatrix;
|
|
||||||
uniform vec3 lightPosition = vec3(0, 10, 0);
|
|
||||||
|
|
||||||
flat out vec3 pass_color;
|
|
||||||
|
|
||||||
out vec3 toLightVector;
|
|
||||||
out vec3 toCameraVector;
|
|
||||||
out vec3 surfaceNormal;
|
|
||||||
|
|
||||||
void main(void){
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
""";
|
|
||||||
|
|
||||||
private static String fragmentShader = """
|
|
||||||
#version 330
|
|
||||||
|
|
||||||
flat in vec3 pass_color;
|
|
||||||
|
|
||||||
in vec3 toLightVector;
|
|
||||||
in vec3 toCameraVector;
|
|
||||||
in vec3 surfaceNormal;
|
|
||||||
|
|
||||||
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(pass_color, 1.0);
|
|
||||||
out_color.w = 1.0;
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
""";
|
|
||||||
|
|
||||||
private int location_ProjectionMatrix = 0;
|
|
||||||
private int location_ViewMatrix = 0;
|
|
||||||
|
|
||||||
public BoardShader() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void LoadShader() {
|
|
||||||
super.LoadProgram(vertexShader, fragmentShader);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void GetAllUniformLocation() {
|
|
||||||
location_ProjectionMatrix = GetUniformLocation("projectionMatrix");
|
|
||||||
location_ViewMatrix = GetUniformLocation("viewMatrix");
|
|
||||||
}
|
|
||||||
|
|
||||||
public void SetCamMatrix(Camera camera) {
|
|
||||||
LoadMat4(location_ProjectionMatrix, camera.getPerspectiveMatrix());
|
|
||||||
LoadMat4(location_ViewMatrix, camera.getViewMatrix());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
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();
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package chess.view.audio;
|
|
||||||
|
|
||||||
import java.io.BufferedInputStream;
|
|
||||||
import java.io.File;
|
|
||||||
import java.io.FileOutputStream;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.InputStream;
|
|
||||||
import java.net.URI;
|
|
||||||
import java.net.URISyntaxException;
|
|
||||||
|
|
||||||
import common.AssetManager;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manage audio files: download, save, and load them.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class AudioFiles {
|
|
||||||
|
|
||||||
private static final String baseURL = "https://images.chesscomfiles.com/chess-themes/sounds/_WAV_/default/";
|
|
||||||
private static final String[] files = { "game-start", "game-end", "capture", "castle", "move-self",
|
|
||||||
"move-check", "promote", "illegal" };
|
|
||||||
private static final String filesExtension = ".wav";
|
|
||||||
private static final String saveDir = "audio/";
|
|
||||||
|
|
||||||
public static boolean initFiles() {
|
|
||||||
createSaveDir();
|
|
||||||
for (String file : files) {
|
|
||||||
if (!initFile(file + filesExtension))
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean downloadFile(String fileName) {
|
|
||||||
System.out.println("[GameAudio] missing " + fileName + " Downloading ...");
|
|
||||||
try (BufferedInputStream in = new BufferedInputStream(new URI(baseURL + fileName).toURL().openStream());
|
|
||||||
FileOutputStream fileOutputStream = new FileOutputStream(saveDir + fileName)) {
|
|
||||||
byte dataBuffer[] = new byte[1024];
|
|
||||||
int bytesRead;
|
|
||||||
while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
|
|
||||||
fileOutputStream.write(dataBuffer, 0, bytesRead);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
} catch (IOException | URISyntaxException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void createSaveDir() {
|
|
||||||
new File(saveDir).mkdir();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean initFile(String fileName) {
|
|
||||||
if (isFileDownloaded(saveDir + fileName))
|
|
||||||
return true;
|
|
||||||
return downloadFile(fileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isFileDownloaded(String fileName) {
|
|
||||||
return AssetManager.getResource(fileName) != null;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static InputStream getAudio(String audioName) {
|
|
||||||
return AssetManager.getResource(saveDir + audioName + filesExtension);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
package chess.view.audio;
|
|
||||||
|
|
||||||
import java.io.BufferedInputStream;
|
|
||||||
import java.io.InputStream;
|
|
||||||
|
|
||||||
import javax.sound.sampled.AudioFormat;
|
|
||||||
import javax.sound.sampled.AudioInputStream;
|
|
||||||
import javax.sound.sampled.AudioSystem;
|
|
||||||
import javax.sound.sampled.Clip;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Audio player class to play sound files.
|
|
||||||
*/
|
|
||||||
public class AudioPlayer {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Play a sound file.
|
|
||||||
* @param audio the audio input stream to play
|
|
||||||
*/
|
|
||||||
public static void playSound(InputStream audio) {
|
|
||||||
new Thread(new Runnable() {
|
|
||||||
// The wrapper thread is unnecessary, unless it blocks on the
|
|
||||||
// Clip finishing; see comments.
|
|
||||||
public void run() {
|
|
||||||
try {
|
|
||||||
Clip clip = AudioSystem.getClip();
|
|
||||||
BufferedInputStream bufferedInputStream = new BufferedInputStream(audio);
|
|
||||||
AudioInputStream inputStream = AudioSystem.getAudioInputStream(bufferedInputStream);
|
|
||||||
clip.open(inputStream);
|
|
||||||
clip.start();
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.err.println(e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}).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) {
|
|
||||||
AudioFormat m_format = audioInputStream.getFormat();
|
|
||||||
|
|
||||||
if ((m_format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) &&
|
|
||||||
(m_format.getEncoding() != AudioFormat.Encoding.PCM_UNSIGNED)) {
|
|
||||||
AudioFormat targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
|
|
||||||
m_format.getSampleRate(), 16,
|
|
||||||
m_format.getChannels(), m_format.getChannels() * 2,
|
|
||||||
m_format.getSampleRate(), m_format.isBigEndian());
|
|
||||||
audioInputStream = AudioSystem.getAudioInputStream(targetFormat, audioInputStream);
|
|
||||||
}
|
|
||||||
|
|
||||||
return audioInputStream;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
package chess.view.audio;
|
|
||||||
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
import chess.controller.event.GameAdapter;
|
|
||||||
import chess.model.Coordinate;
|
|
||||||
import chess.model.Move;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Class to handle audio events in the game.
|
|
||||||
*/
|
|
||||||
public class GameAudio extends GameAdapter {
|
|
||||||
|
|
||||||
private final boolean functional;
|
|
||||||
|
|
||||||
public GameAudio() {
|
|
||||||
this.functional = AudioFiles.initFiles();
|
|
||||||
if(!this.functional){
|
|
||||||
System.err.println("[GameAudio] Failed to initialize audio files. Aborting ...");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private void playSound(String soundName) {
|
|
||||||
if (!this.functional)
|
|
||||||
return;
|
|
||||||
AudioPlayer.playSound(AudioFiles.getAudio(soundName));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameStart() {
|
|
||||||
playSound("game-start");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {
|
|
||||||
playSound("game-end");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMoveNotAllowed(Move move) {
|
|
||||||
playSound("illegal");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMove(Move move, boolean captured) {
|
|
||||||
if (captured) {
|
|
||||||
playSound("capture");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
playSound("move-self");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInCheck() {
|
|
||||||
playSound("move-check");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPawnPromoted(PromoteType promotion, Coordinate coordinate) {
|
|
||||||
playSound("promote");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onCastling(boolean bigCastling, Move kingMove, Move rookMove) {
|
|
||||||
playSound("castle");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package chess.view.consolerender;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Colors class for console output, contains ANSI escape codes.
|
|
||||||
*/
|
|
||||||
public class Colors {
|
|
||||||
// Reset
|
|
||||||
public static final String RESET = "\u001B[0m"; // Text Reset
|
|
||||||
|
|
||||||
// Regular Colors
|
|
||||||
public static final String BLACK = "\033[38;2;0;0;0m";
|
|
||||||
public static final String WHITE = "\033[38;2;255;255;255m";
|
|
||||||
public static final String RED = "\033[38;2;255;0;0m";
|
|
||||||
public static final String GREEN = "\033[38;2;0;255;0m";
|
|
||||||
public static final String YELLOW = "\033[38;2;255;255;0m";
|
|
||||||
public static final String BLUE = "\033[38;2;0;0;255m";
|
|
||||||
public static final String PURPLE = "\033[38;2;255;0;255m";
|
|
||||||
public static final String CYAN = "\033[38;2;0;255;255m";
|
|
||||||
|
|
||||||
// Background
|
|
||||||
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 DARK_GRAY_BACKGROUND = "\033[48;2;120;120;120m";
|
|
||||||
public static final String RED_BACKGROUND = "\033[41m";
|
|
||||||
public static final String GREEN_BACKGROUND = "\033[42m";
|
|
||||||
public static final String YELLOW_BACKGROUND = "\033[43m";
|
|
||||||
public static final String BLUE_BACKGROUND = "\033[44m";
|
|
||||||
public static final String PURPLE_BACKGROUND = "\033[45m";
|
|
||||||
public static final String CYAN_BACKGROUND = "\033[46m";
|
|
||||||
public static final String WHITE_BACKGROUND = "\033[47m";
|
|
||||||
|
|
||||||
// High Intensity backgrounds
|
|
||||||
public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m";
|
|
||||||
public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m";
|
|
||||||
public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m";
|
|
||||||
public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m";
|
|
||||||
public static final String BLUE_BACKGROUND_BRIGHT = "\033[0;104m";
|
|
||||||
public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m";
|
|
||||||
public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m";
|
|
||||||
public static final String WHITE_BACKGROUND_BRIGHT = "\033[0;107m";
|
|
||||||
}
|
|
||||||
@@ -1,374 +0,0 @@
|
|||||||
package chess.view.consolerender;
|
|
||||||
|
|
||||||
import chess.controller.Command;
|
|
||||||
import chess.controller.CommandExecutor;
|
|
||||||
import chess.controller.CommandSender;
|
|
||||||
import chess.controller.commands.*;
|
|
||||||
import chess.controller.commands.PromoteCommand.PromoteType;
|
|
||||||
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 java.util.List;
|
|
||||||
import java.util.Objects;
|
|
||||||
import java.util.Scanner;
|
|
||||||
import java.util.concurrent.ExecutorService;
|
|
||||||
import java.util.concurrent.Executors;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Console renderer.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class Console extends GameView {
|
|
||||||
private final Scanner scanner = new Scanner(System.in);
|
|
||||||
private final CommandExecutor commandExecutor;
|
|
||||||
private final ConsolePieceName consolePieceName = new ConsolePieceName();
|
|
||||||
private boolean captureInput;
|
|
||||||
private final ExecutorService executor;
|
|
||||||
|
|
||||||
public Console(CommandExecutor commandExecutor, boolean captureInput) {
|
|
||||||
this.commandExecutor = commandExecutor;
|
|
||||||
this.executor = Executors.newSingleThreadExecutor();
|
|
||||||
this.captureInput = captureInput;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Console(CommandExecutor commandExecutor) {
|
|
||||||
this(commandExecutor, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
* @throws Exception if the string is not valid
|
|
||||||
*/
|
|
||||||
public Coordinate stringToCoordinate(String coordinates) throws Exception {
|
|
||||||
char xPos = coordinates.charAt(0);
|
|
||||||
char yPos = coordinates.charAt(1);
|
|
||||||
int x;
|
|
||||||
if (xPos >= 'A' && xPos <= 'Z') {
|
|
||||||
x = xPos - 'A';
|
|
||||||
} else if (xPos >= 'a' && xPos <= 'z') {
|
|
||||||
x = xPos - 'a';
|
|
||||||
} else {
|
|
||||||
throw new Exception("Invalid input");
|
|
||||||
}
|
|
||||||
if (!(yPos >= '1' && yPos <= '9')) {
|
|
||||||
throw new Exception("Invalid input");
|
|
||||||
}
|
|
||||||
int y = Coordinate.VALUE_MAX - 1 - (yPos - '1');
|
|
||||||
return new Coordinate(x, y);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Open a dialog so the user can, during their turn, move a piece, show move previews, or surrender.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onPlayerTurn(Color color, boolean undone) {
|
|
||||||
if (!captureInput)
|
|
||||||
return;
|
|
||||||
System.out.println(Colors.RED + "Player turn: " + color + Colors.RESET);
|
|
||||||
this.executor.submit(() -> {
|
|
||||||
boolean endTurn;
|
|
||||||
String line = "0";
|
|
||||||
do {
|
|
||||||
if (!line.isEmpty()) {
|
|
||||||
System.out.println("""
|
|
||||||
Pick your choice:
|
|
||||||
1 - Move
|
|
||||||
2 - Show potential moves
|
|
||||||
3 - Surrender
|
|
||||||
""");
|
|
||||||
System.out.flush();
|
|
||||||
}
|
|
||||||
line = scanner.nextLine();
|
|
||||||
endTurn = switch (line) {
|
|
||||||
case "1" -> playerPickedMove(color);
|
|
||||||
case "2" -> playerPickedShowMoves(color);
|
|
||||||
case "3" -> playerPickedSurrender(color);
|
|
||||||
default -> false;
|
|
||||||
};
|
|
||||||
} while (!endTurn);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean playerPickedSurrender(Color color) {
|
|
||||||
sendSurrender(color);
|
|
||||||
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) {
|
|
||||||
try {
|
|
||||||
System.out.println("Piece to move, or \"castling\" for a castling");
|
|
||||||
String answer = scanner.nextLine();
|
|
||||||
if (answer.equalsIgnoreCase("castling")) {
|
|
||||||
return onAskedCastling();
|
|
||||||
}
|
|
||||||
Coordinate start = stringToCoordinate(answer);
|
|
||||||
System.out.println("New position: ");
|
|
||||||
Coordinate end = stringToCoordinate(scanner.nextLine());
|
|
||||||
Command.CommandResult result = sendMove(new Move(start, end));
|
|
||||||
|
|
||||||
return switch (Objects.requireNonNull(result)) {
|
|
||||||
case Command.CommandResult.Moved, Command.CommandResult.ActionNeeded -> true;
|
|
||||||
default -> false;
|
|
||||||
};
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.out.println(e.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ask the user to pick a piece, and show its potential moves
|
|
||||||
* @param color
|
|
||||||
* @return
|
|
||||||
*/
|
|
||||||
private boolean playerPickedShowMoves(Color color) {
|
|
||||||
try {
|
|
||||||
System.out.println("Piece to examine: ");
|
|
||||||
Coordinate piece = stringToCoordinate(scanner.nextLine());
|
|
||||||
List<Coordinate> allowedMoves = getPieceAllowedMoves(piece);
|
|
||||||
if (allowedMoves.isEmpty()) {
|
|
||||||
System.out.println("No moves allowed for this piece.");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
displayMoves(piece, allowedMoves);
|
|
||||||
return false;
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.out.println(e.getMessage());
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onWin(Color color) {
|
|
||||||
System.out.println(Colors.RED + "Victory of player " + color + Colors.RESET);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInCheck() {
|
|
||||||
System.out.println(Colors.RED + "Check!" + Colors.RESET);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onKingInMat() {
|
|
||||||
System.out.println(Colors.RED + "Checkmate!" + Colors.RESET);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onPatSituation() {
|
|
||||||
System.out.println("Pat! It's a draw!");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onSurrender(Color color) {
|
|
||||||
System.out.println("The " + color + " player has surrendered!");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameStart() {
|
|
||||||
System.out.println("Game start!");
|
|
||||||
onBoardUpdate();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onGameEnd() {
|
|
||||||
System.out.println("Thank you for playing!");
|
|
||||||
this.commandExecutor.close();
|
|
||||||
this.executor.shutdown();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Open the dialog to promote a pawn.
|
|
||||||
* @param pieceCoords the coordinates of the pawn to promote
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onPromotePawn(Coordinate pieceCoords) {
|
|
||||||
System.out.println("The pawn on the " + pieceCoords + " coordinates needs to be promoted.");
|
|
||||||
System.out.println("Enter 'B' to promote it into a Bishop, 'N' for a Knight, 'Q' for a Queen, 'R' for a Rook.");
|
|
||||||
System.out.flush();
|
|
||||||
this.executor.submit(() -> {
|
|
||||||
PromoteType newPiece;
|
|
||||||
boolean valid = false;
|
|
||||||
do {
|
|
||||||
try {
|
|
||||||
String promotion = scanner.next();
|
|
||||||
newPiece = switch (promotion) {
|
|
||||||
case "B", "b", "Bishop", "bishop" -> PromoteType.Bishop;
|
|
||||||
case "N", "n", "Knight", "knight" -> PromoteType.Knight;
|
|
||||||
case "Q", "q", "Queen", "queen" -> PromoteType.Queen;
|
|
||||||
case "R", "r", "Rook", "rook" -> PromoteType.Rook;
|
|
||||||
default -> throw new Exception();
|
|
||||||
};
|
|
||||||
valid = true;
|
|
||||||
sendPawnPromotion(newPiece);
|
|
||||||
} catch (Exception e) {
|
|
||||||
System.out.println("Invalid input!");
|
|
||||||
}
|
|
||||||
} while (!valid);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update and print the board in the console.
|
|
||||||
*/
|
|
||||||
@Override
|
|
||||||
public void onBoardUpdate() {
|
|
||||||
if (!this.captureInput)
|
|
||||||
return;
|
|
||||||
StringBuilder string = new StringBuilder();
|
|
||||||
string.append(" a b c d e f g h \n");
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
string.append(8 - i).append(" ");
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Piece p = getPieceAt(new Coordinate(j, i));
|
|
||||||
if ((i + j) % 2 == 0) {
|
|
||||||
string.append(Colors.LIGHT_GRAY_BACKGROUND);
|
|
||||||
} else {
|
|
||||||
string.append(Colors.DARK_GRAY_BACKGROUND);
|
|
||||||
}
|
|
||||||
if (p == null) {
|
|
||||||
string.append(" " + Colors.RESET);
|
|
||||||
} else {
|
|
||||||
string.append(" ").append(consolePieceName.getString(p)).append(" ").append(Colors.RESET);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
string.append("\n");
|
|
||||||
}
|
|
||||||
System.out.println(string);
|
|
||||||
System.out.flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Display the possible moves of a piece.
|
|
||||||
* @param piece
|
|
||||||
* @param moves
|
|
||||||
*/
|
|
||||||
public void displayMoves(Coordinate piece, List<Coordinate> moves) {
|
|
||||||
StringBuilder string = new StringBuilder();
|
|
||||||
string.append(" a b c d e f g h \n");
|
|
||||||
for (int i = 0; i < Coordinate.VALUE_MAX; i++) {
|
|
||||||
string.append(8 - i).append(" ");
|
|
||||||
for (int j = 0; j < Coordinate.VALUE_MAX; j++) {
|
|
||||||
Coordinate currentCell = new Coordinate(j, i);
|
|
||||||
Piece p = getPieceAt(new Coordinate(j, i));
|
|
||||||
if (moves.contains(currentCell)) {
|
|
||||||
string.append(Colors.YELLOW_BACKGROUND);
|
|
||||||
} else {
|
|
||||||
if ((i + j) % 2 == 0) {
|
|
||||||
string.append(Colors.LIGHT_GRAY_BACKGROUND);
|
|
||||||
} else {
|
|
||||||
string.append(Colors.DARK_GRAY_BACKGROUND);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (p == null) {
|
|
||||||
string.append(" " + Colors.RESET);
|
|
||||||
} else {
|
|
||||||
if (currentCell.equals(piece)) {
|
|
||||||
string.append(Colors.RED_BACKGROUND).append(" ").append(consolePieceName.getString(p))
|
|
||||||
.append(" ").append(Colors.RESET);
|
|
||||||
} else {
|
|
||||||
string.append(" ").append(consolePieceName.getString(p)).append(" ").append(Colors.RESET);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
string.append("\n");
|
|
||||||
}
|
|
||||||
System.out.println(string);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onMoveNotAllowed(Move move) {
|
|
||||||
System.out.println("Move not allowed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void onDraw() {
|
|
||||||
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() {
|
|
||||||
return switch (getAllowedCastlings()) {
|
|
||||||
case Small -> onSmallCastling();
|
|
||||||
case Big -> onBigCastling();
|
|
||||||
case Both -> onBothCastling();
|
|
||||||
default -> {
|
|
||||||
System.out.println("No castling allowed.");
|
|
||||||
yield false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ask the user to confirm a small castling.
|
|
||||||
* @return true if the castling was played, false otherwise
|
|
||||||
*/
|
|
||||||
private boolean onSmallCastling() {
|
|
||||||
System.out.println("Small castling allowed. Confirm with \"y\":");
|
|
||||||
String answer = scanner.nextLine();
|
|
||||||
if (!(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("yes"))) {
|
|
||||||
return false;
|
|
||||||
} else {
|
|
||||||
return (commandExecutor.executeCommand(new CastlingCommand(false)) != Command.CommandResult.Moved);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ask the user to confirm a big castling.
|
|
||||||
* @return true if the castling was played, false otherwise
|
|
||||||
*/
|
|
||||||
private boolean onBigCastling() {
|
|
||||||
System.out.println("Big castling allowed. Confirm with \"y\":");
|
|
||||||
String answer = scanner.nextLine();
|
|
||||||
if (!(answer.equalsIgnoreCase("y") || answer.equalsIgnoreCase("yes"))) {
|
|
||||||
return false;
|
|
||||||
} else {
|
|
||||||
return (commandExecutor.executeCommand(new CastlingCommand(true)) != Command.CommandResult.Moved);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Ask the user to pick a castling when both are allowed.
|
|
||||||
* @return true if a castling was played, false otherwise
|
|
||||||
*/
|
|
||||||
private boolean onBothCastling() {
|
|
||||||
System.out.println("Both castlings allowed. Pick \"s\" to play a castling, \"b\" to play a big castling.");
|
|
||||||
String answer = scanner.nextLine();
|
|
||||||
return switch (answer) {
|
|
||||||
case "s", "S", "small", "Small", "castling", "normal", "Normal" ->
|
|
||||||
(commandExecutor.executeCommand(new CastlingCommand(false)) != Command.CommandResult.Moved);
|
|
||||||
case "b", "B", "big", "Big", "big castling", "Big castling" ->
|
|
||||||
(commandExecutor.executeCommand(new CastlingCommand(true)) != Command.CommandResult.Moved);
|
|
||||||
default -> false;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCaptureInput(boolean captureInput) {
|
|
||||||
this.captureInput = captureInput;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public CommandExecutor getCommandExecutor() {
|
|
||||||
return this.commandExecutor;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void run() {
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package chess.view.consolerender;
|
|
||||||
|
|
||||||
import chess.model.Color;
|
|
||||||
import chess.model.Piece;
|
|
||||||
import chess.model.PieceVisitor;
|
|
||||||
import chess.model.pieces.*;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Manage appearance of pieces in the console.
|
|
||||||
*/
|
|
||||||
|
|
||||||
public class ConsolePieceName implements PieceVisitor<String> {
|
|
||||||
|
|
||||||
public String getString(Piece piece){
|
|
||||||
if (piece.getColor()== Color.Black){
|
|
||||||
return Colors.BLACK + visit(piece);
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return Colors.WHITE + visit(piece);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Bishop bishop) {
|
|
||||||
return "B";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(King king) {
|
|
||||||
return "K";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Knight knight) {
|
|
||||||
return "N";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Pawn pawn) {
|
|
||||||
return "P";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Queen queen) {
|
|
||||||
return "Q";
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public String visitPiece(Rook rook) {
|
|
||||||
return "R";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
61
app/src/main/java/chess/view/render2D/PieceFileName.java
Normal file
61
app/src/main/java/chess/view/render2D/PieceFileName.java
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package chess.view.render2D;
|
||||||
|
|
||||||
|
import chess.model.Piece;
|
||||||
|
import chess.model.PieceVisitor;
|
||||||
|
import chess.model.pieces.*;
|
||||||
|
|
||||||
|
public class PieceFileName implements PieceVisitor {
|
||||||
|
|
||||||
|
private String pieceName;
|
||||||
|
private static final String BASE = "app/src/main/resources/pieces2D/";
|
||||||
|
|
||||||
|
PieceFileName(Piece piece) {
|
||||||
|
visit(piece);
|
||||||
|
pieceName = colorToString(piece.getColor()) +"-"+ pieceName;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String colorToString(int color) {
|
||||||
|
switch (color) {
|
||||||
|
case 0:
|
||||||
|
return "white";
|
||||||
|
case 1:
|
||||||
|
return "black";
|
||||||
|
default:
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitPiece(Bishop p) {
|
||||||
|
this.pieceName = "bishop";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitPiece(Knight p) {
|
||||||
|
this.pieceName = "knight";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitPiece(Pawn p) {
|
||||||
|
this.pieceName = "pawn";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitPiece(Queen p) {
|
||||||
|
this.pieceName = "queen";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitPiece(King p) {
|
||||||
|
this.pieceName = "king";
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visitPiece(Rook p) {
|
||||||
|
this.pieceName = "rook";
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getFileName() {
|
||||||
|
return BASE + pieceName + ".png";
|
||||||
|
}
|
||||||
|
}
|
||||||
23
app/src/main/java/chess/view/render2D/Pieces.java
Normal file
23
app/src/main/java/chess/view/render2D/Pieces.java
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package chess.view.render2D;
|
||||||
|
|
||||||
|
import javax.swing.*;
|
||||||
|
import java.awt.*;
|
||||||
|
|
||||||
|
public enum Pieces {
|
||||||
|
WHITE_KING,
|
||||||
|
WHITE_QUEEN,
|
||||||
|
WHITE_KNIGHT,
|
||||||
|
WHITE_BISHOP,
|
||||||
|
WHITE_ROOK,
|
||||||
|
WHITE_PAWN,
|
||||||
|
BLACK_KING,
|
||||||
|
BLACK_QUEEN,
|
||||||
|
BLACK_KNIGHT,
|
||||||
|
BLACK_BISHOP,
|
||||||
|
BLACK_ROOK,
|
||||||
|
BLACK_PAWN;
|
||||||
|
|
||||||
|
public static ImageIcon getIcon(String path) {
|
||||||
|
return new ImageIcon(new ImageIcon(path).getImage().getScaledInstance(100,100, Image.SCALE_SMOOTH));
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user