40 Commits

Author SHA1 Message Date
c3610c47c9 send disconnect packet
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 23:13:56 +01:00
08ed9b46b1 fix multi login 2025-02-02 23:13:28 +01:00
2595af2d48 doc solver
All checks were successful
Linux arm64 / Build (push) Successful in 44s
2025-02-02 22:56:19 +01:00
edfc5733db fix mixedsolver 2025-02-02 22:56:14 +01:00
Melvyn
71666a3883 refactor : mini fixs
All checks were successful
Linux arm64 / Build (push) Successful in 44s
2025-02-02 22:51:33 +01:00
3f1ef93323 doc: serializer
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 22:29:52 +01:00
a580321bd0 doc: constraints
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-02 22:25:28 +01:00
d7d7dfe787 restore console save
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 22:06:45 +01:00
Janet-Doe
2fb3874a99 update ConsoleInterface
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 21:46:29 +01:00
Janet-Doe
591e4f977a update ConsoleInterface
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-02 21:31:32 +01:00
Janet-Doe
c481f66b0c add doc + delete unused class
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 21:03:36 +01:00
Janet-Doe
aafb025874 doc ConsoleInterface
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 17:50:15 +01:00
Melvyn
627c49b961 refactor : StateManager
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 16:42:31 +01:00
Melvyn
b4157167b5 refactor : SudokuFactory
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-02-02 16:38:04 +01:00
Melvyn
1419898955 refactor : Sudoku
Some checks failed
Linux arm64 / Build (push) Failing after 32s
2025-02-02 16:22:08 +01:00
Melvyn
dd3be67be0 refactor : MultiDoku
Some checks failed
Linux arm64 / Build (push) Failing after 28s
2025-02-02 16:13:51 +01:00
Melvyn
c6a32b8d07 refactor : Difficulty
Some checks failed
Linux arm64 / Build (push) Failing after 30s
2025-02-02 16:07:29 +01:00
Melvyn
a8439df736 refactor : Coordinate
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 16:03:13 +01:00
Melvyn
27032d264d refactor : Block
Some checks failed
Linux arm64 / Build (push) Failing after 30s
2025-02-02 15:57:30 +01:00
Melvyn
8afd51b353 refactor : Cell
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 15:52:10 +01:00
2460b7539e action test after
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 15:42:18 +01:00
0f5020b0b4 fix tests
Some checks failed
Linux arm64 / Build (push) Failing after 29s
2025-02-02 15:41:29 +01:00
ac4f859fd8 refactor build.gradle
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-02 15:07:26 +01:00
4a8644181a build.gradle fix tests
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-02 15:03:26 +01:00
efa357a1ab refactor MixedSolver 2025-02-02 14:56:31 +01:00
618e436270 refactor stupidsolver 2025-02-02 14:43:09 +01:00
d5009371f2 remove unused import
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 14:39:56 +01:00
87727f39e8 refactor HumanSolver
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 14:36:47 +01:00
413201882b change loading text
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 14:24:56 +01:00
d8289b553a fix empty grid gen
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-02 14:24:23 +01:00
Janet-Doe
adeb9b07e5 update solver tests
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-02-02 11:51:56 +01:00
Janet-Doe
4903fd567b tests redaction
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-02 11:36:22 +01:00
990c830590 Fixes #5
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 11:33:21 +01:00
d806420d21 Fixes #32
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 11:01:10 +01:00
4b98341618 feat: basic gen loading 2025-02-02 10:53:24 +01:00
68021b796b Fixes #28
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-02 10:35:00 +01:00
06efbf649b Fixes #33
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-02-02 10:27:42 +01:00
4ee29d8f50 Fixes #10
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-02 10:17:09 +01:00
eda2a1afae Fixes #39 2025-02-02 10:14:27 +01:00
f3bbfd9e6c feat: show resolve logs
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-02-02 00:04:52 +01:00
50 changed files with 1137 additions and 659 deletions

View File

@@ -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

View File

@@ -1,13 +1,18 @@
# Sudoku 🧩
Une application de génération et résolution de MultiDoku.
## Features 🌟
- MultiDoku solvers
- Graphical User Interface (GUI)
- Sudoku saves
- Multiplayer
## Develop ☝🤓
Pour plus de détails, voir le dossier de conception
### Run 🏃
```sh

View File

@@ -11,8 +11,6 @@ plugins {
id 'application'
}
project.ext.os = System.properties['os.name'].toLowerCase().split(" ")[0]
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
@@ -20,7 +18,8 @@ repositories {
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
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'
@@ -28,7 +27,9 @@ dependencies {
implementation "org.lwjgl:lwjgl-stb:3.3.4"
runtimeOnly "org.lwjgl:lwjgl-stb::natives-$os"
implementation "org.lwjgl:lwjgl-stb::natives-linux"
implementation "org.lwjgl:lwjgl-stb::natives-windows"
implementation "org.lwjgl:lwjgl-stb::natives-macos"
}
application {
@@ -48,6 +49,10 @@ jar {
}
}
test {
useJUnitPlatform()
}
run {
enableAssertions = true
}

View 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;
}
}

View File

@@ -31,7 +31,7 @@ public class Main extends Application {
@Override
protected void preRun() {
super.preRun();
Images.loadImages();
Images.reloadImages();
}
@Override

View File

@@ -1,5 +1,6 @@
package gui.constants;
import gui.AssetManager;
import imgui.ImFont;
import imgui.ImFontConfig;
import imgui.ImFontGlyphRangesBuilder;
@@ -20,15 +21,15 @@ public class Fonts {
ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder();
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesDefault());
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesCyrillic());
// builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesChineseFull());
ImFontConfig cfg = new ImFontConfig();
cfg.setGlyphRanges(builder.buildRanges());
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, cfg);
CHERI = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "cheri.ttf", 50.0f);
INFECTED = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "INFECTED.ttf", 50.0f);
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);
}
}

View File

@@ -5,16 +5,21 @@ 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(String fileName) {
private static int loadTexture(byte[] imageData) {
int[] width = new int[1];
int[] height = new int[1];
int[] channelCount = new int[1];
ByteBuffer pixels = STBImage.stbi_load(fileName, width, height, channelCount, 4);
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);
@@ -32,8 +37,8 @@ public class Images {
return textureID;
}
public static void loadImages() {
BACKGROUND = loadTexture("background.png");
public static void reloadImages() {
BACKGROUND = loadTexture(AssetManager.getResource(Options.BackgroundPath));
}
}

View File

@@ -4,5 +4,6 @@ public class Options {
public static Symbols Symboles = Symbols.Numbers;
public static float BackgroundSpeed = 1.0f;
public static String BackgroundPath = "background.png";
}

View File

@@ -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();

View File

@@ -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);
@@ -22,9 +24,10 @@ public class MultiMenu extends BaseView {
ImGui.beginChild("##CreateGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f));
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();
}
@@ -38,9 +41,10 @@ public class MultiMenu extends BaseView {
ImGui.inputText("Adresse", address);
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()));
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, pseudo.get(), address.get(), (short) port.get()));
} catch (IOException e) {
e.printStackTrace();
}

View File

@@ -78,4 +78,9 @@ public class MultiPlayerView extends BaseView {
renderGameStatus();
}
@Override
public void cleanResources() {
this.selector.clean();
}
}

View File

@@ -1,28 +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};
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() {
ImGui.text("Options");
if(ImGui.combo("Jeu de symboles", currentValue, Symbols.getSymbolsNames())){
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)){
if (ImGui.sliderFloat("Vitesse d'animation de l'arrière plan", backgroundSpeed, 0.0f, 10.0f)) {
Options.BackgroundSpeed = backgroundSpeed[0];
}
renderImageSelectButton();
renderReturnButton();
}

View File

@@ -25,4 +25,9 @@ public class SoloMenu extends BaseView {
renderReturnButton();
}
@Override
public void cleanResources() {
this.sudokuSelector.clean();
}
}

View File

@@ -92,6 +92,7 @@ public class SudokuView extends BaseView {
}
private void startSolve(Solver solver) {
this.doku.clearMutableCells();
resolveThread = new Thread(() -> {
List<SolverStep> steps = new ArrayList<>();
try {
@@ -158,6 +159,8 @@ public class SudokuView extends BaseView {
private void renderClearButton() {
if (centeredButton("Effacer")) {
this.doku.clearMutableCells();
this.resolved = false;
this.unresolved = false;
}
}

View File

@@ -9,13 +9,22 @@ public class SmoothProgressBar {
private final float speed = 2.0f;
private final float clipConstant = 0.001f;
public void render(String label, ImVec2 size, float progress) {
float delta = progress - lastProgress;
private void updateProgress(float newProgress) {
float delta = newProgress - lastProgress;
if (Math.abs(delta) < clipConstant)
lastProgress = progress;
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);
}
}

View File

@@ -35,10 +35,15 @@ public class SudokuSelector {
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() {
@@ -56,16 +61,39 @@ public class SudokuSelector {
}
}
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;
if (!empty) {
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.onSelect.emit(this.doku);
});
this.genThread.start();
}
public void renderFileDialog() {
@@ -131,7 +159,12 @@ public class SudokuSelector {
if (ImGui.button("À partir d'un fichier")) {
ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", ".");
}
renderGenProgress();
renderFileDialog();
}
public void clean() {
stopGenThread();
}
}

View File

@@ -28,12 +28,10 @@ public class Client {
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) {

View File

@@ -31,6 +31,7 @@ public class ClientConnexion extends Connexion {
public void close() {
if (!this.isClosed()) {
super.close();
sendPacket(new DisconnectPacket(""));
client.onDisconnect.emit();
}
}

View File

@@ -3,6 +3,9 @@ package sudoku.constraint;
import sudoku.structure.Block;
import sudoku.structure.Sudoku;
/**
* Contrainte de bloc
*/
public class BlockConstraint implements IConstraint{
@Override

View File

@@ -3,6 +3,9 @@ package sudoku.constraint;
import sudoku.structure.Cell;
import sudoku.structure.Sudoku;
/**
* Contrainte de colonne
*/
public class ColumnConstraint implements IConstraint {
@Override

View File

@@ -1,9 +1,9 @@
package sudoku.constraint;
import java.util.List;
import sudoku.structure.Sudoku;
/**
* Enumération utilisée afin de simplifier l'affichage en graphique.
* Un sudoku peut tout de même contenir des contraintes qui ne sont pas dans cette énumération.
*/
public enum Constraint {
Block("Bloc", new BlockConstraint()),
@@ -19,14 +19,6 @@ public enum Constraint {
this.displayName = displayName;
}
public boolean canBePlaced(Sudoku s, int x, int y, int newValue) {
return getConstraint().canBePlaced(s, x, y, newValue);
}
public List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) {
return getConstraint().getPossibleSymbols(s, x, y);
}
public String getDisplayName() {
return displayName;
}

View File

@@ -2,6 +2,9 @@ package sudoku.constraint;
import sudoku.structure.Sudoku;
/**
* Contrainte de diagonale
*/
public class DiagonalConstraint implements IConstraint {
@Override

View File

@@ -1,22 +1,12 @@
package sudoku.constraint;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import sudoku.structure.Sudoku;
public interface IConstraint extends Serializable {
/**
* Interface de base pour la déclaration d'une contrainte
* Elle est en théorie assez générique pour implémenter n'importe quelle
* contrainte
*/
public interface IConstraint {
boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex);
default List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) {
List<Integer> possibilities = new ArrayList<>();
for (int i = 0; i < s.getSize(); i++) {
if (canBePlaced(s, x, y, i)) {
possibilities.add(i);
}
}
return possibilities;
}
}

View File

@@ -2,6 +2,9 @@ package sudoku.constraint;
import sudoku.structure.Sudoku;
/**
* Contrainte de ligne
*/
public class LineConstraint implements IConstraint {
@Override

View File

@@ -11,22 +11,35 @@ import java.util.List;
import java.util.Scanner;
public class ConsoleInterface {
public Scanner reader = new Scanner(System.in);
private final Scanner reader = new Scanner(System.in);
/**
* Début de la séquence console, affiche un message de bienvenue et les crédits
* du projet
* puis donne à l'utilisateur le choix de récupérer un doku sauvegardé
* ou d'en créer un nouveau.
*/
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();
}
}
/**
* Demande à l'utilisateur un fichier de sauvegarde et le laisse jouer au
* MultiDoku.
* qui y est sauvegardé
*/
private void useSavedDoku() {
System.out.println("What save should we use? Please enter the save number.");
MultiDoku md = saveChoice();
MultiDoku md = getSavedDoku();
int blockWidth = md.getSubGrid(0).getBlockWidth();
int blockHeight = md.getSubGrid(0).getBlocks().getFirst().getCells().size() / blockWidth;
List<String> listSymbols = pickSymbols(blockWidth * blockHeight);
@@ -38,7 +51,10 @@ public class ConsoleInterface {
congrats();
}
public void createDoku() {
/**
* Demande à l'utilisateur les paramètres du doku à générer.
*/
private 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();
@@ -58,7 +74,7 @@ public class ConsoleInterface {
System.out.println("Your sudoku will look like this:");
showMultidoku(doku, listSymbols, width, height);
System.out.println(
"You can now manually fill this sudoku ('fill'), or generate a playable one ('generate', default):");
"You can now manually fill this sudoku ('fill'), or generate a playable one from this template ('generate', default):");
if (reader.next().equalsIgnoreCase("fill")) {
findSolution(doku, listSymbols, width, height);
} else {
@@ -66,6 +82,16 @@ public class ConsoleInterface {
}
}
/**
* Remplit un doku vide en fonction de la difficulté que l'utilisateur
* renseigne,
* et le laisse jouer.
*
* @param doku MultiDoku, MultiDoku vide à remplir
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
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?" +
@@ -74,6 +100,7 @@ public class ConsoleInterface {
if (difficulty.equals("full")) {
generateFullDoku(doku);
System.out.println("Here's your sudoku !");
showMultidoku(doku, listSymbols, width, height);
exit();
} else {
generatePartialDoku(doku, difficulty);
@@ -86,36 +113,64 @@ public class ConsoleInterface {
}
}
private void findSolution(MultiDoku doku, List<String> listSymbols, int width, int height){
/**
* Permet à l'utilisateur de remplir manuellement un sudoku vide, et de le
* remplir
* quand souhaité.
*
* @param doku MultiDoku, MultiDoku vide à remplir
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
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();
}
/**
* Message de félicitation quand l'utilisateur a rempli son doku.
*/
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() {
/**
* Renvoie un MultiDoku préenregistré, dont le numéro de sauvegarde est
* renseigné
* par l'utilisateur.
*
* @return Mutidoku, multidoku enregistré à la sauveagrde de numéro donné.
*/
private MultiDoku getSavedDoku() {
int nbSave;
MultiDoku md = null;
do {
nbSave = reader.nextInt();
if (nbSave == -1) {
System.exit(0);
}
try {
md = SudokuSerializer.getSavedMultiDoku(nbSave);
} catch (Exception e) {
System.out.println("There seems to be a problem with this save, please try again.");
System.out.println(
"There seems to be a problem with this save, please try again or write '-1' to abort.");
}
} while (md == null);
return md;
}
public int getBlockWidth() {
/**
* Demande à l'utilisateur la largeur d'un bloc du sudoku à générer.
*
* @return int, largeur d'un bloc du sudoku
*/
private int getBlockWidth() {
System.out.println("Width of a block: ");
int widthBlock = reader.nextInt();
checkValidSize(widthBlock);
@@ -127,7 +182,12 @@ public class ConsoleInterface {
return widthBlock;
}
public int getBlockHeight() {
/**
* Demande à l'utilisateur la hauteur d'un bloc du sudoku à générer.
*
* @return int, hauteur d'un bloc du sudoku
*/
private int getBlockHeight() {
System.out.println("Height of a block: ");
int heightBlock = reader.nextInt();
checkValidSize(heightBlock);
@@ -139,10 +199,23 @@ public class ConsoleInterface {
return heightBlock;
}
/**
* Vérifie si la taille passée en paramètres est une taille valide.
*
* @param size int, longueur à vérifier
* @return true si size>0, false sinon.
*/
private Boolean checkValidSize(int size) {
return (size > 0);
}
/**
* Permet à l'utilisateur de choisir les symboles qu'il souhaite utiliser pour
* l'affichage.
*
* @param numberOfSymbols int, nombre de symboles à choisir
* @return LIst<String>, liste des symboles à utiliser
*/
private List<String> pickSymbols(int numberOfSymbols) {
System.out.println("Would you like to pick the " + numberOfSymbols
+ " symbols from the sudoku? (y/n, default 'no')");
@@ -171,6 +244,12 @@ public class ConsoleInterface {
}
}
/**
* Permet à l'utilisateur de choisir les contraintes qu'il souhaite utiliser
* pour son sudoku.
*
* @return List<IConstraint>, liste des contraintes à utiliser
*/
private List<IConstraint> getListConstraints() {
List<IConstraint> listConstraints = SudokuFactory.DEFAULT_CONSTRAINTS;
System.out.println(
@@ -181,6 +260,12 @@ public class ConsoleInterface {
return listConstraints;
}
/**
* Remplit un sudoku selon la difficulté passée en paramètre.
*
* @param doku MultiDoku, doku vide à remplir selon la difficulté.
* @param difficultyName String, difficulté de résolution du doku à remplir.
*/
private void generatePartialDoku(MultiDoku doku, String difficultyName) {
Difficulty difficulty;
switch (difficultyName) {
@@ -200,34 +285,75 @@ public class ConsoleInterface {
}
}
/**
* Remplit entièrement le doku passé en paramètre.
*
* @param doku MultiDoku, doku à remplir
*/
private void generateFullDoku(MultiDoku doku) {
new RandomSolver().solve(doku);
}
/**
* Affiche le doku passé en paramètre.
*
* @param doku MultiDoku, MultiDoku à afficher
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void showMultidoku(MultiDoku doku, List<String> listSymbols, int width, int height) {
showMultiDoku(RenderableMultidoku.fromMultidoku(doku), listSymbols, width, height);
}
/**
* Affiche le doku passé en paramètre.
*
* @param doku RenderableMultiDoku, MultiDoku à afficher
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void showMultiDoku(RenderableMultidoku doku, List<String> listSymbols, int width, int height) {
SudokuPrinter.printMultiDokuWithIndex(doku, listSymbols, width, height);
}
/**
* Permet à l'utilisateur de sauvegarder l'état de son doku, soit dans un
* nouveau fichier
* de sauvegarde, soit en écrasant une sauvegarde précédente.
*
* @param doku MultiDoku, MultiDoku à sauvegarder
*/
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);
System.out.println("The path to your save is: " + path);
}
/**
* Tour de jeu de l'utilisateur, présenté avec les choix de remplir une case du
* doku,
* de sauvegarder son état actuel dans un fichier de sauvegarde,
* de le résoudre tel qu'il est,
* ou de quitter l'application.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
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').");
"You can now put a number in a cell ('play', default), show a solution ('solution'), save the grid ('save') or exit the program ('exit').");
switch (reader.next()) {
case "save":
saveMultiDoku(doku);
break;
case "solution":
solve(doku);
solve(doku, listSymbols, width, height);
break;
case "exit":
exit();
@@ -238,21 +364,95 @@ public class ConsoleInterface {
}
}
private void solve(MultiDoku doku){
System.out.println("Pick a solver to use : random ('random', default), human ('human') or mixed solver ('mixed').");
switch (reader.next()) {
case "human":
new HumanSolver().solve(doku);
break;
case "mixed":
new MixedSolver().solve(doku);
break;
default:
new RandomSolver().solve(doku);
break;
/**
* Applique l'étape passée en paramètre.
*
* @param step SolverStep, étape à appliquer
*/
private void applyStep(SolverStep step) {
step.getCell().setSymbolIndex(step.getNewValue());
}
/**
* Permet d'afficher une étape de résolution du doku complété.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
* @param step SolverStep, étape de résolution à afficher
* @return boolean, valant true si l'utilisateur veut afficher l'étape, false
* sinon
*/
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");
}
/**
* Permet d'afficher les étapes de résolution du doku complété si l'utilisateur
* le souhaite.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
* @param steps List<SolverStep>, liste des étapes de résolution
*/
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();
if (reader.next().equalsIgnoreCase("y")) {
int stepCount = 0;
while (stepCount < steps.size() && showStep(doku, listSymbols, width, height, steps.get(stepCount))) {
stepCount++;
}
}
}
/**
* Résout le doku en fonction du solver que choisit l'utilisateur.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
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;
}
showMultidoku(doku, listSymbols, width, height);
showSolveSteps(doku, listSymbols, width, height, steps);
}
/**
* Remplissage d'une Cell du doku en fonction des coordonnées et du symboles que
* l'utilisateur choisit.
*
* @param doku MultiDoku, MultiDoku actuel
* @param listSymbols List<String>, liste des symboles à utiliser
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
*/
private void play(MultiDoku doku, List<String> listSymbols, int width, int height) {
int x, y;
RenderableMultidoku rdoku = RenderableMultidoku.fromMultidoku(doku);
@@ -261,8 +461,8 @@ public class ConsoleInterface {
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);
} 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)) {
@@ -273,22 +473,49 @@ public class ConsoleInterface {
showMultiDoku(rdoku, listSymbols, width, height);
}
/**
* Vérifie que la Cell identifiée par les coordonées x et y dans le
* RenderableMultiDOku fourni
* existe et est modifiable.
*
* @param doku RenderableMultiDoku, MultiDoku actuel
* @param width int, largeur d'un bloc du sudoku
* @param height int, hauteur d'un bloc du sudoku
* @param x int, abscisse de la Cell à vérifier
* @param y int, ordonnée de la Cell à vérifier
* @return Boolean true si la Cell aux coordonéees données peut être modifiée,
* false sinon
*/
private boolean isValidCoordinates(RenderableMultidoku doku, int width, int height, int x, int y) {
if (doku.getCell(x, y) != null) {
return true;
}
return false;
Cell cell = doku.getCell(x, y);
return ((cell != null) && cell.isMutable());
}
/**
* Renvoie l'index du symbole passé en paramètre.
*
* @param symbol String, symbole dont on veut l'index
* @param listSymbols List<String>, liste des symboles possibles
* @param nbSymbols int, nombre de symboles possibles
* @return int, index du symbole si celui-ci est valide, Cell.NOSYMBOL sinon.
*/
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;
return Cell.NOSYMBOL;
}
/**
* Vérifie que le symbol passé en paramètre est valide.
*
* @param symbol String, symbole dont on vérifie la validité
* @param listSymbols List<String>, liste des symboles possibles
* @param size int, nombre de symboles possibles
* @return boolean, valant true si le symbole est valide, false sinon.
*/
private boolean isValidSymbol(String symbol, List<String> listSymbols, int size) {
for (int i = 0; i < size; i++) {
if (listSymbols.get(i).equals(symbol)) {
@@ -298,6 +525,9 @@ public class ConsoleInterface {
return false;
}
/**
* Affiche un message d'aurevoir et ferme l'application.
*/
private void exit() {
System.out.println("Thank you for playing!");
System.exit(0);

View File

@@ -1,7 +0,0 @@
package sudoku.io;
public class SudokuFile {
}

View File

@@ -1,15 +0,0 @@
package sudoku.io;
public class SudokuSave {
public static enum AlgoResolution {
Backtracking,
NoBacktring
}
// private final MultiDoku sudoku;
// private final AlgoResolution resolution;
}

View File

@@ -18,8 +18,17 @@ import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
/**
* Classe permettant d'effectuer des opérations sur les sudokus afin de les
* charger/sauvegarder
*/
public class SudokuSerializer {
/**
* Convertit un sudoku en object JSON
* @param multidoku le sudoku à sérialiser
* @return le JSON
*/
public static JSONObject serializeSudoku(final MultiDoku multidoku) {
List<Cell> cellIds = new ArrayList<>();
List<Block> blockIds = new ArrayList<>();
@@ -127,6 +136,14 @@ public class SudokuSerializer {
return jsonRoot;
}
/**
* Crée le répertoire save afin d'y sauvegarder les sudokus
*/
private static void createSaveDir() {
File f = new File("save");
f.mkdir();
}
/**
* Save a serialized MultiDoku in a JSON file.
*
@@ -134,6 +151,7 @@ public class SudokuSerializer {
* @return String, the path of the save.
*/
public static String saveMultiDoku(final MultiDoku doku) {
createSaveDir();
JSONObject jsonRoot = serializeSudoku(doku);
File f = new File("save", "save.json");
@@ -151,6 +169,7 @@ public class SudokuSerializer {
}
public static String saveMultiDoku(final MultiDoku doku, final int saveToOverwrite) {
createSaveDir();
File f;
if (saveToOverwrite == 0) {
f = new File("save", "save.json");
@@ -173,7 +192,7 @@ public class SudokuSerializer {
* 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.
* @return MultiDoku, MultiDoku contained in the file.
* @throws Exception when the given save file does not exist.
*/
public static MultiDoku getSavedMultiDoku(int numberSave) throws Exception {
@@ -195,11 +214,21 @@ public class SudokuSerializer {
}
}
/**
* Construit un sudoku à partir d'un String en JSON
* @param json le sudoku sérialisé
* @return le sudoku désérialisé
*/
public static MultiDoku deserializeSudoku(final String json) {
JSONObject jsonRoot = new JSONObject(json);
return deserializeSudoku(jsonRoot);
}
/**
* Désérialise un sudoku d'un objet JSON
* @param jsonObject l'objet à désérialiser
* @return le sudoku correspondant
*/
public static MultiDoku deserializeSudoku(final JSONObject jsonObject) {
List<Cell> cells = new ArrayList<>();

View File

@@ -11,10 +11,15 @@ import sudoku.structure.MultiDoku;
public class HintHelper {
public static record Hint(Cell cell, int newValue) {
}
public record Hint(Cell cell, int newValue) {}
/**
* Si possible, donne un indice sur la résolution du doku passé en paramètre,
* selon la méthode de résolution rensaignée.
* @param doku MultiDoku, multidoku pour lequel on veut un indice
* @param solver Solver, méthode de résolution souhaitée
* @return Hint, indice sur une case à remplir, valant null si le doku n'a pas de solution.
*/
public static Hint getHint(MultiDoku doku, Solver solver) {
doku.getStateManager().pushState();
doku.clearMutableCells();
@@ -36,7 +41,7 @@ public class HintHelper {
if (newValue == Cell.NOSYMBOL)
return new Hint(cell, newValue);
// we have to change the cell value
if (oldValue != Cell.NOSYMBOL && newValue != oldValue)
if (oldValue != Cell.NOSYMBOL)
return new Hint(cell, newValue);
// there is a valid move

View File

@@ -1,14 +1,9 @@
package sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import gui.constants.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class HumanSolver implements Solver {
@@ -20,39 +15,25 @@ public class HumanSolver implements Solver {
*/
@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;
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(),
Symbols.Numbers));
if (doku.isSolved()) {
return true;
List<Integer> possibleSymbols = cell.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cell.setSymbolIndex(possibleSymbols.getFirst());
addStep(cell, steps);
filledCell = true;
}
List<Cell> cellsToFill = doku.getEmptyCells();
if (cellsToFill.isEmpty()) {
}
// on ne peut plus remplir de cases, on abandonne
if (!filledCell)
return false;
}
for (Cell cellToFill : cellsToFill) {
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() != 1) {
continue;
}
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
addStep(cellToFill, steps);
return this.solve(doku, steps);
}
return doku.isSolved();
return true;
}
}

View File

@@ -1,18 +1,32 @@
package sudoku.solver;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import gui.constants.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class MixedSolver implements Solver {
private List<Cell> findCellsToBacktrack(MultiDoku doku, int maxPossibilities) {
List<Cell> cells = new ArrayList<>();
for (Cell cell : doku.getCells()) {
if (!cell.isMutable() || !cell.isEmpty())
continue;
List<Integer> possibleSymbols = cell.getPossibleSymbols();
if (possibleSymbols.size() == maxPossibilities) {
cells.add(cell);
}
// une cellule nous empêche de continuer
if (possibleSymbols.size() == 0)
return null;
}
return cells;
}
/**
* Résout le MultiDoku passé en paramètre, avec règles de déduction et
* backtracking.
@@ -22,52 +36,52 @@ public class MixedSolver implements Solver {
*/
@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");
}
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(),
Symbols.Numbers));
if (doku.isSolved()) {
if (doku.isSolved())
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
if (findCellsToBacktrack(doku, 0) == null)
return 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);
if (solve(doku, steps))
return true;
cell.setSymbolIndex(Cell.NOSYMBOL);
addStep(cell, steps);
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
}
// on ne peut plus remplir de cases, on tente de backtrack
int maxPossibilities = 2;
List<Cell> backtrackCells = new ArrayList<>();
while (backtrackCells.isEmpty()) {
backtrackCells = findCellsToBacktrack(doku, maxPossibilities);
if (backtrackCells == null || maxPossibilities > doku.getSubGrid(0).getSize())
return false;
maxPossibilities++;
}
// on fait du backtracking
for (Cell backtrackCell : backtrackCells) {
List<Integer> possibilities = backtrackCell.getPossibleSymbols();
for (int symbol : possibilities) {
backtrackCell.setSymbolIndex(symbol);
addStep(backtrackCell, steps);
if (solve(doku, steps))
return true;
}
}
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);
backtrackCell.setSymbolIndex(Cell.NOSYMBOL);
addStep(backtrackCell, steps);
}
return false;

View File

@@ -3,13 +3,9 @@ package sudoku.solver;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import gui.constants.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class RandomSolver implements Solver {
@@ -28,13 +24,6 @@ public class RandomSolver implements Solver {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
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(),
Symbols.Numbers));
if (doku.isSolved()) {
return true;
}

View File

@@ -52,6 +52,13 @@ public interface Solver {
return result;
}
/**
* Méthode utilisée en interne afin de rajouter une étape si l'utilisateur le
* souhaite (steps non null)
*
* @param cell la cellule qui a été modifiée
* @param steps la liste d'étape à mettre à jour
*/
default void addStep(Cell cell, List<SolverStep> steps) {
if (steps == null)
return;

View File

@@ -1,5 +1,6 @@
package sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import sudoku.structure.MultiDoku;
@@ -8,9 +9,9 @@ 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");
@@ -21,27 +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);
for (int symbol = 0; symbol < sudoku.getSize(); 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.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;

View File

@@ -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>
}

View File

@@ -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.
@@ -29,6 +31,10 @@ public class Cell {
*/
private boolean isMutable = true;
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc="METHODES">
public Cell() {
this(Cell.NOSYMBOL);
}
@@ -46,6 +52,22 @@ public class Cell {
return this.symbolIndex;
}
/**
* Renvoie le Block qui la contient.
* @return Block.
*/
public Block getBlock() {
return this.blockContainer;
}
/**
* 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;
}
@@ -57,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;
}
/**
@@ -83,14 +99,6 @@ public class Cell {
return this.symbolIndex == Cell.NOSYMBOL;
}
/**
* 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.
@@ -101,6 +109,11 @@ public class Cell {
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);
@@ -116,6 +129,10 @@ public class Cell {
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++) {
@@ -125,6 +142,11 @@ public class Cell {
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;
@@ -133,4 +155,6 @@ public class Cell {
setSymbolIndex(newValue);
return true;
}
// </editor-fold>
}

View File

@@ -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>
}

View File

@@ -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), VeryHard("Impossible", 0.78);
VeryEasy("Très facile", 0.1),
Easy("Facile", 0.25),
Medium("Moyen", 0.5),
Hard("Difficile", 0.75),
VeryHard("Impossible", 0.78);
/**
* 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;
}

View File

@@ -1,32 +1,99 @@
package sudoku.structure;
import sudoku.io.SudokuSerializer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
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;
this.stateManager = new StateManager(this);
}
/**
* 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() {
for (Sudoku sudoku : this.subGrids) {
if (!sudoku.isSolved())
return false;
}
return true;
}
/**
* 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()) {
if (!cell.isEmpty()) {
result.add(cell);
}
}
return result;
}
/**
* 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()) {
if (cell.isEmpty()) {
result.add(cell);
}
}
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;
}
/**
* Renvoie le nombre de sudoku contenu dans ce MultiDoku.
*
@@ -60,95 +127,6 @@ public class MultiDoku {
return new ArrayList<>(cellsSet);
}
@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 sous-Sudoku
*
* @return List<Sudoku>
*/
public List<Sudoku> getSubGrids() {
return this.subGrids;
}
/**
* 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() {
for (Sudoku sudoku : this.subGrids) {
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) {
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()) {
if (!cell.isEmpty()) {
result.add(cell);
}
}
return result;
}
/**
* 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()) {
if (cell.isEmpty()) {
result.add(cell);
}
}
return result;
}
/**
* Vide une Cell donnée.
*
* @param cell Cell, à vider.
*/
public void empty(Cell cell) {
List<Cell> cells = getCells();
Cell cellToEmpty = cells.get(cells.indexOf(cell));
cellToEmpty.setSymbolIndex(Cell.NOSYMBOL);
}
/**
* Renvoie le nombre de Cell contenue dans le MultiDoku.
*
@@ -167,22 +145,9 @@ public class MultiDoku {
}
}
public StateManager getStateManager() {
return stateManager;
}
/**
* Renvoie une Cell vide choisie aléatoirement.
*
* @param rand Random, pour le choix aléatoire.
* @return Cell, une Cell vide.
* Vide les Cells modifiable.
*/
public Cell getRandomEmptyCell(Random rand) {
List<Cell> emptyCells = getEmptyCells();
int randomIndex = rand.nextInt(emptyCells.size());
return emptyCells.get(randomIndex);
}
public void clearMutableCells() {
for (Sudoku s : getSubGrids()) {
for (Cell cell : s.getCells()) {
@@ -192,8 +157,52 @@ public class MultiDoku {
}
}
/**
* 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(i).getSymbolIndex() != otherSudoku.getCell(i).getSymbolIndex())
return false;
}
}
return true;
}
@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();
}
public MultiDoku clone() {
// TODO: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
}
// </editor-fold>
}

View File

@@ -4,12 +4,22 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
//TODO: doc
/**
* Une pile, qui réprésente les états d'un MultiDoku,
* utile pour les Solvers.
*/
public class StateManager {
private final Stack<Map<Cell, Integer>> states;
/**
* 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;
@@ -21,12 +31,12 @@ public class StateManager {
}
public void popState() {
assert (states.size() > 0);
assert (!states.isEmpty());
restoreState(states.pop());
}
public Map<Cell, Integer> popAndGetState() {
assert (states.size() > 0);
assert (!states.isEmpty());
var currentState = saveState();
restoreState(states.pop());
return currentState;

View File

@@ -1,35 +1,43 @@
package sudoku.structure;
import java.util.ArrayList;
import java.util.List;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import java.util.List;
/**
* @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<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;
// </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;
@@ -97,31 +105,79 @@ public class Sudoku {
}
/**
* Vide la Cell dotn les coordonnées sont renseignées de son symbole.
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses
* contraintes.
*
* @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue.
* @return boolean, valant true si le Sudoku est résolu, false sinon.
*/
public void clearCell(int x, int y) {
assert (isValidCoords(x, y));
Cell cell = getCell(x, y);
cell.setSymbolIndex(Cell.NOSYMBOL);
public boolean isSolved() {
boolean isComplete = isComplete();
boolean isValid = isValid();
return isComplete && isValid;
}
/**
* Vide toutes les Cell du Sudoku.
* 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.
*/
public void clear() {
for (int i = 0; i < getSize() * getSize(); i++) {
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.isMutable())
cell.setSymbolIndex(Cell.NOSYMBOL);
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;
}
/**
* 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 Cell getCell(int x, int y) {
int index = toIndex(x, y);
assert (isValidCoords(x, y));
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;
}
/**
@@ -189,24 +245,14 @@ public class Sudoku {
return true;
}
public Cell getCell(int x, int y) {
int index = toIndex(x, y);
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<IConstraint> getConstraints() {
return constraints;
}
public int getSize() {
return this.blocks.size();
}
@@ -219,16 +265,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;
}
public int getBlockWidth() {
return blockWidth;
}
public void setBlockWidth(int blockWidth) {
this.blockWidth = blockWidth;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Sudoku {");
@@ -243,71 +292,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;
}
/**
* 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 (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;
}
public void setBlockWidth(int blockWidth) {
this.blockWidth = blockWidth;
}
public boolean hasConstraint(Constraint constraint) {
return this.constraints.contains(constraint.getConstraint());
}
// <editor-fold defaultstate="collapsed" desc="METHODES">
}

View File

@@ -1,20 +1,19 @@
package sudoku.structure;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver;
public class SudokuFactory {
/**
@@ -27,8 +26,11 @@ public class SudokuFactory {
* Comprend les contraintes de blocs, de lignes, et de colonnes.
*/
public static List<IConstraint> DEFAULT_CONSTRAINTS = SudokuFactory
.fromConstraints(Arrays.asList(Constraint.Block, Constraint.Column,
Constraint.Line));
.fromConstraints(Arrays.asList(
Constraint.Block,
Constraint.Column,
Constraint.Line)
);
/**
* Créée des Cells et les met dans une liste de taille size.
@@ -65,9 +67,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);
}
}
@@ -86,7 +85,7 @@ public class SudokuFactory {
*/
public static MultiDoku createBasicEmptyRectangleDoku(int widthBlock, int heightBlock,
List<IConstraint> constraints) {
return new MultiDoku(Arrays.asList(createRectangleSudoku(widthBlock, heightBlock, constraints)));
return new MultiDoku(List.of(createRectangleSudoku(widthBlock, heightBlock, constraints)));
}
/**
@@ -96,63 +95,7 @@ public class SudokuFactory {
* @return MultiDoku, MultiDoku vide.
*/
public static MultiDoku createBasicEmptySquareDoku(int size, List<IConstraint> constraints) {
return new MultiDoku(Arrays.asList(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.
*
* @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;
return new MultiDoku(List.of(createSquareSudoku(size, constraints)));
}
/**
@@ -227,6 +170,9 @@ 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.
* 2 3
* 1
* 4 5
*
* @param size int, largeur des Blocks unitraires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
@@ -234,45 +180,25 @@ public class SudokuFactory {
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);
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size));
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size));
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1));
linkRectangleSudokus(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é
* 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<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);
@@ -287,30 +213,65 @@ public class SudokuFactory {
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception {
Solver solver = new RandomSolver();
solver.solve(doku);
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
boolean successfull = newDokuFromFilledOne(doku, nbCellsToEmpty, solver);
doku.setFilledCellsImmutable();
/**
* 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);
}
public static MultiDoku fromfile(String filePath) {
try {
String content = Files.readString(Paths.get(filePath));
MultiDoku doku = SudokuSerializer.deserializeSudoku(content);
return doku;
} catch (IOException e) {
e.printStackTrace();
return null;
}
/**
* 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<>();
homeLessCells.addAll(cells);
List<Cell> homeLessCells = new ArrayList<>(cells);
List<Block> blocks = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < blockCellCount; i++) {
@@ -327,9 +288,79 @@ public class SudokuFactory {
for (Block block : blocks) {
block.getSudokus().add(sudoku);
}
return new MultiDoku(Arrays.asList(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;
}
/**
* Rempli un MultiDoku donné par rapport à un 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));
return SudokuSerializer.deserializeSudoku(content);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Transforme des Constraints en IConstraints 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) {

View File

Before

Width:  |  Height:  |  Size: 399 KiB

After

Width:  |  Height:  |  Size: 399 KiB

View File

@@ -1,7 +1,6 @@
package sudoku;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.util.Random;
@@ -22,7 +21,7 @@ public class SudokuSerializerTest {
new RandomSolver().solve(sudoku);
JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
assertTrue(data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
assertEquals(data.toString(), SudokuSerializer.serializeSudoku(multiDoku).toString());
}
void testSaveWithSize(int blockWidth, int blockHeight) {
@@ -41,7 +40,7 @@ public class SudokuSerializerTest {
File fileToDelete = new File(savePath);
fileToDelete.delete();
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
assert false;
}
}
@@ -52,25 +51,27 @@ public class SudokuSerializerTest {
JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
assertTrue(data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
assertEquals(data.toString(), SudokuSerializer.serializeSudoku(multiDoku).toString());
}
@Test
void testSerialize() {
Random r = new Random();
int testCount = 20;
int minSize = 2;
int maxSize = 3;
for (int i = 0; i < testCount; i++) {
int blockWidth = r.nextInt(4) + 1;
int blockHeight = r.nextInt(4) + 1;
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(4) + 1;
int blockHeight = r.nextInt(4) + 1;
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(2) + 2;
int size = r.nextInt(maxSize - minSize + 1) + minSize;
testSerializeX(size);
}
}

View File

@@ -1,31 +1,68 @@
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 gui.constants.Symbols;
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;
class SolverTest {
private int ns = Cell.NOSYMBOL;
protected static HumanSolver h;
private static RandomSolver r;
private static MixedSolver m;
@Test
void solveTest() {
MultiDoku dokuToTest = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
MultiDoku dokuResult = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
@BeforeAll
public static void initializeSolvers() {
h = new HumanSolver();
r = new RandomSolver();
m = new MixedSolver();
}
Sudoku sudokuToTest = dokuToTest.getSubGrid(0);
Sudoku sudokuResult = dokuResult.getSubGrid(0);
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());
int ns = Cell.NOSYMBOL;
List<Integer> immutableCells = List.of(ns, ns, 0, ns, ns, 2, 8, ns, 1,
assertNotEquals(mdResult, mdTest);
solver.solve(mdTest);
assertTrue(mdTest.isSolved());
assertEquals(mdTest, mdResult);
}
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,
@@ -34,13 +71,9 @@ class SolverTest {
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 (sudokuToTest.setImmutableCellsSymbol(immutableCells));
//SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3);
SudokuPrinter.printMultiDoku(dokuToTest, 3, 3, Symbols.Numbers);
List<Integer> correctCells = List.of(7, 6, 0, 3, 4, 2, 8, 5, 1,
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,
@@ -49,56 +82,43 @@ class SolverTest {
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());
sudokuResult.setCellsSymbol(correctCells);
System.out.println("\n****************************Doku Control\n");
SudokuPrinter.printRectangleSudoku(sudokuResult, 3, 3, Symbols.Russian);
assert (dokuResult.isSolved());
new RandomSolver().solve(dokuToTest);
System.out.println("\n****************************\nDoku solved");
//SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3);
SudokuPrinter.printMultiDoku(dokuToTest, 3, 3, Symbols.Emojis);
assert (dokuToTest.isSolved());
for (Cell cell : sudokuToTest.getCells()) {
cell.setImmutable();
assertNotEquals(mdResult, mdTest);
solver.solve(mdTest);
assert (mdTest.isSolved());
assertEquals(mdTest, mdResult);
}
for (Cell cell : sudokuResult.getCells()) {
cell.setImmutable();
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());
assertTrue(solver.solve(mdTest));
assertTrue(mdTest.isSolved());
assertFalse(mdResult.isSolved());
assertNotEquals(mdTest, mdResult);
solver.solve(mdResult);
assertEquals(mdTest, mdResult);
}
assertEquals(SudokuSerializer.serializeSudoku(dokuResult).toString(),
SudokuSerializer.serializeSudoku(dokuToTest).toString());
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 = new RandomSolver().solve(dokuToTest2);
assert (!isSolved);
MultiDoku dokuToTest3 = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
new RandomSolver().solve(dokuToTest3);
//SudokuPrinter.printRectangleSudoku(dokuToTest3.getSubGrid(0), 3, 3);
SudokuPrinter.printMultiDoku(dokuToTest3, 3, 3, Symbols.Letters);
@Test
void solveTest() {
initializeSolvers();
testSize2(h);
testSize3(h);
testSize2(m);
testSize3(m);
testMDSize3(m);
testSize2(r);
testSize3(r);
testMDSize3(r);
}
}