Compare commits
98 Commits
f1d963e546
...
tests
| Author | SHA1 | Date | |
|---|---|---|---|
| abf6f6c7c3 | |||
|
|
627c49b961 | ||
|
|
b4157167b5 | ||
|
|
1419898955 | ||
|
|
dd3be67be0 | ||
|
|
c6a32b8d07 | ||
|
|
a8439df736 | ||
|
|
27032d264d | ||
|
|
8afd51b353 | ||
| 2460b7539e | |||
| 0f5020b0b4 | |||
| ac4f859fd8 | |||
| 4a8644181a | |||
| efa357a1ab | |||
| 618e436270 | |||
| d5009371f2 | |||
| 87727f39e8 | |||
| 413201882b | |||
| d8289b553a | |||
|
|
adeb9b07e5 | ||
|
|
4903fd567b | ||
| 990c830590 | |||
| d806420d21 | |||
| 4b98341618 | |||
| 68021b796b | |||
| 06efbf649b | |||
| 4ee29d8f50 | |||
| eda2a1afae | |||
| f3bbfd9e6c | |||
|
|
129c3ef0b2 | ||
| 14d0521215 | |||
| 7568208045 | |||
| 86aa6e9bb5 | |||
| 91c645e34f | |||
| 78bdefebe5 | |||
| 3e30332245 | |||
| 275878932b | |||
| 68d577a99a | |||
| fa3124220d | |||
| 3a009256c5 | |||
| d09bf6e9ce | |||
| 5da915932d | |||
| da422e78b8 | |||
| f0a0a8e328 | |||
| 436b641269 | |||
| 34a59546e6 | |||
| 9e2421accf | |||
| 52ca8b208c | |||
|
|
140d37fbd9 | ||
|
|
2b3581a400 | ||
| a6b1fae230 | |||
| a20a5387a7 | |||
|
|
8c672e24ad | ||
|
|
815756b5e9 | ||
| a1032335a5 | |||
| 336d8378ae | |||
| c165ecdae5 | |||
| 352aee49e4 | |||
| f22debdf5f | |||
| 02089c649b | |||
| e98199e1ec | |||
| 438252a8ca | |||
| caf6569409 | |||
| 3863c812c8 | |||
| 6d96455ac4 | |||
| a5c046f891 | |||
|
|
b7f9ca8a98 | ||
| a160042ef4 | |||
| f47e4cc309 | |||
| 25c2270a37 | |||
| bcded60fbe | |||
| edfffaf061 | |||
| a74bf42e59 | |||
| 1f92c49f3c | |||
| c262007ca8 | |||
| 73f572ee18 | |||
| ec07d88577 | |||
| 6caf5d5c54 | |||
|
|
696062e9db | ||
|
|
c825807aea | ||
| 39529e0b64 | |||
| 3fa22a4cf0 | |||
| 337911d038 | |||
| 1930bc02bd | |||
| b9788d6a51 | |||
| 7789209651 | |||
|
|
54a4bd9f22 | ||
| 8596781ce3 | |||
|
|
d6c3504bc7 | ||
| 44a4432ac0 | |||
| a42ec2f27c | |||
| bff7abcd02 | |||
|
|
bf67afe4a9 | ||
| 67da77af2e | |||
| c4becf2d55 | |||
| b9a6617967 | |||
| 03f577828b | |||
| 9b776d4b0f |
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
uses: gradle/actions/setup-gradle@v4
|
||||
|
||||
- name: Build with Gradle
|
||||
run: ./gradlew build
|
||||
run: ./gradlew assemble
|
||||
|
||||
- name: Test
|
||||
run: ./gradlew test
|
||||
|
||||
@@ -18,19 +18,18 @@ repositories {
|
||||
|
||||
dependencies {
|
||||
// Use JUnit Jupiter for testing.
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
|
||||
|
||||
// This dependency is used by the application.
|
||||
implementation 'com.google.guava:guava:31.1-jre'
|
||||
|
||||
// uml
|
||||
implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.26.2'
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
|
||||
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
|
||||
|
||||
implementation 'org.json:json:20250107'
|
||||
|
||||
implementation 'com.fasterxml.jackson.core:jackson-databind:2.18.2'
|
||||
|
||||
implementation "io.github.spair:imgui-java-app:1.88.0"
|
||||
|
||||
implementation "org.lwjgl:lwjgl-stb:3.3.4"
|
||||
|
||||
implementation "org.lwjgl:lwjgl-stb::natives-linux"
|
||||
implementation "org.lwjgl:lwjgl-stb::natives-windows"
|
||||
implementation "org.lwjgl:lwjgl-stb::natives-macos"
|
||||
}
|
||||
|
||||
application {
|
||||
@@ -38,8 +37,19 @@ application {
|
||||
mainClass = 'gui.Main'
|
||||
}
|
||||
|
||||
tasks.named('test') {
|
||||
// Use JUnit Platform for unit tests.
|
||||
// Add libraries into the final jar
|
||||
jar {
|
||||
archiveBaseName = rootProject.getName()
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
manifest {
|
||||
attributes "Main-Class": application.mainClass
|
||||
}
|
||||
from {
|
||||
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
|
||||
}
|
||||
}
|
||||
|
||||
test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
|
||||
27
app/src/main/java/common/ConsumerSignal.java
Normal file
27
app/src/main/java/common/ConsumerSignal.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package common;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class ConsumerSignal<T> {
|
||||
private final Set<Consumer<T>> listeners;
|
||||
|
||||
public ConsumerSignal() {
|
||||
this.listeners = new HashSet<>();
|
||||
}
|
||||
|
||||
public void connect(Consumer<T> listener) {
|
||||
this.listeners.add(listener);
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
this.listeners.clear();
|
||||
}
|
||||
|
||||
public void emit(T arg) {
|
||||
for (Consumer<T> listener : this.listeners) {
|
||||
listener.accept(arg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
package game;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import sudoku.structure.MultiDoku;
|
||||
@@ -8,15 +12,19 @@ import sudoku.structure.MultiDoku;
|
||||
public class Game {
|
||||
|
||||
public static enum GameState {
|
||||
GameNotStarted, GameGoing, GameEnd
|
||||
GameNotStarted, GameGoing
|
||||
}
|
||||
|
||||
private final Map<Integer, Player> players;
|
||||
private final List<Player> leaderboard;
|
||||
private GameState gameState;
|
||||
private MultiDoku doku;
|
||||
private Instant startTime = null;
|
||||
private long gameDuration;
|
||||
|
||||
public Game() {
|
||||
this.players = new HashMap<>();
|
||||
this.leaderboard = new ArrayList<>();
|
||||
this.gameState = GameState.GameNotStarted;
|
||||
}
|
||||
|
||||
@@ -26,19 +34,33 @@ public class Game {
|
||||
|
||||
public void addPlayer(Player player) {
|
||||
players.put(player.getId(), player);
|
||||
leaderboard.add(player);
|
||||
}
|
||||
|
||||
public void setPlayerRemainingCells(Player player, int newScore) {
|
||||
player.setRemainingCells(newScore);
|
||||
Collections.sort(this.leaderboard,
|
||||
(player1, player2) -> Integer.compare(player1.getRemainingCells(), player2.getRemainingCells()));
|
||||
}
|
||||
|
||||
public void removePlayer(int id) {
|
||||
players.remove(id);
|
||||
this.leaderboard.remove(getPlayerById(id));
|
||||
this.players.remove(id);
|
||||
}
|
||||
|
||||
public Map<Integer, Player> getPlayers() {
|
||||
return players;
|
||||
}
|
||||
|
||||
public void startGame(MultiDoku doku) {
|
||||
public void startGame(MultiDoku doku, Instant startTime, long gameDuration) {
|
||||
this.doku = doku;
|
||||
this.gameState = GameState.GameGoing;
|
||||
this.startTime = startTime;
|
||||
this.gameDuration = gameDuration;
|
||||
}
|
||||
|
||||
public void stopGame() {
|
||||
this.gameState = GameState.GameNotStarted;
|
||||
}
|
||||
|
||||
public GameState getGameState() {
|
||||
@@ -49,4 +71,16 @@ public class Game {
|
||||
return doku;
|
||||
}
|
||||
|
||||
public List<Player> getLeaderboard() {
|
||||
return leaderboard;
|
||||
}
|
||||
|
||||
public Instant getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public long getGameDuration() {
|
||||
return gameDuration;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -8,10 +8,20 @@ public class Player implements Serializable {
|
||||
|
||||
private final String pseudo;
|
||||
private final int id;
|
||||
private int score;
|
||||
|
||||
public Player(int id, String pseudo) {
|
||||
this.pseudo = pseudo;
|
||||
this.id = id;
|
||||
this.score = 0;
|
||||
}
|
||||
|
||||
public int getRemainingCells() {
|
||||
return score;
|
||||
}
|
||||
|
||||
void setRemainingCells(int score) {
|
||||
this.score = score;
|
||||
}
|
||||
|
||||
public String getPseudo() {
|
||||
|
||||
32
app/src/main/java/gui/AssetManager.java
Normal file
32
app/src/main/java/gui/AssetManager.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package gui;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
public class AssetManager {
|
||||
|
||||
public static byte[] getResource(String name) {
|
||||
// we first search it in files
|
||||
File f = new File(name);
|
||||
if (f.exists()){
|
||||
FileInputStream fis;
|
||||
try {
|
||||
fis = new FileInputStream(f);
|
||||
return fis.readAllBytes();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
// then in the jar
|
||||
InputStream is = ClassLoader.getSystemResourceAsStream(name);
|
||||
try {
|
||||
return is.readAllBytes();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package gui;
|
||||
|
||||
import imgui.ImFont;
|
||||
import imgui.ImGui;
|
||||
|
||||
public class Fonts {
|
||||
|
||||
public static ImFont ARIAL;
|
||||
public static ImFont ARIAL_BOLD;
|
||||
public static ImFont CHERI;
|
||||
public static ImFont COMIC;
|
||||
public static ImFont INFECTED;
|
||||
|
||||
private static final String baseDir = "";
|
||||
|
||||
public static void createFonts() {
|
||||
COMIC = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "comic.ttf", 50.0f);
|
||||
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial_bold.ttf", 50.0f);
|
||||
ARIAL = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial.ttf", 50.0f);
|
||||
CHERI = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "cheri.ttf", 50.0f);
|
||||
INFECTED = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "INFECTED.ttf", 50.0f);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
package gui;
|
||||
|
||||
import gui.constants.Fonts;
|
||||
import gui.constants.Images;
|
||||
import gui.menu.MainMenu;
|
||||
import gui.menu.StateMachine;
|
||||
import imgui.ImGui;
|
||||
import imgui.app.Application;
|
||||
import imgui.app.Configuration;
|
||||
|
||||
@@ -27,6 +28,12 @@ public class Main extends Application {
|
||||
stateMachine.pushState(new MainMenu(stateMachine));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void preRun() {
|
||||
super.preRun();
|
||||
Images.reloadImages();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void process() {
|
||||
stateMachine.render();
|
||||
|
||||
@@ -27,10 +27,6 @@ public class RenderableMultidoku {
|
||||
this.doku = doku;
|
||||
}
|
||||
|
||||
public boolean isResolved() {
|
||||
return this.doku.isSolved();
|
||||
}
|
||||
|
||||
public int getWidth() {
|
||||
return width;
|
||||
}
|
||||
@@ -51,22 +47,6 @@ public class RenderableMultidoku {
|
||||
return cells.get(index);
|
||||
}
|
||||
|
||||
public boolean setCellValue(Cell cell, int value) {
|
||||
for (Sudoku s : doku.getSubGrids()) {
|
||||
int cellIndex = s.getCells().indexOf(cell);
|
||||
// la cellule existe
|
||||
if (cellIndex != -1) {
|
||||
int cellX = cellIndex % s.getSize();
|
||||
int cellY = cellIndex / s.getSize();
|
||||
if (!s.canBePlaced(cellX, cellY, value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
cell.setSymbolIndex(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static record PositionConstraint(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
|
||||
}
|
||||
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
package gui;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import common.Signal;
|
||||
import imgui.ImGui;
|
||||
import imgui.extension.imguifiledialog.ImGuiFileDialog;
|
||||
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
|
||||
import imgui.type.ImBoolean;
|
||||
import imgui.type.ImInt;
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.structure.Difficulty;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
public class SudokuSelector {
|
||||
|
||||
public final Signal onSelect = new Signal();
|
||||
private MultiDoku doku;
|
||||
|
||||
private final boolean canGenEmptyGrid;
|
||||
|
||||
private final ImInt sudokuType = new ImInt(0);
|
||||
|
||||
private final ImInt difficulty = new ImInt(Difficulty.Medium.ordinal());
|
||||
private final List<ImBoolean> contraints = new ArrayList<>();
|
||||
|
||||
private static final String[] sudokuTypes = { "Carré", "Rectangle", "Multidoku" };
|
||||
private static final int SQUARE = 0, RECTANGLE = 1, MULTIDOKU = 2;
|
||||
|
||||
private final ImInt sudokuSize = new ImInt(3);
|
||||
|
||||
private final ImInt sudokuWidth = new ImInt(3);
|
||||
private final ImInt sudokuHeight = new ImInt(3);
|
||||
|
||||
public SudokuSelector(boolean canGenEmptyGrid) {
|
||||
this.canGenEmptyGrid = canGenEmptyGrid;
|
||||
initConstraints();
|
||||
}
|
||||
|
||||
private List<Constraint> getConstraints() {
|
||||
List<Constraint> constraints = new ArrayList<>();
|
||||
for (int i = 0; i < this.contraints.size(); i++) {
|
||||
if (this.contraints.get(i).get())
|
||||
constraints.add(Constraint.values()[i]);
|
||||
}
|
||||
return constraints;
|
||||
}
|
||||
|
||||
private void initConstraints() {
|
||||
for (Constraint cons : Constraint.values()) {
|
||||
contraints.add(new ImBoolean(SudokuFactory.DEFAULT_CONSTRAINTS.contains(cons)));
|
||||
}
|
||||
}
|
||||
|
||||
private void selectSudoku(MultiDoku doku, boolean empty) {
|
||||
this.doku = doku;
|
||||
if (!empty) {
|
||||
try {
|
||||
SudokuFactory.fillDoku(doku, Difficulty.values()[difficulty.get()]);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
this.onSelect.emit();
|
||||
}
|
||||
|
||||
public void renderFileDialog() {
|
||||
if (ImGuiFileDialog.display("browse-sudoku", ImGuiFileDialogFlags.None)) {
|
||||
if (ImGuiFileDialog.isOk()) {
|
||||
var selection = ImGuiFileDialog.getSelection();
|
||||
for (var entry : selection.entrySet()) {
|
||||
try {
|
||||
String filePath = entry.getValue();
|
||||
this.doku = SudokuFactory.fromfile(filePath);
|
||||
if (this.doku != null)
|
||||
this.onSelect.emit();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGuiFileDialog.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void render() {
|
||||
ImGui.combo("Type de Sudoku", sudokuType, sudokuTypes);
|
||||
ImGui.combo("Difficulté", difficulty, Difficulty.getDifficultyNames());
|
||||
if (ImGui.treeNode("Constraintes")) {
|
||||
for (Constraint cons : Constraint.values()) {
|
||||
ImGui.checkbox(cons.getDisplayName(), contraints.get(cons.ordinal()));
|
||||
}
|
||||
ImGui.treePop();
|
||||
}
|
||||
switch (sudokuType.get()) {
|
||||
case SQUARE:
|
||||
ImGui.inputInt("Taille", sudokuSize);
|
||||
if (ImGui.button("Résoudre un sudoku")) {
|
||||
selectSudoku(SudokuFactory.createBasicEmptySquareDoku(sudokuSize.get(), getConstraints()), false);
|
||||
}
|
||||
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
|
||||
selectSudoku(SudokuFactory.createBasicEmptySquareDoku(sudokuSize.get(), getConstraints()), true);
|
||||
}
|
||||
break;
|
||||
|
||||
case RECTANGLE:
|
||||
ImGui.inputInt("Largeur", sudokuHeight);
|
||||
ImGui.inputInt("Longueur", sudokuWidth);
|
||||
if (ImGui.button("Résoudre un sudoku")) {
|
||||
selectSudoku(
|
||||
SudokuFactory.createBasicEmptyRectangleDoku(sudokuWidth.get(), sudokuHeight.get(),
|
||||
getConstraints()),
|
||||
false);
|
||||
}
|
||||
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
|
||||
selectSudoku(
|
||||
SudokuFactory.createBasicEmptyRectangleDoku(sudokuWidth.get(), sudokuHeight.get(),
|
||||
getConstraints()),
|
||||
true);
|
||||
}
|
||||
break;
|
||||
|
||||
case MULTIDOKU:
|
||||
ImGui.inputInt("Taille", sudokuSize);
|
||||
if (ImGui.button("Résoudre un sudoku")) {
|
||||
selectSudoku(SudokuFactory.createBasicXShapedMultidoku(sudokuSize.get(), getConstraints()), false);
|
||||
}
|
||||
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
|
||||
selectSudoku(SudokuFactory.createBasicXShapedMultidoku(sudokuSize.get(), getConstraints()), true);
|
||||
}
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (ImGui.button("À partir d'un fichier")) {
|
||||
ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", ".");
|
||||
}
|
||||
renderFileDialog();
|
||||
}
|
||||
|
||||
public MultiDoku getDoku() {
|
||||
return doku;
|
||||
}
|
||||
|
||||
}
|
||||
35
app/src/main/java/gui/constants/Fonts.java
Normal file
35
app/src/main/java/gui/constants/Fonts.java
Normal file
@@ -0,0 +1,35 @@
|
||||
package gui.constants;
|
||||
|
||||
import gui.AssetManager;
|
||||
import imgui.ImFont;
|
||||
import imgui.ImFontConfig;
|
||||
import imgui.ImFontGlyphRangesBuilder;
|
||||
import imgui.ImGui;
|
||||
|
||||
public class Fonts {
|
||||
|
||||
public static ImFont ARIAL;
|
||||
public static ImFont ARIAL_BOLD;
|
||||
public static ImFont CHERI;
|
||||
public static ImFont COMIC;
|
||||
public static ImFont INFECTED;
|
||||
public static ImFont EMOJIS;
|
||||
|
||||
private static final String baseDir = "";
|
||||
|
||||
public static void createFonts() {
|
||||
ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder();
|
||||
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesDefault());
|
||||
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesCyrillic());
|
||||
|
||||
ImFontConfig cfg = new ImFontConfig();
|
||||
cfg.setGlyphRanges(builder.buildRanges());
|
||||
|
||||
COMIC = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("comic.ttf"), 50.0f);
|
||||
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("arial_bold.ttf"), 50.0f);
|
||||
ARIAL = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("arial.ttf"), 50.0f, cfg);
|
||||
CHERI = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("cheri.ttf"), 50.0f);
|
||||
INFECTED = ImGui.getIO().getFonts().addFontFromMemoryTTF(AssetManager.getResource("INFECTED.ttf"), 50.0f);
|
||||
}
|
||||
|
||||
}
|
||||
44
app/src/main/java/gui/constants/Images.java
Normal file
44
app/src/main/java/gui/constants/Images.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package gui.constants;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
import org.lwjgl.opengl.GL11;
|
||||
import org.lwjgl.stb.STBImage;
|
||||
|
||||
import gui.AssetManager;
|
||||
|
||||
public class Images {
|
||||
|
||||
public static int BACKGROUND;
|
||||
|
||||
private static int loadTexture(byte[] imageData) {
|
||||
int[] width = new int[1];
|
||||
int[] height = new int[1];
|
||||
int[] channelCount = new int[1];
|
||||
|
||||
ByteBuffer img = ByteBuffer.allocateDirect(imageData.length);
|
||||
img.put(imageData);
|
||||
img.flip();
|
||||
ByteBuffer pixels = STBImage.stbi_load_from_memory(img, width, height, channelCount, 4);
|
||||
|
||||
int textureID = GL11.glGenTextures();
|
||||
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
|
||||
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
|
||||
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
|
||||
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); // Not on WebGL/ES
|
||||
GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0); // Not on WebGL/ES
|
||||
GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0); // Not on WebGL/ES
|
||||
GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); // Not on WebGL/ES
|
||||
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width[0], height[0], 0,
|
||||
GL11.GL_RGBA,
|
||||
GL11.GL_UNSIGNED_BYTE, pixels);
|
||||
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
|
||||
|
||||
return textureID;
|
||||
}
|
||||
|
||||
public static void reloadImages() {
|
||||
BACKGROUND = loadTexture(AssetManager.getResource(Options.BackgroundPath));
|
||||
}
|
||||
|
||||
}
|
||||
9
app/src/main/java/gui/constants/Options.java
Normal file
9
app/src/main/java/gui/constants/Options.java
Normal file
@@ -0,0 +1,9 @@
|
||||
package gui.constants;
|
||||
|
||||
public class Options {
|
||||
|
||||
public static Symbols Symboles = Symbols.Numbers;
|
||||
public static float BackgroundSpeed = 1.0f;
|
||||
public static String BackgroundPath = "background.png";
|
||||
|
||||
}
|
||||
63
app/src/main/java/gui/constants/SudokuType.java
Normal file
63
app/src/main/java/gui/constants/SudokuType.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package gui.constants;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import sudoku.constraint.IConstraint;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.SudokuFactory;;
|
||||
|
||||
public enum SudokuType {
|
||||
|
||||
Square("Carré", 1,
|
||||
(constraints, params) -> SudokuFactory.createBasicEmptySquareDoku(params[0], constraints)),
|
||||
Rectangle("Rectangle", 2,
|
||||
(constraints, params) -> SudokuFactory.createBasicEmptyRectangleDoku(params[0], params[1], constraints)),
|
||||
RandomBloc("Blocs aléatoires", 1,
|
||||
(constraints, params) -> SudokuFactory.createBasicEmptyRandomBlockDoku(params[0], constraints)),
|
||||
MultiDokuSquare("Multidoku carré (X)", 1,
|
||||
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], constraints)),
|
||||
MultidokuRectangle("Multidoku rectangle (X)", 2,
|
||||
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], params[1], constraints));
|
||||
|
||||
String displayName;
|
||||
SudokuMaker maker;
|
||||
int paramCount;
|
||||
|
||||
private SudokuType(String displayName, int paramCount, SudokuMaker maker) {
|
||||
this.displayName = displayName;
|
||||
this.maker = maker;
|
||||
this.paramCount = paramCount;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return this.displayName;
|
||||
}
|
||||
|
||||
public MultiDoku createDoku(List<IConstraint> constraints, int... params) {
|
||||
return maker.makeSudoku(constraints, params);
|
||||
}
|
||||
|
||||
public int getMakerParamCount() {
|
||||
return this.paramCount;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private static interface SudokuMaker {
|
||||
MultiDoku makeSudoku(List<IConstraint> constraints, int... params);
|
||||
}
|
||||
|
||||
private static final String[] dokuNames;
|
||||
|
||||
static {
|
||||
SudokuType[] types = SudokuType.values();
|
||||
dokuNames = new String[types.length];
|
||||
for (int i = 0; i < types.length; i++) {
|
||||
dokuNames[i] = types[i].getDisplayName();
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] getTypeNames() {
|
||||
return dokuNames;
|
||||
}
|
||||
|
||||
}
|
||||
83
app/src/main/java/gui/constants/Symbols.java
Normal file
83
app/src/main/java/gui/constants/Symbols.java
Normal file
@@ -0,0 +1,83 @@
|
||||
package gui.constants;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public enum Symbols {
|
||||
|
||||
Numbers("Nombres", getNumbers()),
|
||||
Letters("Lettres", getLetters()),
|
||||
Russian("Cyrilique", getRussian()),
|
||||
Emojis("Emojis (Console uniquement)", getEmojis());
|
||||
|
||||
String displayName;
|
||||
List<String> symbols;
|
||||
|
||||
private Symbols(String displayName, List<String> symbols) {
|
||||
this.symbols = symbols;
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public List<String> getSymbols() {
|
||||
return symbols;
|
||||
}
|
||||
|
||||
private static List<String> getNumbers() {
|
||||
List<String> sym = new ArrayList<>();
|
||||
for (int i = 1; i <= 100; i++) {
|
||||
sym.add(Integer.toString(i));
|
||||
}
|
||||
return sym;
|
||||
}
|
||||
|
||||
private static List<String> getLetters() {
|
||||
List<String> sym = new ArrayList<>();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
int currentOffset = i;
|
||||
String letter = "";
|
||||
while (currentOffset >= 26) {
|
||||
letter += Character.toString((char) ('A' + currentOffset % 26));
|
||||
currentOffset /= 26;
|
||||
currentOffset--;
|
||||
}
|
||||
letter += Character.toString((char) ('A' + currentOffset % 26));
|
||||
sym.add(new StringBuilder(letter).reverse().toString());
|
||||
}
|
||||
return sym;
|
||||
}
|
||||
|
||||
private static List<String> getRussian() {
|
||||
List<String> sym = new ArrayList<>();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
sym.add(new String(Character.toChars(0X0400 + i)));
|
||||
}
|
||||
return sym;
|
||||
}
|
||||
|
||||
private static List<String> getEmojis() {
|
||||
List<String> sym = new ArrayList<>();
|
||||
for (int i = 0; i < 100; i++) {
|
||||
sym.add(new String(Character.toChars(0X1F600 + i)));
|
||||
}
|
||||
return sym;
|
||||
}
|
||||
|
||||
private static final String[] symbolNames;
|
||||
|
||||
static {
|
||||
Symbols[] symbols = Symbols.values();
|
||||
symbolNames = new String[symbols.length];
|
||||
for (int i = 0; i < symbols.length; i++) {
|
||||
symbolNames[i] = symbols[i].getDisplayName();
|
||||
}
|
||||
}
|
||||
|
||||
public static String[] getSymbolsNames() {
|
||||
return symbolNames;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -14,12 +14,12 @@ public class ConnexionStatusView extends BaseView {
|
||||
|
||||
private String displayText = "Connecting ...";
|
||||
|
||||
public ConnexionStatusView(StateMachine stateMachine, String address, short port)
|
||||
public ConnexionStatusView(StateMachine stateMachine, String pseudo, String address, short port)
|
||||
throws UnknownHostException, IOException {
|
||||
super(stateMachine);
|
||||
Thread t = new Thread(() -> {
|
||||
try {
|
||||
this.client = new Client(address, port);
|
||||
this.client = new Client(pseudo, address, port);
|
||||
bindListeners();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
@@ -29,12 +29,13 @@ public class ConnexionStatusView extends BaseView {
|
||||
t.start();
|
||||
}
|
||||
|
||||
public ConnexionStatusView(StateMachine stateMachine, short port) throws UnknownHostException, IOException {
|
||||
public ConnexionStatusView(StateMachine stateMachine, String pseudo, short port)
|
||||
throws UnknownHostException, IOException {
|
||||
super(stateMachine);
|
||||
Thread t = new Thread(() -> {
|
||||
try {
|
||||
this.server = new Server(port);
|
||||
this.client = new Client("localhost", port);
|
||||
this.client = new Client(pseudo, "localhost", port);
|
||||
bindListeners();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
|
||||
49
app/src/main/java/gui/menu/EndGameView.java
Normal file
49
app/src/main/java/gui/menu/EndGameView.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package gui.menu;
|
||||
|
||||
import game.Player;
|
||||
import gui.ColorGenerator;
|
||||
import gui.widget.SudokuRenderer;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec4;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class EndGameView extends BaseView {
|
||||
|
||||
private final Player winner;
|
||||
private float time = 0;
|
||||
|
||||
private static final ImVec4 YELLOW = new ImVec4(1, 1, 0, 1);
|
||||
|
||||
private final SudokuRenderer sudokuRenderer;
|
||||
|
||||
public EndGameView(StateMachine stateMachine, MultiDoku resolved, Player winner) {
|
||||
super(stateMachine);
|
||||
this.winner = winner;
|
||||
this.sudokuRenderer = new SudokuRenderer(resolved);
|
||||
}
|
||||
|
||||
private ImVec4 getPseudoColor() {
|
||||
time += ImGui.getIO().getDeltaTime();
|
||||
float factor = (float) Math.cos(time);
|
||||
var color = ColorGenerator.hslToRgb(factor * factor, 0.9f, 0.4f);
|
||||
return new ImVec4(color.r, color.g, color.b, 1.0f);
|
||||
}
|
||||
|
||||
private void renderWinText() {
|
||||
String winText = " a gagné !";
|
||||
String text = winner.getPseudo() + winText;
|
||||
float textWidth = ImGui.calcTextSizeX(text);
|
||||
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - textWidth / 2.0f);
|
||||
ImGui.textColored(getPseudoColor(), winner.getPseudo());
|
||||
ImGui.sameLine();
|
||||
ImGui.textColored(YELLOW, winText);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
renderWinText();
|
||||
this.sudokuRenderer.render();
|
||||
renderReturnButton();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package gui.menu;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Random;
|
||||
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
@@ -11,6 +12,7 @@ public class MultiMenu extends BaseView {
|
||||
|
||||
private final ImInt port = new ImInt(25565);
|
||||
private final ImString address = new ImString("localhost");
|
||||
private final ImString pseudo = new ImString("Joueur" + new Random().nextInt());
|
||||
|
||||
public MultiMenu(StateMachine stateMachine) {
|
||||
super(stateMachine);
|
||||
@@ -20,10 +22,12 @@ public class MultiMenu extends BaseView {
|
||||
private void renderCreate() {
|
||||
ImVec2 displaySize = ImGui.getIO().getDisplaySize();
|
||||
ImGui.beginChild("##CreateGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f));
|
||||
ImGui.inputInt("Port", port);
|
||||
if (ImGui.inputInt("Port", port))
|
||||
port.set(Math.clamp(port.get(), 1, 65535));
|
||||
ImGui.inputText("Pseudo", pseudo);
|
||||
if (ImGui.button("Créer")) {
|
||||
try {
|
||||
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, (short) port.get()));
|
||||
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, pseudo.get(), (short) port.get()));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
@@ -35,12 +39,13 @@ public class MultiMenu extends BaseView {
|
||||
ImVec2 displaySize = ImGui.getIO().getDisplaySize();
|
||||
ImGui.beginChild("##JoinGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f));
|
||||
ImGui.inputText("Adresse", address);
|
||||
ImGui.inputInt("Port", port);
|
||||
if (ImGui.inputInt("Port", port))
|
||||
port.set(Math.clamp(port.get(), 1, 65535));
|
||||
ImGui.inputText("Pseudo", pseudo);
|
||||
if (ImGui.button("Rejoindre")) {
|
||||
try {
|
||||
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, address.get(), (short) port.get()));
|
||||
} catch (IOException e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,50 @@
|
||||
package gui.menu;
|
||||
|
||||
import gui.SudokuRenderer;
|
||||
import game.Player;
|
||||
import gui.widget.LeaderboardRenderer;
|
||||
import gui.widget.MultiPlayerCompleteProgress;
|
||||
import gui.widget.SudokuRenderer;
|
||||
import gui.widget.TimerRenderer;
|
||||
import imgui.ImGui;
|
||||
import network.client.Client;
|
||||
import network.server.Server;
|
||||
import sudoku.solver.BacktrackingSolver;
|
||||
import sudoku.solver.Solver;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class MultiPlayerDokuView extends BaseView{
|
||||
public class MultiPlayerDokuView extends BaseView {
|
||||
|
||||
private final Client client;
|
||||
private final Server server;
|
||||
private final SudokuRenderer sudokuRenderer;
|
||||
private final LeaderboardRenderer leaderboardRenderer;
|
||||
private final TimerRenderer timerRenderer;
|
||||
private final MultiPlayerCompleteProgress completeProgress;
|
||||
|
||||
public MultiPlayerDokuView(StateMachine stateMachine, Client client, Server server) {
|
||||
super(stateMachine);
|
||||
this.client = client;
|
||||
this.server = server;
|
||||
this.sudokuRenderer = new SudokuRenderer(this.client.getGame().getDoku());
|
||||
this.leaderboardRenderer = new LeaderboardRenderer(client.getGame(), client.getPlayer());
|
||||
this.sudokuRenderer.onCellChange.connect(this::onCellChange);
|
||||
this.client.onDisconnect.connect(this::onDisconnect);
|
||||
this.client.onGameEnd.connect(this::onGameEnd);
|
||||
this.timerRenderer = new TimerRenderer(this.client.getGame().getStartTime(), this.client.getGame().getGameDuration());
|
||||
this.completeProgress = new MultiPlayerCompleteProgress(this.client.getGame());
|
||||
}
|
||||
|
||||
private void onGameEnd(Player winner) {
|
||||
MultiDoku doku = this.client.getGame().getDoku();
|
||||
doku.clearMutableCells();
|
||||
Solver solver = new BacktrackingSolver();
|
||||
solver.solve(doku);
|
||||
this.stateMachine.overrideState(new EndGameView(stateMachine, doku, winner));
|
||||
}
|
||||
|
||||
private void onCellChange(Cell cell) {
|
||||
this.client.sendCellChange(cell);
|
||||
}
|
||||
|
||||
public void onDisconnect() {
|
||||
@@ -27,6 +55,9 @@ public class MultiPlayerDokuView extends BaseView{
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
this.timerRenderer.render();
|
||||
this.leaderboardRenderer.render();
|
||||
this.completeProgress.render();
|
||||
this.sudokuRenderer.render();
|
||||
if (ImGui.button("Quitter")) {
|
||||
this.client.stop();
|
||||
|
||||
@@ -1,24 +1,30 @@
|
||||
package gui.menu;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
import game.Player;
|
||||
import gui.widget.SudokuSelector;
|
||||
import imgui.ImGui;
|
||||
import imgui.type.ImInt;
|
||||
import network.client.Client;
|
||||
import network.server.Server;
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
public class MultiPlayerView extends BaseView {
|
||||
|
||||
private final Client client;
|
||||
private final Server server;
|
||||
|
||||
private final SudokuSelector selector;
|
||||
|
||||
private ImInt gameDurationMinutes = new ImInt(10);
|
||||
|
||||
private MultiDoku doku = null;
|
||||
|
||||
public MultiPlayerView(StateMachine stateMachine, Client client, Server server) {
|
||||
super(stateMachine);
|
||||
this.client = client;
|
||||
this.server = server;
|
||||
this.selector = new SudokuSelector(false, "Sélectionner le sudoku");
|
||||
this.selector.onSelect.connect(this::onSelected);
|
||||
this.client.onDisconnect.connect(this::onDisconnect);
|
||||
this.client.onGameStarted
|
||||
.connect(() -> this.stateMachine.pushState(new MultiPlayerDokuView(stateMachine, client, server)));
|
||||
@@ -34,27 +40,47 @@ public class MultiPlayerView extends BaseView {
|
||||
this.stateMachine.popState();
|
||||
}
|
||||
|
||||
private void onSelected(MultiDoku doku) {
|
||||
this.doku = doku;
|
||||
}
|
||||
|
||||
public void renderGameStatus() {
|
||||
if (this.server == null) {
|
||||
ImGui.text("En attente de l'administrateur du serveur ...");
|
||||
} else {
|
||||
renderTimer();
|
||||
ImGui.beginDisabled(this.doku == null);
|
||||
if (ImGui.button("Démarrer")) {
|
||||
// temp
|
||||
MultiDoku doku = SudokuFactory.createBasicXShapedMultidoku(3, Arrays.asList(Constraint.Diagonal));
|
||||
this.server.startGame(doku);
|
||||
this.server.startGame(this.doku, this.gameDurationMinutes.get() * 60);
|
||||
}
|
||||
ImGui.endDisabled();
|
||||
selector.render();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
private void renderPlayers() {
|
||||
ImGui.text("Joueurs :");
|
||||
{
|
||||
for (Player player : this.client.getGame().getPlayers().values()) {
|
||||
ImGui.bulletText(player.getPseudo());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void renderTimer() {
|
||||
if (ImGui.inputInt("Temps de la partie (minutes)", gameDurationMinutes))
|
||||
gameDurationMinutes.set(Math.clamp(gameDurationMinutes.get(), 1, 90));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
renderPlayers();
|
||||
renderGameStatus();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cleanResources() {
|
||||
this.selector.clean();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,17 +1,56 @@
|
||||
package gui.menu;
|
||||
|
||||
import gui.constants.Images;
|
||||
import gui.constants.Options;
|
||||
import gui.constants.Symbols;
|
||||
import imgui.ImGui;
|
||||
import imgui.extension.imguifiledialog.ImGuiFileDialog;
|
||||
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
|
||||
import imgui.type.ImInt;
|
||||
|
||||
public class OptionsMenu extends BaseView {
|
||||
|
||||
private ImInt currentValue = new ImInt();
|
||||
private float backgroundSpeed[] = new float[] { Options.BackgroundSpeed };
|
||||
|
||||
public OptionsMenu(StateMachine stateMachine) {
|
||||
super(stateMachine);
|
||||
}
|
||||
|
||||
private void renderImageSelectDialog() {
|
||||
if (ImGuiFileDialog.display("browse-img", ImGuiFileDialogFlags.None)) {
|
||||
if (ImGuiFileDialog.isOk()) {
|
||||
var selection = ImGuiFileDialog.getSelection();
|
||||
for (var entry : selection.entrySet()) {
|
||||
try {
|
||||
String filePath = entry.getValue();
|
||||
Options.BackgroundPath = filePath;
|
||||
Images.reloadImages();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGuiFileDialog.close();
|
||||
}
|
||||
}
|
||||
|
||||
private void renderImageSelectButton() {
|
||||
if (ImGui.button("Changer de fond d'écran"))
|
||||
ImGuiFileDialog.openDialog("browse-img", "Choisissez un fichier", ".png,.jpg,.jpeg", ".");
|
||||
renderImageSelectDialog();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
// TODO Auto-generated method stub
|
||||
ImGui.text("Options");
|
||||
if (ImGui.combo("Jeu de symboles", currentValue, Symbols.getSymbolsNames())) {
|
||||
Options.Symboles = Symbols.values()[currentValue.get()];
|
||||
}
|
||||
if (ImGui.sliderFloat("Vitesse d'animation de l'arrière plan", backgroundSpeed, 0.0f, 10.0f)) {
|
||||
Options.BackgroundSpeed = backgroundSpeed[0];
|
||||
}
|
||||
renderImageSelectButton();
|
||||
renderReturnButton();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package gui.menu;
|
||||
|
||||
import gui.SudokuSelector;
|
||||
import gui.widget.SudokuSelector;
|
||||
import imgui.ImGui;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class SoloMenu extends BaseView {
|
||||
|
||||
@@ -9,12 +10,12 @@ public class SoloMenu extends BaseView {
|
||||
|
||||
public SoloMenu(StateMachine stateMachine) {
|
||||
super(stateMachine);
|
||||
this.sudokuSelector = new SudokuSelector(true);
|
||||
this.sudokuSelector = new SudokuSelector(true, "Résoudre le sudoku");
|
||||
this.sudokuSelector.onSelect.connect(this::pushSudokuState);
|
||||
}
|
||||
|
||||
private void pushSudokuState() {
|
||||
this.stateMachine.pushState(new SudokuView(stateMachine, this.sudokuSelector.getDoku()));
|
||||
private void pushSudokuState(MultiDoku doku) {
|
||||
this.stateMachine.pushState(new SudokuView(stateMachine, doku));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -24,4 +25,9 @@ public class SoloMenu extends BaseView {
|
||||
renderReturnButton();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cleanResources() {
|
||||
this.sudokuSelector.clean();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package gui.menu;
|
||||
|
||||
import java.util.Stack;
|
||||
|
||||
import gui.widget.AnimatedBackground;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
import imgui.flag.ImGuiKey;
|
||||
@@ -10,9 +11,11 @@ import imgui.flag.ImGuiWindowFlags;
|
||||
public class StateMachine {
|
||||
|
||||
private final Stack<BaseView> menus;
|
||||
private final AnimatedBackground background;
|
||||
|
||||
public StateMachine() {
|
||||
this.menus = new Stack<>();
|
||||
this.background = new AnimatedBackground();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
@@ -26,6 +29,11 @@ public class StateMachine {
|
||||
menus.add(menu);
|
||||
}
|
||||
|
||||
public void overrideState(BaseView menu) {
|
||||
menus.getLast().cleanResources();
|
||||
menus.set(menus.size() - 1, menu);
|
||||
}
|
||||
|
||||
public void popState() {
|
||||
menus.getLast().cleanResources();
|
||||
menus.pop();
|
||||
@@ -39,6 +47,7 @@ public class StateMachine {
|
||||
|
||||
public void render() {
|
||||
var displaySize = ImGui.getIO().getDisplaySize();
|
||||
this.background.render();
|
||||
ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f));
|
||||
ImGui.setNextWindowSize(displaySize);
|
||||
ImGui.begin("##Main Window", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
package gui.menu;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
||||
import gui.SudokuRenderer;
|
||||
import gui.widget.SudokuRenderer;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImGuiStyle;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.solver.BacktrackingSolver;
|
||||
import sudoku.solver.HintHelper;
|
||||
import sudoku.solver.HumanSolver;
|
||||
import sudoku.solver.MixedSolver;
|
||||
import sudoku.solver.Solver;
|
||||
import sudoku.solver.SolverStep;
|
||||
import sudoku.solver.HintHelper.Hint;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class SudokuView extends BaseView {
|
||||
@@ -18,6 +25,8 @@ public class SudokuView extends BaseView {
|
||||
private String lastSavePath = null;
|
||||
|
||||
private boolean resolved = false;
|
||||
// if the solver can't solve
|
||||
private volatile boolean unresolved = false;
|
||||
|
||||
public SudokuView(StateMachine stateMachine, MultiDoku doku) {
|
||||
super(stateMachine);
|
||||
@@ -66,34 +75,73 @@ public class SudokuView extends BaseView {
|
||||
stopResolve();
|
||||
}
|
||||
|
||||
private void renderHintButton() {
|
||||
if (!this.resolved && centeredButton("Indice")) {
|
||||
Hint hint = HintHelper.getHint(this.doku, new BacktrackingSolver());
|
||||
assert (hint != null);
|
||||
hint.cell().setSymbolIndex(hint.newValue());
|
||||
if (this.doku.isSolved())
|
||||
this.sudokuRenderer.onResolve.emit();
|
||||
}
|
||||
}
|
||||
|
||||
private void renderUnsolvableText() {
|
||||
if (this.unresolved)
|
||||
ImGui.text("Impossible de résoudre avec l'algorithme actuel !");
|
||||
|
||||
}
|
||||
|
||||
private void startSolve(Solver solver) {
|
||||
this.doku.clearMutableCells();
|
||||
resolveThread = new Thread(() -> {
|
||||
List<SolverStep> steps = new ArrayList<>();
|
||||
try {
|
||||
unresolved = !solver.solve(this.doku, steps);
|
||||
} catch (CancellationException e) {
|
||||
System.out.println("The user is bored !");
|
||||
}
|
||||
stopResolve();
|
||||
});
|
||||
}
|
||||
|
||||
private void renderResolvedText() {
|
||||
if (this.resolved)
|
||||
ImGui.text("Bravo !");
|
||||
}
|
||||
|
||||
private void renderSolvePopup() {
|
||||
if (ImGui.beginPopup("solve")) {
|
||||
if (ImGui.button("Résoudre avec backtrace")) {
|
||||
startSolve(new BacktrackingSolver());
|
||||
ImGui.closeCurrentPopup();
|
||||
}
|
||||
if (ImGui.button("Résoudre avec déduction")) {
|
||||
startSolve(new HumanSolver());
|
||||
ImGui.closeCurrentPopup();
|
||||
}
|
||||
if (ImGui.button("Résoudre avec déduction et backtrace")) {
|
||||
startSolve(new MixedSolver());
|
||||
ImGui.closeCurrentPopup();
|
||||
}
|
||||
ImGui.endPopup();
|
||||
}
|
||||
}
|
||||
|
||||
private void renderSolveButton() {
|
||||
if (resolveThread != null)
|
||||
ImGui.beginDisabled();
|
||||
|
||||
boolean beginSolve = false;
|
||||
|
||||
if (!resolved && centeredButton("Résoudre")) {
|
||||
beginSolve = true;
|
||||
if (!this.resolved && centeredButton("Résoudre")) {
|
||||
ImGui.openPopup("solve");
|
||||
}
|
||||
|
||||
if (resolveThread != null)
|
||||
ImGui.endDisabled();
|
||||
|
||||
if (beginSolve) {
|
||||
resolveThread = new Thread(() -> {
|
||||
try {
|
||||
Random rand = new Random();
|
||||
Solver.solveRandom(doku, rand);
|
||||
Thread.sleep(200);
|
||||
} catch (CancellationException | InterruptedException e) {
|
||||
System.out.println("The user is bored !");
|
||||
}
|
||||
stopResolve();
|
||||
});
|
||||
}
|
||||
renderResolvedText();
|
||||
renderUnsolvableText();
|
||||
|
||||
if (resolved) {
|
||||
ImGui.text("Bravo !");
|
||||
}
|
||||
renderSolvePopup();
|
||||
}
|
||||
|
||||
private void renderSaveButton() {
|
||||
@@ -108,9 +156,19 @@ public class SudokuView extends BaseView {
|
||||
}
|
||||
}
|
||||
|
||||
private void renderClearButton() {
|
||||
if (centeredButton("Effacer")) {
|
||||
this.doku.clearMutableCells();
|
||||
this.resolved = false;
|
||||
this.unresolved = false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void render() {
|
||||
sudokuRenderer.render();
|
||||
renderHintButton();
|
||||
renderClearButton();
|
||||
renderSolveButton();
|
||||
renderSaveButton();
|
||||
renderCancelButton();
|
||||
|
||||
32
app/src/main/java/gui/widget/AnimatedBackground.java
Normal file
32
app/src/main/java/gui/widget/AnimatedBackground.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package gui.widget;
|
||||
|
||||
import gui.constants.Images;
|
||||
import gui.constants.Options;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
import imgui.flag.ImGuiWindowFlags;
|
||||
|
||||
public class AnimatedBackground {
|
||||
|
||||
private float backgroundOffset = 0;
|
||||
|
||||
private static final float defaultSpeed = 0.05f;
|
||||
|
||||
public AnimatedBackground() {
|
||||
|
||||
}
|
||||
|
||||
public void render() {
|
||||
backgroundOffset += ImGui.getIO().getDeltaTime() * defaultSpeed * Options.BackgroundSpeed;
|
||||
var displaySize = ImGui.getIO().getDisplaySize();
|
||||
ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f));
|
||||
ImGui.setNextWindowSize(displaySize);
|
||||
ImGui.begin("Background", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove
|
||||
| ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoBackground
|
||||
| ImGuiWindowFlags.NoBringToFrontOnFocus | ImGuiWindowFlags.NoInputs);
|
||||
ImGui.image(Images.BACKGROUND, displaySize, new ImVec2(backgroundOffset, backgroundOffset),
|
||||
new ImVec2(1.0f + backgroundOffset, 1.0f + backgroundOffset));
|
||||
ImGui.end();
|
||||
}
|
||||
|
||||
}
|
||||
73
app/src/main/java/gui/widget/LeaderboardRenderer.java
Normal file
73
app/src/main/java/gui/widget/LeaderboardRenderer.java
Normal file
@@ -0,0 +1,73 @@
|
||||
package gui.widget;
|
||||
|
||||
import game.Game;
|
||||
import game.Player;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
import imgui.ImVec4;
|
||||
import imgui.flag.ImGuiCol;
|
||||
import imgui.flag.ImGuiStyleVar;
|
||||
|
||||
public class LeaderboardRenderer {
|
||||
|
||||
private final Game game;
|
||||
private final Player currentPlayer;
|
||||
|
||||
private final float cellHeight = 75;
|
||||
private final ImVec2 cellSize = new ImVec2(12 * cellHeight, cellHeight);
|
||||
private final ImVec2 rankSize = new ImVec2(cellHeight, cellHeight);
|
||||
private final ImVec2 scoreSize = rankSize;
|
||||
private final ImVec2 nameSize = new ImVec2(cellSize.x - cellHeight * 2.0f, cellHeight);
|
||||
private final ImVec4 cellColorPlayer = new ImVec4(0.20f, 0.67f, 1.0f, 0.5f);
|
||||
private final ImVec4 cellColorEnemy = new ImVec4(1.0f, 0.0f, 0.0f, 0.5f);
|
||||
private final int maxPlayersShowed = 2;
|
||||
|
||||
private final int emptyCellCount;
|
||||
|
||||
public LeaderboardRenderer(Game game, Player player) {
|
||||
this.game = game;
|
||||
this.currentPlayer = player;
|
||||
this.emptyCellCount = game.getDoku().getEmptyCells().size();
|
||||
}
|
||||
|
||||
private void renderRank(int rank) {
|
||||
ImGui.button(Integer.toString(rank), rankSize);
|
||||
}
|
||||
|
||||
private void renderName(String name) {
|
||||
ImGui.button(name, nameSize);
|
||||
}
|
||||
|
||||
private void renderScore(int score) {
|
||||
ImGui.button(Integer.toString(score), scoreSize);
|
||||
}
|
||||
|
||||
private void renderCell(Player player, int rank, ImVec4 color) {
|
||||
ImGui.pushStyleColor(ImGuiCol.Button, color);
|
||||
ImGui.pushStyleColor(ImGuiCol.ButtonHovered, color);
|
||||
ImGui.pushStyleColor(ImGuiCol.ButtonActive, color);
|
||||
ImGui.beginChild(player.getPseudo() + "##" + player.getId(), cellSize);
|
||||
renderRank(rank);
|
||||
ImGui.sameLine();
|
||||
renderName(player.getPseudo());
|
||||
ImGui.sameLine();
|
||||
renderScore(emptyCellCount - player.getRemainingCells());
|
||||
ImGui.endChild();
|
||||
ImGui.popStyleColor(3);
|
||||
}
|
||||
|
||||
public void render() {
|
||||
var displaySize = ImGui.getIO().getDisplaySize();
|
||||
ImGui.setCursorPosX(displaySize.x / 2.0f - cellSize.x / 2.0f);
|
||||
ImGui.beginChild("Leaderboard", new ImVec2(cellSize.x + 15.0f, cellHeight * maxPlayersShowed));
|
||||
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2());
|
||||
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 3.0f);
|
||||
for (int i = 0; i < game.getLeaderboard().size(); i++) {
|
||||
Player player = game.getLeaderboard().get(i);
|
||||
renderCell(player, i + 1, player == currentPlayer ? cellColorPlayer : cellColorEnemy);
|
||||
}
|
||||
ImGui.popStyleVar(2);
|
||||
ImGui.endChild();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package gui.widget;
|
||||
|
||||
import game.Game;
|
||||
import game.Player;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
|
||||
public class MultiPlayerCompleteProgress {
|
||||
|
||||
private final Game game;
|
||||
private final int emptyCellCount;
|
||||
private final ImVec2 progressSize = new ImVec2(700, 50);
|
||||
private final SmoothProgressBar progressBar;
|
||||
|
||||
public MultiPlayerCompleteProgress(Game game) {
|
||||
this.game = game;
|
||||
this.emptyCellCount = game.getDoku().getEmptyCells().size();
|
||||
this.progressBar = new SmoothProgressBar();
|
||||
}
|
||||
|
||||
public void render() {
|
||||
Player firstPlayer = game.getLeaderboard().getFirst();
|
||||
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - progressSize.x / 2.0f);
|
||||
String progressText = firstPlayer.getPseudo() + " - " + (emptyCellCount - firstPlayer.getRemainingCells()) + "/" + emptyCellCount;
|
||||
this.progressBar.render(progressText, progressSize, 1.0f - firstPlayer.getRemainingCells() / (float) emptyCellCount);
|
||||
}
|
||||
|
||||
}
|
||||
30
app/src/main/java/gui/widget/SmoothProgressBar.java
Normal file
30
app/src/main/java/gui/widget/SmoothProgressBar.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package gui.widget;
|
||||
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
|
||||
public class SmoothProgressBar {
|
||||
|
||||
private float lastProgress = 0;
|
||||
private final float speed = 2.0f;
|
||||
private final float clipConstant = 0.001f;
|
||||
|
||||
private void updateProgress(float newProgress) {
|
||||
float delta = newProgress - lastProgress;
|
||||
if (Math.abs(delta) < clipConstant)
|
||||
lastProgress = newProgress;
|
||||
else
|
||||
lastProgress = lastProgress + delta * ImGui.getIO().getDeltaTime() * speed;
|
||||
}
|
||||
|
||||
public void render(String label, ImVec2 size, float progress) {
|
||||
updateProgress(progress);
|
||||
ImGui.progressBar(lastProgress, size, label);
|
||||
}
|
||||
|
||||
public void render(float progress) {
|
||||
updateProgress(progress);
|
||||
ImGui.progressBar(lastProgress);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package gui;
|
||||
package gui.widget;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
@@ -6,8 +6,14 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import common.ConsumerSignal;
|
||||
import common.Signal;
|
||||
import gui.ColorGenerator;
|
||||
import gui.ColorGenerator.Color;
|
||||
import gui.RenderableMultidoku;
|
||||
import gui.constants.Fonts;
|
||||
import gui.constants.Options;
|
||||
import gui.constants.Symbols;
|
||||
import imgui.ImGui;
|
||||
import imgui.ImVec2;
|
||||
import imgui.ImVec4;
|
||||
@@ -33,6 +39,7 @@ public class SudokuRenderer {
|
||||
private final Set<Cell> diagonals = new HashSet<>();
|
||||
|
||||
public final Signal onResolve = new Signal();
|
||||
public final ConsumerSignal<Cell> onCellChange = new ConsumerSignal<>();
|
||||
|
||||
public SudokuRenderer(MultiDoku doku) {
|
||||
this.doku = RenderableMultidoku.fromMultidoku(doku);
|
||||
@@ -72,12 +79,14 @@ public class SudokuRenderer {
|
||||
if (currentCell.getSymbolIndex() == i) {
|
||||
if (ImGui.button("X", cellSize)) {
|
||||
currentCell.setSymbolIndex(Cell.NOSYMBOL);
|
||||
this.onCellChange.emit(currentCell);
|
||||
ImGui.closeCurrentPopup();
|
||||
}
|
||||
} else {
|
||||
if (ImGui.button(Integer.toString(i + 1), cellSize)) {
|
||||
this.doku.setCellValue(currentCell, i);
|
||||
if (this.doku.isResolved())
|
||||
if (ImGui.button(Options.Symboles.getSymbols().get(i), cellSize)) {
|
||||
currentCell.setSymbolIndex(i);
|
||||
this.onCellChange.emit(currentCell);
|
||||
if (this.doku.getDoku().isSolved())
|
||||
this.onResolve.emit();
|
||||
ImGui.closeCurrentPopup();
|
||||
}
|
||||
@@ -88,6 +97,9 @@ public class SudokuRenderer {
|
||||
}
|
||||
|
||||
public void render() {
|
||||
if (Options.Symboles == Symbols.Russian) {
|
||||
ImGui.pushFont(Fonts.ARIAL);
|
||||
}
|
||||
final float sudokuViewWidth = cellSize.x * doku.getWidth();
|
||||
final float displayWidth = ImGui.getIO().getDisplaySizeX();
|
||||
float offsetX = displayWidth / 2.0f - sudokuViewWidth / 2.0f;
|
||||
@@ -95,7 +107,7 @@ public class SudokuRenderer {
|
||||
if (offsetX > 0) {
|
||||
ImGui.setCursorPosX(offsetX);
|
||||
}
|
||||
ImGui.beginChild(1, new ImVec2(cellSize.x * doku.getWidth(), cellSize.y * doku.getHeight()));
|
||||
ImGui.beginChild("sudokuChild", new ImVec2(cellSize.x * doku.getWidth(), cellSize.y * doku.getHeight()));
|
||||
|
||||
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 2.0f);
|
||||
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2(0.0f, 0.0f));
|
||||
@@ -105,6 +117,7 @@ public class SudokuRenderer {
|
||||
ImGui.sameLine();
|
||||
int index = y * doku.getWidth() + x;
|
||||
Cell cell = doku.getCell(x, y);
|
||||
ImGui.beginDisabled(cell == null);
|
||||
if (cell == null) {
|
||||
ImGui.pushStyleColor(ImGuiCol.Border, TRANSPARENT);
|
||||
ImGui.pushStyleColor(ImGuiCol.Button, TRANSPARENT);
|
||||
@@ -123,18 +136,22 @@ public class SudokuRenderer {
|
||||
ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(blockColor.r, blockColor.g, blockColor.b, 1.0f));
|
||||
String cellText = "";
|
||||
if (symbol != -1)
|
||||
cellText += Integer.toString(symbol + 1);
|
||||
cellText += Options.Symboles.getSymbols().get(symbol);
|
||||
if (ImGui.button(cellText + "##" + index, cellSize) && cell.isMutable()) {
|
||||
ImGui.openPopup("editPopup");
|
||||
currentCell = cell;
|
||||
}
|
||||
}
|
||||
ImGui.endDisabled();
|
||||
ImGui.popStyleColor(2);
|
||||
}
|
||||
}
|
||||
ImGui.popStyleVar(2);
|
||||
renderPopup();
|
||||
ImGui.endChild();
|
||||
if (Options.Symboles == Symbols.Russian) {
|
||||
ImGui.popFont();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
170
app/src/main/java/gui/widget/SudokuSelector.java
Normal file
170
app/src/main/java/gui/widget/SudokuSelector.java
Normal file
@@ -0,0 +1,170 @@
|
||||
package gui.widget;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import common.ConsumerSignal;
|
||||
import gui.constants.SudokuType;
|
||||
import imgui.ImGui;
|
||||
import imgui.extension.imguifiledialog.ImGuiFileDialog;
|
||||
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
|
||||
import imgui.type.ImBoolean;
|
||||
import imgui.type.ImInt;
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.constraint.IConstraint;
|
||||
import sudoku.structure.Difficulty;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
public class SudokuSelector {
|
||||
|
||||
public final ConsumerSignal<MultiDoku> onSelect = new ConsumerSignal<>();
|
||||
private MultiDoku doku;
|
||||
|
||||
private final boolean canGenEmptyGrid;
|
||||
|
||||
private final ImInt sudokuType = new ImInt(0);
|
||||
|
||||
private final ImInt difficulty = new ImInt(Difficulty.Easy.ordinal());
|
||||
private final List<ImBoolean> contraints = new ArrayList<>();
|
||||
|
||||
private final ImInt sudokuSize = new ImInt(3);
|
||||
|
||||
private final ImInt sudokuWidth = new ImInt(3);
|
||||
private final ImInt sudokuHeight = new ImInt(3);
|
||||
|
||||
private final String confirmMessage;
|
||||
|
||||
private Thread genThread = null;
|
||||
|
||||
private final SmoothProgressBar genProgressBar;
|
||||
|
||||
public SudokuSelector(boolean canGenEmptyGrid, String confirmMessage) {
|
||||
this.canGenEmptyGrid = canGenEmptyGrid;
|
||||
this.confirmMessage = confirmMessage;
|
||||
initConstraints();
|
||||
this.genProgressBar = new SmoothProgressBar();
|
||||
}
|
||||
|
||||
private List<IConstraint> getConstraints() {
|
||||
List<IConstraint> constraints = new ArrayList<>();
|
||||
for (int i = 0; i < this.contraints.size(); i++) {
|
||||
if (this.contraints.get(i).get())
|
||||
constraints.add(Constraint.values()[i].getConstraint());
|
||||
}
|
||||
return constraints;
|
||||
}
|
||||
|
||||
private void initConstraints() {
|
||||
for (Constraint cons : Constraint.values()) {
|
||||
contraints.add(new ImBoolean(SudokuFactory.DEFAULT_CONSTRAINTS.contains(cons.getConstraint())));
|
||||
}
|
||||
}
|
||||
|
||||
private void stopGenThread() {
|
||||
if (this.genThread != null) {
|
||||
this.genThread.interrupt();
|
||||
this.genThread = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void renderGenProgress() {
|
||||
if (ImGui.beginPopup("genProgress")) {
|
||||
ImGui.text("Chargement de la grille ...");
|
||||
int filled = this.doku.getFilledCells().size();
|
||||
int total = this.doku.getCells().size();
|
||||
this.genProgressBar.render(filled / (float) total);
|
||||
ImGui.endPopup();
|
||||
} else {
|
||||
stopGenThread();
|
||||
}
|
||||
}
|
||||
|
||||
private void selectSudoku(MultiDoku doku, boolean empty) {
|
||||
this.doku = doku;
|
||||
ImGui.openPopup("genProgress");
|
||||
this.genThread = new Thread(() -> {
|
||||
try {
|
||||
if (!empty) {
|
||||
SudokuFactory.fillDoku(doku, Difficulty.values()[difficulty.get()]);
|
||||
}
|
||||
this.onSelect.emit(this.doku);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
});
|
||||
this.genThread.start();
|
||||
}
|
||||
|
||||
public void renderFileDialog() {
|
||||
if (ImGuiFileDialog.display("browse-sudoku", ImGuiFileDialogFlags.None)) {
|
||||
if (ImGuiFileDialog.isOk()) {
|
||||
var selection = ImGuiFileDialog.getSelection();
|
||||
for (var entry : selection.entrySet()) {
|
||||
try {
|
||||
String filePath = entry.getValue();
|
||||
this.doku = SudokuFactory.fromfile(filePath);
|
||||
if (this.doku != null)
|
||||
this.onSelect.emit(this.doku);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGuiFileDialog.close();
|
||||
}
|
||||
}
|
||||
|
||||
public void render() {
|
||||
ImGui.combo("Difficulté", difficulty, Difficulty.getDifficultyNames());
|
||||
if (ImGui.treeNode("Constraintes")) {
|
||||
for (Constraint cons : Constraint.values()) {
|
||||
ImGui.checkbox(cons.getDisplayName(), contraints.get(cons.ordinal()));
|
||||
}
|
||||
ImGui.treePop();
|
||||
}
|
||||
ImGui.combo("Type de Sudoku", sudokuType, SudokuType.getTypeNames());
|
||||
SudokuType currentType = SudokuType.values()[sudokuType.get()];
|
||||
switch (currentType.getMakerParamCount()) {
|
||||
case 1:
|
||||
if (ImGui.inputInt("Taille", sudokuSize))
|
||||
sudokuSize.set(Math.clamp(sudokuSize.get(), 1, 10));
|
||||
if (ImGui.button(confirmMessage)) {
|
||||
selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), false);
|
||||
}
|
||||
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
|
||||
selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), true);
|
||||
}
|
||||
break;
|
||||
|
||||
case 2:
|
||||
if (ImGui.inputInt("Longueur", sudokuWidth))
|
||||
sudokuWidth.set(Math.clamp(sudokuWidth.get(), 1, 10));
|
||||
if (ImGui.inputInt("Hauteur", sudokuHeight))
|
||||
sudokuHeight.set(Math.clamp(sudokuHeight.get(), 1, 10));
|
||||
if (ImGui.button(confirmMessage)) {
|
||||
selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()),
|
||||
false);
|
||||
}
|
||||
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
|
||||
selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()), true);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
assert (false);
|
||||
break;
|
||||
}
|
||||
|
||||
if (ImGui.button("À partir d'un fichier")) {
|
||||
ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", ".");
|
||||
}
|
||||
renderGenProgress();
|
||||
renderFileDialog();
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
stopGenThread();
|
||||
}
|
||||
|
||||
}
|
||||
29
app/src/main/java/gui/widget/TimerRenderer.java
Normal file
29
app/src/main/java/gui/widget/TimerRenderer.java
Normal file
@@ -0,0 +1,29 @@
|
||||
package gui.widget;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import imgui.ImGui;
|
||||
|
||||
public class TimerRenderer {
|
||||
|
||||
private final long endTime;
|
||||
|
||||
public TimerRenderer(Instant startTime, long duration) {
|
||||
this.endTime = startTime.getEpochSecond() + duration;
|
||||
}
|
||||
|
||||
private long getTimeRemaining() {
|
||||
long currentTime = Instant.now().getEpochSecond();
|
||||
return endTime - currentTime;
|
||||
}
|
||||
|
||||
public void render() {
|
||||
long seconds = getTimeRemaining();
|
||||
long minutes = seconds / 60;
|
||||
String text = String.format("%02d:%02d", minutes, seconds % 60);
|
||||
var textSize = ImGui.calcTextSize(text);
|
||||
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - textSize.x / 2.0f);
|
||||
ImGui.text(text);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -22,7 +22,7 @@ public class ConnexionThread extends Thread {
|
||||
// System.out.println(objectInputStream.available());
|
||||
Object o = objectInputStream.readObject();
|
||||
if (o instanceof Packet packet) {
|
||||
connexion.visitPacket(packet);
|
||||
connexion.visit(packet);
|
||||
}
|
||||
} catch (ClassNotFoundException | IOException e) {
|
||||
e.printStackTrace();
|
||||
|
||||
@@ -4,10 +4,15 @@ import java.io.IOException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Random;
|
||||
|
||||
import common.ConsumerSignal;
|
||||
import common.Signal;
|
||||
import game.Game;
|
||||
import game.Player;
|
||||
import network.protocol.packets.ChangeCellPacket;
|
||||
import network.protocol.packets.LoginPacket;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Sudoku;
|
||||
|
||||
public class Client {
|
||||
private final ClientConnexion clientConnection;
|
||||
@@ -17,15 +22,16 @@ public class Client {
|
||||
public final Signal onDisconnect = new Signal();
|
||||
public final Signal onClosed = new Signal();
|
||||
public final Signal onGameStarted = new Signal();
|
||||
public final ConsumerSignal<Player> onGameEnd = new ConsumerSignal<>();
|
||||
|
||||
Player player;
|
||||
|
||||
String disconnectReason = null;
|
||||
|
||||
public Client(String address, short port) throws UnknownHostException, IOException {
|
||||
public Client(String pseudo, String address, short port) throws UnknownHostException, IOException {
|
||||
this.clientConnection = new ClientConnexion(address, port, this);
|
||||
this.game = new Game();
|
||||
// temp
|
||||
Random r = new Random();
|
||||
login("Player" + r.nextInt());
|
||||
login(pseudo);
|
||||
}
|
||||
|
||||
public void login(String pseudo) {
|
||||
@@ -54,4 +60,20 @@ public class Client {
|
||||
stop();
|
||||
}
|
||||
|
||||
public void sendCellChange(Cell cell) {
|
||||
MultiDoku doku = getGame().getDoku();
|
||||
for (int sudokuIndex = 0; sudokuIndex < doku.getNbSubGrids(); sudokuIndex++) {
|
||||
Sudoku sudoku = doku.getSubGrid(sudokuIndex);
|
||||
int cellIndex = sudoku.getCells().indexOf(cell);
|
||||
if (cellIndex != -1) {
|
||||
this.clientConnection.sendPacket(new ChangeCellPacket(sudokuIndex, cellIndex, cell.getSymbolIndex()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Player getPlayer() {
|
||||
return player;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -6,19 +6,21 @@ import java.net.UnknownHostException;
|
||||
|
||||
import game.Player;
|
||||
import network.Connexion;
|
||||
import network.protocol.packets.ChangeCellPacket;
|
||||
import network.protocol.packets.ConnexionInfoPacket;
|
||||
import network.protocol.packets.DisconnectPacket;
|
||||
import network.protocol.packets.EndGamePacket;
|
||||
import network.protocol.packets.KeepAlivePacket;
|
||||
import network.protocol.packets.LoginPacket;
|
||||
import network.protocol.packets.PlayerJoinPacket;
|
||||
import network.protocol.packets.PlayerLeavePacket;
|
||||
import network.protocol.packets.StartGamePacket;
|
||||
import network.protocol.packets.UpdatePlayerScorePacket;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
|
||||
public class ClientConnexion extends Connexion {
|
||||
|
||||
private final Client client;
|
||||
private Player player = null;
|
||||
|
||||
public ClientConnexion(String address, short port, Client client) throws UnknownHostException, IOException {
|
||||
super(new Socket(address, port));
|
||||
@@ -35,7 +37,7 @@ public class ClientConnexion extends Connexion {
|
||||
|
||||
@Override
|
||||
public void visitPacket(ConnexionInfoPacket packet) {
|
||||
this.player = this.client.getGame().getPlayerById(packet.getConnectionId());
|
||||
this.client.player = this.client.getGame().getPlayerById(packet.getConnectionId());
|
||||
client.onConnect.emit();
|
||||
}
|
||||
|
||||
@@ -69,8 +71,28 @@ public class ClientConnexion extends Connexion {
|
||||
|
||||
@Override
|
||||
public void visitPacket(StartGamePacket packet) {
|
||||
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()));
|
||||
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()),
|
||||
packet.getInstant(), packet.getGameDuration());
|
||||
this.client.onGameStarted.emit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitPacket(EndGamePacket packet) {
|
||||
Player winner = this.client.getGame().getLeaderboard().getFirst();
|
||||
this.client.getGame().stopGame();
|
||||
this.client.onGameEnd.emit(winner);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitPacket(UpdatePlayerScorePacket packet) {
|
||||
Player player = this.client.getGame().getPlayerById(packet.getPlayerId());
|
||||
assert (player != null);
|
||||
this.client.getGame().setPlayerRemainingCells(player, packet.getCellsLeft());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitPacket(ChangeCellPacket packet) {
|
||||
throw new UnsupportedOperationException("Unimplemented method 'visitPacketChangeCell'");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
package network.protocol;
|
||||
|
||||
import network.protocol.packets.ChangeCellPacket;
|
||||
import network.protocol.packets.ConnexionInfoPacket;
|
||||
import network.protocol.packets.DisconnectPacket;
|
||||
import network.protocol.packets.EndGamePacket;
|
||||
import network.protocol.packets.KeepAlivePacket;
|
||||
import network.protocol.packets.LoginPacket;
|
||||
import network.protocol.packets.PlayerJoinPacket;
|
||||
import network.protocol.packets.PlayerLeavePacket;
|
||||
import network.protocol.packets.StartGamePacket;
|
||||
import network.protocol.packets.UpdatePlayerScorePacket;
|
||||
|
||||
public interface PacketVisitor {
|
||||
|
||||
default void visitPacket(Packet packet) {
|
||||
default void visit(Packet packet) {
|
||||
packet.accept(this);
|
||||
}
|
||||
|
||||
@@ -21,5 +24,8 @@ public interface PacketVisitor {
|
||||
void visitPacket(PlayerJoinPacket packet);
|
||||
void visitPacket(PlayerLeavePacket packet);
|
||||
void visitPacket(StartGamePacket packet);
|
||||
void visitPacket(EndGamePacket packet);
|
||||
void visitPacket(UpdatePlayerScorePacket packet);
|
||||
void visitPacket(ChangeCellPacket packet);
|
||||
|
||||
}
|
||||
|
||||
@@ -2,6 +2,6 @@ package network.protocol;
|
||||
|
||||
public enum Packets {
|
||||
|
||||
ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame
|
||||
ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame, ChangeCell, EndGame, UpdatePlayerScore
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package network.protocol.packets;
|
||||
|
||||
import network.protocol.Packet;
|
||||
import network.protocol.PacketVisitor;
|
||||
import network.protocol.Packets;
|
||||
|
||||
public class ChangeCellPacket extends Packet {
|
||||
|
||||
static private final long serialVersionUID = Packets.ChangeCell.ordinal();
|
||||
|
||||
private final int sudokuIndex;
|
||||
private final int cellIndex;
|
||||
private final int newValue;
|
||||
|
||||
public ChangeCellPacket(int sudokuIndex, int cellIndex, int newValue) {
|
||||
this.sudokuIndex = sudokuIndex;
|
||||
this.cellIndex = cellIndex;
|
||||
this.newValue = newValue;
|
||||
}
|
||||
|
||||
public int getSudokuIndex() {
|
||||
return sudokuIndex;
|
||||
}
|
||||
|
||||
public int getCellIndex() {
|
||||
return cellIndex;
|
||||
}
|
||||
|
||||
public int getNewValue() {
|
||||
return newValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(PacketVisitor packetVisitor) {
|
||||
packetVisitor.visitPacket(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package network.protocol.packets;
|
||||
|
||||
import network.protocol.Packet;
|
||||
import network.protocol.PacketVisitor;
|
||||
import network.protocol.Packets;
|
||||
|
||||
public class EndGamePacket extends Packet {
|
||||
|
||||
static private final long serialVersionUID = Packets.EndGame.ordinal();
|
||||
|
||||
public EndGamePacket() { }
|
||||
|
||||
@Override
|
||||
public void accept(PacketVisitor packetVisitor) {
|
||||
packetVisitor.visitPacket(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
package network.protocol.packets;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import network.protocol.Packet;
|
||||
import network.protocol.PacketVisitor;
|
||||
import network.protocol.Packets;
|
||||
@@ -9,15 +11,28 @@ public class StartGamePacket extends Packet {
|
||||
static private final long serialVersionUID = Packets.StartGame.ordinal();
|
||||
|
||||
private final String serializedSudoku;
|
||||
// used to resume game
|
||||
private final Instant instant;
|
||||
private final long gameDuration;
|
||||
|
||||
public StartGamePacket(String serializedSudoku) {
|
||||
public StartGamePacket(String serializedSudoku, Instant instant, long gameDuration) {
|
||||
this.serializedSudoku = serializedSudoku;
|
||||
this.instant = instant;
|
||||
this.gameDuration = gameDuration;
|
||||
}
|
||||
|
||||
public String getSerializedSudoku() {
|
||||
return serializedSudoku;
|
||||
}
|
||||
|
||||
public Instant getInstant() {
|
||||
return instant;
|
||||
}
|
||||
|
||||
public long getGameDuration() {
|
||||
return gameDuration;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(PacketVisitor packetVisitor) {
|
||||
packetVisitor.visitPacket(this);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package network.protocol.packets;
|
||||
|
||||
import network.protocol.Packet;
|
||||
import network.protocol.PacketVisitor;
|
||||
import network.protocol.Packets;
|
||||
|
||||
public class UpdatePlayerScorePacket extends Packet {
|
||||
|
||||
static private final long serialVersionUID = Packets.UpdatePlayerScore.ordinal();
|
||||
|
||||
private final int playerId;
|
||||
private final int cellsLeft;
|
||||
|
||||
public UpdatePlayerScorePacket(int playerId, int cellsLeft) {
|
||||
this.playerId = playerId;
|
||||
this.cellsLeft = cellsLeft;
|
||||
}
|
||||
|
||||
public int getPlayerId() {
|
||||
return playerId;
|
||||
}
|
||||
|
||||
public int getCellsLeft() {
|
||||
return cellsLeft;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void accept(PacketVisitor packetVisitor) {
|
||||
packetVisitor.visitPacket(this);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,12 +2,15 @@ package network.server;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import game.Game;
|
||||
import game.Player;
|
||||
import game.Game.GameState;
|
||||
import network.protocol.Packet;
|
||||
import network.protocol.packets.EndGamePacket;
|
||||
import network.protocol.packets.StartGamePacket;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.structure.MultiDoku;
|
||||
@@ -37,7 +40,16 @@ public class Server {
|
||||
}
|
||||
}
|
||||
|
||||
public void update() {
|
||||
private void checkTimer() {
|
||||
if (getGame() == null || getGame().getGameState() != GameState.GameGoing)
|
||||
return;
|
||||
long now = Instant.now().getEpochSecond();
|
||||
long end = getGame().getStartTime().getEpochSecond() + getGame().getGameDuration();
|
||||
if (now > end)
|
||||
stopGame();
|
||||
}
|
||||
|
||||
private void checkConnexions() {
|
||||
for (var it = connexions.iterator(); it.hasNext();) {
|
||||
ServerConnexion connexion = it.next();
|
||||
if (!connexion.update()) {
|
||||
@@ -48,6 +60,11 @@ public class Server {
|
||||
}
|
||||
}
|
||||
|
||||
public void update() {
|
||||
checkTimer();
|
||||
checkConnexions();
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
this.acceptThread.cancel();
|
||||
this.logicThread.cancel();
|
||||
@@ -68,9 +85,19 @@ public class Server {
|
||||
return game;
|
||||
}
|
||||
|
||||
public void startGame(MultiDoku doku) {
|
||||
this.game.startGame(doku);
|
||||
broadcastPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(doku).toString()));
|
||||
public void startGame(MultiDoku doku, long gameDuration) {
|
||||
Instant now = Instant.now();
|
||||
this.game.startGame(doku, now, gameDuration);
|
||||
for (ServerConnexion connexion : this.connexions) {
|
||||
connexion.setSudoku(doku.clone());
|
||||
}
|
||||
broadcastPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(doku).toString(), now, gameDuration));
|
||||
}
|
||||
|
||||
public void stopGame() {
|
||||
// we don't need to specify the winner since it has to be the first
|
||||
broadcastPacket(new EndGamePacket());
|
||||
getGame().stopGame();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,17 +3,23 @@ package network.server;
|
||||
import java.io.IOException;
|
||||
import java.net.Socket;
|
||||
|
||||
import game.Game;
|
||||
import game.Player;
|
||||
import game.Game.GameState;
|
||||
import network.Connexion;
|
||||
import network.protocol.packets.ChangeCellPacket;
|
||||
import network.protocol.packets.ConnexionInfoPacket;
|
||||
import network.protocol.packets.DisconnectPacket;
|
||||
import network.protocol.packets.EndGamePacket;
|
||||
import network.protocol.packets.KeepAlivePacket;
|
||||
import network.protocol.packets.LoginPacket;
|
||||
import network.protocol.packets.PlayerJoinPacket;
|
||||
import network.protocol.packets.PlayerLeavePacket;
|
||||
import network.protocol.packets.StartGamePacket;
|
||||
import network.protocol.packets.UpdatePlayerScorePacket;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class ServerConnexion extends Connexion {
|
||||
|
||||
@@ -21,6 +27,7 @@ public class ServerConnexion extends Connexion {
|
||||
private final KeepAliveHandler keepAliveHandler;
|
||||
private boolean shouldClose = false;
|
||||
private Player player = null;
|
||||
private MultiDoku doku;
|
||||
|
||||
public ServerConnexion(Socket socket, Server server) throws IOException {
|
||||
super(socket);
|
||||
@@ -29,7 +36,7 @@ public class ServerConnexion extends Connexion {
|
||||
}
|
||||
|
||||
public boolean update() {
|
||||
if (shouldClose | isClosed())
|
||||
if (shouldClose || isClosed())
|
||||
return false;
|
||||
return this.keepAliveHandler.update();
|
||||
}
|
||||
@@ -44,7 +51,7 @@ public class ServerConnexion extends Connexion {
|
||||
|
||||
@Override
|
||||
public synchronized void close() {
|
||||
if(shouldClose)
|
||||
if (shouldClose)
|
||||
return;
|
||||
super.close();
|
||||
shouldClose = true;
|
||||
@@ -54,13 +61,22 @@ public class ServerConnexion extends Connexion {
|
||||
private void finishLogin() {
|
||||
// send players that have already joined (excluding this one)
|
||||
for (Player p : this.server.getGame().getPlayers().values()) {
|
||||
if (p.getId() != player.getId())
|
||||
if (p.getId() != player.getId()) {
|
||||
sendPacket(new PlayerJoinPacket(p));
|
||||
sendPacket(new UpdatePlayerScorePacket(p.getId(), p.getRemainingCells()));
|
||||
}
|
||||
}
|
||||
|
||||
this.server.broadcastPacket(new PlayerJoinPacket(player));
|
||||
sendPacket(new ConnexionInfoPacket(player.getId()));
|
||||
if (this.server.getGame().getGameState() == GameState.GameGoing) {
|
||||
sendPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(this.server.getGame().getDoku()).toString()));
|
||||
|
||||
Game game = this.server.getGame();
|
||||
|
||||
if (game.getGameState() == GameState.GameGoing) {
|
||||
setSudoku(game.getDoku().clone());
|
||||
sendPacket(
|
||||
new StartGamePacket(SudokuSerializer.serializeSudoku(game.getDoku()).toString(),
|
||||
game.getStartTime(), game.getGameDuration()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,4 +118,50 @@ public class ServerConnexion extends Connexion {
|
||||
throw new UnsupportedOperationException("Unimplemented method 'visitPacketStartGame'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitPacket(EndGamePacket packet) {
|
||||
throw new UnsupportedOperationException("Unimplemented method 'visitPacket'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitPacket(UpdatePlayerScorePacket packet) {
|
||||
throw new UnsupportedOperationException("Unimplemented method 'visitPacket'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitPacket(ChangeCellPacket packet) {
|
||||
Cell cell = this.doku.getSubGrid(packet.getSudokuIndex()).getCell(packet.getCellIndex());
|
||||
if (cell.getSymbolIndex() == Cell.NOSYMBOL && packet.getNewValue() == Cell.NOSYMBOL)
|
||||
return;
|
||||
if (cell.getSymbolIndex() != Cell.NOSYMBOL && packet.getNewValue() != Cell.NOSYMBOL) {
|
||||
cell.trySetValue(packet.getNewValue());
|
||||
return;
|
||||
}
|
||||
if (cell.getSymbolIndex() != Cell.NOSYMBOL && packet.getNewValue() == Cell.NOSYMBOL) {
|
||||
cell.empty();
|
||||
this.server.getGame().setPlayerRemainingCells(player, player.getRemainingCells() + 1);
|
||||
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
|
||||
return;
|
||||
}
|
||||
// on rajoute un chiffre à la grille
|
||||
if (cell.trySetValue(packet.getNewValue())) {
|
||||
this.server.getGame().setPlayerRemainingCells(player, player.getRemainingCells() - 1);
|
||||
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
|
||||
}
|
||||
checkWin();
|
||||
}
|
||||
|
||||
private void checkWin() {
|
||||
if (this.player.getRemainingCells() == 0) {
|
||||
this.server.stopGame();
|
||||
}
|
||||
}
|
||||
|
||||
public void setSudoku(MultiDoku doku) {
|
||||
this.doku = doku;
|
||||
assert (player != null);
|
||||
this.server.getGame().setPlayerRemainingCells(player, this.doku.getEmptyCells().size());
|
||||
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ public class ServerLogicThread extends Thread {
|
||||
try {
|
||||
Thread.sleep(50);
|
||||
} catch (InterruptedException e) {
|
||||
// e.printStackTrace();
|
||||
e.printStackTrace();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,15 +3,48 @@
|
||||
*/
|
||||
package sudoku;
|
||||
|
||||
import gui.RenderableMultidoku;
|
||||
import gui.constants.Symbols;
|
||||
import sudoku.io.ConsoleInterface;
|
||||
import sudoku.io.SudokuPrinter;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.solver.RandomSolver;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
public class Main {
|
||||
public String getGreeting() {
|
||||
return "Hello World!";
|
||||
}
|
||||
|
||||
public static void voidTest(){
|
||||
MultiDoku md = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
SudokuPrinter.printMultiDoku(RenderableMultidoku.fromMultidoku(md), Symbols.Numbers, 3, 3);
|
||||
SudokuSerializer.saveMultiDoku(md);
|
||||
}
|
||||
|
||||
public static void filledTest(){
|
||||
MultiDoku md = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
new RandomSolver().solve(md);
|
||||
SudokuPrinter.printMultiDoku(RenderableMultidoku.fromMultidoku(md), Symbols.Numbers, 3, 3);
|
||||
SudokuSerializer.saveMultiDoku(md);
|
||||
}
|
||||
|
||||
public static void overwriteTest(int n){
|
||||
MultiDoku md = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
new RandomSolver().solve(md);
|
||||
SudokuPrinter.printMultiDoku(RenderableMultidoku.fromMultidoku(md), Symbols.Numbers, 3, 3);
|
||||
SudokuSerializer.saveMultiDoku(md, n);
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ConsoleInterface console = new ConsoleInterface();
|
||||
console.start();
|
||||
/*
|
||||
voidTest();
|
||||
filledTest();
|
||||
overwriteTest(0);
|
||||
overwriteTest(17)
|
||||
*/
|
||||
console.welcome();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
package sudoku.constraint;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import sudoku.structure.Sudoku;
|
||||
|
||||
public interface IConstraint {
|
||||
|
||||
public interface IConstraint extends Serializable {
|
||||
boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex);
|
||||
|
||||
default List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) {
|
||||
|
||||
@@ -1,69 +1,118 @@
|
||||
package sudoku.io;
|
||||
|
||||
import gui.RenderableMultidoku;
|
||||
import gui.constants.Symbols;
|
||||
import sudoku.constraint.*;
|
||||
import sudoku.solver.Solver;
|
||||
import sudoku.structure.Difficulty;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Sudoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
import sudoku.solver.*;
|
||||
import sudoku.structure.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class ConsoleInterface {
|
||||
public Scanner reader = new Scanner(System.in);
|
||||
|
||||
public void start(){
|
||||
welcome();
|
||||
public void welcome() {
|
||||
System.out.println("Welcome to our Sudoku Solver!");
|
||||
System.out.println("This is the project of Melvyn Bauvent, Lilas Grenier and Simon Pribylski.");
|
||||
System.out.println("Do you have a save sudoku you would like to continue? (y/n, default n)");
|
||||
if (reader.next().equalsIgnoreCase("y")) {
|
||||
useSavedDoku();
|
||||
} else {
|
||||
createDoku();
|
||||
}
|
||||
}
|
||||
|
||||
private void useSavedDoku() {
|
||||
System.out.println("What save should we use? Please enter the save number.");
|
||||
MultiDoku md = saveChoice();
|
||||
int blockWidth = md.getSubGrid(0).getBlockWidth();
|
||||
int blockHeight = md.getSubGrid(0).getBlocks().getFirst().getCells().size() / blockWidth;
|
||||
List<String> listSymbols = pickSymbols(blockWidth * blockHeight);
|
||||
System.out.println("This is the saved sudoku:");
|
||||
showMultidoku(md, listSymbols, blockWidth, blockHeight);
|
||||
do {
|
||||
turn(md, listSymbols, blockWidth, blockHeight);
|
||||
} while (!md.isSolved());
|
||||
congrats();
|
||||
}
|
||||
|
||||
public void createDoku() {
|
||||
System.out.println("First of all, you need to tell me the size of the sudoku you want to generate.");
|
||||
int width = getBlockWidth();
|
||||
int height = getBlockHeight();
|
||||
System.out.println("Your sudoku will have blocks of a " + width + " x " + height + " format.");
|
||||
int numberOfSymbols = width * height;
|
||||
System.out.println("Would you like to pick the " + numberOfSymbols + " symbols from the sudoku? (y/n, default 'no' will use numbers)" );
|
||||
List<String> listSymbols = new ArrayList<>();
|
||||
if(reader.next().equalsIgnoreCase("y")){
|
||||
pickSymbols(listSymbols, numberOfSymbols);
|
||||
}
|
||||
else {
|
||||
// TODO
|
||||
System.out.println("Simon doit finir sa partie.");
|
||||
assert false;
|
||||
}
|
||||
List<Constraint> listConstraints = getListConstraints();
|
||||
|
||||
|
||||
System.out.println("Now that we have the size of our sudoku, would you rather have a single grid ('one', default), " +
|
||||
List<String> listSymbols = pickSymbols(numberOfSymbols);
|
||||
List<IConstraint> listConstraints = getListConstraints();
|
||||
System.out.println("Now that we have the size of our sudoku, " +
|
||||
"would you rather have a single grid ('one', default), " +
|
||||
"or a a multidoku composed of 5 subgrids ('multi') ?");
|
||||
List<Sudoku> subGrids = new ArrayList<>();
|
||||
MultiDoku doku;
|
||||
if (reader.next().equalsIgnoreCase("multi")) {
|
||||
doku = SudokuFactory.createBasicXShapedMultidoku(width, height, listConstraints);
|
||||
} else {
|
||||
doku = SudokuFactory.createBasicEmptyRectangleDoku(width, height, listConstraints);
|
||||
}
|
||||
else {
|
||||
doku = SudokuFactory.createBasicXShapedMultidoku(width, height, listConstraints);
|
||||
}
|
||||
System.out.println("Your sudoku will look like this:");
|
||||
// TODO printMultiDoku method not yet implemented
|
||||
SudokuPrinter.printMultiDoku(doku, width, height);
|
||||
System.out.println("We now will fill this sudoku.");
|
||||
System.out.println("What level of difficulty would you like? ('very easy', 'easy', 'medium' (default), 'hard', 'full' (sudoku fully completed))");
|
||||
showMultidoku(doku, listSymbols, width, height);
|
||||
System.out.println(
|
||||
"You can now manually fill this sudoku ('fill'), or generate a playable one ('generate', default):");
|
||||
if (reader.next().equalsIgnoreCase("fill")) {
|
||||
findSolution(doku, listSymbols, width, height);
|
||||
} else {
|
||||
playableDoku(doku, listSymbols, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
private void playableDoku(MultiDoku doku, List<String> listSymbols, int width, int height) {
|
||||
System.out.println("We will now fill this sudoku.");
|
||||
System.out.println("What level of difficulty would you like?" +
|
||||
" ('very easy', 'easy', 'medium' (default), 'hard', 'full' (sudoku fully completed))");
|
||||
String difficulty = reader.next().toLowerCase();
|
||||
if (difficulty.equals("full")) {
|
||||
generateFullDoku(doku);
|
||||
}
|
||||
else {
|
||||
System.out.println("Here's your sudoku !");
|
||||
exit();
|
||||
} else {
|
||||
generatePartialDoku(doku, difficulty);
|
||||
System.out.println("Here's your sudoku !");
|
||||
showMultidoku(doku, listSymbols, width, height);
|
||||
do {
|
||||
turn(doku, listSymbols, width, height);
|
||||
} while (!doku.isSolved());
|
||||
congrats();
|
||||
}
|
||||
System.out.println("Here's your sudoku !");
|
||||
SudokuPrinter.printMultiDoku(doku, width, height);
|
||||
}
|
||||
|
||||
public void welcome(){
|
||||
System.out.println("Welcome to our Sudoku Solver!");
|
||||
System.out.println("This is the project of Melvyn Bauvent, Lilas Grenier and Simon Priblyski.");
|
||||
private void findSolution(MultiDoku doku, List<String> listSymbols, int width, int height){
|
||||
do {
|
||||
turn(doku, listSymbols, width, height);
|
||||
} while (!doku.isSolved());
|
||||
System.out.println("This doku can be solved like this :");
|
||||
showMultidoku(doku, listSymbols, width, height);
|
||||
exit();
|
||||
|
||||
}
|
||||
|
||||
private void congrats() {
|
||||
System.out.println("Congrats! You've solved this sudoku! We hope this was fun! Let's play together again!");
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
private MultiDoku saveChoice() {
|
||||
int nbSave;
|
||||
MultiDoku md = null;
|
||||
do {
|
||||
nbSave = reader.nextInt();
|
||||
try {
|
||||
md = SudokuSerializer.getSavedMultiDoku(nbSave);
|
||||
} catch (Exception e) {
|
||||
System.out.println("There seems to be a problem with this save, please try again.");
|
||||
}
|
||||
} while (md == null);
|
||||
return md;
|
||||
}
|
||||
|
||||
public int getBlockWidth() {
|
||||
@@ -94,36 +143,55 @@ public class ConsoleInterface {
|
||||
return (size > 0);
|
||||
}
|
||||
|
||||
private void pickSymbols(List<String> listSymbols, int numberOfSymbols) {
|
||||
System.out.println("You have chosen to pick your own symbols.");
|
||||
for (int i = 0; i < numberOfSymbols; i++) {
|
||||
System.out.println("Choose for the symbol number " + i + ": ");
|
||||
String newSymbol = reader.next();
|
||||
while (listSymbols.contains(newSymbol)) {
|
||||
System.out.println("This symbol has already been given. Try again:");
|
||||
newSymbol = reader.next();
|
||||
private List<String> pickSymbols(int numberOfSymbols) {
|
||||
System.out.println("Would you like to pick the " + numberOfSymbols
|
||||
+ " symbols from the sudoku? (y/n, default 'no')");
|
||||
if (reader.next().equalsIgnoreCase("y")) {
|
||||
List<String> listSymbols = new ArrayList<>();
|
||||
System.out.println("You have chosen to pick your own symbols.");
|
||||
for (int i = 0; i < numberOfSymbols; i++) {
|
||||
System.out.println("Choose for the symbol number " + i + ": ");
|
||||
String newSymbol = reader.next();
|
||||
while (listSymbols.contains(newSymbol)) {
|
||||
System.out.println("This symbol has already been given. Try again:");
|
||||
newSymbol = reader.next();
|
||||
}
|
||||
listSymbols.add(newSymbol);
|
||||
}
|
||||
listSymbols.add(newSymbol);
|
||||
System.out.println("You chose the symbols: " + listSymbols.toString());
|
||||
return listSymbols;
|
||||
} else {
|
||||
System.out.println(
|
||||
"What existing sets of symbols do you want to use? Numbers ('n', default), letters ('l'), or emojis ('e', may not work on all consoles)?");
|
||||
return switch (reader.next().toLowerCase()) {
|
||||
case "l" -> Symbols.Letters.getSymbols();
|
||||
case "e" -> Symbols.Emojis.getSymbols();
|
||||
default -> Symbols.Numbers.getSymbols();
|
||||
};
|
||||
}
|
||||
System.out.println("You chose the symbols: " + listSymbols.toString());
|
||||
}
|
||||
|
||||
private List<Constraint> getListConstraints() {
|
||||
List<Constraint> listConstraints = SudokuFactory.DEFAULT_CONSTRAINTS;
|
||||
System.out.println("The sudoku have constraints of blocks, lines and columns. Would you like to add the diagonal constraints ? (y/n, default 'no')");
|
||||
if(reader.next().equalsIgnoreCase("y")){
|
||||
listConstraints.add(Constraint.Diagonal);
|
||||
private List<IConstraint> getListConstraints() {
|
||||
List<IConstraint> listConstraints = SudokuFactory.DEFAULT_CONSTRAINTS;
|
||||
System.out.println(
|
||||
"The sudoku have constraints of blocks, lines and columns. Would you like to add the diagonal constraints ? (y/n, default 'no')");
|
||||
if (reader.next().equalsIgnoreCase("y")) {
|
||||
listConstraints.add(Constraint.Diagonal.getConstraint());
|
||||
}
|
||||
return listConstraints;
|
||||
}
|
||||
|
||||
private void generatePartialDoku(MultiDoku doku, String difficultyName) {
|
||||
Difficulty difficulty;
|
||||
switch (difficultyName){
|
||||
case "very easy": difficulty = Difficulty.VeryEasy;
|
||||
case "easy": difficulty = Difficulty.Easy;
|
||||
case "hard": difficulty = Difficulty.Hard;
|
||||
default: difficulty = Difficulty.Medium;
|
||||
switch (difficultyName) {
|
||||
case "very easy":
|
||||
difficulty = Difficulty.VeryEasy;
|
||||
case "easy":
|
||||
difficulty = Difficulty.Easy;
|
||||
case "hard":
|
||||
difficulty = Difficulty.Hard;
|
||||
default:
|
||||
difficulty = Difficulty.Medium;
|
||||
}
|
||||
try {
|
||||
SudokuFactory.fillDoku(doku, difficulty);
|
||||
@@ -133,7 +201,136 @@ public class ConsoleInterface {
|
||||
}
|
||||
|
||||
private void generateFullDoku(MultiDoku doku) {
|
||||
Solver.solveRandom(doku, new Random());
|
||||
new RandomSolver().solve(doku);
|
||||
}
|
||||
|
||||
private void showMultidoku(MultiDoku doku, List<String> listSymbols, int width, int height) {
|
||||
showMultiDoku(RenderableMultidoku.fromMultidoku(doku), listSymbols, width, height);
|
||||
}
|
||||
|
||||
private void showMultiDoku(RenderableMultidoku doku, List<String> listSymbols, int width, int height) {
|
||||
SudokuPrinter.printMultiDokuWithIndex(doku, listSymbols, width, height);
|
||||
}
|
||||
|
||||
private void saveMultiDoku(MultiDoku doku) {
|
||||
System.out.println("Number of the file to overwrite ('-1' or unused save file number to create a new save) :");
|
||||
int n = reader.nextInt();
|
||||
String path = SudokuSerializer.saveMultiDoku(doku, n);
|
||||
System.out.println("The path to your save is:" + path);
|
||||
}
|
||||
|
||||
private void turn(MultiDoku doku, List<String> listSymbols, int width, int height) {
|
||||
System.out.println(
|
||||
"You can now put a number in a cell ('play', default), save the state of the doku ('save'), show a solution ('solution') or exit the program ('exit').");
|
||||
switch (reader.next()) {
|
||||
case "save":
|
||||
saveMultiDoku(doku);
|
||||
break;
|
||||
case "solution":
|
||||
solve(doku, listSymbols, width, height);
|
||||
break;
|
||||
case "exit":
|
||||
exit();
|
||||
break;
|
||||
default:
|
||||
play(doku, listSymbols, width, height);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void applyStep(SolverStep step) {
|
||||
step.getCell().setSymbolIndex(step.getNewValue());
|
||||
}
|
||||
|
||||
private boolean showStep(MultiDoku doku, List<String> listSymbols, int width, int height, SolverStep step) {
|
||||
System.out.println("Here is the step : \n");
|
||||
showMultidoku(doku, listSymbols, width, height);
|
||||
applyStep(step);
|
||||
System.out.println("\nTurns into :\n");
|
||||
showMultidoku(doku, listSymbols, width, height);
|
||||
System.out.println("Do you want to see the next step ? (y/n, default n)");
|
||||
return reader.next().equals("y");
|
||||
}
|
||||
|
||||
private void showSolveSteps(MultiDoku doku, List<String> listSymbols, int width, int height, List<SolverStep> steps) {
|
||||
System.out.println("Would you like to see the steps of the solver ? (y/n, default n)");
|
||||
doku.getStateManager().popState();
|
||||
switch (reader.next()) {
|
||||
case "y":
|
||||
int stepCount = 0;
|
||||
while(stepCount < steps.size() && showStep(doku, listSymbols, width, height, steps.get(stepCount))){stepCount++;}
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void solve(MultiDoku doku, List<String> listSymbols, int width, int height){
|
||||
System.out.println("Pick a solver to use : random ('random', default), human ('human') or mixed solver ('mixed').");
|
||||
List<SolverStep> steps = new ArrayList<>();
|
||||
doku.getStateManager().pushState();
|
||||
switch (reader.next()) {
|
||||
case "human":
|
||||
new HumanSolver().solve(doku, steps);
|
||||
break;
|
||||
case "mixed":
|
||||
new MixedSolver().solve(doku, steps);
|
||||
break;
|
||||
default:
|
||||
new RandomSolver().solve(doku, steps);
|
||||
break;
|
||||
}
|
||||
showSolveSteps(doku, listSymbols, width, height, steps);
|
||||
}
|
||||
|
||||
private void play(MultiDoku doku, List<String> listSymbols, int width, int height) {
|
||||
int x, y;
|
||||
RenderableMultidoku rdoku = RenderableMultidoku.fromMultidoku(doku);
|
||||
do {
|
||||
System.out.println("Line of the cell to fill:");
|
||||
y = reader.nextInt();
|
||||
System.out.println("Column of the cell to fill:");
|
||||
x = reader.nextInt();
|
||||
} while (!isValidCoordinates(rdoku, width, height, x-1, y-1));
|
||||
Cell cell = rdoku.getCell(x-1, y-1);
|
||||
System.out.println("Character to put in the (" + x + ", " + y + ") cell:");
|
||||
String character = reader.next();
|
||||
while (!isValidSymbol(character, listSymbols, width * height)) {
|
||||
System.out.println("This is not a valid symbol; try again:");
|
||||
character = reader.next();
|
||||
}
|
||||
cell.setSymbolIndex(indexOfSymbol(character, listSymbols, width * height));
|
||||
showMultiDoku(rdoku, listSymbols, width, height);
|
||||
}
|
||||
|
||||
private boolean isValidCoordinates(RenderableMultidoku doku, int width, int height, int x, int y) {
|
||||
if (doku.getCell(x, y) != null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private int indexOfSymbol(String symbol, List<String> listSymbols, int nbSymbols) {
|
||||
for (int i = 0; i < nbSymbols; i++) {
|
||||
if (listSymbols.get(i).equals(symbol)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private boolean isValidSymbol(String symbol, List<String> listSymbols, int size) {
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (listSymbols.get(i).equals(symbol)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void exit() {
|
||||
System.out.println("Thank you for playing!");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,39 @@
|
||||
package sudoku.io;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import gui.RenderableMultidoku;
|
||||
import gui.constants.Symbols;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Sudoku;
|
||||
|
||||
public class SudokuPrinter {
|
||||
public static final String ANSI_RESET = "\u001B[0m";
|
||||
public static final String ANSI_RED = "\u001B[31m";
|
||||
public static final String ANSI_GREEN = "\u001B[32m";
|
||||
public static final String ANSI_YELLOW = "\u001B[33m";
|
||||
public static final String ANSI_BLUE = "\u001B[34m";
|
||||
public static final String ANSI_PURPLE = "\u001B[35m";
|
||||
public static final String ANSI_CYAN = "\u001B[36m";
|
||||
|
||||
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight) {
|
||||
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, Symbols symbols) {
|
||||
printRectangleSudoku(s, blockWidth, blockHeight, symbols.getSymbols());
|
||||
}
|
||||
|
||||
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, List<String> listSymbols) {
|
||||
for (int y = 0; y < s.getSize(); y++) {
|
||||
if (y % blockHeight == 0 && y > 0) {
|
||||
System.out.println();
|
||||
}
|
||||
StringBuilder line = new StringBuilder("[ ");
|
||||
for (int x = 0; x < s.getSize(); x++) {
|
||||
line.append((s.getCell(x, y).getSymbolIndex() + 1)).append(" ");
|
||||
Cell c = s.getCell(x, y);
|
||||
if (c.getSymbolIndex() == Cell.NOSYMBOL) {
|
||||
line.append(" ");
|
||||
} else {
|
||||
line.append(listSymbols.get(c.getSymbolIndex())).append(" ");
|
||||
}
|
||||
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
|
||||
line.append("| ");
|
||||
}
|
||||
@@ -22,7 +43,120 @@ public class SudokuPrinter {
|
||||
}
|
||||
}
|
||||
|
||||
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight) {
|
||||
public static void printRectangleSudokuWithIndex(final Sudoku s, int blockWidth, int blockHeight,
|
||||
List<String> listSymbols) {
|
||||
StringBuilder header = new StringBuilder("");
|
||||
header.append(" ");
|
||||
for (int x = 0; x < blockWidth * blockHeight; x++) {
|
||||
header.append(x + 1).append(" ");
|
||||
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
|
||||
header.append(" ");
|
||||
}
|
||||
}
|
||||
header.append("\n");
|
||||
System.out.println(header);
|
||||
for (int y = 0; y < s.getSize(); y++) {
|
||||
if (y % blockHeight == 0 && y > 0) {
|
||||
System.out.println();
|
||||
}
|
||||
StringBuilder line = new StringBuilder(y + 1);
|
||||
line.append(" [ ");
|
||||
for (int x = 0; x < s.getSize(); x++) {
|
||||
Cell c = s.getCell(x, y);
|
||||
if (c.getSymbolIndex() == Cell.NOSYMBOL) {
|
||||
line.append(" ");
|
||||
} else {
|
||||
line.append(listSymbols.get(c.getSymbolIndex())).append(" ");
|
||||
}
|
||||
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
|
||||
line.append("| ");
|
||||
}
|
||||
}
|
||||
line.append("]");
|
||||
System.out.println(line);
|
||||
}
|
||||
}
|
||||
|
||||
public static String printMultiDoku(final RenderableMultidoku rm, Symbols symbols, int blockWidth,
|
||||
int blockHeight) {
|
||||
return printMultiDoku(rm, symbols.getSymbols(), blockWidth, blockHeight);
|
||||
}
|
||||
|
||||
public static String printMultiDoku(final RenderableMultidoku rm, List<String> listSymbols, int blockWidth,
|
||||
int blockHeight) {
|
||||
StringBuilder line = new StringBuilder("\n");
|
||||
int nBlockInWidth = rm.getWidth() / blockWidth;
|
||||
for (int y = 0; y < rm.getHeight(); y++) {
|
||||
if (y % blockHeight == 0) {
|
||||
line.append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
|
||||
}
|
||||
line.append("[ ");
|
||||
for (int x = 0; x < rm.getWidth(); x++) {
|
||||
if (x % blockWidth == 0 && x > 0) {
|
||||
line.append("| ");
|
||||
}
|
||||
Cell cell = rm.getCell(x, y);
|
||||
if (cell != null) {
|
||||
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
|
||||
line.append("- ");
|
||||
} else {
|
||||
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
|
||||
}
|
||||
} else {
|
||||
line.append(" ");
|
||||
}
|
||||
}
|
||||
line.append("]\n");
|
||||
}
|
||||
line.append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
|
||||
// System.out.println(line);
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
public static void printMultiDokuWithIndex(final RenderableMultidoku rm, List<String> listSymbols, int blockWidth,
|
||||
int blockHeight) {
|
||||
StringBuilder line = new StringBuilder("\n");
|
||||
line.append(" ");
|
||||
for (int x = 0; x < rm.getWidth(); x++) {
|
||||
line.append(x + 1).append(" ");
|
||||
if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
|
||||
line.append(" ");
|
||||
}
|
||||
}
|
||||
line.append("\n");
|
||||
int nBlockInWidth = rm.getWidth() / blockWidth;
|
||||
for (int y = 0; y < rm.getHeight(); y++) {
|
||||
if (y % blockHeight == 0) {
|
||||
line.append(" ").append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
|
||||
}
|
||||
line.append(y + 1).append(" [ ");
|
||||
for (int x = 0; x < rm.getWidth(); x++) {
|
||||
if (x % blockWidth == 0 && x > 0) {
|
||||
line.append("| ");
|
||||
}
|
||||
Cell cell = rm.getCell(x, y);
|
||||
if (cell != null) {
|
||||
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
|
||||
line.append("- ");
|
||||
} else {
|
||||
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
|
||||
}
|
||||
} else {
|
||||
line.append(" ");
|
||||
}
|
||||
}
|
||||
line.append("]\n");
|
||||
}
|
||||
line.append(" ").append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).append("_\n");
|
||||
System.out.println(line);
|
||||
}
|
||||
|
||||
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, Symbols symbols) {
|
||||
return toStringRectangleSudoku(s, blockWidth, blockHeight, symbols.getSymbols());
|
||||
}
|
||||
|
||||
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight,
|
||||
List<String> listSymbols) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int y = 0; y < s.getSize(); y++) {
|
||||
// Ajouter une ligne vide entre les blocs horizontaux
|
||||
@@ -32,7 +166,12 @@ public class SudokuPrinter {
|
||||
StringBuilder line = new StringBuilder("[ ");
|
||||
for (int x = 0; x < s.getSize(); x++) {
|
||||
// Ajouter la valeur de la cellule
|
||||
line.append((s.getCell(x, y).getSymbolIndex() + 1)).append(" ");
|
||||
Cell cell = s.getCell(x, y);
|
||||
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
|
||||
line.append(" ");
|
||||
} else {
|
||||
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
|
||||
}
|
||||
|
||||
// Ajouter un séparateur vertical entre les blocs
|
||||
if (x % blockWidth == blockWidth - 1 && x != s.getSize() - 1) {
|
||||
@@ -45,7 +184,25 @@ public class SudokuPrinter {
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public static void printMultiDoku(final MultiDoku doku, int blockWidth, int blockHeight){
|
||||
// TODO
|
||||
public static String printMultiDoku(final MultiDoku doku) {
|
||||
int blockWidth = doku.getSubGrid(0).getBlockWidth();
|
||||
if (blockWidth == 0)
|
||||
return printMultiDoku(doku, 0, 0, Symbols.Numbers);
|
||||
else
|
||||
return printMultiDoku(doku, blockWidth, doku.getSubGrid(0).getSize() / blockWidth, Symbols.Letters);
|
||||
}
|
||||
|
||||
public static String printMultiDoku(final MultiDoku doku, int blockWidth, int blockHeight, Symbols symbols) {
|
||||
return printMultiDoku(RenderableMultidoku.fromMultidoku(doku), symbols, blockWidth, blockHeight);
|
||||
}
|
||||
|
||||
public static void printMultiDokuWithIndex(final MultiDoku doku, int blockWidth, int blockHeight, Symbols symbols) {
|
||||
if (doku.getNbSubGrids() == 1) {
|
||||
printRectangleSudokuWithIndex(doku.getSubGrid(0), blockWidth, blockHeight, symbols.getSymbols());
|
||||
} else {
|
||||
printMultiDokuWithIndex(RenderableMultidoku.fromMultidoku(doku), symbols.getSymbols(), blockWidth,
|
||||
blockHeight);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
package sudoku.io;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
@@ -11,20 +12,20 @@ import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.constraint.IConstraint;
|
||||
import sudoku.structure.Block;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Sudoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
public class SudokuSerializer {
|
||||
|
||||
public static JSONObject serializeSudoku(final MultiDoku multidoku) {
|
||||
List<Cell> cellIds = new ArrayList<>();
|
||||
List<Cell> cellIds = new ArrayList<>();
|
||||
List<Block> blockIds = new ArrayList<>();
|
||||
|
||||
JSONObject jsonRoot = new JSONObject();
|
||||
JSONArray jsonCells = new JSONArray();
|
||||
JSONObject jsonRoot = new JSONObject();
|
||||
JSONArray jsonCells = new JSONArray();
|
||||
JSONArray jsonBlocks = new JSONArray();
|
||||
JSONArray jsonSudokus = new JSONArray(multidoku.getNbSubGrids());
|
||||
|
||||
@@ -33,9 +34,10 @@ public class SudokuSerializer {
|
||||
|
||||
// init cells
|
||||
for (Cell cell : sudoku.getCells()) {
|
||||
if (!cellIds.contains(cell)) {
|
||||
cellIds.add(cell);
|
||||
}
|
||||
if (cellIds.contains(cell))
|
||||
continue;
|
||||
|
||||
cellIds.add(cell);
|
||||
|
||||
Block block = cell.getBlock();
|
||||
if (!blockIds.contains(block)) {
|
||||
@@ -43,6 +45,7 @@ public class SudokuSerializer {
|
||||
}
|
||||
|
||||
int blockID = blockIds.indexOf(block);
|
||||
assert (blockID >= 0);
|
||||
int symbolIndex = cell.getSymbolIndex();
|
||||
|
||||
JSONObject cellJsonObject = new JSONObject();
|
||||
@@ -58,16 +61,17 @@ public class SudokuSerializer {
|
||||
|
||||
// init blocks
|
||||
|
||||
for (Block blockId : blockIds) {
|
||||
JSONObject blockJsonObject = new JSONObject();
|
||||
JSONArray cellsJsonArray = new JSONArray();
|
||||
for (Cell cell : blockId.getCells()) {
|
||||
int cellID = cellIds.indexOf(cell);
|
||||
cellsJsonArray.put(cellID);
|
||||
}
|
||||
blockJsonObject.put("cellIDs", cellsJsonArray);
|
||||
jsonBlocks.put(blockJsonObject);
|
||||
}
|
||||
for (Block blockId : blockIds) {
|
||||
JSONObject blockJsonObject = new JSONObject();
|
||||
JSONArray cellsJsonArray = new JSONArray();
|
||||
for (Cell cell : blockId.getCells()) {
|
||||
int cellID = cellIds.indexOf(cell);
|
||||
assert (cellID >= 0);
|
||||
cellsJsonArray.put(cellID);
|
||||
}
|
||||
blockJsonObject.put("cellIDs", cellsJsonArray);
|
||||
jsonBlocks.put(blockJsonObject);
|
||||
}
|
||||
|
||||
for (int i = 0; i < multidoku.getNbSubGrids(); i++) {
|
||||
// serialise sub grid
|
||||
@@ -82,6 +86,7 @@ public class SudokuSerializer {
|
||||
|
||||
for (Cell cell : sudoku.getCells()) {
|
||||
int cellID = cellIds.indexOf(cell);
|
||||
assert (cellID >= 0);
|
||||
cellsJsonArray.put(cellID);
|
||||
}
|
||||
|
||||
@@ -89,13 +94,23 @@ public class SudokuSerializer {
|
||||
|
||||
for (Block block : sudoku.getBlocks()) {
|
||||
int blockID = blockIds.indexOf(block);
|
||||
assert (blockID >= 0);
|
||||
blocksJsonArray.put(blockID);
|
||||
}
|
||||
|
||||
// serialize constraints
|
||||
|
||||
for (Constraint cons : sudoku.getConstraints()) {
|
||||
constraintsJsonArray.put(cons.ordinal());
|
||||
for (IConstraint cons : sudoku.getConstraints()) {
|
||||
boolean constraintSerialized = false;
|
||||
for (Constraint enumCons : Constraint.values()) {
|
||||
if (cons.getClass().isAssignableFrom(enumCons.getConstraint().getClass())) {
|
||||
constraintSerialized = true;
|
||||
constraintsJsonArray.put(enumCons.ordinal());
|
||||
}
|
||||
}
|
||||
if (!constraintSerialized) {
|
||||
System.out.println("La contrainte " + cons.getClass() + " n'a pas pu être sérialisé !");
|
||||
}
|
||||
}
|
||||
|
||||
jsonSudoku.put("constraints", constraintsJsonArray);
|
||||
@@ -114,21 +129,19 @@ public class SudokuSerializer {
|
||||
|
||||
/**
|
||||
* Save a serialized MultiDoku in a JSON file.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku to save.
|
||||
* @return String, the path of the save.
|
||||
*/
|
||||
public static String saveMultiDoku(final MultiDoku doku) {
|
||||
|
||||
JSONObject jsonRoot = serializeSudoku(doku);
|
||||
|
||||
File f = new File("save", "save.json");
|
||||
int i = 0;
|
||||
|
||||
while (f.exists()) {
|
||||
String newName = "save-" + ++i + ".json";
|
||||
f = new File("save", newName);
|
||||
}
|
||||
|
||||
try (FileWriter file = new FileWriter(f)) {
|
||||
file.write(jsonRoot.toString(3));
|
||||
} catch (IOException e) {
|
||||
@@ -137,8 +150,28 @@ public class SudokuSerializer {
|
||||
return f.getAbsolutePath();
|
||||
}
|
||||
|
||||
public static String saveMultiDoku(final MultiDoku doku, final int saveToOverwrite) {
|
||||
File f;
|
||||
if (saveToOverwrite == 0) {
|
||||
f = new File("save", "save.json");
|
||||
} else {
|
||||
f = new File("save", "save-" + saveToOverwrite + ".json");
|
||||
}
|
||||
if (!f.exists()) {
|
||||
return saveMultiDoku(doku);
|
||||
} else {
|
||||
try (FileWriter file = new FileWriter(f)) {
|
||||
file.write(serializeSudoku(doku).toString(3));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return f.getAbsolutePath();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a MultiDoku from a pre-existing json save file.
|
||||
*
|
||||
* @param numberSave int, number of the save file to open.
|
||||
* @return MultiDoku, MultoDoku contained in the file.
|
||||
* @throws Exception when the given save file does not exist.
|
||||
@@ -158,20 +191,6 @@ public class SudokuSerializer {
|
||||
throw new Exception("This save does not exist.");
|
||||
} else {
|
||||
fileContent = new String(Files.readAllBytes(Paths.get("save/" + fileName)));
|
||||
/*
|
||||
try {
|
||||
FileReader file = new FileReader(f);
|
||||
char[] rawFileContent = {};
|
||||
int length = 1000;
|
||||
while (file.read(rawFileContent, 0, length) != -1) {
|
||||
rawFileContent = new char[]{};
|
||||
length = length * 10;
|
||||
}
|
||||
fileContent = new String(rawFileContent);
|
||||
} catch (IOException e) {
|
||||
throw new Exception("Error reading file.");
|
||||
}
|
||||
*/
|
||||
return deserializeSudoku(fileContent);
|
||||
}
|
||||
}
|
||||
@@ -224,7 +243,7 @@ public class SudokuSerializer {
|
||||
|
||||
List<Cell> sudokuCells = new ArrayList<>();
|
||||
List<Block> sudokuBlocks = new ArrayList<>();
|
||||
List<Constraint> sudokuConstraints = new ArrayList<>();
|
||||
List<IConstraint> sudokuConstraints = new ArrayList<>();
|
||||
|
||||
for (int j = 0; j < sudokuCellsJsonArray.length(); j++) {
|
||||
int cellID = sudokuCellsJsonArray.getInt(j);
|
||||
@@ -238,7 +257,7 @@ public class SudokuSerializer {
|
||||
|
||||
for (int j = 0; j < sudokuConstraintsJsonArray.length(); j++) {
|
||||
int constraintID = sudokuConstraintsJsonArray.getInt(j);
|
||||
sudokuConstraints.add(Constraint.values()[constraintID]);
|
||||
sudokuConstraints.add(Constraint.values()[constraintID].getConstraint());
|
||||
}
|
||||
|
||||
Sudoku s = new Sudoku(sudokuCells, sudokuBlocks, sudokuConstraints);
|
||||
|
||||
49
app/src/main/java/sudoku/solver/BacktrackingSolver.java
Normal file
49
app/src/main/java/sudoku/solver/BacktrackingSolver.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class BacktrackingSolver implements Solver {
|
||||
|
||||
/**
|
||||
* Résout le MultiDoku passé en paramètre, avec backtracking.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku à résoudre.
|
||||
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
|
||||
*/
|
||||
@Override
|
||||
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
|
||||
if (Thread.interrupted())
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
|
||||
if (doku.isSolved()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Cell cellToFill = doku.getFirstEmptyCell();
|
||||
if (cellToFill == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
|
||||
if (possibleSymbols.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int symbol : possibleSymbols) {
|
||||
cellToFill.setSymbolIndex(symbol);
|
||||
addStep(cellToFill, steps);
|
||||
if (this.solve(doku, steps)) {
|
||||
return true;
|
||||
} else {
|
||||
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
|
||||
addStep(cellToFill, steps);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
53
app/src/main/java/sudoku/solver/HintHelper.java
Normal file
53
app/src/main/java/sudoku/solver/HintHelper.java
Normal file
@@ -0,0 +1,53 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
//TODO
|
||||
public class HintHelper {
|
||||
|
||||
public static record Hint(Cell cell, int newValue) {}
|
||||
|
||||
public static Hint getHint(MultiDoku doku, Solver solver) {
|
||||
doku.getStateManager().pushState();
|
||||
doku.clearMutableCells();
|
||||
if (!solver.solve(doku))
|
||||
return null;
|
||||
var stateSolved = doku.getStateManager().popAndGetState();
|
||||
// find differences
|
||||
Map<Cell, Integer> newValues = new HashMap<>();
|
||||
for (var entry : stateSolved.entrySet()) {
|
||||
Cell cell = entry.getKey();
|
||||
// we only want the cells that can be filled
|
||||
if (!cell.isMutable())
|
||||
continue;
|
||||
int oldValue = cell.getSymbolIndex();
|
||||
int newValue = stateSolved.get(cell);
|
||||
if (oldValue == newValue)
|
||||
continue;
|
||||
// we have to clear the cell
|
||||
if (newValue == Cell.NOSYMBOL)
|
||||
return new Hint(cell, newValue);
|
||||
// we have to change the cell value
|
||||
if (oldValue != Cell.NOSYMBOL)
|
||||
return new Hint(cell, newValue);
|
||||
|
||||
// there is a valid move
|
||||
newValues.put(cell, newValue);
|
||||
}
|
||||
|
||||
// this is too complex just for fetching a random entry, but whatever ...
|
||||
Random r = new Random();
|
||||
List<Cell> cells = new ArrayList<>(newValues.keySet());
|
||||
Cell randomCell = cells.get(r.nextInt(cells.size()));
|
||||
int randomCellValue = newValues.get(randomCell);
|
||||
return new Hint(randomCell, randomCellValue);
|
||||
}
|
||||
|
||||
}
|
||||
39
app/src/main/java/sudoku/solver/HumanSolver.java
Normal file
39
app/src/main/java/sudoku/solver/HumanSolver.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class HumanSolver implements Solver {
|
||||
|
||||
/**
|
||||
* Résout le MultiDoku passé en paramètre, avec règles de déduction.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku à résoudre.
|
||||
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
|
||||
*/
|
||||
@Override
|
||||
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
|
||||
while (!doku.isSolved()) {
|
||||
boolean filledCell = false;
|
||||
for (Cell cell : doku.getCells()) {
|
||||
if (!cell.isMutable() || !cell.isEmpty())
|
||||
continue;
|
||||
|
||||
List<Integer> possibleSymbols = cell.getPossibleSymbols();
|
||||
if (possibleSymbols.size() == 1) {
|
||||
cell.setSymbolIndex(possibleSymbols.getFirst());
|
||||
addStep(cell, steps);
|
||||
filledCell = true;
|
||||
}
|
||||
}
|
||||
// on ne peut plus remplir de cases, on abandonne
|
||||
if (!filledCell)
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
74
app/src/main/java/sudoku/solver/MixedSolver.java
Normal file
74
app/src/main/java/sudoku/solver/MixedSolver.java
Normal file
@@ -0,0 +1,74 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class MixedSolver implements Solver {
|
||||
|
||||
private Cell findCellToBacktrack(MultiDoku doku, int maxPossibilities) {
|
||||
for (Cell cell : doku.getCells()) {
|
||||
if (!cell.isMutable() || !cell.isEmpty())
|
||||
continue;
|
||||
|
||||
List<Integer> possibleSymbols = cell.getPossibleSymbols();
|
||||
if (possibleSymbols.size() == maxPossibilities) {
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout le MultiDoku passé en paramètre, avec règles de déduction et
|
||||
* backtracking.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku à résoudre.
|
||||
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
|
||||
*/
|
||||
@Override
|
||||
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
|
||||
if (Thread.interrupted()) {
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
}
|
||||
|
||||
while (!doku.isSolved()) {
|
||||
boolean filledCell = false;
|
||||
for (Cell cell : doku.getCells()) {
|
||||
if (!cell.isMutable() || !cell.isEmpty())
|
||||
continue;
|
||||
|
||||
List<Integer> possibleSymbols = cell.getPossibleSymbols();
|
||||
if (possibleSymbols.size() == 1) {
|
||||
cell.setSymbolIndex(possibleSymbols.getFirst());
|
||||
addStep(cell, steps);
|
||||
filledCell = true;
|
||||
}
|
||||
}
|
||||
// on ne peut plus remplir de cases, on tente de backtrack
|
||||
if (!filledCell) {
|
||||
int maxPossibilities = 2;
|
||||
Cell backtrackCell = null;
|
||||
while (backtrackCell == null) {
|
||||
backtrackCell = findCellToBacktrack(doku, maxPossibilities);
|
||||
maxPossibilities++;
|
||||
}
|
||||
// on fait du backtracking
|
||||
List<Integer> possibilities = backtrackCell.getPossibleSymbols();
|
||||
for (int symbol : possibilities) {
|
||||
doku.getStateManager().pushState();
|
||||
backtrackCell.setSymbolIndex(symbol);
|
||||
if (solve(doku, steps))
|
||||
return true;
|
||||
doku.getStateManager().popState();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
55
app/src/main/java/sudoku/solver/RandomSolver.java
Normal file
55
app/src/main/java/sudoku/solver/RandomSolver.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public class RandomSolver implements Solver {
|
||||
|
||||
/**
|
||||
* Résout, si possible, le multidoku passé en paramètre
|
||||
* en testant toutes les possibilités, de manière aléatoire, avec un algorithme
|
||||
* de backtracking.
|
||||
*
|
||||
* @param doku Multidoku, à résoudre
|
||||
* @return boolean, true s'il est résolu ou false s'il ne l'est pas.
|
||||
*/
|
||||
@Override
|
||||
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
|
||||
Random rand = new Random();
|
||||
|
||||
if (Thread.interrupted())
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
|
||||
if (doku.isSolved()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Cell cellToFill = doku.getFirstEmptyCell();
|
||||
if (cellToFill == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
|
||||
|
||||
while (!possibleSymbols.isEmpty()) {
|
||||
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
|
||||
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
|
||||
|
||||
cellToFill.setSymbolIndex(nextSymbol);
|
||||
addStep(cellToFill, steps);
|
||||
if (this.solve(doku, steps)) {
|
||||
return true;
|
||||
}
|
||||
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
|
||||
addStep(cellToFill, steps);
|
||||
possibleSymbols.remove(nextPossibleSymbolIndex);
|
||||
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,177 +1,61 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import sudoku.io.SudokuPrinter;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.Sudoku;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class Solver {
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.MultiDoku;
|
||||
|
||||
public interface Solver {
|
||||
|
||||
/**
|
||||
* Log du Solver, qui garde trace des actions réalisées.
|
||||
*/
|
||||
private static final Logger logger = Logger.getLogger("SolverLogger");
|
||||
public static final Logger logger = Logger.getLogger("SolverLogger");
|
||||
|
||||
/**
|
||||
* Résout, si possible, le multidoku passé en paramètre
|
||||
* en testant toutes les possibilités, de manière aléatoire, avec un algorithme
|
||||
* de backtracking.
|
||||
*
|
||||
* @param doku Multidoku, à résoudre
|
||||
* @param rand Random, pour tester aléatoirement les symboles
|
||||
* @return boolean, true s'il est résolu ou false s'il ne l'est pas.
|
||||
*/
|
||||
public static boolean solveRandom(MultiDoku doku, Random rand) {
|
||||
if (Thread.interrupted())
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
boolean solve(MultiDoku doku, List<SolverStep> solverSteps);
|
||||
|
||||
Sudoku sudoku = doku.getSubGrid(0);
|
||||
logger.log(Level.FINE,
|
||||
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
|
||||
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
|
||||
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
|
||||
|
||||
if (doku.isSolved()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Cell cellToFill = doku.getFirstEmptyCell();
|
||||
if (cellToFill == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
|
||||
|
||||
while (!possibleSymbols.isEmpty()) {
|
||||
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
|
||||
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
|
||||
|
||||
cellToFill.setSymbolIndex(nextSymbol);
|
||||
if (Solver.solveRandom(doku, rand)) {
|
||||
return true;
|
||||
}
|
||||
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
|
||||
possibleSymbols.remove(nextPossibleSymbolIndex);
|
||||
|
||||
}
|
||||
return false;
|
||||
default boolean solve(MultiDoku doku) {
|
||||
return solve(doku, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
|
||||
* @param oldDoku MultiDoku, MultiDoku dont on veut le nombre de solutions.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku dont on veut le nombre de solutions.
|
||||
* @return int, nombre de solutions possibles.
|
||||
*/
|
||||
public static int countSolution(MultiDoku oldDoku) {
|
||||
default int countSolution(MultiDoku doku) {
|
||||
int result = 0;
|
||||
|
||||
MultiDoku doku = oldDoku.clone();
|
||||
|
||||
if (doku.isSolved()) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
Cell cellToFill = doku.getFirstEmptyCell();
|
||||
if (cellToFill == null) {
|
||||
System.out.println("AAAAAAAAAAAAAA");
|
||||
return 0;
|
||||
}
|
||||
assert (cellToFill != null);
|
||||
|
||||
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
|
||||
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
|
||||
|
||||
for (int symbol : possibleSymbols) {
|
||||
doku.getStateManager().pushState();
|
||||
cellToFill.setSymbolIndex(symbol);
|
||||
System.out.println("symbol : "+symbol);
|
||||
System.out.println("doku.isSolved() || Solver.solve(doku) ? "+ (doku.isSolved() || Solver.solve(doku)));
|
||||
if (doku.isSolved() || Solver.solve(doku)) {
|
||||
if (solve(doku)) {
|
||||
result++;
|
||||
if (result > 1) {
|
||||
doku.getStateManager().popState();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
|
||||
doku.getStateManager().popState();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout le MultiDoku passé en paramètre, avec backtracking.
|
||||
* @param doku MultiDoku, MultiDoku à résoudre.
|
||||
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
|
||||
*/
|
||||
public static boolean solve(MultiDoku doku) {
|
||||
if (Thread.interrupted())
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
|
||||
if (doku.isSolved()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Cell cellToFill = doku.getFirstEmptyCell();
|
||||
if (cellToFill == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
|
||||
if (possibleSymbols.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int symbol : possibleSymbols) {
|
||||
|
||||
cellToFill.setSymbolIndex(symbol);
|
||||
if (Solver.solve(doku)) {
|
||||
return true;
|
||||
} else {
|
||||
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
|
||||
}
|
||||
|
||||
}
|
||||
return false;
|
||||
default void addStep(Cell cell, List<SolverStep> steps) {
|
||||
if (steps == null)
|
||||
return;
|
||||
steps.add(new SolverStep(cell));
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout le MultiDoku passé en paramètre, sans backtracking.
|
||||
* @param doku MultiDoku, MultiDoku à résoudre.
|
||||
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
|
||||
*/
|
||||
public static boolean humanSolve(MultiDoku doku) {
|
||||
if (Thread.interrupted())
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
|
||||
List<Cell> cellsToFill = doku.getEmptyCells();
|
||||
|
||||
while (!cellsToFill.isEmpty()) {
|
||||
|
||||
Sudoku sudoku = doku.getSubGrid(0);
|
||||
logger.log(Level.FINE,
|
||||
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
|
||||
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
|
||||
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
|
||||
|
||||
boolean blocked = true;
|
||||
for (Cell cellToFill : cellsToFill) {
|
||||
|
||||
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
|
||||
if (possibleSymbols.size() != 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
|
||||
cellsToFill.remove(cellToFill);
|
||||
blocked = false;
|
||||
break;
|
||||
}
|
||||
|
||||
if (blocked) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return doku.isSolved();
|
||||
}
|
||||
}
|
||||
|
||||
23
app/src/main/java/sudoku/solver/SolverStep.java
Normal file
23
app/src/main/java/sudoku/solver/SolverStep.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import sudoku.structure.Cell;
|
||||
|
||||
public class SolverStep {
|
||||
|
||||
private final Cell cell;
|
||||
private final int newValue;
|
||||
|
||||
public SolverStep(Cell cell) {
|
||||
this.cell = cell;
|
||||
this.newValue = cell.getSymbolIndex();
|
||||
}
|
||||
|
||||
public int getNewValue() {
|
||||
return newValue;
|
||||
}
|
||||
|
||||
public Cell getCell() {
|
||||
return cell;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CancellationException;
|
||||
|
||||
import sudoku.structure.Coordinate;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Sudoku;
|
||||
|
||||
/**
|
||||
* Class de test non utilisé
|
||||
*/
|
||||
public class StupidSolver {
|
||||
public class StupidSolver implements Solver{
|
||||
|
||||
private static boolean solve(Sudoku sudoku, int index) {
|
||||
private boolean solve(Sudoku sudoku, int index, List<SolverStep> steps) {
|
||||
// mécanisme d'abandon
|
||||
if (Thread.interrupted())
|
||||
throw new CancellationException("User wants to stop the solver");
|
||||
@@ -22,28 +22,30 @@ public class StupidSolver {
|
||||
|
||||
// si la case n'est pas modifiable, on passe à la suivante
|
||||
if (!sudoku.getCell(index).isMutable())
|
||||
return solve(sudoku, index + 1);
|
||||
return solve(sudoku, index + 1, steps);
|
||||
|
||||
Coordinate coords = sudoku.toCoords(index);
|
||||
for (int symbol = 0; symbol < sudoku.getSize(); symbol++) {
|
||||
if (sudoku.tryPlaceCellSymbol(coords.getX(), coords.getY(), symbol)) {
|
||||
if (sudoku.getCell(index).trySetValue(symbol)) {
|
||||
addStep(sudoku.getCell(index), steps);
|
||||
// on tente de placer sur la case suivante
|
||||
if (solve(sudoku, index + 1)) {
|
||||
if (solve(sudoku, index + 1, steps)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// on a tout essayé et rien n'a fonctionné
|
||||
sudoku.clearCell(coords.getX(), coords.getY());
|
||||
sudoku.getCell(index).empty();
|
||||
addStep(sudoku.getCell(index), steps);
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean solve(MultiDoku doku) {
|
||||
@Override
|
||||
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
|
||||
if (doku.isSolved())
|
||||
return true;
|
||||
|
||||
for (Sudoku sudoku : doku.getSubGrids()) {
|
||||
if (!solve(sudoku, 0))
|
||||
if (!solve(sudoku, 0, steps))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -4,28 +4,41 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Class qui représente les block de chaque sudoku,
|
||||
* Un block étant un ensemble de cellule avec une contrainte de block qui lui
|
||||
* ait associé
|
||||
* Class qui représente les Block de chaque Sudoku,
|
||||
* Un Block étant un ensemble de cellule avec une contrainte de block qui lui
|
||||
* ait associé.
|
||||
*/
|
||||
public class Block {
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
|
||||
|
||||
/**
|
||||
* L'ensemble des cellules du block
|
||||
* L'ensemble des cellules du block.
|
||||
*/
|
||||
private final List<Cell> cells;
|
||||
|
||||
/**
|
||||
* List de sudoku qui contiennent le block
|
||||
* Pour un acces plus rapide aux sudokus
|
||||
* Liste de Sudoku qui contiennent le block
|
||||
* Pour un accès plus rapide aux sudokus.
|
||||
*/
|
||||
private final List<Sudoku> sudokus;
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="METHODES">
|
||||
|
||||
/**
|
||||
* Crée un Block avec une liste de Cell donnée.
|
||||
* @param cells List<Cell>
|
||||
*/
|
||||
public Block(List<Cell> cells) {
|
||||
this.cells = cells;
|
||||
this.sudokus = new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée un Block avec une liste de Cell vide.
|
||||
*/
|
||||
public Block() {
|
||||
this(new ArrayList<>());
|
||||
}
|
||||
@@ -33,13 +46,16 @@ public class Block {
|
||||
public List<Cell> getCells() {
|
||||
return cells;
|
||||
}
|
||||
public List<Sudoku> getSudokus() {
|
||||
return sudokus;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute une Cell au Block
|
||||
*
|
||||
* @param newCell Cell, à ajouter
|
||||
*/
|
||||
void addCell(Cell newCell) {
|
||||
public void addCell(Cell newCell) {
|
||||
this.cells.add(newCell);
|
||||
}
|
||||
|
||||
@@ -57,16 +73,5 @@ public class Block {
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean containsCell(Cell cell) {
|
||||
for (Cell cellTmp : this.cells) {
|
||||
if (cellTmp.equals(cell)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public List<Sudoku> getSudokus() {
|
||||
return sudokus;
|
||||
}
|
||||
// </editor-fold>
|
||||
}
|
||||
|
||||
@@ -9,6 +9,8 @@ import java.util.List;
|
||||
*/
|
||||
public class Cell {
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
|
||||
|
||||
/**
|
||||
* Constante de valeur d'index de symbole quand il n'y en a pas,
|
||||
* soit que la Cell est vide.
|
||||
@@ -24,28 +26,25 @@ public class Cell {
|
||||
* Il est initialisé à Cell.NOSYMBOL.
|
||||
*/
|
||||
private int symbolIndex = Cell.NOSYMBOL;
|
||||
/**
|
||||
* Liste des index de symbole possibles pour cette Cell,
|
||||
* en fonction des contraintes de sudoku dans lequel elle est.
|
||||
*/
|
||||
private final List<Integer> possibleSymbols;
|
||||
/**
|
||||
* Si cette Cell peut être modififié ou non.
|
||||
*/
|
||||
private boolean isMutable = true;
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="METHODES">
|
||||
|
||||
public Cell() {
|
||||
this.possibleSymbols = new ArrayList<>();
|
||||
this(Cell.NOSYMBOL);
|
||||
}
|
||||
|
||||
public Cell(int symbolIndex) {
|
||||
this.symbolIndex = symbolIndex;
|
||||
this.possibleSymbols = new ArrayList<>();
|
||||
}
|
||||
|
||||
public Cell(int symbolIndex, boolean isMutable) {
|
||||
this.symbolIndex = symbolIndex;
|
||||
this.possibleSymbols = new ArrayList<>();
|
||||
this.isMutable = isMutable;
|
||||
}
|
||||
|
||||
@@ -53,13 +52,24 @@ public class Cell {
|
||||
return this.symbolIndex;
|
||||
}
|
||||
|
||||
public void setSymbolIndex(int symbolIndex) {
|
||||
this.symbolIndex = symbolIndex;
|
||||
/**
|
||||
* Renvoie le Block qui la contient.
|
||||
* @return Block.
|
||||
*/
|
||||
public Block getBlock() {
|
||||
return this.blockContainer;
|
||||
}
|
||||
|
||||
public void setPossibleSymbols(List<Integer> possibleSymbols) {
|
||||
this.possibleSymbols.clear();
|
||||
this.possibleSymbols.addAll(possibleSymbols);
|
||||
/**
|
||||
* Renvoie si la Cell est modifiable
|
||||
* @return boolean, true si elle est modifiable ou false sinon.
|
||||
*/
|
||||
public boolean isMutable() {
|
||||
return this.isMutable;
|
||||
}
|
||||
|
||||
public void setSymbolIndex(int symbolIndex) {
|
||||
this.symbolIndex = symbolIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -69,22 +79,16 @@ public class Cell {
|
||||
this.isMutable = false;
|
||||
}
|
||||
|
||||
public Block getBlock() {
|
||||
return this.blockContainer;
|
||||
}
|
||||
|
||||
public void setBlock(Block block) {
|
||||
this.blockContainer = block;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the current symbolIndex and returns it
|
||||
* @return integer symbolIndex cleared
|
||||
* Vide la Cell.
|
||||
*/
|
||||
public int clearCurrentSymbol() {
|
||||
int i = this.symbolIndex;
|
||||
public void clearCurrentSymbol() {
|
||||
setSymbolIndex(NOSYMBOL);
|
||||
return i;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,22 +99,6 @@ public class Cell {
|
||||
return this.symbolIndex == Cell.NOSYMBOL;
|
||||
}
|
||||
|
||||
public void removeSymbolFromPossibilities(int indexSymbol) {
|
||||
possibleSymbols.remove(indexSymbol);
|
||||
}
|
||||
|
||||
public List<Integer> getPossibleSymbols() {
|
||||
return this.possibleSymbols;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie si la Cell est modifiable
|
||||
* @return boolean, true si elle est modifiable ou false sinon.
|
||||
*/
|
||||
public boolean isMutable() {
|
||||
return this.isMutable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vide la Cell, en renvoie l'ancien index du symbole qui était dedans.
|
||||
* @return int, index du symbole anciennement contenue dans la Cell.
|
||||
@@ -120,4 +108,53 @@ public class Cell {
|
||||
this.symbolIndex = Cell.NOSYMBOL;
|
||||
return oldSymbol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si la Cell peut prendre ce symbole par rapport aux contraintes de ses Sudokus.
|
||||
* @param value int, index du symbole
|
||||
* @return boolean, true si elle peut, false sinon.
|
||||
*/
|
||||
public boolean canHaveValue(int value) {
|
||||
for (Sudoku s :getBlock().getSudokus()) {
|
||||
int cellIndex = s.getCells().indexOf(this);
|
||||
// la cellule existe
|
||||
if (cellIndex != -1) {
|
||||
int cellX = cellIndex % s.getSize();
|
||||
int cellY = cellIndex / s.getSize();
|
||||
if (!s.canBePlaced(cellX, cellY, value)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie les symboles que peut prendre cette Cell par rapport aux contraintes de ses Sudokus.
|
||||
* @return List<Integer>, la liste des symboles possibles.
|
||||
*/
|
||||
public List<Integer> getPossibleSymbols() {
|
||||
List<Integer> result = new ArrayList<>();
|
||||
for (int i = 0; i < getBlock().getSudokus().get(0).getSize(); i++) {
|
||||
if (canHaveValue(i))
|
||||
result.add(i);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Essaye de placer la valeur et renvoie false si ce n'est pas possible.
|
||||
* @param newValue int, valeur à placer.
|
||||
* @return boolean, true si la Cell à pris la valeur newValue, false sinon.
|
||||
*/
|
||||
public boolean trySetValue(int newValue) {
|
||||
if (!isMutable())
|
||||
return false;
|
||||
if (!canHaveValue(newValue))
|
||||
return false;
|
||||
setSymbolIndex(newValue);
|
||||
return true;
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
package sudoku.structure;
|
||||
|
||||
/**
|
||||
* Représente les coordonnées d'une Cell
|
||||
* Représente les coordonnées d'une Cell.
|
||||
*/
|
||||
public class Coordinate {
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
|
||||
|
||||
/**
|
||||
* L'abscisse de la Cell.
|
||||
*/
|
||||
@@ -14,6 +16,10 @@ public class Coordinate {
|
||||
*/
|
||||
private int y;
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="METHODES">
|
||||
|
||||
public Coordinate(int x, int y) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
@@ -35,16 +41,23 @@ public class Coordinate {
|
||||
this.y = y;
|
||||
}
|
||||
|
||||
public int calculateIndex(int size) {
|
||||
return this.y * size + this.x;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajoute la Coordiante donnée à celle-ci.
|
||||
* @param other Coordiante, à ajouter.
|
||||
* @return Coordinate, le résultat de l'addition.
|
||||
*/
|
||||
public Coordinate add(Coordinate other) {
|
||||
return new Coordinate(this.x + other.x, this.y + other.y);
|
||||
}
|
||||
|
||||
/**
|
||||
* Soustrait la Coordiante donnée à celle-ci.
|
||||
* @param other Coordiante, à soustraire.
|
||||
* @return Coordinate, le résultat de la soustraction.
|
||||
*/
|
||||
public Coordinate sub(Coordinate other) {
|
||||
return new Coordinate(this.x - other.x, this.y - other.y);
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
}
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
package sudoku.structure;
|
||||
|
||||
//TODO: melvyn va passer par là
|
||||
/**
|
||||
* Les difficultés d'un Sudoku,
|
||||
* représente le nombre de cases à enlever, en proportion, à un Sudoku.
|
||||
* Par exemple, avec 0.1 de factor, on enlevera 10% des cases.
|
||||
*/
|
||||
public enum Difficulty {
|
||||
|
||||
VeryEasy("Très facile", 0.1), Easy("Facile", 0.25), Medium("Moyen", 0.5), Hard("Difficile", 0.75);
|
||||
VeryEasy("Très facile", 0.1),
|
||||
Easy("Facile", 0.25),
|
||||
Medium("Moyen", 0.5),
|
||||
Hard("Difficile", 0.75),
|
||||
VeryHard("Impossible", 0.78);
|
||||
|
||||
double factor;
|
||||
String displayName;
|
||||
/**
|
||||
* Le pourcentage de Cell à enlever.
|
||||
*/
|
||||
final double factor;
|
||||
/**
|
||||
* Le nom de la difficulté.
|
||||
*/
|
||||
final String displayName;
|
||||
|
||||
private Difficulty(String displayName, double factor) {
|
||||
Difficulty(String displayName, double factor) {
|
||||
this.factor = factor;
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public double getFactor() {
|
||||
return factor;
|
||||
}
|
||||
|
||||
private static final String[] difficultyNames;
|
||||
|
||||
static {
|
||||
@@ -31,6 +37,14 @@ public enum Difficulty {
|
||||
}
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public double getFactor() {
|
||||
return factor;
|
||||
}
|
||||
|
||||
public static String[] getDifficultyNames() {
|
||||
return difficultyNames;
|
||||
}
|
||||
|
||||
@@ -1,166 +1,63 @@
|
||||
package sudoku.structure;
|
||||
|
||||
import sudoku.io.SudokuPrinter;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import sudoku.io.SudokuSerializer;
|
||||
|
||||
/**
|
||||
* @class MultiDoku
|
||||
* @brief Représente une grille de Multidoku.
|
||||
* Une grille de sudoku est un multidoku avec un seul sous-sudoku
|
||||
* Une grille de sudoku est un multidoku avec un seul sous-sudoku.
|
||||
*/
|
||||
public class MultiDoku {
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
|
||||
|
||||
/**
|
||||
* Liste des sous-Sudoku contenue dans le multidoku.
|
||||
*/
|
||||
private final List<Sudoku> subGrids;
|
||||
|
||||
/**
|
||||
* Pile, qui contient des états du MultiDoku,
|
||||
* utile pour la résolution.
|
||||
*/
|
||||
private final StateManager stateManager;
|
||||
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="METHODES">
|
||||
|
||||
public MultiDoku(List<Sudoku> subGrids) {
|
||||
this.subGrids = subGrids;
|
||||
}
|
||||
|
||||
public MultiDoku clone() {
|
||||
//TODO: ahhhhhhhhhhhhhhhhhhhhhhh
|
||||
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
|
||||
this.stateManager = new StateManager(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie le nombre de sudoku contenu dans ce MultiDoku.
|
||||
* @return int
|
||||
*/
|
||||
public int getNbSubGrids(){
|
||||
return subGrids.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la ie sudoku contenue dans ce MultiDoku.
|
||||
* @param i int, indice du sudoku à renvoyer.
|
||||
* @return Sudoku, ie Sudoku
|
||||
*/
|
||||
public Sudoku getSubGrid(int i){
|
||||
return subGrids.get(i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells contenue dans ce MultiDoku,
|
||||
* soit les Cells contenues de chaques sous-Sudoku.
|
||||
* @return List<Cell>
|
||||
*/
|
||||
public List<Cell> getCells(){
|
||||
Set<Cell> cellsSet = new HashSet<>();
|
||||
for (Sudoku sudoku : subGrids){
|
||||
cellsSet.addAll(sudoku.getCells());
|
||||
}
|
||||
return new ArrayList<>(cellsSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour les symboles possibles de chaque Cell.
|
||||
* @throws Exception, si ce n'est pas possible.
|
||||
*/
|
||||
public void updateSymbolsPossibilities() throws Exception {
|
||||
for (Sudoku sudoku : subGrids){
|
||||
sudoku.updateSymbolsPossibilities();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Multidoku {");
|
||||
for (Sudoku sudoku : subGrids){
|
||||
sb.append("\n\t").append(sudoku.toString());
|
||||
}
|
||||
sb.append("\n}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie les symboles possibles d'une Cell donnée.
|
||||
* @param cellToFill Cell.
|
||||
* @return List<Integer>, liste des symboles possible.
|
||||
*/
|
||||
public List<Integer> getPossibleSymbolsOfCell(Cell cellToFill) {
|
||||
List<Integer> result = new ArrayList<>();
|
||||
boolean hasBeenFill = false;
|
||||
|
||||
for (Sudoku sudoku : this.subGrids) {
|
||||
if (sudoku.contains(cellToFill)) {
|
||||
if (!hasBeenFill) {
|
||||
result.addAll(sudoku.getPossibleSymbolsOfCell(cellToFill));
|
||||
hasBeenFill = true;
|
||||
} else {
|
||||
result.retainAll(sudoku.getPossibleSymbolsOfCell(cellToFill));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie les sous-Sudoku
|
||||
* @return List<Sudoku>
|
||||
*/
|
||||
public List<Sudoku> getSubGrids() {
|
||||
return this.subGrids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check si le MultiDoku est valide, en fonction de ses sous-Sudokus.
|
||||
* @return boolean, true s'il est valide et false sinon.
|
||||
* Check si le MultiDoku est résolu, c'est à dire complet et cohérent avec ses contraintes.
|
||||
*
|
||||
* @return boolean, true s'il est résolu et false sinon.
|
||||
*/
|
||||
public boolean isSolved() {
|
||||
boolean result = true;
|
||||
for (Sudoku sudoku : this.subGrids) {
|
||||
result = sudoku.isSolved() && result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (!(object instanceof MultiDoku)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.getNbSubGrids() != ((MultiDoku) object).getNbSubGrids()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < this.getNbSubGrids(); i++) {
|
||||
if (!this.getSubGrid(i).equals(((MultiDoku) object).getSubGrid(i))) {
|
||||
if (!sudoku.isSolved())
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la 1re Cell vide des sous-Sudoku.
|
||||
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
|
||||
*/
|
||||
public Cell getFirstEmptyCell() {
|
||||
for (Sudoku sudoku : this.subGrids) {
|
||||
Cell cellTmp = sudoku.getFirstEmptyCell();
|
||||
if (cellTmp != null && cellTmp.isEmpty()) {
|
||||
return cellTmp;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells préalablement remplies du MultiDoku.
|
||||
*
|
||||
* @return List<Cell>, vide si aucune Cell n'est remplie.
|
||||
*/
|
||||
public List<Cell> getFilledCells() {
|
||||
List<Cell> result = new ArrayList<>();
|
||||
for (Cell cell : this.getCells()){
|
||||
for (Cell cell : this.getCells()) {
|
||||
if (!cell.isEmpty()) {
|
||||
result.add(cell);
|
||||
}
|
||||
@@ -170,11 +67,12 @@ public class MultiDoku {
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells vides du MultiDoku.
|
||||
*
|
||||
* @return List<Cell>, vide si aucune Cell ne l'est.
|
||||
*/
|
||||
public List<Cell> getEmptyCells() {
|
||||
List<Cell> result = new ArrayList<>();
|
||||
for (Cell cell : this.getCells()){
|
||||
for (Cell cell : this.getCells()) {
|
||||
if (cell.isEmpty()) {
|
||||
result.add(cell);
|
||||
}
|
||||
@@ -182,19 +80,57 @@ public class MultiDoku {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la 1re Cell vide des sous-Sudoku.
|
||||
*
|
||||
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
|
||||
*/
|
||||
public Cell getFirstEmptyCell() {
|
||||
for (Sudoku sudoku : this.subGrids) {
|
||||
Cell cellTmp = sudoku.getFirstEmptyCell();
|
||||
if (cellTmp != null) {
|
||||
return cellTmp;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vide une Cell donnée.
|
||||
* @param cell Cell, à vider.
|
||||
* Renvoie le nombre de sudoku contenu dans ce MultiDoku.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public void empty(Cell cell) {
|
||||
List<Cell> cells = getCells();
|
||||
Cell cellToEmpty = cells.get(cells.indexOf(cell));
|
||||
cellToEmpty.setSymbolIndex(Cell.NOSYMBOL);
|
||||
public int getNbSubGrids() {
|
||||
return subGrids.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la ie sudoku contenue dans ce MultiDoku.
|
||||
*
|
||||
* @param i int, indice du sudoku à renvoyer.
|
||||
* @return Sudoku, ie Sudoku
|
||||
*/
|
||||
public Sudoku getSubGrid(int i) {
|
||||
return subGrids.get(i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells contenue dans ce MultiDoku,
|
||||
* soit les Cells contenues de chaques sous-Sudoku.
|
||||
*
|
||||
* @return List<Cell>
|
||||
*/
|
||||
public List<Cell> getCells() {
|
||||
Set<Cell> cellsSet = new HashSet<>();
|
||||
for (Sudoku sudoku : subGrids) {
|
||||
cellsSet.addAll(sudoku.getCells());
|
||||
}
|
||||
return new ArrayList<>(cellsSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie le nombre de Cell contenue dans le MultiDoku.
|
||||
*
|
||||
* @return int, nombre de Cell dans le MultiDoku.
|
||||
*/
|
||||
public int getNbCells() {
|
||||
@@ -209,5 +145,60 @@ public class MultiDoku {
|
||||
filledCell.setImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vide les Cells modifiable.
|
||||
*/
|
||||
public void clearMutableCells() {
|
||||
for (Sudoku s : getSubGrids()) {
|
||||
for (Cell cell : s.getCells()) {
|
||||
if (cell.isMutable())
|
||||
cell.clearCurrentSymbol();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie les sous-Sudoku
|
||||
*
|
||||
* @return List<Sudoku>
|
||||
*/
|
||||
public List<Sudoku> getSubGrids() {
|
||||
return this.subGrids;
|
||||
}
|
||||
|
||||
public StateManager getStateManager() {
|
||||
return stateManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (!(other instanceof MultiDoku otherDoku))
|
||||
return false;
|
||||
if (this.getNbSubGrids() != otherDoku.getNbSubGrids())
|
||||
return false;
|
||||
for (int i = 0; i < this.getNbSubGrids(); i++) {
|
||||
Sudoku sudoku = this.getSubGrid(i);
|
||||
Sudoku otherSudoku = otherDoku.getSubGrid(i);
|
||||
if (sudoku.getSize() != otherSudoku.getSize())
|
||||
return false;
|
||||
for (int j = 0; j < sudoku.getSize() * sudoku.getSize(); j++) {
|
||||
if (sudoku.getCell(j).getSymbolIndex() != otherSudoku.getCell(j).getSymbolIndex())
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return SudokuPrinter.printMultiDoku(this);
|
||||
}
|
||||
|
||||
public MultiDoku clone() {
|
||||
// TODO: C'est pas dingue de le faire comme ça...
|
||||
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
|
||||
}
|
||||
|
||||
// </editor-fold>
|
||||
}
|
||||
|
||||
59
app/src/main/java/sudoku/structure/StateManager.java
Normal file
59
app/src/main/java/sudoku/structure/StateManager.java
Normal file
@@ -0,0 +1,59 @@
|
||||
package sudoku.structure;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Une pile, qui réprésente les états d'un MultiDoku,
|
||||
* utile pour les Solvers.
|
||||
*/
|
||||
public class StateManager {
|
||||
|
||||
/**
|
||||
* Le MultiDoku auquel il est associé.
|
||||
*/
|
||||
private final MultiDoku doku;
|
||||
|
||||
/**
|
||||
* La pile des états du MultiDoku associé.
|
||||
*/
|
||||
private final Stack<Map<Cell, Integer>> states;
|
||||
|
||||
public StateManager(MultiDoku doku) {
|
||||
this.states = new Stack<>();
|
||||
this.doku = doku;
|
||||
}
|
||||
|
||||
public Map<Cell, Integer> pushState() {
|
||||
states.add(saveState());
|
||||
return states.getLast();
|
||||
}
|
||||
|
||||
public void popState() {
|
||||
assert (!states.isEmpty());
|
||||
restoreState(states.pop());
|
||||
}
|
||||
|
||||
public Map<Cell, Integer> popAndGetState() {
|
||||
assert (!states.isEmpty());
|
||||
var currentState = saveState();
|
||||
restoreState(states.pop());
|
||||
return currentState;
|
||||
}
|
||||
|
||||
private void restoreState(Map<Cell, Integer> state) {
|
||||
for (var entry : state.entrySet()) {
|
||||
entry.getKey().setSymbolIndex(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
private Map<Cell, Integer> saveState() {
|
||||
Map<Cell, Integer> state = new HashMap<>();
|
||||
for (Cell cell : this.doku.getCells()) {
|
||||
state.put(cell, cell.getSymbolIndex());
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,36 +1,45 @@
|
||||
package sudoku.structure;
|
||||
|
||||
import sudoku.constraint.BlockConstraint;
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.constraint.IConstraint;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.constraint.IConstraint;
|
||||
|
||||
/**
|
||||
* @class Sudoku
|
||||
* @brief Représent un Sudoku
|
||||
*/
|
||||
public class Sudoku {
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="ATTRIBUTS">
|
||||
|
||||
/**
|
||||
* Liste des Block contenus dans le Sudoku.
|
||||
*/
|
||||
private final List<Block> blocks;
|
||||
|
||||
/**
|
||||
* Liste des Cells contenus dans le Sudoku.
|
||||
*/
|
||||
private List<Cell> cells = new ArrayList<>();
|
||||
private final List<Cell> cells;
|
||||
|
||||
/**
|
||||
* Liste des contraintes (TODO) du Sudoku.
|
||||
*/
|
||||
private final List<Constraint> constraints;
|
||||
private final List<IConstraint> constraints;
|
||||
|
||||
/**
|
||||
* Largeur des Blocks s'ils sont rectangulaires, valant 0 si ce n'est pas le cas.
|
||||
* Largeur des Blocks s'ils sont rectangulaires,
|
||||
* valant 0 si ce n'est pas le cas.
|
||||
*/
|
||||
private int blockWidth;
|
||||
|
||||
public Sudoku(List<Cell> cells, List<Block> blocks, List<Constraint> constraints) {
|
||||
// </editor-fold>
|
||||
|
||||
// <editor-fold defaultstate="collapsed" desc="METHODES">
|
||||
|
||||
public Sudoku(List<Cell> cells, List<Block> blocks, List<IConstraint> constraints) {
|
||||
this.cells = cells;
|
||||
this.blocks = blocks;
|
||||
this.constraints = constraints;
|
||||
@@ -48,6 +57,7 @@ public class Sudoku {
|
||||
|
||||
/**
|
||||
* Transforme des coordonées d'une Cell en index.
|
||||
*
|
||||
* @param x int, abscisse.
|
||||
* @param y int, ordonnée.
|
||||
* @return int, index correspondant.
|
||||
@@ -58,7 +68,9 @@ public class Sudoku {
|
||||
|
||||
/**
|
||||
* Vérifie que des coordonnées correspondent bien à une Cell dans le Sudoku.
|
||||
* @return boolean, valant true si les coordonnées sont dans les bornes du Sudoku, false sinon.
|
||||
*
|
||||
* @return boolean, valant true si les coordonnées sont dans les bornes du
|
||||
* Sudoku, false sinon.
|
||||
*/
|
||||
public boolean isValidCoords(int x, int y) {
|
||||
int index = toIndex(x, y);
|
||||
@@ -67,21 +79,25 @@ public class Sudoku {
|
||||
|
||||
/**
|
||||
* Vérifie que l'index correspond bien à une Cell dans le Sudoku.
|
||||
* @return boolean, valant true si l'index est dans les bornes du Sudoku, false sinon.
|
||||
*
|
||||
* @return boolean, valant true si l'index est dans les bornes du Sudoku, false
|
||||
* sinon.
|
||||
*/
|
||||
public boolean isValidCoords(int index) {
|
||||
return index < getSize() * getSize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Teste si on peut placer la value dans la Cell aux coordonnées x, y d'après les contraintes du Sudoku.
|
||||
* Teste si on peut placer la value dans la Cell aux coordonnées x, y d'après
|
||||
* les contraintes du Sudoku.
|
||||
*
|
||||
* @param x int, abscisse de la Cell voulue.
|
||||
* @param y int, ordonnée de la Cell voulue.
|
||||
* @param value int, index du symbole qu'on veut placer.
|
||||
* @return boolean, true si on peut la placer et false sinon.
|
||||
*/
|
||||
public boolean canBePlaced(int x, int y, int value) {
|
||||
for (Constraint constraint : this.constraints) {
|
||||
for (IConstraint constraint : this.constraints) {
|
||||
if (!constraint.canBePlaced(this, x, y, value)) {
|
||||
return false;
|
||||
}
|
||||
@@ -90,50 +106,84 @@ public class Sudoku {
|
||||
}
|
||||
|
||||
/**
|
||||
* Tente de placer le symbole value dans la Cell de coordonnées x, y.
|
||||
* @param x int, abscisse de la Cell voulue.
|
||||
* @param y int, coordonnée de la Cell voulue;
|
||||
* @param value int, index du symbole que l'on veut placer.
|
||||
* @return boolean, true si le symbole a été placé, false sinon
|
||||
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses
|
||||
* contraintes.
|
||||
*
|
||||
* @return boolean, valant true si le Sudoku est résolu, false sinon.
|
||||
*/
|
||||
public boolean tryPlaceCellSymbol(int x, int y, int value) {
|
||||
assert (isValidCoords(x, y));
|
||||
if (!canBePlaced(x, y, value))
|
||||
return false;
|
||||
Cell cell = getCell(x, y);
|
||||
cell.setSymbolIndex(value);
|
||||
public boolean isSolved() {
|
||||
boolean isComplete = isComplete();
|
||||
boolean isValid = isValid();
|
||||
return isComplete && isValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie que le Sudoku est complet, soit qu'il n'y ait aucune case vide.
|
||||
*
|
||||
* @return boolean, true si le Sudoku est complet, false sinon.
|
||||
*/
|
||||
private boolean isComplete() {
|
||||
return getFirstEmptyCell() == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si le Sudoku est valide, soit qu'il est cohérent avec ses
|
||||
* contraintes.
|
||||
*
|
||||
* @return bollean, true si le Sudoku est valide, false sinon
|
||||
*/
|
||||
private boolean isValid() {
|
||||
for (int i = 0; i < cells.size(); i++) {
|
||||
Cell cell = getCell(i);
|
||||
if (cell.isEmpty())
|
||||
continue;
|
||||
|
||||
Coordinate coordinate = toCoords(i);
|
||||
|
||||
int symbolPlaced = cell.empty();
|
||||
if (!canBePlaced(coordinate.getX(), coordinate.getY(), symbolPlaced)) {
|
||||
cell.setSymbolIndex(symbolPlaced);
|
||||
return false;
|
||||
}
|
||||
cell.setSymbolIndex(symbolPlaced);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vide la Cell dotn les coordonnées sont renseignées de son symbole.
|
||||
* @param x int, abscisse de la Cell voulue.
|
||||
* @param y int, coordonnée de la Cell voulue.
|
||||
* Renvoie la Cell aux coordonées données.
|
||||
*
|
||||
* @param x int, abscisse.
|
||||
* @param y int, ordonnée.
|
||||
* @return Cell, si une Cell existe aux coordonnées données, null sinon.
|
||||
*/
|
||||
|
||||
public void clearCell(int x, int y) {
|
||||
public Cell getCell(int x, int y) {
|
||||
int index = toIndex(x, y);
|
||||
assert (isValidCoords(x, y));
|
||||
Cell cell = getCell(x, y);
|
||||
cell.setSymbolIndex(Cell.NOSYMBOL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Vide toutes les Cell du Sudoku.
|
||||
*/
|
||||
public void clear() {
|
||||
for (int i = 0; i < getSize() * getSize(); i++) {
|
||||
Cell cell = getCell(i);
|
||||
if (cell.isMutable())
|
||||
cell.setSymbolIndex(Cell.NOSYMBOL);
|
||||
try {
|
||||
return this.cells.get(index);
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public int getBlockWidth() {
|
||||
return blockWidth;
|
||||
/**
|
||||
* Renvoie la 1re Cell vide du Sudoku.
|
||||
*
|
||||
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
|
||||
*/
|
||||
public Cell getFirstEmptyCell() {
|
||||
for (Cell cell : this.cells) {
|
||||
if (cell.isEmpty()) {
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Place le symbole d'index value dans la Cell de coordonnées précisées.
|
||||
*
|
||||
* @param x int, abscisse de la Cell voulue.
|
||||
* @param y int, coordonnée de la Cell voulue.
|
||||
* @param value int, index du symbole à placer.
|
||||
@@ -141,7 +191,7 @@ public class Sudoku {
|
||||
*/
|
||||
public Cell setCellSymbol(int x, int y, int value) {
|
||||
assert (isValidCoords(x, y));
|
||||
for (Constraint constraint : this.constraints) {
|
||||
for (IConstraint constraint : this.constraints) {
|
||||
if (!constraint.canBePlaced(this, x, y, value)) {
|
||||
return null;
|
||||
}
|
||||
@@ -153,6 +203,7 @@ public class Sudoku {
|
||||
|
||||
/**
|
||||
* Place les symboles d'index contenus dans values dans les cases du Sudoku.
|
||||
*
|
||||
* @param values List<Integer>, liste des index des symboles à placer.
|
||||
* @return boolean, vaut true si les symboles ont été placés, false sinon.
|
||||
*/
|
||||
@@ -170,7 +221,9 @@ public class Sudoku {
|
||||
}
|
||||
|
||||
/**
|
||||
* Place les symboles d'index contenus dans values dans les cases du Sudoku et rend ces cases immuables.
|
||||
* Place les symboles d'index contenus dans values dans les cases du Sudoku et
|
||||
* rend ces cases immuables.
|
||||
*
|
||||
* @param values List<Integer>, liste des index des symboles à placer.
|
||||
* @return boolean, vaut true si les symboles ont été placés, false sinon.
|
||||
*/
|
||||
@@ -193,24 +246,14 @@ public class Sudoku {
|
||||
return true;
|
||||
}
|
||||
|
||||
public Cell getCell(int x, int y) {
|
||||
int index = y * getSize() + x;
|
||||
assert (isValidCoords(x, y));
|
||||
try {
|
||||
return this.cells.get(index);
|
||||
} catch (IndexOutOfBoundsException e) {
|
||||
return null;
|
||||
}
|
||||
public boolean hasConstraint(Constraint constraint) {
|
||||
return this.constraints.contains(constraint.getConstraint());
|
||||
}
|
||||
|
||||
public Cell getCell(int i) {
|
||||
return this.cells.get(i);
|
||||
}
|
||||
|
||||
public List<Constraint> getConstraints() {
|
||||
return constraints;
|
||||
}
|
||||
|
||||
public int getSize() {
|
||||
return this.blocks.size();
|
||||
}
|
||||
@@ -223,71 +266,19 @@ public class Sudoku {
|
||||
return this.blocks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si une Cell appartient au Sudoku.
|
||||
* @param cell Cell, cellule dont on veut vérifier l'appartenance au Sudoku.
|
||||
* @return boolean, vaut true si la Cell appartient au Sudoku.
|
||||
*/
|
||||
public boolean contains(Cell cell) {
|
||||
return this.cells.contains(cell);
|
||||
public List<IConstraint> getConstraints() {
|
||||
return constraints;
|
||||
}
|
||||
|
||||
/**
|
||||
* Localise la Cell dans le Sudoku.
|
||||
* @param c Cell, cellule dont on veut les coordonées.
|
||||
* @return Coordinate, coordonnées de la Cell.
|
||||
* @throws Exception si la Cell n'appartient pas au Sudoku.
|
||||
*/
|
||||
private Coordinate getCoordinateCell(Cell c) throws Exception {
|
||||
int x = 0, y = 0;
|
||||
int size = this.getSize();
|
||||
|
||||
if (!this.contains(c)) {
|
||||
throw new Exception("The given cell is not in this sudoku.");
|
||||
}
|
||||
|
||||
// TODO: use this.cells.indexOf();
|
||||
|
||||
for (Cell cell : this.cells) {
|
||||
if (cell == c) {
|
||||
return new Coordinate(x, y);
|
||||
}
|
||||
if (x == size - 1) {
|
||||
y += 1;
|
||||
x = 0;
|
||||
} else {
|
||||
x += 1;
|
||||
}
|
||||
}
|
||||
return new Coordinate(x, y);
|
||||
public int getBlockWidth() {
|
||||
return blockWidth;
|
||||
}
|
||||
|
||||
/**
|
||||
* Met à jour les symboles possibles des Cells du Sudoku.
|
||||
*
|
||||
*/
|
||||
public void updateSymbolsPossibilities() {
|
||||
for (Constraint constraint : constraints) {
|
||||
List<Cell> cells = this.getCells();
|
||||
for (Cell cell : cells) {
|
||||
Coordinate coord = null;
|
||||
try {
|
||||
coord = this.getCoordinateCell(cell);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Cas jamais atteint.");
|
||||
}
|
||||
List<Integer> newPossibleSymbols = cell.getPossibleSymbols();
|
||||
newPossibleSymbols.retainAll(constraint.getPossibleSymbols(
|
||||
this,
|
||||
coord.getX(),
|
||||
coord.getY()
|
||||
));
|
||||
|
||||
cell.setPossibleSymbols(newPossibleSymbols);
|
||||
}
|
||||
}
|
||||
public void setBlockWidth(int blockWidth) {
|
||||
this.blockWidth = blockWidth;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Sudoku {");
|
||||
@@ -302,158 +293,6 @@ public class Sudoku {
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la 1re Cell vide du Sudoku.
|
||||
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
|
||||
*/
|
||||
public Cell getFirstEmptyCell() {
|
||||
for (Cell cell : this.cells) {
|
||||
if (cell.isEmpty()) {
|
||||
return cell;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie l'index des symboles possibles de la Cell passée en paramètres.
|
||||
* @param cellToFill Cell, cellule dont on cherche les symboles posisbles.
|
||||
* @return List<Integer>, la liste des index des symboles possibles, vide si la Cell n'appartient pas au Sudoku.
|
||||
*/
|
||||
public List<Integer> getPossibleSymbolsOfCell(Cell cellToFill) {
|
||||
List<Integer> result = new ArrayList<>();
|
||||
Coordinate cellCoordinates;
|
||||
try {
|
||||
cellCoordinates = this.getCoordinateCell(cellToFill);
|
||||
} catch (Exception e) {
|
||||
return result;
|
||||
}
|
||||
for (int i = 0; i < this.constraints.size(); i++) {
|
||||
Constraint constraint = this.constraints.get(i);
|
||||
if (i == 0) {
|
||||
result.addAll(constraint.getPossibleSymbols(this, cellCoordinates.getX(), cellCoordinates.getY()));
|
||||
} else {
|
||||
result.retainAll(constraint.getPossibleSymbols(this, cellCoordinates.getX(), cellCoordinates.getY()));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses contraintes.
|
||||
* @return boolean, valant true si le Sudoku est résolu, false sinon.
|
||||
*/
|
||||
public boolean isSolved() {
|
||||
boolean isComplete = isComplete();
|
||||
boolean isValid = isValid();
|
||||
return isComplete && isValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie que le Sudoku est complet, soit qu'il n'y ait aucune case vide.
|
||||
* @return boolean, true si le Sudoku est complet, false sinon.
|
||||
*/
|
||||
private boolean isComplete() {
|
||||
return getFirstEmptyCell() == null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifie si le Sudoku est valide, soit qu'il est cohérent avec ses contraintes.
|
||||
* @return bollean, true si le Sudoku est valide, false sinon
|
||||
*/
|
||||
private boolean isValid() {
|
||||
for (Cell cell : this.getFilledCells()) {
|
||||
for (Constraint constraint : this.constraints) {
|
||||
try {
|
||||
Coordinate coords = this.getCoordinateCell(cell);
|
||||
|
||||
int symbolPlaced = cell.empty();
|
||||
List<Integer> possibleSymbols = constraint.getPossibleSymbols(
|
||||
this,
|
||||
coords.getX(),
|
||||
coords.getY()
|
||||
);
|
||||
|
||||
cell.setSymbolIndex(symbolPlaced);
|
||||
if (!possibleSymbols.contains(symbolPlaced)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells remplies.
|
||||
* @return List<Cell>
|
||||
*/
|
||||
private List<Cell> getFilledCells() {
|
||||
List<Cell> result = new ArrayList<>();
|
||||
for (Cell cell : getCells()) {
|
||||
if (!cell.isEmpty()) {
|
||||
result.add(cell);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells modifiables.
|
||||
* @return List<Cell>
|
||||
*/
|
||||
private List<Cell> getEmptyCells() {
|
||||
List<Cell> result = new ArrayList<>();
|
||||
for (Cell cell : getCells()) {
|
||||
if (cell.isMutable()) {
|
||||
result.add(cell);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renvoie la liste des Cells immuables.
|
||||
* @return List<Cell>
|
||||
*/
|
||||
private List<Cell> getImmutableCells() {
|
||||
List<Cell> result = new ArrayList<>();
|
||||
for (Cell cell : getCells()) {
|
||||
if (!cell.isMutable()) {
|
||||
result.add(cell);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object object) {
|
||||
if (!(object instanceof Sudoku)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.getSize() != ((Sudoku) object).getSize()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < this.getSize(); i++) {
|
||||
if (this.getCell(i).getSymbolIndex() != ((Sudoku) object).getCell(i).getSymbolIndex()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void setBlockWidth(int blockWidth) {
|
||||
this.blockWidth = blockWidth;
|
||||
}
|
||||
|
||||
public boolean hasConstraint(Constraint constraint) {
|
||||
return this.constraints.contains(constraint);
|
||||
}
|
||||
// <editor-fold defaultstate="collapsed" desc="METHODES">
|
||||
|
||||
}
|
||||
|
||||
@@ -9,14 +9,10 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Random;
|
||||
|
||||
import sudoku.io.SudokuSerializer;
|
||||
|
||||
import sudoku.constraint.BlockConstraint;
|
||||
import sudoku.constraint.ColumnConstraint;
|
||||
import sudoku.constraint.Constraint;
|
||||
import sudoku.constraint.DiagonalConstraint;
|
||||
import sudoku.constraint.IConstraint;
|
||||
import sudoku.constraint.LineConstraint;
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.solver.RandomSolver;
|
||||
import sudoku.solver.Solver;
|
||||
|
||||
public class SudokuFactory {
|
||||
@@ -30,11 +26,16 @@ public class SudokuFactory {
|
||||
* Liste des contraintes par défaut d'un Multi- ou Sudoku.
|
||||
* Comprend les contraintes de blocs, de lignes, et de colonnes.
|
||||
*/
|
||||
public static List<Constraint> DEFAULT_CONSTRAINTS = Arrays.asList(Constraint.Block, Constraint.Column,
|
||||
Constraint.Line);
|
||||
public static List<IConstraint> DEFAULT_CONSTRAINTS = SudokuFactory
|
||||
.fromConstraints(Arrays.asList(
|
||||
Constraint.Block,
|
||||
Constraint.Column,
|
||||
Constraint.Line)
|
||||
);
|
||||
|
||||
/**
|
||||
* Créée des Cells et les met dans une liste de taille size.
|
||||
*
|
||||
* @param size int, nombre de Cells à initialiser.
|
||||
* @return List<Cell>, liste des Cells initialisées.
|
||||
*/
|
||||
@@ -47,9 +48,11 @@ public class SudokuFactory {
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée des Blocks de taille width par height à partir des cellules données, et les met dans une liste.
|
||||
* @param cells List<Cell>, liste des Cells à découper en Blocks.
|
||||
* @param width int, largeur des Blocks à créer.
|
||||
* Créée des Blocks de taille width par height à partir des cellules données, et
|
||||
* les met dans une liste.
|
||||
*
|
||||
* @param cells List<Cell>, liste des Cells à découper en Blocks.
|
||||
* @param width int, largeur des Blocks à créer.
|
||||
* @param height int, hauteur des Blocks à créer.
|
||||
* @return List<Block>, liste des Blocks créés.
|
||||
*/
|
||||
@@ -65,9 +68,6 @@ public class SudokuFactory {
|
||||
int index = ((y + blockY * height) * size + (x + blockX * width));
|
||||
Cell blockCell = cells.get(index);
|
||||
blockCell.setBlock(newBlock);
|
||||
// List<Block> blockContainers = new ArrayList<>();
|
||||
// blockContainers.add(newBlock);
|
||||
// blockCell.setBlockContainers(blockContainers);
|
||||
newBlock.addCell(blockCell);
|
||||
}
|
||||
}
|
||||
@@ -77,91 +77,37 @@ public class SudokuFactory {
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par heightBlock.
|
||||
* @param widthBlock int, largeur des Blocks.
|
||||
* Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par
|
||||
* heightBlock.
|
||||
*
|
||||
* @param widthBlock int, largeur des Blocks.
|
||||
* @param heightBlock int, hauteur des Blocks.
|
||||
* @return MultiDoku, MultiDoku vide.
|
||||
*/
|
||||
public static MultiDoku createBasicEmptyRectangleDoku(int widthBlock, int heightBlock,
|
||||
List<Constraint> constraints) {
|
||||
return new MultiDoku(Arrays.asList(createRectangleSudoku(widthBlock, heightBlock, constraints)));
|
||||
List<IConstraint> constraints) {
|
||||
return new MultiDoku(List.of(createRectangleSudoku(widthBlock, heightBlock, constraints)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku vide dont les Blocks sont carrés de longueur size.
|
||||
*
|
||||
* @param size int, taille des Blocks.
|
||||
* @return MultiDoku, MultiDoku vide.
|
||||
*/
|
||||
public static MultiDoku createBasicEmptySquareDoku(int size, List<Constraint> constraints) {
|
||||
return new MultiDoku(Arrays.asList(createSquareSudoku(size, constraints)));
|
||||
public static MultiDoku createBasicEmptySquareDoku(int size, List<IConstraint> constraints) {
|
||||
return new MultiDoku(List.of(createSquareSudoku(size, constraints)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Place des Cells immutables de valeurs fournies, aux Coordinate fournies dans le MultiDoku doku fourni.
|
||||
* @param doku MultiDoku, MultiDoku à remplir.
|
||||
* @param immutableCells Map<Coordinate, Integer>, association de Coordinate coordonnées et Integer valeurs, correspondant aux cases à remplir.
|
||||
*/
|
||||
public static void setImmutableCells(MultiDoku doku, Map<Coordinate, Integer> immutableCells) {
|
||||
immutableCells.forEach((coordinate, symbol) -> {
|
||||
for (Sudoku sudoku : doku.getSubGrids()) {
|
||||
Cell cell = sudoku.getCell(coordinate.getX(), coordinate.getY());
|
||||
if (cell != null) {
|
||||
cell.setSymbolIndex(symbol);
|
||||
cell.setImmutable();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku de difficulté difficulty à partir d'un MultiDoku fourni.
|
||||
* Créée un Sudoku vide dont les Blocks sont de taille widthBlock par
|
||||
* heightBlock.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku dont on doit vider des Cells.
|
||||
* @param nbCellsToEmpty int, nombre de cases à retirer.
|
||||
* @return boolean, valant true si un MultiDoku de difficulté donnée peut être créée, false sinon.
|
||||
* @throws Exception si la difficulté n'est pas compatible avec la taille du MultiDoku.
|
||||
*/
|
||||
public static boolean newDokuFromFilledOne(MultiDoku doku, int nbCellsToEmpty) throws Exception {
|
||||
|
||||
System.out.println("nbCellsToEmpty : "+nbCellsToEmpty);
|
||||
if (nbCellsToEmpty >= doku.getCells().size()) {
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
if (nbCellsToEmpty == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
List<Cell> cellsThatCanBeEmptied = doku.getFilledCells();
|
||||
|
||||
while (!cellsThatCanBeEmptied.isEmpty()) {
|
||||
int index = random.nextInt(cellsThatCanBeEmptied.size());
|
||||
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
|
||||
|
||||
int oldSymbol = cellToEmpty.empty();
|
||||
|
||||
int nbDokuSultions = Solver.countSolution(doku);
|
||||
System.out.println("oldSymbol : "+oldSymbol);
|
||||
if (nbDokuSultions == 1) {
|
||||
if (newDokuFromFilledOne(doku, --nbCellsToEmpty)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
cellToEmpty.setSymbolIndex(oldSymbol);
|
||||
cellsThatCanBeEmptied.remove(cellToEmpty);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un Sudoku vide dont les Blocks sont de taille widthBlock par heightBlock.
|
||||
* @param widthBlock int, largeur des Blocks.
|
||||
* @param heightBlock int, hauteur des Blocks.
|
||||
* @return Sudoku, Sudoku vide.
|
||||
*/
|
||||
private static Sudoku createRectangleSudoku(int widthBlock, int heightBlock, List<Constraint> constraints) {
|
||||
private static Sudoku createRectangleSudoku(int widthBlock, int heightBlock, List<IConstraint> constraints) {
|
||||
int symbolCount = widthBlock * heightBlock;
|
||||
List<Cell> cases = initCells(symbolCount);
|
||||
List<Block> blocs = initRectangleBlocs(cases, widthBlock, heightBlock);
|
||||
@@ -175,34 +121,37 @@ public class SudokuFactory {
|
||||
|
||||
/**
|
||||
* Créée un Sudoku vide dont les Blocks sont carrés de longueur size.
|
||||
*
|
||||
* @param size int, taille des Blocks.
|
||||
* @return Sudoku, Sudoku vide.
|
||||
*/
|
||||
private static Sudoku createSquareSudoku(int size, List<Constraint> constraints) {
|
||||
private static Sudoku createSquareSudoku(int size, List<IConstraint> constraints) {
|
||||
return createRectangleSudoku(size, size, constraints);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connecte deux Sudokus selon la décalage offset fourni.
|
||||
*
|
||||
* @param sudoku1 Sudoku, premier sudoku à connecter.
|
||||
* @param sudoku2 Sudoku, second sudoku à connecter.
|
||||
* @param offset Coordinate, décalage entre les deux Sudokus.
|
||||
*/
|
||||
private static void linkSquareSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
|
||||
private static void linkRectangleSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
|
||||
int blockWidth = sudoku1.getBlockWidth();
|
||||
for (int dx = 0; dx < blockWidth; dx++) {
|
||||
int blockHeight = sudoku1.getSize() / blockWidth;
|
||||
for (int dx = 0; dx < blockHeight; dx++) {
|
||||
for (int dy = 0; dy < blockWidth; dy++) {
|
||||
int block1X = dx + offset.getX();
|
||||
int block1Y = dy + offset.getY();
|
||||
int block2X = dx;
|
||||
int block2Y = dy;
|
||||
|
||||
if ((block1X < blockWidth) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
|
||||
Block block1 = sudoku1.getBlocks().get(block1Y * blockWidth + block1X);
|
||||
Block block2 = sudoku2.getBlocks().get(block2Y * blockWidth + block2X);
|
||||
if ((block1X < blockHeight) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
|
||||
Block block1 = sudoku1.getBlocks().get(block1Y * blockHeight + block1X);
|
||||
Block block2 = sudoku2.getBlocks().get(block2Y * blockHeight + block2X);
|
||||
|
||||
// on remplace le bloc
|
||||
sudoku2.getBlocks().set(block2Y * blockWidth + block2X, block1);
|
||||
sudoku2.getBlocks().set(block2Y * blockHeight + block2X, block1);
|
||||
block1.getSudokus().add(sudoku2);
|
||||
|
||||
// on remplace les cellules
|
||||
@@ -219,83 +168,205 @@ public class SudokuFactory {
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku de Blocks carrés de taille size composé de cinq Sudokus, dont un central qui partage chacun de ses Blockss d'angle avec un autre Sudoku.
|
||||
* Créée un MultiDoku de Blocks carrés de taille size composé de cinq Sudokus,
|
||||
* dont un central qui partage chacun de ses Blockss d'angle avec un autre
|
||||
* Sudoku.
|
||||
* 2 3
|
||||
* 1
|
||||
* 4 5
|
||||
*
|
||||
* @param size int, largeur des Blocks unitraires des Sudokus à crééer.
|
||||
* @return MultiDoku, MultiDoku de forme X.
|
||||
*/
|
||||
public static MultiDoku createBasicXShapedMultidoku(int size, List<Constraint> constraints) {
|
||||
public static MultiDoku createBasicXShapedMultidoku(int size, List<IConstraint> constraints) {
|
||||
assert (size > 1);
|
||||
|
||||
/*
|
||||
* 2 3
|
||||
* 1
|
||||
* 4 5
|
||||
*/
|
||||
|
||||
Sudoku sudoku1 = createSquareSudoku(size, constraints);
|
||||
Sudoku sudoku2 = createSquareSudoku(size, constraints);
|
||||
Sudoku sudoku3 = createSquareSudoku(size, constraints);
|
||||
Sudoku sudoku4 = createSquareSudoku(size, constraints);
|
||||
Sudoku sudoku5 = createSquareSudoku(size, constraints);
|
||||
|
||||
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size));
|
||||
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size));
|
||||
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1));
|
||||
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(size - 1, size - 1));
|
||||
|
||||
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
|
||||
return createBasicXShapedMultidoku(size, size, constraints);
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku de Blocks rectangulaires de forme width par height composé de cinq Sudokus,
|
||||
* Créée un MultiDoku de Blocks rectangulaires de forme X, de taille width par height composé
|
||||
* de cinq Sudokus,
|
||||
* dont un central qui partage chacun de ses Blocks d'angle avec un autre
|
||||
* Sudoku.
|
||||
* 2 3
|
||||
* 1
|
||||
* 4 5
|
||||
*
|
||||
* @param width int, largeur des Blocks unitraires des Sudokus à crééer.
|
||||
* @param height int, hauteur des Blocks unitraires des Sudokus à crééer.
|
||||
* @param width int, largeur des Blocks unitaires des Sudokus à crééer.
|
||||
* @param height int, hauteur des Blocks unitaires des Sudokus à crééer.
|
||||
* @return MultiDoku, MultiDoku de forme X.
|
||||
*/
|
||||
public static MultiDoku createBasicXShapedMultidoku(int width, int height, List<Constraint> constraints) {
|
||||
public static MultiDoku createBasicXShapedMultidoku(int width, int height, List<IConstraint> constraints) {
|
||||
assert (width > 1 && height > 1);
|
||||
|
||||
/*
|
||||
* 2 3
|
||||
* 1
|
||||
* 4 5
|
||||
*/
|
||||
|
||||
Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
|
||||
|
||||
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - width, 1 - height));
|
||||
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(width - 1, 1 - height));
|
||||
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - width, height - 1));
|
||||
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(width - 1, height - 1));
|
||||
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 1 - width));
|
||||
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(height - 1, 1 - width));
|
||||
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - height, width - 1));
|
||||
linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(height - 1, width - 1));
|
||||
|
||||
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
|
||||
}
|
||||
|
||||
public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception {
|
||||
Solver.solveRandom(doku, random);
|
||||
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
|
||||
boolean successfull = newDokuFromFilledOne(doku, nbCellsToEmpty);
|
||||
if (!successfull) {
|
||||
throw new Exception("Canno't create this doku with this difficulty");
|
||||
/**
|
||||
* Créée un MultiDoku de Blocks carrés de forme +, de taille size composé
|
||||
* de cinq Sudokus,
|
||||
* dont un central qui partage chacun de ses Blocks de bord avec un autre
|
||||
* Sudoku.
|
||||
* 3
|
||||
* 2 1 4
|
||||
* 5
|
||||
*
|
||||
* @param size int, largeur des Blocks unitaires des Sudokus à crééer.
|
||||
* @return MultiDoku, MultiDoku de forme +.
|
||||
*/
|
||||
public static MultiDoku createBasicPlusShapedMultidoku(int size, List<IConstraint> constraints) {
|
||||
assert (size > 1);
|
||||
|
||||
return createBasicPlusShapedMultidoku(size, size, constraints);
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku de Blocks rectangulaires de forme +, de taille width par height composé
|
||||
* de cinq Sudokus,
|
||||
* dont un central qui partage chacun de ses Blocks de bord avec un autre
|
||||
* Sudoku.
|
||||
* 3
|
||||
* 2 1 4
|
||||
* 5
|
||||
*
|
||||
* @param width int, largeur des Blocks unitaires des Sudokus à crééer.
|
||||
* @param height int, hauteur des Blocks unitaires des Sudokus à crééer.
|
||||
* @return MultiDoku, MultiDoku de forme +.
|
||||
*/
|
||||
public static MultiDoku createBasicPlusShapedMultidoku(int width, int height, List<IConstraint> constraints) {
|
||||
assert (width > 1 && height > 1);
|
||||
|
||||
Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
|
||||
Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
|
||||
|
||||
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 0));
|
||||
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(0, 1 - width));
|
||||
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(height - 1, 0));
|
||||
linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(0, width - 1));
|
||||
|
||||
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
|
||||
}
|
||||
|
||||
/**
|
||||
* Crée un Sudoku vide avec les Blocks aléatoires.
|
||||
*
|
||||
* @param blockSize int, la taille des Block.
|
||||
* @param constraints List<IConstraint>, la liste des contraintes.
|
||||
* @return MultiDoku, avec un seul Sudoku.
|
||||
*/
|
||||
public static MultiDoku createBasicEmptyRandomBlockDoku(int blockSize, List<IConstraint> constraints) {
|
||||
int blockCellCount = blockSize * blockSize;
|
||||
List<Cell> cells = initCells(blockCellCount);
|
||||
List<Cell> homeLessCells = new ArrayList<>(cells);
|
||||
List<Block> blocks = new ArrayList<>();
|
||||
Random r = new Random();
|
||||
for (int i = 0; i < blockCellCount; i++) {
|
||||
Block b = new Block();
|
||||
for (int j = 0; j < blockCellCount; j++) {
|
||||
int cellIndex = r.nextInt(homeLessCells.size());
|
||||
Cell cell = homeLessCells.remove(cellIndex);
|
||||
b.addCell(cell);
|
||||
cell.setBlock(b);
|
||||
}
|
||||
blocks.add(b);
|
||||
}
|
||||
Sudoku sudoku = new Sudoku(cells, blocks, constraints);
|
||||
for (Block block : blocks) {
|
||||
block.getSudokus().add(sudoku);
|
||||
}
|
||||
return new MultiDoku(List.of(sudoku));
|
||||
}
|
||||
|
||||
/**
|
||||
* Créée un MultiDoku de difficulté difficulty à partir d'un MultiDoku fourni.
|
||||
*
|
||||
* @param doku MultiDoku, MultiDoku dont on doit vider des Cells.
|
||||
* @param nbCellsToEmpty int, nombre de cases à retirer.
|
||||
* @return boolean, valant true si un MultiDoku de difficulté donnée peut être
|
||||
* créée, false sinon.
|
||||
* @throws Exception si la difficulté n'est pas compatible avec la taille du
|
||||
* MultiDoku.
|
||||
*/
|
||||
public static boolean newDokuFromFilledOne(MultiDoku doku, int nbCellsToEmpty, Solver solver) throws Exception {
|
||||
|
||||
if (nbCellsToEmpty >= doku.getCells().size()) {
|
||||
throw new Exception();
|
||||
}
|
||||
|
||||
if (nbCellsToEmpty == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
List<Cell> cellsThatCanBeEmptied = doku.getFilledCells();
|
||||
|
||||
int index = random.nextInt(cellsThatCanBeEmptied.size());
|
||||
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
|
||||
|
||||
cellToEmpty.empty();
|
||||
|
||||
int nbDokuSultions = solver.countSolution(doku);
|
||||
if (nbDokuSultions == 1) {
|
||||
return newDokuFromFilledOne(doku, --nbCellsToEmpty, solver);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remplit un MultiDoku donné par rapport à une difficulté.
|
||||
*
|
||||
* @param doku MultiDoku, vide.
|
||||
* @param difficulty Difficulty, qui correspond au pourcentage de cases à enlever.
|
||||
*/
|
||||
public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception {
|
||||
Solver solver = new RandomSolver();
|
||||
solver.solve(doku);
|
||||
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
|
||||
newDokuFromFilledOne(doku, nbCellsToEmpty, solver);
|
||||
doku.setFilledCellsImmutable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Génère un MultiDoku à partir d'un fichier de sauvegarde.
|
||||
*
|
||||
* @param filePath String, chemin du fichier.
|
||||
* @return MultiDoku.
|
||||
*/
|
||||
public static MultiDoku fromfile(String filePath) {
|
||||
try {
|
||||
String content = Files.readString(Paths.get(filePath));
|
||||
MultiDoku doku = SudokuSerializer.deserializeSudoku(content);
|
||||
return doku;
|
||||
return SudokuSerializer.deserializeSudoku(content);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforme des Constraint en IConstraint correspondants
|
||||
* @param constraints List<Constraints>
|
||||
* @return List<IConstraints>
|
||||
*/
|
||||
public static List<IConstraint> fromConstraints(List<Constraint> constraints) {
|
||||
List<IConstraint> iconstraints = new ArrayList<>();
|
||||
for (Constraint cons : constraints) {
|
||||
iconstraints.add(cons.getConstraint());
|
||||
}
|
||||
return iconstraints;
|
||||
}
|
||||
}
|
||||
|
||||
BIN
app/src/main/resources/background.png
Normal file
BIN
app/src/main/resources/background.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 399 KiB |
@@ -1,5 +1,7 @@
|
||||
package sudoku;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Random;
|
||||
|
||||
@@ -7,58 +9,71 @@ import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.solver.Solver;
|
||||
import sudoku.solver.RandomSolver;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
public class SudokuSerializerTest {
|
||||
|
||||
void testSerializeWithSize(int blockWidth, int blockHeight, Random r) {
|
||||
MultiDoku sudoku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
|
||||
void testSerializeWithSize(int blockWidth, int blockHeight) {
|
||||
var sudoku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
|
||||
SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
Solver.solveRandom(sudoku, r);
|
||||
new RandomSolver().solve(sudoku);
|
||||
JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
|
||||
MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
|
||||
assert (data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
|
||||
assertEquals(data.toString(), SudokuSerializer.serializeSudoku(multiDoku).toString());
|
||||
}
|
||||
|
||||
void testSaveWithSize(int blockWidth, int blockHeight, Random r) {
|
||||
void testSaveWithSize(int blockWidth, int blockHeight) {
|
||||
MultiDoku doku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
|
||||
SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
Solver.solveRandom(doku, r);
|
||||
new RandomSolver().solve(doku);
|
||||
String savePath = SudokuSerializer.saveMultiDoku(doku);
|
||||
MultiDoku otherDoku = null;
|
||||
try {
|
||||
otherDoku = SudokuFactory.fromfile(savePath);
|
||||
assert (otherDoku != null);
|
||||
|
||||
assertEquals(SudokuSerializer.serializeSudoku(doku).toString(),
|
||||
SudokuSerializer.serializeSudoku(otherDoku).toString());
|
||||
// clean file after test
|
||||
File fileToDelete = new File(savePath);
|
||||
fileToDelete.delete();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.out.println(e.getMessage());
|
||||
assert false;
|
||||
}
|
||||
assert (doku.equals(otherDoku));
|
||||
}
|
||||
|
||||
void testSerializeX(int size) {
|
||||
var sudoku = SudokuFactory.createBasicXShapedMultidoku(size, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
new RandomSolver().solve(sudoku);
|
||||
JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
|
||||
MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
|
||||
|
||||
assertEquals(data.toString(), SudokuSerializer.serializeSudoku(multiDoku).toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSerialize() {
|
||||
Random r = new Random();
|
||||
testSerializeWithSize(3, 3, r);
|
||||
|
||||
/**
|
||||
int testCount = 5;
|
||||
int testCount = 20;
|
||||
int minSize = 2;
|
||||
int maxSize = 3;
|
||||
for (int i = 0; i < testCount; i++) {
|
||||
int blockWidth = r.nextInt(10) + 1;
|
||||
int blockHeight = r.nextInt(10) + 1;
|
||||
testSerializeWithSize(blockWidth, blockHeight, r);
|
||||
int blockWidth = r.nextInt(maxSize - minSize + 1) + minSize;
|
||||
int blockHeight = r.nextInt(maxSize - minSize + 1) + minSize;
|
||||
testSerializeWithSize(blockWidth, blockHeight);
|
||||
}
|
||||
for (int i = 0; i < testCount; i++) {
|
||||
int blockWidth = r.nextInt(10) + 1;
|
||||
int blockHeight = r.nextInt(10) + 1;
|
||||
testSaveWithSize(blockWidth, blockHeight, r);
|
||||
int blockWidth = r.nextInt(maxSize - minSize + 1) + minSize;
|
||||
int blockHeight = r.nextInt(maxSize - minSize + 1) + minSize;
|
||||
testSaveWithSize(blockWidth, blockHeight);
|
||||
}
|
||||
for (int i = 0; i < testCount; i++) {
|
||||
int size = r.nextInt(maxSize - minSize + 1) + minSize;
|
||||
testSerializeX(size);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,91 +1,132 @@
|
||||
package sudoku.solver;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import sudoku.io.SudokuPrinter;
|
||||
|
||||
import sudoku.io.SudokuSerializer;
|
||||
import sudoku.structure.Cell;
|
||||
import sudoku.structure.Difficulty;
|
||||
import sudoku.structure.MultiDoku;
|
||||
import sudoku.structure.Sudoku;
|
||||
import sudoku.structure.SudokuFactory;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
class SolverTest {
|
||||
private int ns = Cell.NOSYMBOL;
|
||||
protected static HumanSolver h;
|
||||
private static RandomSolver r;
|
||||
private static MixedSolver m;
|
||||
|
||||
@Test
|
||||
void solveTest() {
|
||||
Random rand = new Random();
|
||||
@BeforeAll
|
||||
public static void initializeSolvers() {
|
||||
h = new HumanSolver();
|
||||
r = new RandomSolver();
|
||||
m = new MixedSolver();
|
||||
}
|
||||
|
||||
MultiDoku dokuToTest = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
MultiDoku dokuResult = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
private void testSize2(Solver solver) {
|
||||
MultiDoku mdTest = SudokuFactory.createBasicEmptySquareDoku(2, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
MultiDoku mdResult = SudokuFactory.createBasicEmptySquareDoku(2, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
Sudoku test = mdTest.getSubGrid(0);
|
||||
Sudoku result = mdResult.getSubGrid(0);
|
||||
List<Integer> immutableCells = List.of(
|
||||
ns, 2, 3, ns,
|
||||
0, ns, ns, ns,
|
||||
ns, ns, ns, 3,
|
||||
ns, 0, 1, ns);
|
||||
assertTrue(test.setImmutableCellsSymbol(immutableCells));
|
||||
List<Integer> correctCells = List.of(
|
||||
1, 2, 3, 0,
|
||||
0, 3, 2, 1,
|
||||
2, 1, 0, 3,
|
||||
3, 0, 1, 2);
|
||||
assertTrue(result.setCellsSymbol(correctCells));
|
||||
assertTrue(result.isSolved());
|
||||
|
||||
Sudoku sudokuToTest = dokuToTest.getSubGrid(0);
|
||||
Sudoku sudokuResult = dokuResult.getSubGrid(0);
|
||||
assertNotEquals(mdResult, mdTest);
|
||||
solver.solve(mdTest);
|
||||
assertTrue(mdTest.isSolved());
|
||||
|
||||
int ns = Cell.NOSYMBOL;
|
||||
List<Integer> immutableCells = List.of(ns, ns, 0, ns, ns, 2, 8, ns, 1,
|
||||
ns, 3, ns, ns, 5, 6, 7, ns, ns,
|
||||
ns, ns, ns, 8, ns, 7, ns, ns, 6,
|
||||
0, ns, 1, ns, ns, ns, ns, ns, ns,
|
||||
4, 8, 7, 5, 1, ns, 6, ns, ns,
|
||||
6, ns, 3, 2, ns, ns, ns, 8, 0,
|
||||
ns, ns, 6, ns, ns, 8, ns, 7, 5,
|
||||
8, 0, ns, 7, ns, 5, 2, ns, 3,
|
||||
5, ns, ns, ns, 3, 1, 0, ns, ns);
|
||||
assertEquals(mdTest, mdResult);
|
||||
}
|
||||
|
||||
assert (sudokuToTest.setImmutableCellsSymbol(immutableCells));
|
||||
private void testSize3(Solver solver) {
|
||||
MultiDoku mdTest = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
MultiDoku mdResult = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
Sudoku test = mdTest.getSubGrid(0);
|
||||
Sudoku result = mdResult.getSubGrid(0);
|
||||
List<Integer> immutableCells = List.of(
|
||||
ns, ns, 0, ns, ns, 2, 8, ns, 1,
|
||||
ns, 3, ns, ns, 5, 6, 7, ns, ns,
|
||||
ns, ns, ns, 8, ns, 7, ns, ns, 6,
|
||||
0, ns, 1, ns, ns, ns, ns, ns, ns,
|
||||
4, 8, 7, 5, 1, ns, 6, ns, ns,
|
||||
6, ns, 3, 2, ns, ns, ns, 8, 0,
|
||||
ns, ns, 6, ns, ns, 8, ns, 7, 5,
|
||||
8, 0, ns, 7, ns, 5, 2, ns, 3,
|
||||
5, ns, ns, ns, 3, 1, 0, ns, ns);
|
||||
assert (test.setImmutableCellsSymbol(immutableCells));
|
||||
List<Integer> correctCells = List.of(
|
||||
7, 6, 0, 3, 4, 2, 8, 5, 1,
|
||||
2, 3, 8, 1, 5, 6, 7, 0, 4,
|
||||
1, 4, 5, 8, 0, 7, 3, 2, 6,
|
||||
0, 2, 1, 6, 8, 3, 5, 4, 7,
|
||||
4, 8, 7, 5, 1, 0, 6, 3, 2,
|
||||
6, 5, 3, 2, 7, 4, 1, 8, 0,
|
||||
3, 1, 6, 0, 2, 8, 4, 7, 5,
|
||||
8, 0, 4, 7, 6, 5, 2, 1, 3,
|
||||
5, 7, 2, 4, 3, 1, 0, 6, 8);
|
||||
assert (result.setCellsSymbol(correctCells));
|
||||
assert (result.isSolved());
|
||||
|
||||
SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3);
|
||||
assertNotEquals(mdResult, mdTest);
|
||||
solver.solve(mdTest);
|
||||
assert (mdTest.isSolved());
|
||||
assertEquals(mdTest, mdResult);
|
||||
}
|
||||
|
||||
List<Integer> correctCells = List.of(7, 6, 0, 3, 4, 2, 8, 5, 1,
|
||||
2, 3, 8, 1, 5, 6, 7, 0, 4,
|
||||
1, 4, 5, 8, 0, 7, 3, 2, 6,
|
||||
0, 2, 1, 6, 8, 3, 5, 4, 7,
|
||||
4, 8, 7, 5, 1, 0, 6, 3, 2,
|
||||
6, 5, 3, 2, 7, 4, 1, 8, 0,
|
||||
3, 1, 6, 0, 2, 8, 4, 7, 5,
|
||||
8, 0, 4, 7, 6, 5, 2, 1, 3,
|
||||
5, 7, 2, 4, 3, 1, 0, 6, 8);
|
||||
private void testMDSize3(Solver solver) {
|
||||
MultiDoku mdTest = SudokuFactory.createBasicXShapedMultidoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
try {
|
||||
SudokuFactory.fillDoku(mdTest, Difficulty.Easy);
|
||||
} catch (Exception e) {
|
||||
assert (false);
|
||||
}
|
||||
MultiDoku mdResult = SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(mdTest));
|
||||
assertFalse(mdTest.isSolved());
|
||||
assertFalse(mdResult.isSolved());
|
||||
assertEquals(mdTest, mdResult);
|
||||
|
||||
sudokuResult.setCellsSymbol(correctCells);
|
||||
assertTrue(solver.solve(mdTest));
|
||||
|
||||
System.out.println("\n****************************Doku Control\n");
|
||||
SudokuPrinter.printRectangleSudoku(sudokuResult, 3, 3);
|
||||
assertTrue(mdTest.isSolved());
|
||||
assertFalse(mdResult.isSolved());
|
||||
System.out.println(mdTest);
|
||||
System.out.println(mdResult);
|
||||
assertNotEquals(mdTest, mdResult);
|
||||
|
||||
assert(dokuResult.isSolved());
|
||||
assertTrue(solver.solve(mdResult));
|
||||
|
||||
Solver.solveRandom(dokuToTest, rand);
|
||||
assertEquals(mdTest, mdResult);
|
||||
}
|
||||
|
||||
System.out.println("\n****************************\nDoku solved");
|
||||
SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3);
|
||||
|
||||
|
||||
assert(dokuToTest.isSolved());
|
||||
|
||||
assert(dokuToTest.equals(dokuResult));
|
||||
|
||||
MultiDoku dokuToTest2 = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
Sudoku sudokuToTest2 = dokuToTest2.getSubGrid(0);
|
||||
|
||||
List<Integer> immutableCells2 = List.of(ns, ns, 0, ns, ns, 2, 8, ns, 1,
|
||||
1, 3, ns, ns, 5, 6, 7, ns, ns,
|
||||
ns, ns, ns, 8, ns, 7, ns, ns, 6,
|
||||
0, ns, 1, ns, ns, ns, ns, ns, ns,
|
||||
4, 8, 7, 5, 1, ns, 6, ns, ns,
|
||||
6, ns, 3, 2, ns, ns, ns, 8, 0,
|
||||
ns, ns, 6, ns, ns, 8, ns, 7, 5,
|
||||
8, 0, ns, 7, ns, 5, 2, ns, 3,
|
||||
5, ns, ns, ns, 3, 1, 0, ns, ns);
|
||||
sudokuToTest2.setImmutableCellsSymbol(immutableCells2);
|
||||
|
||||
boolean isSolved = Solver.solveRandom(dokuToTest2, rand);
|
||||
|
||||
assert (!isSolved);
|
||||
|
||||
MultiDoku dokuToTest3 = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
|
||||
|
||||
Solver.solveRandom(dokuToTest3, rand);
|
||||
|
||||
SudokuPrinter.printRectangleSudoku(dokuToTest3.getSubGrid(0), 3, 3);
|
||||
}
|
||||
@Test
|
||||
void solveTest() {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
testSize2(h);
|
||||
testSize3(h);
|
||||
testSize2(m);
|
||||
testSize3(m);
|
||||
testMDSize3(m);
|
||||
testSize2(r);
|
||||
testSize3(r);
|
||||
testMDSize3(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user