106 Commits

Author SHA1 Message Date
1e67e7a9d4 fix renderable multidoku max coords
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-02-02 00:37:07 +01:00
Melvyn
70eef1646d refactor
All checks were successful
Linux arm64 / Build (push) Successful in 31s
2025-02-02 00:16:27 +01:00
5dfe4382fe feat: render new sudoku types
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-02-02 00:10:25 +01:00
Melvyn
059886c2a4 feat : createPlusMMultidoku
All checks were successful
Linux arm64 / Build (push) Successful in 30s
2025-02-02 00:02:47 +01:00
Melvyn
129c3ef0b2 fix : countSolutions
All checks were successful
Linux arm64 / Build (push) Successful in 36s
2025-02-01 23:39:04 +01:00
14d0521215 NOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-02-01 23:15:57 +01:00
7568208045 fix warnings
All checks were successful
Linux arm64 / Build (push) Successful in 41s
2025-02-01 23:07:53 +01:00
86aa6e9bb5 refactor: move classes
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-02-01 23:06:11 +01:00
91c645e34f fix steps
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-02-01 23:00:36 +01:00
78bdefebe5 feat: add history 2025-02-01 22:54:02 +01:00
3e30332245 Merge branch 'constraint'
All checks were successful
Linux arm64 / Build (push) Successful in 4m2s
2025-02-01 22:29:03 +01:00
275878932b refactor: IConstraints in sudoku
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 22:24:26 +01:00
68d577a99a Merge pull request 'finished console interface' (#37) from osekour into master
All checks were successful
Linux arm64 / Build (push) Successful in 23m58s
Reviewed-on: #37
2025-02-01 20:48:26 +00:00
fa3124220d finished console interface
All checks were successful
Linux arm64 / Build (push) Successful in 5m14s
2025-02-01 20:43:01 +00:00
3a009256c5 Fixes #12
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 21:16:36 +01:00
d09bf6e9ce feat: allow user to be wrong
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 21:12:13 +01:00
5da915932d Fixes #31
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 21:00:59 +01:00
da422e78b8 Fixes #30
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 20:59:06 +01:00
f0a0a8e328 Fixes #23
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 20:55:08 +01:00
436b641269 Fixes #34 2025-02-01 20:47:40 +01:00
34a59546e6 remove unused import
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-02-01 20:46:06 +01:00
9e2421accf Fixes #25 2025-02-01 20:45:56 +01:00
52ca8b208c fix: sudoku save
All checks were successful
Linux arm64 / Build (push) Successful in 23m59s
2025-02-01 16:11:38 +00:00
Janet-Doe
140d37fbd9 update console interface
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 15:51:45 +01:00
Janet-Doe
2b3581a400 fix
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 14:56:45 +01:00
a6b1fae230 Merge branch 'gradle'
Some checks failed
Linux arm64 / Build (push) Failing after 23s
2025-02-01 14:49:54 +01:00
a20a5387a7 chore: bundle deps in jar 2025-02-01 14:34:19 +01:00
Janet-Doe
8c672e24ad merged version
Some checks failed
Linux arm64 / Build (push) Failing after 22s
2025-02-01 14:32:11 +01:00
Janet-Doe
815756b5e9 functional multidoku printer
# Conflicts:
#	app/src/main/java/sudoku/io/ConsoleInterface.java
#	app/src/main/java/sudoku/solver/Solver.java
2025-02-01 14:29:54 +01:00
a1032335a5 chore: remove unused deps 2025-02-01 14:10:15 +01:00
336d8378ae fix: slower background animation speed by default
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 13:45:44 +01:00
c165ecdae5 Merge pull request 'Fixes #15' (#36) from multiplayer into master
All checks were successful
Linux arm64 / Build (push) Successful in 39s
Reviewed-on: #36
2025-02-01 12:43:13 +00:00
352aee49e4 feat: make timer stop game (Fixes #15)
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-02-01 13:41:13 +01:00
f22debdf5f fix: score display
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 12:54:11 +01:00
02089c649b feat: select game duration
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 12:27:50 +01:00
e98199e1ec refactor: remove sysout
All checks were successful
Linux arm64 / Build (push) Successful in 25s
2025-02-01 11:59:05 +01:00
438252a8ca feat: first player progress display 2025-02-01 11:58:42 +01:00
caf6569409 fix: synced timer
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-02-01 11:22:59 +01:00
3863c812c8 fix: format timer
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-02-01 10:56:02 +01:00
6d96455ac4 feat: display wrong timer
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 00:19:00 +01:00
a5c046f891 feat: good leaderboard 2025-02-01 00:09:25 +01:00
Melvyn
b7f9ca8a98 fix : MixedSolver
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-31 18:26:44 +01:00
a160042ef4 feat: uggly leaderboard
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-31 13:48:51 +01:00
f47e4cc309 feat: animated background
All checks were successful
Linux arm64 / Build (push) Successful in 10m56s
2025-01-30 22:28:26 +01:00
25c2270a37 feat: multi synced player scores
All checks were successful
Linux arm64 / Build (push) Successful in 31s
2025-01-30 22:16:29 +01:00
bcded60fbe small fix 2025-01-30 21:46:55 +01:00
edfffaf061 feat: multi select sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-30 18:35:41 +01:00
a74bf42e59 refactor solvers
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-30 18:05:18 +01:00
1f92c49f3c feat: select solve algorithm
All checks were successful
Linux arm64 / Build (push) Successful in 25m12s
2025-01-30 17:28:43 +01:00
c262007ca8 fix multithreading issue 2025-01-30 17:28:22 +01:00
73f572ee18 fix merge
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-30 16:37:10 +01:00
ec07d88577 Merge branch 'symbols' 2025-01-30 16:35:05 +01:00
6caf5d5c54 feat: add cyrilic
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-01-30 16:32:09 +01:00
Janet-Doe
696062e9db merge image branch with main
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-01-30 16:23:07 +01:00
Janet-Doe
c825807aea set background picture 2025-01-30 16:23:03 +01:00
39529e0b64 fix agaaaaain 2025-01-30 16:22:47 +01:00
3fa22a4cf0 fix build.gradle (agin) 2025-01-30 16:22:43 +01:00
337911d038 bye bye png lib 2025-01-30 16:21:53 +01:00
1930bc02bd aaaaaa
# Conflicts:
#	app/src/main/java/sudoku/Main.java
#	app/src/main/java/sudoku/solver/Solver.java
2025-01-30 16:21:43 +01:00
b9788d6a51 application du cours d'APO de 15h
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 15:24:57 +01:00
7789209651 feat: change symbols
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-30 15:23:54 +01:00
Melvyn
54a4bd9f22 feat : diminue automatiquement la difficulté si elle n'est pas possible
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-30 14:59:19 +01:00
8596781ce3 Fixes #14
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-30 14:51:21 +01:00
Melvyn
d6c3504bc7 feat : mixedSolve
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 14:32:15 +01:00
44a4432ac0 Merge branch 'master' of git.ale-pri.com:Ryuk/Sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 13:21:05 +01:00
a42ec2f27c fix merge 2025-01-30 13:14:43 +01:00
bff7abcd02 Merge branch 'serialize-fix' 2025-01-30 13:13:44 +01:00
Melvyn
bf67afe4a9 refactor : Solver
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 12:03:03 +01:00
67da77af2e feat: add states
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-30 11:54:23 +01:00
c4becf2d55 fix: serialize 2025-01-30 11:54:21 +01:00
Janet-Doe
f1d963e546 semi-functionning console interface
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-30 11:51:17 +01:00
b9a6617967 feat: add states
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-30 09:34:00 +01:00
03f577828b fix: serialize 2025-01-30 00:51:22 +01:00
9b776d4b0f custom symbols
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-29 19:47:46 +01:00
d4beaec8a8 Merge pull request 'fix desezrialize' (#18) from fix into master
All checks were successful
Linux arm64 / Build (push) Successful in 37s
Reviewed-on: #18
2025-01-29 18:29:32 +00:00
a742cace3a fix desezrialize
All checks were successful
Linux arm64 / Build (push) Successful in 25s
2025-01-29 19:28:36 +01:00
Melvyn
e12955ab4a merge
All checks were successful
Linux arm64 / Build (push) Successful in 36s
2025-01-29 18:57:00 +01:00
Melvyn
412684e6f0 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	app/src/main/java/sudoku/structure/MultiDoku.java
#	app/src/main/java/sudoku/structure/Sudoku.java
#	app/src/main/java/sudoku/structure/SudokuFactory.java
#	app/src/test/java/sudoku/solver/SolverTest.java
2025-01-29 18:51:23 +01:00
Melvyn
cd4d01e1e6 fix : MultiDoku.getCells 2025-01-29 18:42:58 +01:00
ff85cbef01 Fix #4
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-29 18:32:50 +01:00
c16f2b8f5a feat: dynamic constraints (Fixes #8)
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-29 17:19:44 +01:00
5e26bea609 refactor: remove sudokufactory difficulties 2025-01-29 16:11:56 +01:00
cd792a0f8a add diagonal constraint
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 15:48:01 +01:00
de1f3c59d6 refactor isValid
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-01-29 15:13:43 +01:00
c0a3f85f24 test: clean serializer files 2025-01-29 15:12:52 +01:00
a616ab63e4 gui: save sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 15:08:30 +01:00
00866256a7 gui: revert suoku scrolling 2025-01-29 15:07:34 +01:00
ed9b636b58 tests: make it faster 2025-01-29 14:59:06 +01:00
a10d2eda9a gui: fix big grid display
All checks were successful
Linux arm64 / Build (push) Successful in 1m2s
2025-01-29 14:42:41 +01:00
c4a9bf6354 gui: select from file
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 14:14:54 +01:00
074131b69c refactor sudoku selection
All checks were successful
Linux arm64 / Build (push) Successful in 1m8s
2025-01-29 12:42:06 +01:00
21b7011ece 🗣️🔥
All checks were successful
Linux arm64 / Build (push) Successful in 59s
2025-01-29 12:25:43 +01:00
859d5795d0 nerd
All checks were successful
Linux arm64 / Build (push) Successful in 57s
2025-01-29 12:22:19 +01:00
cd81334c95 basic README
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 12:18:33 +01:00
89653f8517 gui: display victory
All checks were successful
Linux arm64 / Build (push) Successful in 58s
2025-01-29 12:10:30 +01:00
9213a10c17 gui: difficulties
All checks were successful
Linux arm64 / Build (push) Successful in 1m20s
2025-01-29 11:56:32 +01:00
4190bf15d8 difficulties
All checks were successful
Linux arm64 / Build (push) Successful in 52s
2025-01-29 11:47:18 +01:00
Melvyn
a221233c06 fix : création MultiDoku à résoudre avec cell imuable
All checks were successful
Linux arm64 / Build (push) Successful in 53s
2025-01-29 11:26:36 +01:00
5ad8fa30f4 fix edit of immutable cells
All checks were successful
Linux arm64 / Build (push) Successful in 43s
2025-01-29 11:24:43 +01:00
532b2d152b Prepare fix for #5
All checks were successful
Linux arm64 / Build (push) Successful in 57s
2025-01-29 11:23:16 +01:00
ec36e19c4e Fixes #2
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 11:05:15 +01:00
Janet-Doe
aa86e9b956 valid tests save and getFromSave sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-29 10:55:35 +01:00
b8553428ee fix: create solvable sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 53s
2025-01-29 10:34:40 +01:00
Melvyn
7c06fe2e31 feat : création MultiDoku à résoudre
All checks were successful
Linux arm64 / Build (push) Successful in 1m7s
2025-01-29 10:21:26 +01:00
Melvyn
cd45d1c22c feat : humanSolve
All checks were successful
Linux arm64 / Build (push) Successful in 50s
2025-01-29 09:55:14 +01:00
Melvyn
c7217894b2 adding documentation 2025-01-29 09:13:24 +01:00
69 changed files with 3121 additions and 11544 deletions

21
README.md Normal file
View File

@@ -0,0 +1,21 @@
# Sudoku 🧩
## Features 🌟
- Graphical User Interface (GUI)
- Sudoku saves
- Multiplayer
## Develop ☝🤓
### Run 🏃
```sh
./gradlew run
```
### Run tests 🗣️🔥
```sh
./gradlew test
```

BIN
app/background.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 399 KiB

View File

@@ -11,6 +11,8 @@ plugins {
id 'application' id 'application'
} }
project.ext.os = System.properties['os.name'].toLowerCase().split(" ")[0]
repositories { repositories {
// Use Maven Central for resolving dependencies. // Use Maven Central for resolving dependencies.
mavenCentral() mavenCentral()
@@ -20,17 +22,13 @@ dependencies {
// Use JUnit Jupiter for testing. // Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1' 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'
implementation 'org.json:json:20250107' 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 "io.github.spair:imgui-java-app:1.88.0"
implementation "org.lwjgl:lwjgl-stb:3.3.4"
runtimeOnly "org.lwjgl:lwjgl-stb::natives-$os"
} }
application { application {
@@ -38,9 +36,16 @@ application {
mainClass = 'gui.Main' mainClass = 'gui.Main'
} }
tasks.named('test') { // Add libraries into the final jar
// Use JUnit Platform for unit tests. jar {
useJUnitPlatform() archiveBaseName = rootProject.getName()
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest {
attributes "Main-Class": application.mainClass
}
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
} }
run { run {

0
app/save/.gitignore vendored Normal file
View File

File diff suppressed because it is too large Load Diff

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

View File

@@ -1,6 +1,10 @@
package game; package game;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
@@ -8,15 +12,19 @@ import sudoku.structure.MultiDoku;
public class Game { public class Game {
public static enum GameState { public static enum GameState {
GameNotStarted, GameGoing, GameEnd GameNotStarted, GameGoing
} }
private final Map<Integer, Player> players; private final Map<Integer, Player> players;
private final List<Player> leaderboard;
private GameState gameState; private GameState gameState;
private MultiDoku doku; private MultiDoku doku;
private Instant startTime = null;
private long gameDuration;
public Game() { public Game() {
this.players = new HashMap<>(); this.players = new HashMap<>();
this.leaderboard = new ArrayList<>();
this.gameState = GameState.GameNotStarted; this.gameState = GameState.GameNotStarted;
} }
@@ -26,19 +34,33 @@ public class Game {
public void addPlayer(Player player) { public void addPlayer(Player player) {
players.put(player.getId(), 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) { public void removePlayer(int id) {
players.remove(id); this.leaderboard.remove(getPlayerById(id));
this.players.remove(id);
} }
public Map<Integer, Player> getPlayers() { public Map<Integer, Player> getPlayers() {
return players; return players;
} }
public void startGame(MultiDoku doku) { public void startGame(MultiDoku doku, Instant startTime, long gameDuration) {
this.doku = doku; this.doku = doku;
this.gameState = GameState.GameGoing; this.gameState = GameState.GameGoing;
this.startTime = startTime;
this.gameDuration = gameDuration;
}
public void stopGame() {
this.gameState = GameState.GameNotStarted;
} }
public GameState getGameState() { public GameState getGameState() {
@@ -49,4 +71,16 @@ public class Game {
return doku; return doku;
} }
public List<Player> getLeaderboard() {
return leaderboard;
}
public Instant getStartTime() {
return startTime;
}
public long getGameDuration() {
return gameDuration;
}
} }

View File

@@ -8,10 +8,20 @@ public class Player implements Serializable {
private final String pseudo; private final String pseudo;
private final int id; private final int id;
private int score;
public Player(int id, String pseudo) { public Player(int id, String pseudo) {
this.pseudo = pseudo; this.pseudo = pseudo;
this.id = id; this.id = id;
this.score = 0;
}
public int getRemainingCells() {
return score;
}
void setRemainingCells(int score) {
this.score = score;
} }
public String getPseudo() { public String getPseudo() {

View File

@@ -1,22 +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;
public static void createFonts() {
COMIC = ImGui.getIO().getFonts().addFontFromFileTTF("comic.ttf", 50.0f);
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromFileTTF("arial_bold.ttf", 50.0f);
ARIAL = ImGui.getIO().getFonts().addFontFromFileTTF("arial.ttf", 50.0f);
CHERI = ImGui.getIO().getFonts().addFontFromFileTTF("cheri.ttf", 50.0f);
INFECTED = ImGui.getIO().getFonts().addFontFromFileTTF("INFECTED.ttf", 50.0f);
}
}

View File

@@ -1,10 +1,16 @@
package gui; package gui;
import gui.constants.Fonts;
import gui.constants.Images;
import gui.constants.Symbols;
import gui.menu.MainMenu; import gui.menu.MainMenu;
import gui.menu.StateMachine; import gui.menu.StateMachine;
import imgui.ImGui;
import imgui.app.Application; import imgui.app.Application;
import imgui.app.Configuration; import imgui.app.Configuration;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Difficulty;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class Main extends Application { public class Main extends Application {
@@ -26,6 +32,12 @@ public class Main extends Application {
Fonts.createFonts(); Fonts.createFonts();
stateMachine.pushState(new MainMenu(stateMachine)); stateMachine.pushState(new MainMenu(stateMachine));
} }
@Override
protected void preRun() {
super.preRun();
Images.loadImages();
}
@Override @Override
public void process() { public void process() {
@@ -34,6 +46,13 @@ public class Main extends Application {
} }
public static void main(String[] args) { public static void main(String[] args) {
launch(new Main()); MultiDoku doku = SudokuFactory.createBasicPlusShapedMultidoku(3, 3, SudokuFactory.DEFAULT_CONSTRAINTS);
try {
SudokuFactory.fillDoku(doku, Difficulty.Easy);
} catch (Exception e) {
throw new RuntimeException();
}
SudokuPrinter.printMultiDoku(doku, 3, 3, Symbols.Numbers);
//launch(new Main());
} }
} }

View File

@@ -47,22 +47,6 @@ public class RenderableMultidoku {
return cells.get(index); 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) { private static record PositionConstraint(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
} }
@@ -106,29 +90,23 @@ public class RenderableMultidoku {
} }
private static Coordinate getMaxSudokuCoordinate(Map<Sudoku, Coordinate> sudokusOffset) { private static Coordinate getMaxSudokuCoordinate(Map<Sudoku, Coordinate> sudokusOffset) {
Coordinate maxCoordinate = null; int maxX = 0;
Sudoku maxSudoku = null; int maxY = 0;
float maxDistanceSquared = 0; Sudoku lastSudoku = null;
for (var entry : sudokusOffset.entrySet()) { for (var entry : sudokusOffset.entrySet()) {
Coordinate coordinate = entry.getValue(); Coordinate coordinate = entry.getValue();
float distanceSquared = coordinate.getX() * coordinate.getX() + coordinate.getY() * coordinate.getY(); if (coordinate.getX() > maxX)
if (maxCoordinate == null) { maxX = coordinate.getX();
maxCoordinate = coordinate; if (coordinate.getY() > maxY)
maxDistanceSquared = distanceSquared; maxY = coordinate.getY();
maxSudoku = entry.getKey(); lastSudoku = entry.getKey();
}
if (distanceSquared > maxDistanceSquared) {
maxDistanceSquared = distanceSquared;
maxSudoku = entry.getKey();
maxCoordinate = coordinate;
}
} }
int blockWidth = maxSudoku.getBlockWidth(); Coordinate maxCoordinate = new Coordinate(maxX, maxY);
int blockHeight = maxSudoku.getSize() / blockWidth; // tous les sudokus sont censés faire la même taille
int sudokuSize = lastSudoku.getSize();
return new Coordinate(maxCoordinate.getX() + maxSudoku.getSize(), maxCoordinate.getY() + maxSudoku.getSize()); return new Coordinate(maxCoordinate.getX() + sudokuSize, maxCoordinate.getY() + sudokuSize);
} }
public static RenderableMultidoku fromMultidoku(MultiDoku doku) { public static RenderableMultidoku fromMultidoku(MultiDoku doku) {

View File

@@ -1,107 +0,0 @@
package gui;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import gui.ColorGenerator.Color;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class SudokuRenderer {
private final RenderableMultidoku doku;
private Cell currentCell = null;
private final Map<Block, Color> colorPalette;
public SudokuRenderer(MultiDoku doku) {
this.doku = RenderableMultidoku.fromMultidoku(doku);
this.colorPalette = initColors();
}
private Map<Block, Color> initColors() {
List<Color> colors = ColorGenerator.greatPalette(doku.getBlocks().size());
Map<Block, Color> colorPalette = new HashMap<>();
int index = 0;
for (Block block : doku.getBlocks()) {
colorPalette.put(block, colors.get(index));
index++;
}
return colorPalette;
}
private void renderPopup() {
final ImVec2 buttonSize = new ImVec2(50, 50);
if (ImGui.beginPopup("editPopup")) {
Block block = currentCell.getBlock();
int symbolCount = block.getCells().size();
for (int i = 0; i < symbolCount; i++) {
if ((i + 1) % (int) (Math.sqrt(symbolCount)) != 1)
ImGui.sameLine();
if (currentCell.getSymbolIndex() == i) {
if (ImGui.button("X", buttonSize)) {
currentCell.setSymbolIndex(Cell.NOSYMBOL);
ImGui.closeCurrentPopup();
}
}else {
if (ImGui.button(Integer.toString(i + 1), buttonSize)) {
this.doku.setCellValue(currentCell, i);
ImGui.closeCurrentPopup();
}
}
}
ImGui.endPopup();
}
}
public void render() {
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 2.0f);
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2(0.0f, 0.0f));
ImGui.pushStyleColor(ImGuiCol.Border, new ImVec4(0.0f, 0.0f, 0.0f, 1.0f));
for (int y = 0; y < doku.getHeight(); y++) {
for (int x = 0; x < doku.getWidth(); x++) {
if (x > 0)
ImGui.sameLine();
int index = y * doku.getWidth() + x;
Cell cell = doku.getCell(x, y);
if (cell == null) {
ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(0.0f, 0.0f, 0.0f, 1.0f));
ImGui.button("##" + index, new ImVec2(50, 50));
} else {
int symbol = cell.getSymbolIndex();
Color blockColor = colorPalette.get(cell.getBlock());
if (!cell.isMutable()) {
// ImGui.pushFont(Fonts.ARIAL_BOLD);
blockColor = new Color(blockColor.r - 0.20f, blockColor.g - 0.20f, blockColor.b - 0.20f);
// ImGui.pushStyleColor(ImGuiCol.Text, new ImVec4(0.1f, 0.1f, 0.1f, 1.0f));
} else {
// ImGui.pushFont(Fonts.CHERI);
}
ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(blockColor.r, blockColor.g, blockColor.b, 1.0f));
String cellText = "";
if (symbol != -1)
cellText += Integer.toString(symbol + 1);
if (ImGui.button(cellText + "##" + index, new ImVec2(50, 50))) {
ImGui.openPopup("editPopup");
currentCell = cell;
}
if (!cell.isMutable()) {
// ImGui.popStyleColor();
}
// ImGui.popFont();
}
ImGui.popStyleColor();
}
}
ImGui.popStyleColor();
ImGui.popStyleVar(2);
renderPopup();
}
}

View File

@@ -0,0 +1,34 @@
package gui.constants;
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());
// 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);
}
}

View File

@@ -0,0 +1,39 @@
package gui.constants;
import java.nio.ByteBuffer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.stb.STBImage;
public class Images {
public static int BACKGROUND;
private static int loadTexture(String fileName) {
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);
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 loadImages() {
BACKGROUND = loadTexture("background.png");
}
}

View File

@@ -0,0 +1,8 @@
package gui.constants;
public class Options {
public static Symbols Symboles = Symbols.Numbers;
public static float BackgroundSpeed = 1.0f;
}

View File

@@ -0,0 +1,67 @@
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)),
MultiDokuXSquare("Multidoku carré (X)", 1,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], constraints)),
MultidokuXRectangle("Multidoku rectangle (X)", 2,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], params[1], constraints)),
MultiDokuPSquare("Multidoku carré (+)", 1,
(constraints, params) -> SudokuFactory.createBasicPlusShapedMultidoku(params[0], constraints)),
MultiDokuPRectangle("Multidoku rectangle (+)", 2,
(constraints, params) -> SudokuFactory.createBasicPlusShapedMultidoku(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;
}
}

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

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

View File

@@ -20,7 +20,8 @@ public class MultiMenu extends BaseView {
private void renderCreate() { private void renderCreate() {
ImVec2 displaySize = ImGui.getIO().getDisplaySize(); ImVec2 displaySize = ImGui.getIO().getDisplaySize();
ImGui.beginChild("##CreateGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f)); 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));
if (ImGui.button("Créer")) { if (ImGui.button("Créer")) {
try { try {
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, (short) port.get())); this.stateMachine.pushState(new ConnexionStatusView(stateMachine, (short) port.get()));
@@ -35,12 +36,12 @@ public class MultiMenu extends BaseView {
ImVec2 displaySize = ImGui.getIO().getDisplaySize(); ImVec2 displaySize = ImGui.getIO().getDisplaySize();
ImGui.beginChild("##JoinGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f)); ImGui.beginChild("##JoinGame", new ImVec2(displaySize.x / 2.0f, displaySize.y * 8.0f / 9.0f));
ImGui.inputText("Adresse", address); ImGui.inputText("Adresse", address);
ImGui.inputInt("Port", port); if (ImGui.inputInt("Port", port))
port.set(Math.clamp(port.get(), 1, 65535));
if (ImGui.button("Rejoindre")) { if (ImGui.button("Rejoindre")) {
try { try {
this.stateMachine.pushState(new ConnexionStatusView(stateMachine, address.get(), (short) port.get())); this.stateMachine.pushState(new ConnexionStatusView(stateMachine, address.get(), (short) port.get()));
} catch (IOException e) { } catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();
} }
} }

View File

@@ -1,22 +1,50 @@
package gui.menu; 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 imgui.ImGui;
import network.client.Client; import network.client.Client;
import network.server.Server; 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 Client client;
private final Server server; private final Server server;
private final SudokuRenderer sudokuRenderer; private final SudokuRenderer sudokuRenderer;
private final LeaderboardRenderer leaderboardRenderer;
private final TimerRenderer timerRenderer;
private final MultiPlayerCompleteProgress completeProgress;
public MultiPlayerDokuView(StateMachine stateMachine, Client client, Server server) { public MultiPlayerDokuView(StateMachine stateMachine, Client client, Server server) {
super(stateMachine); super(stateMachine);
this.client = client; this.client = client;
this.server = server; this.server = server;
this.sudokuRenderer = new SudokuRenderer(this.client.getGame().getDoku()); 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.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() { public void onDisconnect() {
@@ -27,6 +55,9 @@ public class MultiPlayerDokuView extends BaseView{
@Override @Override
public void render() { public void render() {
this.timerRenderer.render();
this.leaderboardRenderer.render();
this.completeProgress.render();
this.sudokuRenderer.render(); this.sudokuRenderer.render();
if (ImGui.button("Quitter")) { if (ImGui.button("Quitter")) {
this.client.stop(); this.client.stop();

View File

@@ -1,23 +1,33 @@
package gui.menu; package gui.menu;
import game.Player; import game.Player;
import gui.widget.SudokuSelector;
import imgui.ImGui; import imgui.ImGui;
import imgui.type.ImInt;
import network.client.Client; import network.client.Client;
import network.server.Server; import network.server.Server;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class MultiPlayerView extends BaseView { public class MultiPlayerView extends BaseView {
private final Client client; private final Client client;
private final Server server; 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) { public MultiPlayerView(StateMachine stateMachine, Client client, Server server) {
super(stateMachine); super(stateMachine);
this.client = client; this.client = client;
this.server = server; 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.onDisconnect.connect(this::onDisconnect);
this.client.onGameStarted.connect(() -> this.stateMachine.pushState(new MultiPlayerDokuView(stateMachine, client, server))); this.client.onGameStarted
.connect(() -> this.stateMachine.pushState(new MultiPlayerDokuView(stateMachine, client, server)));
} }
@Override @Override
@@ -30,26 +40,41 @@ public class MultiPlayerView extends BaseView {
this.stateMachine.popState(); this.stateMachine.popState();
} }
private void onSelected(MultiDoku doku) {
this.doku = doku;
}
public void renderGameStatus() { public void renderGameStatus() {
if (this.server == null) { if (this.server == null) {
ImGui.text("En attente de l'administrateur du serveur ..."); ImGui.text("En attente de l'administrateur du serveur ...");
} else { } else {
renderTimer();
ImGui.beginDisabled(this.doku == null);
if (ImGui.button("Démarrer")) { if (ImGui.button("Démarrer")) {
// temp this.server.startGame(this.doku, this.gameDurationMinutes.get() * 60);
MultiDoku doku = SudokuFactory.createBasicSquareMultidoku(3);
this.server.startGame(doku);
} }
ImGui.endDisabled();
selector.render();
} }
} }
@Override private void renderPlayers() {
public void render() {
ImGui.text("Joueurs :"); ImGui.text("Joueurs :");
{ {
for (Player player : this.client.getGame().getPlayers().values()) { for (Player player : this.client.getGame().getPlayers().values()) {
ImGui.bulletText(player.getPseudo()); 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(); renderGameStatus();
} }

View File

@@ -1,17 +1,28 @@
package gui.menu; package gui.menu;
import gui.constants.Options;
import gui.constants.Symbols;
import imgui.ImGui; import imgui.ImGui;
import imgui.type.ImInt;
public class OptionsMenu extends BaseView { public class OptionsMenu extends BaseView {
private ImInt currentValue = new ImInt();
private float backgroundSpeed[] = new float[]{Options.BackgroundSpeed};
public OptionsMenu(StateMachine stateMachine) { public OptionsMenu(StateMachine stateMachine) {
super(stateMachine); super(stateMachine);
} }
@Override @Override
public void render() { public void render() {
// TODO Auto-generated method stub
ImGui.text("Options"); 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];
}
renderReturnButton(); renderReturnButton();
} }

View File

@@ -1,93 +1,27 @@
package gui.menu; package gui.menu;
import gui.widget.SudokuSelector;
import imgui.ImGui; import imgui.ImGui;
import imgui.type.ImInt;
import sudoku.solver.Solver;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
import sudoku.structure.SudokuFactory;
public class SoloMenu extends BaseView { public class SoloMenu extends BaseView {
private final ImInt sudokuType = new ImInt(0); private final SudokuSelector sudokuSelector;
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 SoloMenu(StateMachine stateMachine) { public SoloMenu(StateMachine stateMachine) {
super(stateMachine); super(stateMachine);
this.sudokuSelector = new SudokuSelector(true, "Résoudre le sudoku");
this.sudokuSelector.onSelect.connect(this::pushSudokuState);
} }
private void pushSudokuState(MultiDoku doku, boolean empty) { private void pushSudokuState(MultiDoku doku) {
if (!empty) {
try {
int level = 0;
for (Sudoku sudoku : doku.getSubGrids()) {
level += sudoku.getSize() * sudoku.getSize() / 10 * 3;
}
Solver.solve(doku);
level = (level - 1) / doku.getNbSubGrids();
SudokuFactory.newDokuFromFilledOne(doku, level);
for (Sudoku sudoku : doku.getSubGrids()) {
for (Cell cell : sudoku.getCells()) {
if (cell.getSymbolIndex() != Cell.NOSYMBOL) {
cell.setImmutable();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
this.stateMachine.pushState(new SudokuView(stateMachine, doku)); this.stateMachine.pushState(new SudokuView(stateMachine, doku));
} }
@Override @Override
public void render() { public void render() {
ImGui.text("Solo"); ImGui.text("Solo");
ImGui.combo("Type de Sudoku", sudokuType, sudokuTypes); sudokuSelector.render();
switch (sudokuType.get()) {
case SQUARE:
ImGui.inputInt("Taille", sudokuSize);
if (ImGui.button("Résoudre un sudoku")) {
pushSudokuState(SudokuFactory.createBasicEmptySquareSudoku(sudokuSize.get()), false);
}
if (ImGui.button("Générer une grille vide")) {
pushSudokuState(SudokuFactory.createBasicEmptySquareSudoku(sudokuSize.get()), true);
}
break;
case RECTANGLE:
ImGui.inputInt("Largeur", sudokuHeight);
ImGui.inputInt("Longueur", sudokuWidth);
if (ImGui.button("Résoudre un sudoku")) {
pushSudokuState(
SudokuFactory.createBasicEmptyRectangleSudoku(sudokuWidth.get(), sudokuHeight.get()),
false);
}
if (ImGui.button("Générer une grille vide")) {
pushSudokuState(
SudokuFactory.createBasicEmptyRectangleSudoku(sudokuWidth.get(), sudokuHeight.get()), true);
}
break;
case MULTIDOKU:
ImGui.inputInt("Taille", sudokuSize);
if (ImGui.button("Résoudre un sudoku")) {
pushSudokuState(SudokuFactory.createBasicSquareMultidoku(sudokuSize.get()), false);
}
if (ImGui.button("Générer une grille vide")) {
pushSudokuState(SudokuFactory.createBasicSquareMultidoku(sudokuSize.get()), true);
}
default:
break;
}
renderReturnButton(); renderReturnButton();
} }

View File

@@ -2,6 +2,7 @@ package gui.menu;
import java.util.Stack; import java.util.Stack;
import gui.widget.AnimatedBackground;
import imgui.ImGui; import imgui.ImGui;
import imgui.ImVec2; import imgui.ImVec2;
import imgui.flag.ImGuiKey; import imgui.flag.ImGuiKey;
@@ -10,9 +11,11 @@ import imgui.flag.ImGuiWindowFlags;
public class StateMachine { public class StateMachine {
private final Stack<BaseView> menus; private final Stack<BaseView> menus;
private final AnimatedBackground background;
public StateMachine() { public StateMachine() {
this.menus = new Stack<>(); this.menus = new Stack<>();
this.background = new AnimatedBackground();
} }
public void clear() { public void clear() {
@@ -26,6 +29,11 @@ public class StateMachine {
menus.add(menu); menus.add(menu);
} }
public void overrideState(BaseView menu) {
menus.getLast().cleanResources();
menus.set(menus.size() - 1, menu);
}
public void popState() { public void popState() {
menus.getLast().cleanResources(); menus.getLast().cleanResources();
menus.pop(); menus.pop();
@@ -39,6 +47,7 @@ public class StateMachine {
public void render() { public void render() {
var displaySize = ImGui.getIO().getDisplaySize(); var displaySize = ImGui.getIO().getDisplaySize();
this.background.render();
ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f)); ImGui.setNextWindowPos(new ImVec2(0.0f, 0.0f));
ImGui.setNextWindowSize(displaySize); ImGui.setNextWindowSize(displaySize);
ImGui.begin("##Main Window", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove ImGui.begin("##Main Window", null, ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoMove

View File

@@ -1,11 +1,20 @@
package gui.menu; package gui.menu;
import java.util.Random; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import gui.SudokuRenderer; import gui.widget.SudokuRenderer;
import imgui.ImGui; 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.Solver;
import sudoku.solver.SolverStep;
import sudoku.solver.HintHelper.Hint;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
public class SudokuView extends BaseView { public class SudokuView extends BaseView {
@@ -13,30 +22,21 @@ public class SudokuView extends BaseView {
private final SudokuRenderer sudokuRenderer; private final SudokuRenderer sudokuRenderer;
private Thread resolveThread; private Thread resolveThread;
private final MultiDoku doku; private final MultiDoku doku;
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) { public SudokuView(StateMachine stateMachine, MultiDoku doku) {
super(stateMachine); super(stateMachine);
this.doku = doku; this.doku = doku;
this.sudokuRenderer = new SudokuRenderer(doku); this.sudokuRenderer = new SudokuRenderer(doku);
// int level = 0; this.sudokuRenderer.onResolve.connect(this::onResolve);
// for (Sudoku sudoku : this.doku.getSubGrids()) { }
// level += sudoku.getSize() * sudoku.getSize() / 10;
// } private void onResolve() {
// try { this.resolved = true;
// Solver.solve(doku);
// SudokuFactory.newDokuFromFilledOne(doku, level);
// for (Sudoku sudoku : this.doku.getSubGrids()) {
// for (Cell cell : sudoku.getCells()) {
// if (cell.getSymbolIndex() != Cell.NOSYMBOL) {
// cell.setImmutable();
// }
// }
// }
// } catch (Exception e) {
// e.printStackTrace();
// System.out.println("non ça n'arrivera pas");
// //TODO: ça va arriver
// }
} }
private void stopResolve() { private void stopResolve() {
@@ -46,11 +46,24 @@ public class SudokuView extends BaseView {
} }
} }
boolean centeredButton(String label) {
ImGuiStyle style = ImGui.getStyle();
float size = ImGui.calcTextSizeX(label) + style.getFramePaddingX() * 2.0f;
float avail = ImGui.getContentRegionAvailX();
float off = (avail - size) * 0.5f;
if (off > 0.0f)
ImGui.setCursorPosX(ImGui.getCursorPosX() + off);
return ImGui.button(label);
}
private void renderCancelButton() { private void renderCancelButton() {
boolean wantsToStop = false; boolean wantsToStop = false;
if (resolveThread != null && resolveThread.isAlive()) { if (resolveThread != null && resolveThread.isAlive()) {
// ImGui.endDisabled(); // ImGui.endDisabled();
if (ImGui.button("Annuler")) { if (centeredButton("Annuler")) {
// we can't stop the Thread right now // we can't stop the Thread right now
wantsToStop = true; wantsToStop = true;
} }
@@ -62,36 +75,99 @@ public class SudokuView extends BaseView {
stopResolve(); 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) {
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() { private void renderSolveButton() {
if (resolveThread != null) if (resolveThread != null)
ImGui.beginDisabled(); ImGui.beginDisabled();
boolean beginSolve = false; if (!this.resolved && centeredButton("Résoudre")) {
ImGui.openPopup("solve");
if (ImGui.button("Résoudre")) {
beginSolve = true;
} }
if (resolveThread != null) if (resolveThread != null)
ImGui.endDisabled(); ImGui.endDisabled();
if (beginSolve) { renderResolvedText();
resolveThread = new Thread(() -> { renderUnsolvableText();
try {
Random rand = new Random(); renderSolvePopup();
Solver.solveRandom(doku, rand); }
Thread.sleep(200);
} catch (CancellationException | InterruptedException e) { private void renderSaveButton() {
System.out.println("The user is bored !"); if (ImGui.button("Sauvegarder l'état de la grille")) {
} lastSavePath = SudokuSerializer.saveMultiDoku(doku);
stopResolve(); ImGui.openPopup("saveDone");
}); }
if (ImGui.beginPopup("saveDone")) {
ImGui.text("Sudoku sauvegardé dans ");
ImGui.text(lastSavePath);
ImGui.endPopup();
}
}
private void renderClearButton() {
if (centeredButton("Effacer")) {
this.doku.clearMutableCells();
} }
} }
@Override @Override
public void render() { public void render() {
sudokuRenderer.render(); sudokuRenderer.render();
renderHintButton();
renderClearButton();
renderSolveButton(); renderSolveButton();
renderSaveButton();
renderCancelButton(); renderCancelButton();
renderReturnButton(); renderReturnButton();
} }

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

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

View File

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

View File

@@ -0,0 +1,21 @@
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;
public void render(String label, ImVec2 size, float progress) {
float delta = progress - lastProgress;
if (Math.abs(delta) < clipConstant)
lastProgress = progress;
else
lastProgress = lastProgress + delta * ImGui.getIO().getDeltaTime() * speed;
ImGui.progressBar(lastProgress, size, label);
}
}

View File

@@ -0,0 +1,157 @@
package gui.widget;
import java.util.HashMap;
import java.util.HashSet;
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;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar;
import sudoku.constraint.Constraint;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class SudokuRenderer {
private final RenderableMultidoku doku;
private Cell currentCell = null;
private final Map<Block, Color> colorPalette;
private static final ImVec4 BLACK = new ImVec4(0, 0, 0, 1);
private static final ImVec4 TRANSPARENT = new ImVec4();
private static final ImVec4 WHITE = new ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
private static final ImVec2 cellSize = new ImVec2(50, 50);
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);
this.colorPalette = initColors();
initDiagonals();
}
private void initDiagonals() {
for (Sudoku sudoku : this.doku.getDoku().getSubGrids()) {
if (sudoku.hasConstraint(Constraint.Diagonal)) {
for (int i = 0; i < sudoku.getSize(); i++) {
this.diagonals.add(sudoku.getCell(i, i));
this.diagonals.add(sudoku.getCell(sudoku.getSize() - i - 1, i));
}
}
}
}
private Map<Block, Color> initColors() {
List<Color> colors = ColorGenerator.greatPalette(doku.getBlocks().size());
Map<Block, Color> colorPalette = new HashMap<>();
int index = 0;
for (Block block : doku.getBlocks()) {
colorPalette.put(block, colors.get(index));
index++;
}
return colorPalette;
}
private void renderPopup() {
if (ImGui.beginPopup("editPopup")) {
Block block = currentCell.getBlock();
int symbolCount = block.getCells().size();
for (int i = 0; i < symbolCount; i++) {
if ((i + 1) % (int) (Math.sqrt(symbolCount)) != 1)
ImGui.sameLine();
if (currentCell.getSymbolIndex() == i) {
if (ImGui.button("X", cellSize)) {
currentCell.setSymbolIndex(Cell.NOSYMBOL);
this.onCellChange.emit(currentCell);
ImGui.closeCurrentPopup();
}
} else {
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();
}
}
}
ImGui.endPopup();
}
}
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;
// if the grid is too big, don't offset it
if (offsetX > 0) {
ImGui.setCursorPosX(offsetX);
}
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));
for (int y = 0; y < doku.getHeight(); y++) {
for (int x = 0; x < doku.getWidth(); x++) {
if (x > 0)
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);
ImGui.button("##" + index, cellSize);
} else {
if (diagonals.contains(cell)) {
ImGui.pushStyleColor(ImGuiCol.Border, WHITE);
} else {
ImGui.pushStyleColor(ImGuiCol.Border, BLACK);
}
int symbol = cell.getSymbolIndex();
Color blockColor = colorPalette.get(cell.getBlock());
if (!cell.isMutable()) {
blockColor = new Color(blockColor.r - 0.20f, blockColor.g - 0.20f, blockColor.b - 0.20f);
}
ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(blockColor.r, blockColor.g, blockColor.b, 1.0f));
String cellText = "";
if (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();
}
}
}

View File

@@ -0,0 +1,137 @@
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;
public SudokuSelector(boolean canGenEmptyGrid, String confirmMessage) {
this.canGenEmptyGrid = canGenEmptyGrid;
this.confirmMessage = confirmMessage;
initConstraints();
}
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 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(this.doku);
}
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", ".");
}
renderFileDialog();
}
}

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

View File

@@ -22,7 +22,7 @@ public class ConnexionThread extends Thread {
// System.out.println(objectInputStream.available()); // System.out.println(objectInputStream.available());
Object o = objectInputStream.readObject(); Object o = objectInputStream.readObject();
if (o instanceof Packet packet) { if (o instanceof Packet packet) {
connexion.visitPacket(packet); connexion.visit(packet);
} }
} catch (ClassNotFoundException | IOException e) { } catch (ClassNotFoundException | IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

@@ -4,10 +4,15 @@ import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Random; import java.util.Random;
import common.ConsumerSignal;
import common.Signal; import common.Signal;
import game.Game; import game.Game;
import game.Player; import game.Player;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.LoginPacket; import network.protocol.packets.LoginPacket;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class Client { public class Client {
private final ClientConnexion clientConnection; private final ClientConnexion clientConnection;
@@ -17,6 +22,9 @@ public class Client {
public final Signal onDisconnect = new Signal(); public final Signal onDisconnect = new Signal();
public final Signal onClosed = new Signal(); public final Signal onClosed = new Signal();
public final Signal onGameStarted = new Signal(); public final Signal onGameStarted = new Signal();
public final ConsumerSignal<Player> onGameEnd = new ConsumerSignal<>();
Player player;
String disconnectReason = null; String disconnectReason = null;
@@ -54,4 +62,20 @@ public class Client {
stop(); 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;
}
} }

View File

@@ -6,19 +6,21 @@ import java.net.UnknownHostException;
import game.Player; import game.Player;
import network.Connexion; import network.Connexion;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket; import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket; import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket; import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket; import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket; import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket; import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket; import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
import sudoku.io.SudokuSerializer; import sudoku.io.SudokuSerializer;
public class ClientConnexion extends Connexion { public class ClientConnexion extends Connexion {
private final Client client; private final Client client;
private Player player = null;
public ClientConnexion(String address, short port, Client client) throws UnknownHostException, IOException { public ClientConnexion(String address, short port, Client client) throws UnknownHostException, IOException {
super(new Socket(address, port)); super(new Socket(address, port));
@@ -35,7 +37,7 @@ public class ClientConnexion extends Connexion {
@Override @Override
public void visitPacket(ConnexionInfoPacket packet) { 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(); client.onConnect.emit();
} }
@@ -69,8 +71,28 @@ public class ClientConnexion extends Connexion {
@Override @Override
public void visitPacket(StartGamePacket packet) { 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(); 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'");
}
} }

View File

@@ -1,16 +1,19 @@
package network.protocol; package network.protocol;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket; import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket; import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket; import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket; import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket; import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket; import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket; import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
public interface PacketVisitor { public interface PacketVisitor {
default void visitPacket(Packet packet) { default void visit(Packet packet) {
packet.accept(this); packet.accept(this);
} }
@@ -21,5 +24,8 @@ public interface PacketVisitor {
void visitPacket(PlayerJoinPacket packet); void visitPacket(PlayerJoinPacket packet);
void visitPacket(PlayerLeavePacket packet); void visitPacket(PlayerLeavePacket packet);
void visitPacket(StartGamePacket packet); void visitPacket(StartGamePacket packet);
void visitPacket(EndGamePacket packet);
void visitPacket(UpdatePlayerScorePacket packet);
void visitPacket(ChangeCellPacket packet);
} }

View File

@@ -2,6 +2,6 @@ package network.protocol;
public enum Packets { public enum Packets {
ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame, ChangeCell, EndGame, UpdatePlayerScore
} }

View File

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

View File

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

View File

@@ -1,5 +1,7 @@
package network.protocol.packets; package network.protocol.packets;
import java.time.Instant;
import network.protocol.Packet; import network.protocol.Packet;
import network.protocol.PacketVisitor; import network.protocol.PacketVisitor;
import network.protocol.Packets; import network.protocol.Packets;
@@ -9,15 +11,28 @@ public class StartGamePacket extends Packet {
static private final long serialVersionUID = Packets.StartGame.ordinal(); static private final long serialVersionUID = Packets.StartGame.ordinal();
private final String serializedSudoku; 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.serializedSudoku = serializedSudoku;
this.instant = instant;
this.gameDuration = gameDuration;
} }
public String getSerializedSudoku() { public String getSerializedSudoku() {
return serializedSudoku; return serializedSudoku;
} }
public Instant getInstant() {
return instant;
}
public long getGameDuration() {
return gameDuration;
}
@Override @Override
public void accept(PacketVisitor packetVisitor) { public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this); packetVisitor.visitPacket(this);

View File

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

View File

@@ -2,12 +2,15 @@ package network.server;
import java.io.IOException; import java.io.IOException;
import java.net.ServerSocket; import java.net.ServerSocket;
import java.time.Instant;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import game.Game; import game.Game;
import game.Player; import game.Player;
import game.Game.GameState;
import network.protocol.Packet; import network.protocol.Packet;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.StartGamePacket; import network.protocol.packets.StartGamePacket;
import sudoku.io.SudokuSerializer; import sudoku.io.SudokuSerializer;
import sudoku.structure.MultiDoku; 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();) { for (var it = connexions.iterator(); it.hasNext();) {
ServerConnexion connexion = it.next(); ServerConnexion connexion = it.next();
if (!connexion.update()) { if (!connexion.update()) {
@@ -48,6 +60,11 @@ public class Server {
} }
} }
public void update() {
checkTimer();
checkConnexions();
}
public void stop() { public void stop() {
this.acceptThread.cancel(); this.acceptThread.cancel();
this.logicThread.cancel(); this.logicThread.cancel();
@@ -68,9 +85,19 @@ public class Server {
return game; return game;
} }
public void startGame(MultiDoku doku) { public void startGame(MultiDoku doku, long gameDuration) {
this.game.startGame(doku); Instant now = Instant.now();
broadcastPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(doku).toString())); 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();
} }
} }

View File

@@ -3,17 +3,23 @@ package network.server;
import java.io.IOException; import java.io.IOException;
import java.net.Socket; import java.net.Socket;
import game.Game;
import game.Player; import game.Player;
import game.Game.GameState; import game.Game.GameState;
import network.Connexion; import network.Connexion;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket; import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket; import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket; import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket; import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket; import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket; import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket; import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
import sudoku.io.SudokuSerializer; import sudoku.io.SudokuSerializer;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class ServerConnexion extends Connexion { public class ServerConnexion extends Connexion {
@@ -21,6 +27,7 @@ public class ServerConnexion extends Connexion {
private final KeepAliveHandler keepAliveHandler; private final KeepAliveHandler keepAliveHandler;
private boolean shouldClose = false; private boolean shouldClose = false;
private Player player = null; private Player player = null;
private MultiDoku doku;
public ServerConnexion(Socket socket, Server server) throws IOException { public ServerConnexion(Socket socket, Server server) throws IOException {
super(socket); super(socket);
@@ -29,7 +36,7 @@ public class ServerConnexion extends Connexion {
} }
public boolean update() { public boolean update() {
if (shouldClose | isClosed()) if (shouldClose || isClosed())
return false; return false;
return this.keepAliveHandler.update(); return this.keepAliveHandler.update();
} }
@@ -44,7 +51,7 @@ public class ServerConnexion extends Connexion {
@Override @Override
public synchronized void close() { public synchronized void close() {
if(shouldClose) if (shouldClose)
return; return;
super.close(); super.close();
shouldClose = true; shouldClose = true;
@@ -54,13 +61,22 @@ public class ServerConnexion extends Connexion {
private void finishLogin() { private void finishLogin() {
// send players that have already joined (excluding this one) // send players that have already joined (excluding this one)
for (Player p : this.server.getGame().getPlayers().values()) { for (Player p : this.server.getGame().getPlayers().values()) {
if (p.getId() != player.getId()) if (p.getId() != player.getId()) {
sendPacket(new PlayerJoinPacket(p)); sendPacket(new PlayerJoinPacket(p));
sendPacket(new UpdatePlayerScorePacket(p.getId(), p.getRemainingCells()));
}
} }
this.server.broadcastPacket(new PlayerJoinPacket(player)); this.server.broadcastPacket(new PlayerJoinPacket(player));
sendPacket(new ConnexionInfoPacket(player.getId())); 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'"); 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()));
}
} }

View File

@@ -19,7 +19,7 @@ public class ServerLogicThread extends Thread {
try { try {
Thread.sleep(50); Thread.sleep(50);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// e.printStackTrace(); e.printStackTrace();
break; break;
} }
} }

View File

@@ -3,45 +3,48 @@
*/ */
package sudoku; package sudoku;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.io.ConsoleInterface;
import sudoku.io.SudokuPrinter; import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory; import sudoku.structure.SudokuFactory;
import java.util.Arrays;
public class Main { public class Main {
public String getGreeting() { public String getGreeting() {
return "Hello World!"; 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) { public static void main(String[] args) {
System.out.println(new Main().getGreeting()); ConsoleInterface console = new ConsoleInterface();
int blockWidth = 2;
int blockHeight = 2;
var multidoku = SudokuFactory.createBasicEmptyRectangleSudoku(blockWidth, blockHeight);
var sudoku = multidoku.getSubGrid(0);
if(!sudoku.setCellsSymbol(Arrays.asList(0,1,2,3, 2,3,1,1, 1,0,3,2, 3,2,1,1))){
System.out.println("At least one of those values does not respect the constraints.");
}
//sudoku.setCellSymbol(8,3,0);
SudokuPrinter.printRectangleSudoku(multidoku.getSubGrid(0), blockWidth , blockHeight);
/* /*
Solver solver = new Solver(); voidTest();
ArrayList<IConstraint> constraints = new ArrayList<>(); filledTest();
constraints.add(new LineConstraint()); overwriteTest(0);
constraints.add(new ColumnConstraint()); overwriteTest(17)
constraints.add(new BlockConstraint());
try {
solver.solve(multidoku, constraints);
} catch (Exception e) {
System.out.println(e);
}
*/ */
console.welcome();
} }
} }

View File

@@ -1,5 +1,6 @@
package sudoku.constraint; package sudoku.constraint;
import sudoku.structure.Cell;
import sudoku.structure.Sudoku; import sudoku.structure.Sudoku;
public class ColumnConstraint implements IConstraint { public class ColumnConstraint implements IConstraint {
@@ -7,10 +8,12 @@ public class ColumnConstraint implements IConstraint {
@Override @Override
public boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex) { public boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex) {
for (int i = 0; i < s.getSize(); i++) { for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(x, i).getSymbolIndex() == newSymbolIndex) Cell cell = s.getCell(x, i);
int symbol = cell.getSymbolIndex();
if (symbol == newSymbolIndex) {
return false; return false;
}
} }
return true; return true;
} }
} }

View File

@@ -0,0 +1,52 @@
package sudoku.constraint;
import java.util.List;
import sudoku.structure.Sudoku;
public enum Constraint {
Block("Bloc", new BlockConstraint()),
Column("Colonne", new ColumnConstraint()),
Line("Ligne", new LineConstraint()),
Diagonal("Diagonale", new DiagonalConstraint());
String displayName;
IConstraint constraint;
private Constraint(String displayName, IConstraint contraint) {
this.constraint = contraint;
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;
}
public IConstraint getConstraint() {
return constraint;
}
private static final String[] constraintNames;
static {
Constraint[] cons = Constraint.values();
constraintNames = new String[cons.length];
for (int i = 0; i < cons.length; i++) {
constraintNames[i] = cons[i].getDisplayName();
}
}
public static String[] getConstraintNames() {
return constraintNames;
}
}

View File

@@ -0,0 +1,24 @@
package sudoku.constraint;
import sudoku.structure.Sudoku;
public class DiagonalConstraint implements IConstraint {
@Override
public boolean canBePlaced(Sudoku s, int x, int y, int newSymbolIndex) {
if (x == y) {
for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(i, i).getSymbolIndex() == newSymbolIndex)
return false;
}
} else if (s.getSize() - x == y) {
for (int i = 0; i < s.getSize(); i++) {
if (s.getCell(s.getSize() - i - 1, i).getSymbolIndex() == newSymbolIndex)
return false;
}
}
// not in diagonal
return true;
}
}

View File

@@ -1,12 +1,12 @@
package sudoku.constraint; package sudoku.constraint;
import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import sudoku.structure.Sudoku; import sudoku.structure.Sudoku;
public interface IConstraint { public interface IConstraint extends Serializable {
boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex); boolean canBePlaced(final Sudoku s, int x, int y, int newSymbolIndex);
default List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) { default List<Integer> getPossibleSymbols(final Sudoku s, int x, int y) {

View File

@@ -0,0 +1,305 @@
package sudoku.io;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.constraint.*;
import sudoku.solver.*;
import sudoku.structure.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConsoleInterface {
public Scanner reader = new Scanner(System.in);
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;
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') ?");
MultiDoku doku;
if (reader.next().equalsIgnoreCase("multi")) {
doku = SudokuFactory.createBasicXShapedMultidoku(width, height, listConstraints);
} else {
doku = SudokuFactory.createBasicEmptyRectangleDoku(width, height, listConstraints);
}
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):");
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);
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();
}
}
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() {
System.out.println("Width of a block: ");
int widthBlock = reader.nextInt();
checkValidSize(widthBlock);
while (!checkValidSize(widthBlock)) {
System.out.println("That is not a valid width for a block. Try again:");
widthBlock = reader.nextInt();
}
System.out.println("You have chose a width of " + widthBlock + ".");
return widthBlock;
}
public int getBlockHeight() {
System.out.println("Height of a block: ");
int heightBlock = reader.nextInt();
checkValidSize(heightBlock);
while (!checkValidSize(heightBlock)) {
System.out.println("That is not a valid height for a block. Try again:");
heightBlock = reader.nextInt();
}
System.out.println("You have chose a height of " + heightBlock + ".");
return heightBlock;
}
private Boolean checkValidSize(int size) {
return (size > 0);
}
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);
}
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();
};
}
}
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;
}
try {
SudokuFactory.fillDoku(doku, difficulty);
} catch (Exception e) {
System.out.println("There seems to be a problem with those settings. Let's start again.");
}
}
private void generateFullDoku(MultiDoku doku) {
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);
break;
case "exit":
exit();
break;
default:
play(doku, listSymbols, width, height);
break;
}
}
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;
}
}
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);
}
}

View File

@@ -1,17 +1,39 @@
package sudoku.io; package sudoku.io;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku; import sudoku.structure.Sudoku;
public class SudokuPrinter { import java.util.List;
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight) { 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, 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++) { for (int y = 0; y < s.getSize(); y++) {
if (y % blockHeight == 0 && y > 0) { if (y % blockHeight == 0 && y > 0) {
System.out.println(); System.out.println();
} }
StringBuilder line = new StringBuilder("[ "); StringBuilder line = new StringBuilder("[ ");
for (int x = 0; x < s.getSize(); x++) { 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) { if (x % blockWidth == blockWidth - 1 && x != blockWidth * blockHeight - 1) {
line.append("| "); line.append("| ");
} }
@@ -21,7 +43,118 @@ 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 void printMultiDoku(final RenderableMultidoku rm, Symbols symbols, int blockWidth, int blockHeight) {
printMultiDoku(rm, symbols.getSymbols(), blockWidth, blockHeight);
}
public static void 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);
}
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(); StringBuilder result = new StringBuilder();
for (int y = 0; y < s.getSize(); y++) { for (int y = 0; y < s.getSize(); y++) {
// Ajouter une ligne vide entre les blocs horizontaux // Ajouter une ligne vide entre les blocs horizontaux
@@ -31,7 +164,12 @@ public class SudokuPrinter {
StringBuilder line = new StringBuilder("[ "); StringBuilder line = new StringBuilder("[ ");
for (int x = 0; x < s.getSize(); x++) { for (int x = 0; x < s.getSize(); x++) {
// Ajouter la valeur de la cellule // 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 // Ajouter un séparateur vertical entre les blocs
if (x % blockWidth == blockWidth - 1 && x != s.getSize() - 1) { if (x % blockWidth == blockWidth - 1 && x != s.getSize() - 1) {
@@ -43,4 +181,22 @@ public class SudokuPrinter {
} }
return result.toString(); return result.toString();
} }
public static void printMultiDoku(final MultiDoku doku, int blockWidth, int blockHeight, Symbols symbols) {
if (doku.getNbSubGrids() == 1) {
printRectangleSudoku(doku.getSubGrid(0), blockWidth, blockHeight, symbols);
} else {
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);
}
}
} }

View File

@@ -1,26 +1,31 @@
package sudoku.io; package sudoku.io;
import java.io.*; 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; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.structure.Block; import sudoku.structure.Block;
import sudoku.structure.Cell; import sudoku.structure.Cell;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku; import sudoku.structure.Sudoku;
import sudoku.structure.SudokuFactory;
public class SudokuSerializer { public class SudokuSerializer {
public static JSONObject serializeSudoku(final MultiDoku multidoku) { public static JSONObject serializeSudoku(final MultiDoku multidoku) {
List<Cell> cellIds = new ArrayList<>(); List<Cell> cellIds = new ArrayList<>();
List<Block> blockIds = new ArrayList<>(); List<Block> blockIds = new ArrayList<>();
JSONObject jsonRoot = new JSONObject(); JSONObject jsonRoot = new JSONObject();
JSONArray jsonCells = new JSONArray(); JSONArray jsonCells = new JSONArray();
JSONArray jsonBlocks = new JSONArray(); JSONArray jsonBlocks = new JSONArray();
JSONArray jsonSudokus = new JSONArray(multidoku.getNbSubGrids()); JSONArray jsonSudokus = new JSONArray(multidoku.getNbSubGrids());
@@ -29,10 +34,10 @@ public class SudokuSerializer {
// init cells // init cells
for (Cell cell : sudoku.getCells()) { for (Cell cell : sudoku.getCells()) {
if (!cellIds.contains(cell)) { if (cellIds.contains(cell))
cellIds.add(cell); continue;
} cellIds.add(cell);
Block block = cell.getBlock(); Block block = cell.getBlock();
if (!blockIds.contains(block)) { if (!blockIds.contains(block)) {
@@ -40,6 +45,7 @@ public class SudokuSerializer {
} }
int blockID = blockIds.indexOf(block); int blockID = blockIds.indexOf(block);
assert (blockID >= 0);
int symbolIndex = cell.getSymbolIndex(); int symbolIndex = cell.getSymbolIndex();
JSONObject cellJsonObject = new JSONObject(); JSONObject cellJsonObject = new JSONObject();
@@ -55,22 +61,24 @@ public class SudokuSerializer {
// init blocks // init blocks
for (Block blockId : blockIds) { for (Block blockId : blockIds) {
JSONObject blockJsonObject = new JSONObject(); JSONObject blockJsonObject = new JSONObject();
JSONArray cellsJsonArray = new JSONArray(); JSONArray cellsJsonArray = new JSONArray();
for (Cell cell : blockId.getCells()) { for (Cell cell : blockId.getCells()) {
int cellID = cellIds.indexOf(cell); int cellID = cellIds.indexOf(cell);
cellsJsonArray.put(cellID); assert (cellID >= 0);
} cellsJsonArray.put(cellID);
blockJsonObject.put("cellIDs", cellsJsonArray); }
jsonBlocks.put(blockJsonObject); blockJsonObject.put("cellIDs", cellsJsonArray);
} jsonBlocks.put(blockJsonObject);
}
for (int i = 0; i < multidoku.getNbSubGrids(); i++) { for (int i = 0; i < multidoku.getNbSubGrids(); i++) {
// serialise sub grid // serialise sub grid
JSONObject jsonSudoku = new JSONObject(); JSONObject jsonSudoku = new JSONObject();
JSONArray cellsJsonArray = new JSONArray(); JSONArray cellsJsonArray = new JSONArray();
JSONArray blocksJsonArray = new JSONArray(); JSONArray blocksJsonArray = new JSONArray();
JSONArray constraintsJsonArray = new JSONArray();
Sudoku sudoku = multidoku.getSubGrid(i); Sudoku sudoku = multidoku.getSubGrid(i);
@@ -78,6 +86,7 @@ public class SudokuSerializer {
for (Cell cell : sudoku.getCells()) { for (Cell cell : sudoku.getCells()) {
int cellID = cellIds.indexOf(cell); int cellID = cellIds.indexOf(cell);
assert (cellID >= 0);
cellsJsonArray.put(cellID); cellsJsonArray.put(cellID);
} }
@@ -85,9 +94,26 @@ public class SudokuSerializer {
for (Block block : sudoku.getBlocks()) { for (Block block : sudoku.getBlocks()) {
int blockID = blockIds.indexOf(block); int blockID = blockIds.indexOf(block);
assert (blockID >= 0);
blocksJsonArray.put(blockID); blocksJsonArray.put(blockID);
} }
// serialize constraints
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);
jsonSudoku.put("cells", cellsJsonArray); jsonSudoku.put("cells", cellsJsonArray);
jsonSudoku.put("blocks", blocksJsonArray); jsonSudoku.put("blocks", blocksJsonArray);
jsonSudoku.put("blockWidth", sudoku.getBlockWidth()); jsonSudoku.put("blockWidth", sudoku.getBlockWidth());
@@ -101,25 +127,71 @@ public class SudokuSerializer {
return jsonRoot; return jsonRoot;
} }
public static void saveMultiDoku(final MultiDoku doku) { /**
* 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); JSONObject jsonRoot = serializeSudoku(doku);
File f = new File("save", "save.json"); File f = new File("save", "save.json");
InputStream is = null; int i = 0;
int i = 1;
while (f.exists()) { while (f.exists()) {
String newName = "save-" + i + ".json"; String newName = "save-" + ++i + ".json";
f = new File("save", newName); f = new File("save", newName);
i++;
} }
try (FileWriter file = new FileWriter(f)) { try (FileWriter file = new FileWriter(f)) {
file.write(jsonRoot.toString(3)); file.write(jsonRoot.toString(3));
//file.flush();
} catch (IOException e) { } catch (IOException e) {
e.fillInStackTrace(); e.printStackTrace();
}
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.
*/
public static MultiDoku getSavedMultiDoku(int numberSave) throws Exception {
String fileName;
if (numberSave < 1) {
fileName = "save.json";
} else {
fileName = "save-" + numberSave + ".json";
}
File f = new File("save", fileName);
String fileContent;
if (!f.exists()) {
throw new Exception("This save does not exist.");
} else {
fileContent = new String(Files.readAllBytes(Paths.get("save/" + fileName)));
return deserializeSudoku(fileContent);
} }
} }
@@ -167,9 +239,11 @@ public class SudokuSerializer {
JSONObject sudokuJsonObject = multidokuJsonObject.getJSONObject(i); JSONObject sudokuJsonObject = multidokuJsonObject.getJSONObject(i);
JSONArray sudokuCellsJsonArray = sudokuJsonObject.getJSONArray("cells"); JSONArray sudokuCellsJsonArray = sudokuJsonObject.getJSONArray("cells");
JSONArray sudokuBlocksJsonArray = sudokuJsonObject.getJSONArray("blocks"); JSONArray sudokuBlocksJsonArray = sudokuJsonObject.getJSONArray("blocks");
JSONArray sudokuConstraintsJsonArray = sudokuJsonObject.getJSONArray("constraints");
List<Cell> sudokuCells = new ArrayList<>(); List<Cell> sudokuCells = new ArrayList<>();
List<Block> sudokuBlocks = new ArrayList<>(); List<Block> sudokuBlocks = new ArrayList<>();
List<IConstraint> sudokuConstraints = new ArrayList<>();
for (int j = 0; j < sudokuCellsJsonArray.length(); j++) { for (int j = 0; j < sudokuCellsJsonArray.length(); j++) {
int cellID = sudokuCellsJsonArray.getInt(j); int cellID = sudokuCellsJsonArray.getInt(j);
@@ -181,8 +255,16 @@ public class SudokuSerializer {
sudokuBlocks.add(blocks.get(blockID)); sudokuBlocks.add(blocks.get(blockID));
} }
Sudoku s = new Sudoku(sudokuCells, sudokuBlocks, SudokuFactory.DEFAULT_CONSTRAINTS); for (int j = 0; j < sudokuConstraintsJsonArray.length(); j++) {
int constraintID = sudokuConstraintsJsonArray.getInt(j);
sudokuConstraints.add(Constraint.values()[constraintID].getConstraint());
}
Sudoku s = new Sudoku(sudokuCells, sudokuBlocks, sudokuConstraints);
s.setBlockWidth(sudokuJsonObject.getInt("blockWidth")); s.setBlockWidth(sudokuJsonObject.getInt("blockWidth"));
for (Block block : s.getBlocks()) {
block.getSudokus().add(s);
}
sudokus.add(s); sudokus.add(s);
} }

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

View File

@@ -0,0 +1,54 @@
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;
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 && newValue != oldValue)
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);
}
}

View File

@@ -0,0 +1,58 @@
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 {
/**
* 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) {
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;
}
List<Cell> cellsToFill = doku.getEmptyCells();
if (cellsToFill.isEmpty()) {
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();
}
}

View File

@@ -0,0 +1,76 @@
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 MixedSolver implements Solver {
/**
* 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) {
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()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
addStep(cellToFill, steps);
if (this.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);
}
return false;
}
}

View File

@@ -0,0 +1,66 @@
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 {
/**
* 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");
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;
}
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;
}
}

View File

@@ -1,118 +1,61 @@
package sudoku.solver; 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.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
public class Solver { import sudoku.structure.Cell;
private static final Logger logger = Logger.getLogger("SolverLogger"); import sudoku.structure.MultiDoku;
public interface Solver {
/** /**
* Résout le multidoku passé en paramètre si c'est possible. * Log du Solver, qui garde trace des actions réalisées.
* 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) { public static final Logger logger = Logger.getLogger("SolverLogger");
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0); boolean solve(MultiDoku doku, List<SolverStep> solverSteps);
logger.log(Level.INFO,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isValid()) { default boolean solve(MultiDoku doku) {
return true; return solve(doku, null);
}
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;
} }
public static int countSolution(MultiDoku doku) { /**
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
*
* @param doku MultiDoku, MultiDoku dont on veut le nombre de solutions.
* @return int, nombre de solutions possibles.
*/
default int countSolution(MultiDoku doku) {
int result = 0; int result = 0;
if (doku.isValid()) { if (doku.isSolved()) {
return 1; return 1;
} }
Cell cellToFill = doku.getFirstEmptyCell(); Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) { assert (cellToFill != null);
return 0;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill); List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
for (int symbol : possibleSymbols) { for (int symbol : possibleSymbols) {
doku.getStateManager().pushState();
cellToFill.setSymbolIndex(symbol); cellToFill.setSymbolIndex(symbol);
if (Solver.solve(doku)) { if (solve(doku)) {
result++; result++;
if (result > 1) {
doku.getStateManager().popState();
return result;
}
} }
cellToFill.setSymbolIndex(Cell.NOSYMBOL); doku.getStateManager().popState();
} }
return result; return result;
} }
public static boolean solve(MultiDoku doku) { default void addStep(Cell cell, List<SolverStep> steps) {
if (Thread.interrupted()) if (steps == null)
throw new CancellationException("User wants to stop the solver"); return;
steps.add(new SolverStep(cell));
if (doku.isValid()) {
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;
} }
} }

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

View File

@@ -2,7 +2,6 @@ package sudoku.solver;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import sudoku.structure.Coordinate;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku; import sudoku.structure.Sudoku;
@@ -24,9 +23,8 @@ public class StupidSolver {
if (!sudoku.getCell(index).isMutable()) if (!sudoku.getCell(index).isMutable())
return solve(sudoku, index + 1); return solve(sudoku, index + 1);
Coordinate coords = sudoku.toCoords(index);
for (int symbol = 0; symbol < sudoku.getSize(); symbol++) { for (int symbol = 0; symbol < sudoku.getSize(); symbol++) {
if (sudoku.tryPlaceCellSymbol(coords.getX(), coords.getY(), symbol)) { if (sudoku.getCell(index).trySetValue(symbol)) {
// on tente de placer sur la case suivante // on tente de placer sur la case suivante
if (solve(sudoku, index + 1)) { if (solve(sudoku, index + 1)) {
return true; return true;
@@ -34,12 +32,12 @@ public class StupidSolver {
} }
} }
// on a tout essayé et rien n'a fonctionné // on a tout essayé et rien n'a fonctionné
sudoku.clearCell(coords.getX(), coords.getY()); sudoku.getCell(index).empty();
return false; return false;
} }
public static boolean solve(MultiDoku doku) { public static boolean solve(MultiDoku doku) {
if (doku.isValid()) if (doku.isSolved())
return true; return true;
for (Sudoku sudoku : doku.getSubGrids()) { for (Sudoku sudoku : doku.getSubGrids()) {

View File

@@ -5,7 +5,8 @@ import java.util.List;
/** /**
* Class qui représente les block de chaque sudoku, * 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é * Un block étant un ensemble de cellule avec une contrainte de block qui lui
* ait associé
*/ */
public class Block { public class Block {
@@ -18,14 +19,15 @@ public class Block {
* List de sudoku qui contiennent le block * List de sudoku qui contiennent le block
* Pour un acces plus rapide aux sudokus * Pour un acces plus rapide aux sudokus
*/ */
private List<Sudoku> sudokus; private final List<Sudoku> sudokus;
public Block(List<Cell> cells) { public Block(List<Cell> cells) {
this.cells = cells; this.cells = cells;
this.sudokus = new ArrayList<>();
} }
public Block() { public Block() {
this.cells = new ArrayList<>(); this(new ArrayList<>());
} }
public List<Cell> getCells() { public List<Cell> getCells() {
@@ -34,6 +36,7 @@ public class Block {
/** /**
* Ajoute une Cell au Block * Ajoute une Cell au Block
*
* @param newCell Cell, à ajouter * @param newCell Cell, à ajouter
*/ */
void addCell(Cell newCell) { void addCell(Cell newCell) {
@@ -42,6 +45,7 @@ public class Block {
/** /**
* Cherche si le Block contient déjà un symbole donné. * Cherche si le Block contient déjà un symbole donné.
*
* @param symbolIndex int, un index de symbole * @param symbolIndex int, un index de symbole
* @return boolean, true s'il contient le symbole et false sinon * @return boolean, true s'il contient le symbole et false sinon
*/ */
@@ -65,8 +69,4 @@ public class Block {
public List<Sudoku> getSudokus() { public List<Sudoku> getSudokus() {
return sudokus; return sudokus;
} }
void setSudokus(List<Sudoku> sudokus) {
this.sudokus = sudokus;
}
} }

View File

@@ -24,28 +24,21 @@ public class Cell {
* Il est initialisé à Cell.NOSYMBOL. * Il est initialisé à Cell.NOSYMBOL.
*/ */
private int symbolIndex = 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. * Si cette Cell peut être modififié ou non.
*/ */
private boolean isMutable = true; private boolean isMutable = true;
public Cell() { public Cell() {
this.possibleSymbols = new ArrayList<>(); this(Cell.NOSYMBOL);
} }
public Cell(int symbolIndex) { public Cell(int symbolIndex) {
this.symbolIndex = symbolIndex; this.symbolIndex = symbolIndex;
this.possibleSymbols = new ArrayList<>();
} }
public Cell(int symbolIndex, boolean isMutable) { public Cell(int symbolIndex, boolean isMutable) {
this.symbolIndex = symbolIndex; this.symbolIndex = symbolIndex;
this.possibleSymbols = new ArrayList<>();
this.isMutable = isMutable; this.isMutable = isMutable;
} }
@@ -57,11 +50,6 @@ public class Cell {
this.symbolIndex = symbolIndex; this.symbolIndex = symbolIndex;
} }
public void setPossibleSymbols(List<Integer> possibleSymbols) {
this.possibleSymbols.clear();
this.possibleSymbols.addAll(possibleSymbols);
}
/** /**
* Rend la Cell immuable. * Rend la Cell immuable.
*/ */
@@ -95,14 +83,6 @@ public class Cell {
return this.symbolIndex == Cell.NOSYMBOL; 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 * Renvoie si la Cell est modifiable
* @return boolean, true si elle est modifiable ou false sinon. * @return boolean, true si elle est modifiable ou false sinon.
@@ -120,4 +100,37 @@ public class Cell {
this.symbolIndex = Cell.NOSYMBOL; this.symbolIndex = Cell.NOSYMBOL;
return oldSymbol; return oldSymbol;
} }
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;
}
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;
}
public boolean trySetValue(int newValue) {
if (!isMutable())
return false;
if (!canHaveValue(newValue))
return false;
setSymbolIndex(newValue);
return true;
}
} }

View File

@@ -0,0 +1,38 @@
package sudoku.structure;
//TODO: melvyn va passer par là
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);
final double factor;
final String displayName;
private 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 {
Difficulty[] diffs = Difficulty.values();
difficultyNames = new String[diffs.length];
for (int i = 0; i < diffs.length; i++) {
difficultyNames[i] = diffs[i].getDisplayName();
}
}
public static String[] getDifficultyNames() {
return difficultyNames;
}
}

View File

@@ -1,7 +1,10 @@
package sudoku.structure; package sudoku.structure;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Random;
import java.util.Set;
import sudoku.io.SudokuSerializer; import sudoku.io.SudokuSerializer;
@@ -17,90 +20,60 @@ public class MultiDoku {
*/ */
private final List<Sudoku> subGrids; private final List<Sudoku> subGrids;
private final StateManager stateManager;
public MultiDoku(List<Sudoku> subGrids) { public MultiDoku(List<Sudoku> subGrids) {
this.subGrids = subGrids; this.subGrids = subGrids;
} this.stateManager = new StateManager(this);
public MultiDoku clone() {
//TODO: ahhhhhhhhhhhhhhhhhhhhhhh
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
} }
/** /**
* Renvoie le nombre de sudoku contenu dans ce MultiDoku. * Renvoie le nombre de sudoku contenu dans ce MultiDoku.
*
* @return int * @return int
*/ */
public int getNbSubGrids(){ public int getNbSubGrids() {
return subGrids.size(); return subGrids.size();
} }
/** /**
* Renvoie la ie sudoku contenue dans ce MultiDoku. * Renvoie la ie sudoku contenue dans ce MultiDoku.
*
* @param i int, indice du sudoku à renvoyer. * @param i int, indice du sudoku à renvoyer.
* @return Sudoku, ie Sudoku * @return Sudoku, ie Sudoku
*/ */
public Sudoku getSubGrid(int i){ public Sudoku getSubGrid(int i) {
return subGrids.get(i); return subGrids.get(i);
} }
/** /**
* Renvoie la liste des Cells contenue dans ce MultiDoku, * Renvoie la liste des Cells contenue dans ce MultiDoku,
* soit les Cells contenues de chaques sous-Sudoku. * soit les Cells contenues de chaques sous-Sudoku.
*
* @return List<Cell> * @return List<Cell>
*/ */
public List<Cell> getCells(){ public List<Cell> getCells() {
List<Cell> cells = new ArrayList<>(); Set<Cell> cellsSet = new HashSet<>();
for (Sudoku sudoku : subGrids){ for (Sudoku sudoku : subGrids) {
cells.addAll(sudoku.getCells()); cellsSet.addAll(sudoku.getCells());
}
return cells;
}
/**
* 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();
} }
return new ArrayList<>(cellsSet);
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Multidoku {"); sb.append("Multidoku {");
for (Sudoku sudoku : subGrids){ for (Sudoku sudoku : subGrids) {
sb.append("\n\t").append(sudoku.toString()); sb.append("\n\t").append(sudoku.toString());
} }
sb.append("\n}"); sb.append("\n}");
return sb.toString(); 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 * Renvoie les sous-Sudoku
*
* @return List<Sudoku> * @return List<Sudoku>
*/ */
public List<Sudoku> getSubGrids() { public List<Sudoku> getSubGrids() {
@@ -108,44 +81,27 @@ public class MultiDoku {
} }
/** /**
* Check si le MultiDoku est valide, en fonction de ses sous-Sudokus. * Check si le MultiDoku est résolu, c'est à dire complet et cohérent avec ses contraintes.
* @return boolean, true s'il est valide et false sinon. *
* @return boolean, true s'il est résolu et false sinon.
*/ */
public boolean isValid() { public boolean isSolved() {
boolean result = true;
for (Sudoku sudoku : this.subGrids) { for (Sudoku sudoku : this.subGrids) {
result = sudoku.isValid() && result; if (!sudoku.isSolved())
}
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))) {
return false; return false;
}
} }
return true; return true;
} }
/** /**
* Renvoie la 1re Cell vide des sous-Sudoku. * Renvoie la 1re Cell vide des sous-Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas. * @return Cell, une Cell vide, ou null s'il n'y en a pas.
*/ */
public Cell getFirstEmptyCell() { public Cell getFirstEmptyCell() {
for (Sudoku sudoku : this.subGrids) { for (Sudoku sudoku : this.subGrids) {
Cell cellTmp = sudoku.getFirstEmptyCell(); Cell cellTmp = sudoku.getFirstEmptyCell();
if (cellTmp != null && cellTmp.isEmpty()) { if (cellTmp != null) {
return cellTmp; return cellTmp;
} }
} }
@@ -154,11 +110,12 @@ public class MultiDoku {
/** /**
* Renvoie la liste des Cells préalablement remplies du MultiDoku. * Renvoie la liste des Cells préalablement remplies du MultiDoku.
*
* @return List<Cell>, vide si aucune Cell n'est remplie. * @return List<Cell>, vide si aucune Cell n'est remplie.
*/ */
public List<Cell> getFilledCells() { public List<Cell> getFilledCells() {
List<Cell> result = new ArrayList<>(); List<Cell> result = new ArrayList<>();
for (Cell cell : this.getCells()){ for (Cell cell : this.getCells()) {
if (!cell.isEmpty()) { if (!cell.isEmpty()) {
result.add(cell); result.add(cell);
} }
@@ -166,8 +123,24 @@ public class MultiDoku {
return result; 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. * Vide une Cell donnée.
*
* @param cell Cell, à vider. * @param cell Cell, à vider.
*/ */
public void empty(Cell cell) { public void empty(Cell cell) {
@@ -175,5 +148,52 @@ public class MultiDoku {
Cell cellToEmpty = cells.get(cells.indexOf(cell)); Cell cellToEmpty = cells.get(cells.indexOf(cell));
cellToEmpty.setSymbolIndex(Cell.NOSYMBOL); cellToEmpty.setSymbolIndex(Cell.NOSYMBOL);
} }
}
/**
* Renvoie le nombre de Cell contenue dans le MultiDoku.
*
* @return int, nombre de Cell dans le MultiDoku.
*/
public int getNbCells() {
return getCells().size();
}
/**
* Change les Cells de ce MultiDoku avec des symboles, en Cells immuables.
*/
public void setFilledCellsImmutable() {
for (Cell filledCell : getFilledCells()) {
filledCell.setImmutable();
}
}
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.
*/
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()) {
if (cell.isMutable())
cell.clearCurrentSymbol();
}
}
}
public MultiDoku clone() {
// TODO: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
}
}

View File

@@ -0,0 +1,49 @@
package sudoku.structure;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
//TODO: doc
public class StateManager {
private final Stack<Map<Cell, Integer>> states;
private final MultiDoku doku;
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.size() > 0);
restoreState(states.pop());
}
public Map<Cell, Integer> popAndGetState() {
assert (states.size() > 0);
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;
}
}

View File

@@ -1,10 +1,11 @@
package sudoku.structure; package sudoku.structure;
import sudoku.constraint.IConstraint;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
/** /**
* @class Sudoku * @class Sudoku
* @brief Représent un Sudoku * @brief Représent un Sudoku
@@ -18,13 +19,14 @@ public class Sudoku {
/** /**
* Liste des Cells contenus dans le Sudoku. * Liste des Cells contenus dans le Sudoku.
*/ */
private final List<Cell> cells; private List<Cell> cells = new ArrayList<>();
/** /**
* Liste des contraintes (TODO) du Sudoku. * Liste des contraintes (TODO) du Sudoku.
*/ */
private final List<IConstraint> constraints; private final List<IConstraint> constraints;
/** /**
* Largeur des Blocks s'ils sont rectangulaires, sinon ça vaut 0. * Largeur des Blocks s'ils sont rectangulaires, valant 0 si ce n'est pas le
* cas.
*/ */
private int blockWidth; private int blockWidth;
@@ -35,17 +37,18 @@ public class Sudoku {
} }
/** /**
* Transforme un index de Cell en Coordiante. * Transforme un index de Cell en Coordinate.
* *
* @param index int, index d'une Cell. * @param index int, index d'une Cell.
* @return Coordinate, correspondante à l'index donné. * @return Coordinate, correspondante à l'index donné.
*/ */
public Coordinate toCoords(int index) { public Coordinate toCoords(int index) {
return new Coordinate( index % getSize(), index / getSize() ); return new Coordinate(index % getSize(), index / getSize());
} }
/** /**
* Transforme des coordonées d'une Cell en index. * Transforme des coordonées d'une Cell en index.
*
* @param x int, abscisse. * @param x int, abscisse.
* @param y int, ordonnée. * @param y int, ordonnée.
* @return int, index correspondant. * @return int, index correspondant.
@@ -56,7 +59,9 @@ public class Sudoku {
/** /**
* Vérifie que des coordonnées correspondent bien à une Cell dans le Sudoku. * Vérifie que des coordonnées correspondent bien à une Cell dans le Sudoku.
* @return boolean, wether the coords are in the sudoku *
* @return boolean, valant true si les coordonnées sont dans les bornes du
* Sudoku, false sinon.
*/ */
public boolean isValidCoords(int x, int y) { public boolean isValidCoords(int x, int y) {
int index = toIndex(x, y); int index = toIndex(x, y);
@@ -64,12 +69,24 @@ public class Sudoku {
} }
/** /**
* @return wether the coords are in the 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.
*/ */
public boolean isValidCoords(int index) { public boolean isValidCoords(int index) {
return index < getSize() * getSize(); 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.
*
* @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) { public boolean canBePlaced(int x, int y, int value) {
for (IConstraint constraint : this.constraints) { for (IConstraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) { if (!constraint.canBePlaced(this, x, y, value)) {
@@ -79,14 +96,12 @@ public class Sudoku {
return true; return true;
} }
public boolean tryPlaceCellSymbol(int x, int y, int value) { /**
assert (isValidCoords(x, y)); * Vide la Cell dotn les coordonnées sont renseignées de son symbole.
if (!canBePlaced(x, y, value)) *
return false; * @param x int, abscisse de la Cell voulue.
Cell cell = getCell(x, y); * @param y int, coordonnée de la Cell voulue.
cell.setSymbolIndex(value); */
return true;
}
public void clearCell(int x, int y) { public void clearCell(int x, int y) {
assert (isValidCoords(x, y)); assert (isValidCoords(x, y));
@@ -94,6 +109,9 @@ public class Sudoku {
cell.setSymbolIndex(Cell.NOSYMBOL); cell.setSymbolIndex(Cell.NOSYMBOL);
} }
/**
* Vide toutes les Cell du Sudoku.
*/
public void clear() { public void clear() {
for (int i = 0; i < getSize() * getSize(); i++) { for (int i = 0; i < getSize() * getSize(); i++) {
Cell cell = getCell(i); Cell cell = getCell(i);
@@ -107,9 +125,12 @@ public class Sudoku {
} }
/** /**
* Try to place a cell at the given coordinate * Place le symbole d'index value dans la Cell de coordonnées précisées.
* *
* @return Cell created or null if it can't be done * @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue.
* @param value int, index du symbole à placer.
* @return Cell, la Cell qui a été modifiée.
*/ */
public Cell setCellSymbol(int x, int y, int value) { public Cell setCellSymbol(int x, int y, int value) {
assert (isValidCoords(x, y)); assert (isValidCoords(x, y));
@@ -123,6 +144,12 @@ public class Sudoku {
return cell; return cell;
} }
/**
* 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.
*/
public boolean setCellsSymbol(List<Integer> values) { public boolean setCellsSymbol(List<Integer> values) {
if (values.size() > this.cells.size()) { if (values.size() > this.cells.size()) {
return false; return false;
@@ -136,6 +163,13 @@ public class Sudoku {
return true; return true;
} }
/**
* 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.
*/
public boolean setImmutableCellsSymbol(List<Integer> values) { public boolean setImmutableCellsSymbol(List<Integer> values) {
if (values.size() > this.cells.size()) { if (values.size() > this.cells.size()) {
return false; return false;
@@ -156,7 +190,7 @@ public class Sudoku {
} }
public Cell getCell(int x, int y) { public Cell getCell(int x, int y) {
int index = y * getSize() + x; int index = toIndex(x, y);
assert (isValidCoords(x, y)); assert (isValidCoords(x, y));
try { try {
return this.cells.get(index); return this.cells.get(index);
@@ -185,56 +219,16 @@ public class Sudoku {
return this.blocks; 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) { public boolean contains(Cell cell) {
return this.cells.contains(cell); return this.cells.contains(cell);
} }
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 void updateSymbolsPossibilities() throws Exception {
for (IConstraint constraint : constraints) {
List<Cell> cells = this.getCells();
for (Cell cell : cells) {
Coordinate coord = null;
try {
coord = this.getCoordinateCell(cell);
} catch (Exception e) {
throw new RuntimeException(e);
}
List<Integer> newPossibleSymbols = cell.getPossibleSymbols();
newPossibleSymbols.retainAll(constraint.getPossibleSymbols(this, coord.getX(), coord.getY()));
cell.setPossibleSymbols(newPossibleSymbols);
if (cell.getPossibleSymbols().isEmpty()) {
throw new Exception("Rollback bitch");
}
}
}
}
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Sudoku {"); sb.append("Sudoku {");
@@ -249,6 +243,11 @@ public class Sudoku {
return sb.toString(); 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() { public Cell getFirstEmptyCell() {
for (Cell cell : this.cells) { for (Cell cell : this.cells) {
if (cell.isEmpty()) { if (cell.isEmpty()) {
@@ -258,70 +257,48 @@ public class Sudoku {
return null; return null;
} }
public List<Integer> getPossibleSymbolsOfCell(Cell cellToFill) { /**
List<Integer> result = new ArrayList<>(); * Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses
Coordinate cellCoordinates; * contraintes.
try { *
cellCoordinates = this.getCoordinateCell(cellToFill); * @return boolean, valant true si le Sudoku est résolu, false sinon.
} catch (Exception e) { */
return result; public boolean isSolved() {
} boolean isComplete = isComplete();
for (int i = 0; i < this.constraints.size(); i++) { boolean isValid = isValid();
IConstraint constraint = this.constraints.get(i); return isComplete && isValid;
if (i == 0) {
result.addAll(constraint.getPossibleSymbols(this, cellCoordinates.getX(), cellCoordinates.getY()));
} else {
result.retainAll(constraint.getPossibleSymbols(this, cellCoordinates.getX(), cellCoordinates.getY()));
}
}
return result;
} }
public boolean isValid() { /**
for (Cell cell : this.cells) { * Vérifie que le Sudoku est complet, soit qu'il n'y ait aucune case vide.
if (cell.isMutable()) { *
if (cell.isEmpty()) { * @return boolean, true si le Sudoku est complet, false sinon.
return false; */
} private boolean isComplete() {
for (IConstraint constraint : this.constraints) { return getFirstEmptyCell() == null;
Coordinate coords;
try {
int symbolPlaced = cell.getSymbolIndex();
coords = this.getCoordinateCell(cell);
cell.setSymbolIndex(Cell.NOSYMBOL);
List<Integer> possibleSymbols = constraint.getPossibleSymbols(this, coords.getX(),
coords.getY());
cell.setSymbolIndex(symbolPlaced);
if (possibleSymbols.size() != 1 || possibleSymbols.get(0) != symbolPlaced) {
return false;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
return true;
} }
@Override /**
public boolean equals(Object object) { * Vérifie si le Sudoku est valide, soit qu'il est cohérent avec ses
if (!(object instanceof Sudoku)) { * contraintes.
return false; *
} * @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;
if (this.getSize() != ((Sudoku) object).getSize()) { Coordinate coordinate = toCoords(i);
return false;
}
for (int i = 0; i < this.getSize(); i++) { int symbolPlaced = cell.empty();
if (this.getCell(i).getSymbolIndex() != ((Sudoku) object).getCell(i).getSymbolIndex()) { if (!canBePlaced(coordinate.getX(), coordinate.getY(), symbolPlaced)) {
cell.setSymbolIndex(symbolPlaced);
return false; return false;
} }
cell.setSymbolIndex(symbolPlaced);
} }
return true; return true;
} }
@@ -329,4 +306,8 @@ public class Sudoku {
this.blockWidth = blockWidth; this.blockWidth = blockWidth;
} }
public boolean hasConstraint(Constraint constraint) {
return this.constraints.contains(constraint.getConstraint());
}
} }

View File

@@ -1,22 +1,41 @@
package sudoku.structure; package sudoku.structure;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import sudoku.constraint.BlockConstraint; import sudoku.constraint.Constraint;
import sudoku.constraint.ColumnConstraint;
import sudoku.constraint.IConstraint; import sudoku.constraint.IConstraint;
import sudoku.constraint.LineConstraint; import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver; import sudoku.solver.Solver;
public class SudokuFactory { public class SudokuFactory {
/**
* Générateur de nombre aléatoire.
*/
private static final Random random = new Random(); private static final Random random = new Random();
public static List<IConstraint> DEFAULT_CONSTRAINTS = Arrays.asList(new BlockConstraint(), new LineConstraint(), new ColumnConstraint());
/**
* Liste des contraintes par défaut d'un Multi- ou Sudoku.
* 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));
/**
* 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.
*/
private static List<Cell> initCells(int size) { private static List<Cell> initCells(int size) {
List<Cell> cells = new ArrayList<>(size * size); List<Cell> cells = new ArrayList<>(size * size);
for (int i = 0; i < size * size; i++) { for (int i = 0; i < size * size; i++) {
@@ -25,6 +44,15 @@ public class SudokuFactory {
return cells; return cells;
} }
/**
* 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.
*/
private static List<Block> initRectangleBlocs(List<Cell> cells, int width, int height) { private static List<Block> initRectangleBlocs(List<Cell> cells, int width, int height) {
List<Block> blocs = new ArrayList<>(); List<Block> blocs = new ArrayList<>();
int size = width * height; int size = width * height;
@@ -48,16 +76,39 @@ public class SudokuFactory {
return blocs; return blocs;
} }
public static MultiDoku createBasicEmptyRectangleSudoku(int widthBlock, int heightBlock) { /**
Sudoku s = createRectangleSudoku(widthBlock, heightBlock); * Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par
return new MultiDoku(Arrays.asList(s)); * 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<IConstraint> constraints) {
return new MultiDoku(Arrays.asList(createRectangleSudoku(widthBlock, heightBlock, constraints)));
} }
public static MultiDoku createBasicEmptySquareSudoku(int size) { /**
return createBasicEmptyRectangleSudoku(size, size); * 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<IConstraint> constraints) {
return new MultiDoku(Arrays.asList(createSquareSudoku(size, constraints)));
} }
public static void setIMMutableCells(MultiDoku doku, Map<Coordinate, Integer> immutableCells) { /**
* 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) -> { immutableCells.forEach((coordinate, symbol) -> {
for (Sudoku sudoku : doku.getSubGrids()) { for (Sudoku sudoku : doku.getSubGrids()) {
Cell cell = sudoku.getCell(coordinate.getX(), coordinate.getY()); Cell cell = sudoku.getCell(coordinate.getX(), coordinate.getY());
@@ -69,65 +120,95 @@ public class SudokuFactory {
}); });
} }
public static boolean newDokuFromFilledOne (MultiDoku doku, int difficulty) throws Exception { /**
* 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 (difficulty > doku.getCells().size()) { if (nbCellsToEmpty >= doku.getCells().size()) {
throw new Exception(); throw new Exception();
} }
if (difficulty == 0) { if (nbCellsToEmpty == 0) {
return true; return true;
} }
List<Cell> cellsThatCanBeEmptied = doku.getFilledCells(); List<Cell> cellsThatCanBeEmptied = doku.getFilledCells();
while (!cellsThatCanBeEmptied.isEmpty()) { int index = random.nextInt(cellsThatCanBeEmptied.size());
int index = random.nextInt(cellsThatCanBeEmptied.size()); Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
int oldSymbol = cellToEmpty.empty(); cellToEmpty.empty();
if (Solver.countSolution(doku) == 1) { int nbDokuSultions = solver.countSolution(doku);
if (newDokuFromFilledOne(doku, --difficulty)) { if (nbDokuSultions == 1) {
return true; return newDokuFromFilledOne(doku, --nbCellsToEmpty, solver);
}
}
cellToEmpty.setSymbolIndex(oldSymbol);
cellsThatCanBeEmptied.remove(cellToEmpty);
} }
return false; return false;
} }
private static Sudoku createRectangleSudoku(int width, int height) { /**
int symbolCount = width * height; * 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<IConstraint> constraints) {
int symbolCount = widthBlock * heightBlock;
List<Cell> cases = initCells(symbolCount); List<Cell> cases = initCells(symbolCount);
List<Block> blocs = initRectangleBlocs(cases, width, height); List<Block> blocs = initRectangleBlocs(cases, widthBlock, heightBlock);
Sudoku s = new Sudoku(cases, blocs, DEFAULT_CONSTRAINTS); Sudoku s = new Sudoku(cases, blocs, constraints);
s.setBlockWidth(width); for (Block block : s.getBlocks()) {
block.getSudokus().add(s);
}
s.setBlockWidth(widthBlock);
return s; return s;
} }
private static Sudoku createSquareSudoku(int size) { /**
return createRectangleSudoku(size, size); * 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<IConstraint> constraints) {
return createRectangleSudoku(size, size, constraints);
} }
private static void linkSquareSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) { /**
* 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 linkRectangleSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
int blockWidth = sudoku1.getBlockWidth(); 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++) { for (int dy = 0; dy < blockWidth; dy++) {
int block1X = dx + offset.getX(); int block1X = dx + offset.getX();
int block1Y = dy + offset.getY(); int block1Y = dy + offset.getY();
int block2X = dx; int block2X = dx;
int block2Y = dy; int block2Y = dy;
if ((block1X < blockWidth) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) { if ((block1X < blockHeight) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
Block block1 = sudoku1.getBlocks().get(block1Y * blockWidth + block1X); Block block1 = sudoku1.getBlocks().get(block1Y * blockHeight + block1X);
Block block2 = sudoku2.getBlocks().get(block2Y * blockWidth + block2X); Block block2 = sudoku2.getBlocks().get(block2Y * blockHeight + block2X);
// on remplace le bloc // 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 // on remplace les cellules
for (int i = 0; i < block1.getCells().size(); i++) { for (int i = 0; i < block1.getCells().size(); i++) {
@@ -142,26 +223,149 @@ public class SudokuFactory {
} }
} }
public static MultiDoku createBasicSquareMultidoku(int size) { /**
* 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.
*
* @param size int, largeur des Blocks unitraires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
*/
public static MultiDoku createBasicXShapedMultidoku(int size, List<IConstraint> constraints) {
assert (size > 1); assert (size > 1);
/** return createBasicXShapedMultidoku(size, size, constraints);
}
/**
* Créée un MultiDoku de Blocks rectangulaires de forme width par height composé
* de cinq Sudokus,
* dont un central qui partage chacun de ses Blocks d'angle avec un autre
* Sudoku.
*
* @param width int, largeur des Blocks unitraires des Sudokus à crééer.
* @param height int, hauteur des Blocks unitraires 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 * 2 3
* 1 * 1
* 4 5 * 4 5
*/ */
Sudoku sudoku1 = createSquareSudoku(size); Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku2 = createSquareSudoku(size); Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku3 = createSquareSudoku(size); Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku4 = createSquareSudoku(size); Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku5 = createSquareSudoku(size); Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size)); linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 1 - width));
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size)); linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(height - 1, 1 - width));
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1)); linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - height, width - 1));
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(size - 1, size - 1)); linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(height - 1, width - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5)); return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
} }
/**
* TODO
* 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.
*
* @param size int, largeur des Blocks unitraires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
*/
public static MultiDoku createBasicPlusShapedMultidoku(int size, List<IConstraint> constraints) {
assert (size > 1);
return createBasicPlusShapedMultidoku(size, size, constraints);
}
/**
* TODO
* Créée un MultiDoku de Blocks rectangulaires de forme width par height composé
* de cinq Sudokus,
* dont un central qui partage chacun de ses Blocks d'angle avec un autre
* Sudoku.
*
* @param width int, largeur des Blocks unitraires des Sudokus à crééer.
* @param height int, hauteur des Blocks unitraires des Sudokus à crééer.
* @return MultiDoku, MultiDoku de forme X.
*/
public static MultiDoku createBasicPlusShapedMultidoku(int width, int height, List<IConstraint> constraints) {
assert (width > 1 && height > 1);
/*
* 3
* 2 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);
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));
}
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();
}
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;
}
}
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(Arrays.asList(sudoku));
}
public static List<IConstraint> fromConstraints(List<Constraint> constraints) {
List<IConstraint> iconstraints = new ArrayList<>();
for (Constraint cons : constraints) {
iconstraints.add(cons.getConstraint());
}
return iconstraints;
}
} }

View File

@@ -3,34 +3,76 @@ package sudoku;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.util.Random;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer; import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory; import sudoku.structure.SudokuFactory;
import java.util.Random;
public class SudokuSerializerTest { public class SudokuSerializerTest {
void testSerializeWithSize(int blockWidth, int blockHeight) { void testSerializeWithSize(int blockWidth, int blockHeight) {
var sudoku = SudokuFactory.createBasicEmptyRectangleSudoku(blockWidth, blockHeight); var sudoku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
SudokuFactory.DEFAULT_CONSTRAINTS);
new RandomSolver().solve(sudoku);
JSONObject data = SudokuSerializer.serializeSudoku(sudoku); JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
SudokuSerializer.saveMultiDoku(sudoku); MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
//MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data); assertTrue(data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
//assertEquals(data, SudokuSerializer.serializeSudoku(multiDoku)); }
void testSaveWithSize(int blockWidth, int blockHeight) {
MultiDoku doku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
SudokuFactory.DEFAULT_CONSTRAINTS);
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();
assert false;
}
}
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);
assertTrue(data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
} }
@Test @Test
void testSerialize() { void testSerialize() {
int testCount = 5;
Random r = new Random(); Random r = new Random();
int testCount = 20;
for (int i = 0; i < testCount; i++) { for (int i = 0; i < testCount; i++) {
int blockWidth = r.nextInt(20) + 1; int blockWidth = r.nextInt(4) + 1;
int blockHeight = r.nextInt(20) + 1; int blockHeight = r.nextInt(4) + 1;
testSerializeWithSize(blockWidth, blockHeight); testSerializeWithSize(blockWidth, blockHeight);
} }
for (int i = 0; i < testCount; i++) {
int blockWidth = r.nextInt(4) + 1;
int blockHeight = r.nextInt(4) + 1;
testSaveWithSize(blockWidth, blockHeight);
}
for (int i = 0; i < testCount; i++) {
int size = r.nextInt(2) + 2;
testSerializeX(size);
}
} }
} }

View File

@@ -1,96 +1,104 @@
package sudoku.solver; package sudoku.solver;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import gui.constants.Symbols;
import sudoku.io.SudokuPrinter; import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer;
import sudoku.structure.Cell; import sudoku.structure.Cell;
import sudoku.structure.MultiDoku; import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku; import sudoku.structure.Sudoku;
import sudoku.structure.SudokuFactory; import sudoku.structure.SudokuFactory;
import java.util.List;
import java.util.Random;
class SolverTest { class SolverTest {
@Test @Test
void solveTest() { void solveTest() {
Random rand = new Random(); MultiDoku dokuToTest = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
MultiDoku dokuResult = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
MultiDoku dokuToTest = SudokuFactory.createBasicEmptySquareSudoku(3); Sudoku sudokuToTest = dokuToTest.getSubGrid(0);
MultiDoku dokuResult = SudokuFactory.createBasicEmptySquareSudoku(3); Sudoku sudokuResult = dokuResult.getSubGrid(0);
Sudoku sudokuToTest = dokuToTest.getSubGrid(0); int ns = Cell.NOSYMBOL;
Sudoku sudokuResult = dokuResult.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);
int ns = Cell.NOSYMBOL; assert (sudokuToTest.setImmutableCellsSymbol(immutableCells));
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(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,
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);
SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3); sudokuResult.setCellsSymbol(correctCells);
System.out.println("\n****************************Doku Control\n");
SudokuPrinter.printRectangleSudoku(sudokuResult, 3, 3, Symbols.Russian);
List<Integer> correctCells = List.of(7, 6, 0, 3, 4, 2, 8, 5, 1, assert (dokuResult.isSolved());
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);
sudokuResult.setCellsSymbol(correctCells); new RandomSolver().solve(dokuToTest);
System.out.println("\n****************************\nDoku solved");
//SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3);
SudokuPrinter.printMultiDoku(dokuToTest, 3, 3, Symbols.Emojis);
System.out.println("\n****************************Doku Control\n"); assert (dokuToTest.isSolved());
SudokuPrinter.printRectangleSudoku(sudokuResult, 3, 3);
for (Cell cell : sudokuToTest.getCells()) {
cell.setImmutable();
}
assert(dokuResult.isValid()); for (Cell cell : sudokuResult.getCells()) {
cell.setImmutable();
}
Solver.solveRandom(dokuToTest, rand); assertEquals(SudokuSerializer.serializeSudoku(dokuResult).toString(),
SudokuSerializer.serializeSudoku(dokuToTest).toString());
MultiDoku dokuToTest2 = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
Sudoku sudokuToTest2 = dokuToTest2.getSubGrid(0);
System.out.println("\n****************************\nDoku solved"); List<Integer> immutableCells2 = List.of(ns, ns, 0, ns, ns, 2, 8, ns, 1,
SudokuPrinter.printRectangleSudoku(dokuToTest.getSubGrid(0), 3, 3); 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(dokuToTest.isValid()); assert (!isSolved);
assert(dokuToTest.equals(dokuResult)); MultiDoku dokuToTest3 = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
MultiDoku dokuToTest2 = SudokuFactory.createBasicEmptySquareSudoku(3); new RandomSolver().solve(dokuToTest3);
Sudoku sudokuToTest2 = dokuToTest2.getSubGrid(0);
List<Integer> immutableCells2 = List.of(ns, ns, 0, ns, ns, 2, 8, ns, 1, //SudokuPrinter.printRectangleSudoku(dokuToTest3.getSubGrid(0), 3, 3);
1, 3, ns, ns, 5, 6, 7, ns, ns, SudokuPrinter.printMultiDoku(dokuToTest3, 3, 3, Symbols.Letters);
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.createBasicEmptySquareSudoku(3);
Solver.solveRandom(dokuToTest3, rand);
SudokuPrinter.printRectangleSudoku(dokuToTest3.getSubGrid(0), 3, 3);
}
} }