1 Commits

Author SHA1 Message Date
Janet-Doe
0795f9256d big merge je vais dcd
All checks were successful
Linux arm64 / Build (push) Successful in 11m6s
2025-01-30 18:56:46 +01:00
58 changed files with 1526 additions and 1511 deletions

View File

@@ -16,14 +16,25 @@ project.ext.os = System.properties['os.name'].toLowerCase().split(" ")[0]
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
flatDir {
dirs("$rootProject.projectDir/libs")
}
}
dependencies {
// Use JUnit Jupiter for testing.
testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
// This dependency is used by the application.
implementation 'com.google.guava:guava:31.1-jre'
// uml
implementation 'com.github.javaparser:javaparser-symbol-solver-core:3.26.2'
implementation 'org.json:json:20250107'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.18.2'
implementation "io.github.spair:imgui-java-app:1.88.0"
implementation "org.lwjgl:lwjgl-stb:3.3.4"
@@ -36,16 +47,9 @@ application {
mainClass = 'gui.Main'
}
// Add libraries into the final jar
jar {
archiveBaseName = rootProject.getName()
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
manifest {
attributes "Main-Class": application.mainClass
}
from {
configurations.compileClasspath.collect { it.isDirectory() ? it : zipTree(it) }
}
tasks.named('test') {
// Use JUnit Platform for unit tests.
useJUnitPlatform()
}
run {

572
app/save/save-1.json Normal file
View File

@@ -0,0 +1,572 @@
{
"cells": [
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": 0
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 0
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 8
}
],
"blocks": [
{"cellIDs": [
0,
1,
2,
9,
10,
11,
18,
19,
20
]},
{"cellIDs": [
3,
4,
5,
12,
13,
14,
21,
22,
23
]},
{"cellIDs": [
6,
7,
8,
15,
16,
17,
24,
25,
26
]},
{"cellIDs": [
27,
28,
29,
36,
37,
38,
45,
46,
47
]},
{"cellIDs": [
30,
31,
32,
39,
40,
41,
48,
49,
50
]},
{"cellIDs": [
33,
34,
35,
42,
43,
44,
51,
52,
53
]},
{"cellIDs": [
54,
55,
56,
63,
64,
65,
72,
73,
74
]},
{"cellIDs": [
57,
58,
59,
66,
67,
68,
75,
76,
77
]},
{"cellIDs": [
60,
61,
62,
69,
70,
71,
78,
79,
80
]}
],
"multidoku": [{
"blockWidth": 3,
"cells": [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80
],
"blocks": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"constraints": [
0,
1,
2
]
}]
}

572
app/save/save.json Normal file
View File

@@ -0,0 +1,572 @@
{
"cells": [
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 0,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 0,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 1,
"symbolIndex": -1
},
{
"blockID": 1,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 2,
"symbolIndex": -1
},
{
"blockID": 2,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 2
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 5,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"symbolIndex": -1
},
{
"blockID": 3,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 4,
"symbolIndex": -1
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 4,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 5,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 4
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 5
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 8
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 3
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 6
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 6,
"immutable": true,
"symbolIndex": 0
},
{
"blockID": 6,
"symbolIndex": -1
},
{
"blockID": 7,
"immutable": true,
"symbolIndex": 7
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 7,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 1
},
{
"blockID": 8,
"symbolIndex": -1
},
{
"blockID": 8,
"immutable": true,
"symbolIndex": 8
}
],
"blocks": [
{"cellIDs": [
0,
1,
2,
9,
10,
11,
18,
19,
20
]},
{"cellIDs": [
3,
4,
5,
12,
13,
14,
21,
22,
23
]},
{"cellIDs": [
6,
7,
8,
15,
16,
17,
24,
25,
26
]},
{"cellIDs": [
27,
28,
29,
36,
37,
38,
45,
46,
47
]},
{"cellIDs": [
30,
31,
32,
39,
40,
41,
48,
49,
50
]},
{"cellIDs": [
33,
34,
35,
42,
43,
44,
51,
52,
53
]},
{"cellIDs": [
54,
55,
56,
63,
64,
65,
72,
73,
74
]},
{"cellIDs": [
57,
58,
59,
66,
67,
68,
75,
76,
77
]},
{"cellIDs": [
60,
61,
62,
69,
70,
71,
78,
79,
80
]}
],
"multidoku": [{
"blockWidth": 3,
"cells": [
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80
],
"blocks": [
0,
1,
2,
3,
4,
5,
6,
7,
8
],
"constraints": [
0,
1,
2
]
}]
}

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
package gui.constants;
package gui;
import imgui.ImFont;
import imgui.ImFontConfig;

View File

@@ -1,4 +1,4 @@
package gui.constants;
package gui;
import java.nio.ByteBuffer;

View File

@@ -1,16 +1,10 @@
package gui;
import gui.constants.Fonts;
import gui.constants.Images;
import gui.constants.Symbols;
import gui.menu.MainMenu;
import gui.menu.StateMachine;
import imgui.ImGui;
import imgui.app.Application;
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 {
@@ -46,13 +40,6 @@ public class Main extends Application {
}
public static void main(String[] args) {
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());
launch(new Main());
}
}

View File

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

View File

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

View File

@@ -1,4 +1,4 @@
package gui.widget;
package gui;
import java.util.HashMap;
import java.util.HashSet;
@@ -6,14 +6,8 @@ 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;
@@ -39,7 +33,6 @@ public class SudokuRenderer {
private final Set<Cell> diagonals = new HashSet<>();
public final Signal onResolve = new Signal();
public final ConsumerSignal<Cell> onCellChange = new ConsumerSignal<>();
public SudokuRenderer(MultiDoku doku) {
this.doku = RenderableMultidoku.fromMultidoku(doku);
@@ -79,13 +72,11 @@ public class SudokuRenderer {
if (currentCell.getSymbolIndex() == i) {
if (ImGui.button("X", cellSize)) {
currentCell.setSymbolIndex(Cell.NOSYMBOL);
this.onCellChange.emit(currentCell);
ImGui.closeCurrentPopup();
}
} else {
if (ImGui.button(Options.Symboles.getSymbols().get(i), cellSize)) {
currentCell.setSymbolIndex(i);
this.onCellChange.emit(currentCell);
currentCell.trySetValue(i);
if (this.doku.getDoku().isSolved())
this.onResolve.emit();
ImGui.closeCurrentPopup();
@@ -107,7 +98,7 @@ public class SudokuRenderer {
if (offsetX > 0) {
ImGui.setCursorPosX(offsetX);
}
ImGui.beginChild("sudokuChild", new ImVec2(cellSize.x * doku.getWidth(), cellSize.y * doku.getHeight()));
ImGui.beginChild(1, 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));
@@ -117,7 +108,6 @@ public class SudokuRenderer {
ImGui.sameLine();
int index = y * doku.getWidth() + x;
Cell cell = doku.getCell(x, y);
ImGui.beginDisabled(cell == null);
if (cell == null) {
ImGui.pushStyleColor(ImGuiCol.Border, TRANSPARENT);
ImGui.pushStyleColor(ImGuiCol.Button, TRANSPARENT);
@@ -142,7 +132,6 @@ public class SudokuRenderer {
currentCell = cell;
}
}
ImGui.endDisabled();
ImGui.popStyleColor(2);
}
}

View File

@@ -1,58 +1,56 @@
package gui.widget;
package gui;
import java.util.ArrayList;
import java.util.List;
import common.ConsumerSignal;
import gui.constants.SudokuType;
import common.Signal;
import imgui.ImGui;
import imgui.extension.imguifiledialog.ImGuiFileDialog;
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
import imgui.type.ImBoolean;
import imgui.type.ImInt;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.structure.Difficulty;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class SudokuSelector {
public final ConsumerSignal<MultiDoku> onSelect = new ConsumerSignal<>();
public final Signal onSelect = new Signal();
private MultiDoku doku;
private final boolean canGenEmptyGrid;
private final ImInt sudokuType = new ImInt(0);
private final ImInt difficulty = new ImInt(Difficulty.Easy.ordinal());
private final ImInt difficulty = new ImInt(Difficulty.Medium.ordinal());
private final List<ImBoolean> contraints = new ArrayList<>();
private static final String[] sudokuTypes = { "Carré", "Rectangle", "Multidoku" };
private static final int SQUARE = 0, RECTANGLE = 1, MULTIDOKU = 2;
private final ImInt sudokuSize = new ImInt(3);
private final ImInt sudokuWidth = new ImInt(3);
private final ImInt sudokuHeight = new ImInt(3);
private final String confirmMessage;
public SudokuSelector(boolean canGenEmptyGrid, String confirmMessage) {
public SudokuSelector(boolean canGenEmptyGrid) {
this.canGenEmptyGrid = canGenEmptyGrid;
this.confirmMessage = confirmMessage;
initConstraints();
}
private List<IConstraint> getConstraints() {
List<IConstraint> constraints = new ArrayList<>();
private List<Constraint> getConstraints() {
List<Constraint> constraints = new ArrayList<>();
for (int i = 0; i < this.contraints.size(); i++) {
if (this.contraints.get(i).get())
constraints.add(Constraint.values()[i].getConstraint());
constraints.add(Constraint.values()[i]);
}
return constraints;
}
private void initConstraints() {
for (Constraint cons : Constraint.values()) {
contraints.add(new ImBoolean(SudokuFactory.DEFAULT_CONSTRAINTS.contains(cons.getConstraint())));
contraints.add(new ImBoolean(SudokuFactory.DEFAULT_CONSTRAINTS.contains(cons)));
}
}
@@ -65,7 +63,7 @@ public class SudokuSelector {
e.printStackTrace();
}
}
this.onSelect.emit(this.doku);
this.onSelect.emit();
}
public void renderFileDialog() {
@@ -77,7 +75,7 @@ public class SudokuSelector {
String filePath = entry.getValue();
this.doku = SudokuFactory.fromfile(filePath);
if (this.doku != null)
this.onSelect.emit(this.doku);
this.onSelect.emit();
} catch (Exception e) {
e.printStackTrace();
}
@@ -99,9 +97,8 @@ public class SudokuSelector {
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)) {
ImGui.inputInt("Taille", sudokuSize);
if (ImGui.button("Résoudre un sudoku")) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), false);
}
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
@@ -110,11 +107,9 @@ public class SudokuSelector {
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)) {
ImGui.inputInt("Largeur", sudokuHeight);
ImGui.inputInt("Longueur", sudokuWidth);
if (ImGui.button("Résoudre un sudoku")) {
selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()),
false);
}
@@ -134,4 +129,8 @@ public class SudokuSelector {
renderFileDialog();
}
public MultiDoku getDoku() {
return doku;
}
}

View File

@@ -1,8 +1,8 @@
package gui.constants;
package gui;
import java.util.List;
import sudoku.constraint.IConstraint;
import sudoku.constraint.Constraint;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;;
@@ -14,14 +14,10 @@ public enum SudokuType {
(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,
MultiDokuSquare("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));
MultidokuRectangle("Multidoku rectangle (X)", 2,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], params[1], constraints));
String displayName;
SudokuMaker maker;
@@ -37,7 +33,7 @@ public enum SudokuType {
return this.displayName;
}
public MultiDoku createDoku(List<IConstraint> constraints, int... params) {
public MultiDoku createDoku(List<Constraint> constraints, int... params) {
return maker.makeSudoku(constraints, params);
}
@@ -47,7 +43,7 @@ public enum SudokuType {
@FunctionalInterface
private static interface SudokuMaker {
MultiDoku makeSudoku(List<IConstraint> constraints, int... params);
MultiDoku makeSudoku(List<Constraint> constraints, int... params);
}
private static final String[] dokuNames;

View File

@@ -1,4 +1,4 @@
package gui.constants;
package gui;
import java.util.ArrayList;
import java.util.List;

View File

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

View File

@@ -1,50 +1,22 @@
package gui.menu;
import game.Player;
import gui.widget.LeaderboardRenderer;
import gui.widget.MultiPlayerCompleteProgress;
import gui.widget.SudokuRenderer;
import gui.widget.TimerRenderer;
import gui.SudokuRenderer;
import imgui.ImGui;
import network.client.Client;
import network.server.Server;
import sudoku.solver.BacktrackingSolver;
import sudoku.solver.Solver;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class MultiPlayerDokuView extends BaseView {
public class MultiPlayerDokuView extends BaseView{
private final Client client;
private final Server server;
private final SudokuRenderer sudokuRenderer;
private final LeaderboardRenderer leaderboardRenderer;
private final TimerRenderer timerRenderer;
private final MultiPlayerCompleteProgress completeProgress;
public MultiPlayerDokuView(StateMachine stateMachine, Client client, Server server) {
super(stateMachine);
this.client = client;
this.server = server;
this.sudokuRenderer = new SudokuRenderer(this.client.getGame().getDoku());
this.leaderboardRenderer = new LeaderboardRenderer(client.getGame(), client.getPlayer());
this.sudokuRenderer.onCellChange.connect(this::onCellChange);
this.client.onDisconnect.connect(this::onDisconnect);
this.client.onGameEnd.connect(this::onGameEnd);
this.timerRenderer = new TimerRenderer(this.client.getGame().getStartTime(), this.client.getGame().getGameDuration());
this.completeProgress = new MultiPlayerCompleteProgress(this.client.getGame());
}
private void onGameEnd(Player winner) {
MultiDoku doku = this.client.getGame().getDoku();
doku.clearMutableCells();
Solver solver = new BacktrackingSolver();
solver.solve(doku);
this.stateMachine.overrideState(new EndGameView(stateMachine, doku, winner));
}
private void onCellChange(Cell cell) {
this.client.sendCellChange(cell);
}
public void onDisconnect() {
@@ -55,9 +27,6 @@ public class MultiPlayerDokuView extends BaseView {
@Override
public void render() {
this.timerRenderer.render();
this.leaderboardRenderer.render();
this.completeProgress.render();
this.sudokuRenderer.render();
if (ImGui.button("Quitter")) {
this.client.stop();

View File

@@ -1,30 +1,24 @@
package gui.menu;
import java.util.Arrays;
import game.Player;
import gui.widget.SudokuSelector;
import imgui.ImGui;
import imgui.type.ImInt;
import network.client.Client;
import network.server.Server;
import sudoku.constraint.Constraint;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class MultiPlayerView extends BaseView {
private final Client client;
private final Server server;
private final SudokuSelector selector;
private ImInt gameDurationMinutes = new ImInt(10);
private MultiDoku doku = null;
public MultiPlayerView(StateMachine stateMachine, Client client, Server server) {
super(stateMachine);
this.client = client;
this.server = server;
this.selector = new SudokuSelector(false, "Sélectionner le sudoku");
this.selector.onSelect.connect(this::onSelected);
this.client.onDisconnect.connect(this::onDisconnect);
this.client.onGameStarted
.connect(() -> this.stateMachine.pushState(new MultiPlayerDokuView(stateMachine, client, server)));
@@ -40,41 +34,26 @@ public class MultiPlayerView extends BaseView {
this.stateMachine.popState();
}
private void onSelected(MultiDoku doku) {
this.doku = doku;
}
public void renderGameStatus() {
if (this.server == null) {
ImGui.text("En attente de l'administrateur du serveur ...");
} else {
renderTimer();
ImGui.beginDisabled(this.doku == null);
if (ImGui.button("Démarrer")) {
this.server.startGame(this.doku, this.gameDurationMinutes.get() * 60);
// temp
MultiDoku doku = SudokuFactory.createBasicXShapedMultidoku(3, Arrays.asList(Constraint.Diagonal));
this.server.startGame(doku);
}
ImGui.endDisabled();
selector.render();
}
}
private void renderPlayers() {
@Override
public void render() {
ImGui.text("Joueurs :");
{
for (Player player : this.client.getGame().getPlayers().values()) {
ImGui.bulletText(player.getPseudo());
}
}
}
private void renderTimer() {
if (ImGui.inputInt("Temps de la partie (minutes)", gameDurationMinutes))
gameDurationMinutes.set(Math.clamp(gameDurationMinutes.get(), 1, 90));
}
@Override
public void render() {
renderPlayers();
renderGameStatus();
}

View File

@@ -1,14 +1,13 @@
package gui.menu;
import gui.constants.Options;
import gui.constants.Symbols;
import gui.Options;
import gui.Symbols;
import imgui.ImGui;
import imgui.type.ImInt;
public class OptionsMenu extends BaseView {
private ImInt currentValue = new ImInt();
private float backgroundSpeed[] = new float[]{Options.BackgroundSpeed};
public OptionsMenu(StateMachine stateMachine) {
super(stateMachine);
@@ -20,9 +19,6 @@ public class OptionsMenu extends BaseView {
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();
}

View File

@@ -1,8 +1,7 @@
package gui.menu;
import gui.widget.SudokuSelector;
import gui.SudokuSelector;
import imgui.ImGui;
import sudoku.structure.MultiDoku;
public class SoloMenu extends BaseView {
@@ -10,12 +9,12 @@ public class SoloMenu extends BaseView {
public SoloMenu(StateMachine stateMachine) {
super(stateMachine);
this.sudokuSelector = new SudokuSelector(true, "Résoudre le sudoku");
this.sudokuSelector = new SudokuSelector(true);
this.sudokuSelector.onSelect.connect(this::pushSudokuState);
}
private void pushSudokuState(MultiDoku doku) {
this.stateMachine.pushState(new SudokuView(stateMachine, doku));
private void pushSudokuState() {
this.stateMachine.pushState(new SudokuView(stateMachine, this.sudokuSelector.getDoku()));
}
@Override

View File

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

View File

@@ -1,20 +1,15 @@
package gui.menu;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import gui.widget.SudokuRenderer;
import gui.SudokuRenderer;
import imgui.ImGui;
import imgui.ImGuiStyle;
import sudoku.io.SudokuSerializer;
import sudoku.solver.BacktrackingSolver;
import sudoku.solver.HintHelper;
import sudoku.solver.HumanSolver;
import sudoku.solver.MixedSolver;
import sudoku.solver.Solver;
import sudoku.solver.SolverStep;
import sudoku.solver.HintHelper.Hint;
import sudoku.structure.MultiDoku;
public class SudokuView extends BaseView {
@@ -25,8 +20,6 @@ public class SudokuView extends BaseView {
private String lastSavePath = null;
private boolean resolved = false;
// if the solver can't solve
private volatile boolean unresolved = false;
public SudokuView(StateMachine stateMachine, MultiDoku doku) {
super(stateMachine);
@@ -75,27 +68,10 @@ public class SudokuView extends BaseView {
stopResolve();
}
private void renderHintButton() {
if (!this.resolved && centeredButton("Indice")) {
Hint hint = HintHelper.getHint(this.doku, new BacktrackingSolver());
assert (hint != null);
hint.cell().setSymbolIndex(hint.newValue());
if (this.doku.isSolved())
this.sudokuRenderer.onResolve.emit();
}
}
private void renderUnsolvableText() {
if (this.unresolved)
ImGui.text("Impossible de résoudre avec l'algorithme actuel !");
}
private void startSolve(Solver solver) {
resolveThread = new Thread(() -> {
List<SolverStep> steps = new ArrayList<>();
try {
unresolved = !solver.solve(this.doku, steps);
solver.solve(this.doku);
} catch (CancellationException e) {
System.out.println("The user is bored !");
}
@@ -103,11 +79,6 @@ public class SudokuView extends BaseView {
});
}
private void renderResolvedText() {
if (this.resolved)
ImGui.text("Bravo !");
}
private void renderSolvePopup() {
if (ImGui.beginPopup("solve")) {
if (ImGui.button("Résoudre avec backtrace")) {
@@ -131,14 +102,16 @@ public class SudokuView extends BaseView {
ImGui.beginDisabled();
if (!this.resolved && centeredButton("Résoudre")) {
// beginSolve = true;
ImGui.openPopup("solve");
}
if (resolveThread != null)
ImGui.endDisabled();
renderResolvedText();
renderUnsolvableText();
if (this.resolved) {
ImGui.text("Bravo !");
}
renderSolvePopup();
}
@@ -155,17 +128,9 @@ public class SudokuView extends BaseView {
}
}
private void renderClearButton() {
if (centeredButton("Effacer")) {
this.doku.clearMutableCells();
}
}
@Override
public void render() {
sudokuRenderer.render();
renderHintButton();
renderClearButton();
renderSolveButton();
renderSaveButton();
renderCancelButton();

View File

@@ -1,32 +0,0 @@
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

@@ -1,73 +0,0 @@
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

@@ -1,28 +0,0 @@
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

@@ -1,21 +0,0 @@
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

@@ -1,29 +0,0 @@
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());
Object o = objectInputStream.readObject();
if (o instanceof Packet packet) {
connexion.visit(packet);
connexion.visitPacket(packet);
}
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();

View File

@@ -4,15 +4,10 @@ import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Random;
import common.ConsumerSignal;
import common.Signal;
import game.Game;
import game.Player;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.LoginPacket;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class Client {
private final ClientConnexion clientConnection;
@@ -22,9 +17,6 @@ public class Client {
public final Signal onDisconnect = new Signal();
public final Signal onClosed = new Signal();
public final Signal onGameStarted = new Signal();
public final ConsumerSignal<Player> onGameEnd = new ConsumerSignal<>();
Player player;
String disconnectReason = null;
@@ -62,20 +54,4 @@ public class Client {
stop();
}
public void sendCellChange(Cell cell) {
MultiDoku doku = getGame().getDoku();
for (int sudokuIndex = 0; sudokuIndex < doku.getNbSubGrids(); sudokuIndex++) {
Sudoku sudoku = doku.getSubGrid(sudokuIndex);
int cellIndex = sudoku.getCells().indexOf(cell);
if (cellIndex != -1) {
this.clientConnection.sendPacket(new ChangeCellPacket(sudokuIndex, cellIndex, cell.getSymbolIndex()));
return;
}
}
}
public Player getPlayer() {
return player;
}
}

View File

@@ -6,21 +6,19 @@ import java.net.UnknownHostException;
import game.Player;
import network.Connexion;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
import sudoku.io.SudokuSerializer;
public class ClientConnexion extends Connexion {
private final Client client;
private Player player = null;
public ClientConnexion(String address, short port, Client client) throws UnknownHostException, IOException {
super(new Socket(address, port));
@@ -37,7 +35,7 @@ public class ClientConnexion extends Connexion {
@Override
public void visitPacket(ConnexionInfoPacket packet) {
this.client.player = this.client.getGame().getPlayerById(packet.getConnectionId());
this.player = this.client.getGame().getPlayerById(packet.getConnectionId());
client.onConnect.emit();
}
@@ -71,28 +69,8 @@ public class ClientConnexion extends Connexion {
@Override
public void visitPacket(StartGamePacket packet) {
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()),
packet.getInstant(), packet.getGameDuration());
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()));
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,19 +1,16 @@
package network.protocol;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
public interface PacketVisitor {
default void visit(Packet packet) {
default void visitPacket(Packet packet) {
packet.accept(this);
}
@@ -24,8 +21,5 @@ public interface PacketVisitor {
void visitPacket(PlayerJoinPacket packet);
void visitPacket(PlayerLeavePacket packet);
void visitPacket(StartGamePacket packet);
void visitPacket(EndGamePacket packet);
void visitPacket(UpdatePlayerScorePacket packet);
void visitPacket(ChangeCellPacket packet);
}

View File

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

View File

@@ -1,38 +0,0 @@
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

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

View File

@@ -1,32 +0,0 @@
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,15 +2,12 @@ package network.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import game.Game;
import game.Player;
import game.Game.GameState;
import network.protocol.Packet;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.StartGamePacket;
import sudoku.io.SudokuSerializer;
import sudoku.structure.MultiDoku;
@@ -40,16 +37,7 @@ public class Server {
}
}
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() {
public void update() {
for (var it = connexions.iterator(); it.hasNext();) {
ServerConnexion connexion = it.next();
if (!connexion.update()) {
@@ -60,11 +48,6 @@ public class Server {
}
}
public void update() {
checkTimer();
checkConnexions();
}
public void stop() {
this.acceptThread.cancel();
this.logicThread.cancel();
@@ -85,19 +68,9 @@ public class Server {
return game;
}
public void startGame(MultiDoku doku, long gameDuration) {
Instant now = Instant.now();
this.game.startGame(doku, now, gameDuration);
for (ServerConnexion connexion : this.connexions) {
connexion.setSudoku(doku.clone());
}
broadcastPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(doku).toString(), now, gameDuration));
}
public void stopGame() {
// we don't need to specify the winner since it has to be the first
broadcastPacket(new EndGamePacket());
getGame().stopGame();
public void startGame(MultiDoku doku) {
this.game.startGame(doku);
broadcastPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(doku).toString()));
}
}

View File

@@ -3,23 +3,17 @@ package network.server;
import java.io.IOException;
import java.net.Socket;
import game.Game;
import game.Player;
import game.Game.GameState;
import network.Connexion;
import network.protocol.packets.ChangeCellPacket;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
import network.protocol.packets.EndGamePacket;
import network.protocol.packets.KeepAlivePacket;
import network.protocol.packets.LoginPacket;
import network.protocol.packets.PlayerJoinPacket;
import network.protocol.packets.PlayerLeavePacket;
import network.protocol.packets.StartGamePacket;
import network.protocol.packets.UpdatePlayerScorePacket;
import sudoku.io.SudokuSerializer;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
public class ServerConnexion extends Connexion {
@@ -27,7 +21,6 @@ public class ServerConnexion extends Connexion {
private final KeepAliveHandler keepAliveHandler;
private boolean shouldClose = false;
private Player player = null;
private MultiDoku doku;
public ServerConnexion(Socket socket, Server server) throws IOException {
super(socket);
@@ -36,7 +29,7 @@ public class ServerConnexion extends Connexion {
}
public boolean update() {
if (shouldClose || isClosed())
if (shouldClose | isClosed())
return false;
return this.keepAliveHandler.update();
}
@@ -51,7 +44,7 @@ public class ServerConnexion extends Connexion {
@Override
public synchronized void close() {
if (shouldClose)
if(shouldClose)
return;
super.close();
shouldClose = true;
@@ -61,22 +54,13 @@ public class ServerConnexion extends Connexion {
private void finishLogin() {
// send players that have already joined (excluding this one)
for (Player p : this.server.getGame().getPlayers().values()) {
if (p.getId() != player.getId()) {
if (p.getId() != player.getId())
sendPacket(new PlayerJoinPacket(p));
sendPacket(new UpdatePlayerScorePacket(p.getId(), p.getRemainingCells()));
}
}
this.server.broadcastPacket(new PlayerJoinPacket(player));
sendPacket(new ConnexionInfoPacket(player.getId()));
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()));
if (this.server.getGame().getGameState() == GameState.GameGoing) {
sendPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(this.server.getGame().getDoku()).toString()));
}
}
@@ -118,50 +102,4 @@ public class ServerConnexion extends Connexion {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketStartGame'");
}
@Override
public void visitPacket(EndGamePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacket'");
}
@Override
public void visitPacket(UpdatePlayerScorePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacket'");
}
@Override
public void visitPacket(ChangeCellPacket packet) {
Cell cell = this.doku.getSubGrid(packet.getSudokuIndex()).getCell(packet.getCellIndex());
if (cell.getSymbolIndex() == Cell.NOSYMBOL && packet.getNewValue() == Cell.NOSYMBOL)
return;
if (cell.getSymbolIndex() != Cell.NOSYMBOL && packet.getNewValue() != Cell.NOSYMBOL) {
cell.trySetValue(packet.getNewValue());
return;
}
if (cell.getSymbolIndex() != Cell.NOSYMBOL && packet.getNewValue() == Cell.NOSYMBOL) {
cell.empty();
this.server.getGame().setPlayerRemainingCells(player, player.getRemainingCells() + 1);
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
return;
}
// on rajoute un chiffre à la grille
if (cell.trySetValue(packet.getNewValue())) {
this.server.getGame().setPlayerRemainingCells(player, player.getRemainingCells() - 1);
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
}
checkWin();
}
private void checkWin() {
if (this.player.getRemainingCells() == 0) {
this.server.stopGame();
}
}
public void setSudoku(MultiDoku doku) {
this.doku = doku;
assert (player != null);
this.server.getGame().setPlayerRemainingCells(player, this.doku.getEmptyCells().size());
this.server.broadcastPacket(new UpdatePlayerScorePacket(player.getId(), player.getRemainingCells()));
}
}

View File

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

View File

@@ -4,14 +4,16 @@
package sudoku;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import gui.Symbols;
import sudoku.io.ConsoleInterface;
import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
import java.util.Random;
public class Main {
public String getGreeting() {
return "Hello World!";
@@ -20,21 +22,12 @@ public class Main {
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) {
@@ -42,8 +35,7 @@ public class Main {
/*
voidTest();
filledTest();
overwriteTest(0);
overwriteTest(17)
filledTest();
*/
console.welcome();
}

View File

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

View File

@@ -1,10 +1,12 @@
package sudoku.io;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import gui.Symbols;
import sudoku.constraint.*;
import sudoku.solver.*;
import sudoku.structure.*;
import sudoku.solver.RandomSolver;
import sudoku.structure.Difficulty;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
import java.util.ArrayList;
import java.util.List;
@@ -13,106 +15,50 @@ import java.util.Scanner;
public class ConsoleInterface {
public Scanner reader = new Scanner(System.in);
public void welcome() {
public void welcome(){
System.out.println("Welcome to our Sudoku Solver!");
System.out.println("This is the project of Melvyn Bauvent, Lilas Grenier and Simon Pribylski.");
System.out.println("Do you have a save sudoku you would like to continue? (y/n, default n)");
if (reader.next().equalsIgnoreCase("y")) {
useSavedDoku();
} else {
createDoku();
}
System.out.println("This is the project of Melvyn Bauvent, Lilas Grenier and Simon Priblyski.");
start();
}
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() {
public void start(){
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), " +
System.out.println("Would you like to pick the " + numberOfSymbols + " symbols from the sudoku? (y/n, default 'no' will use numbers)" );
List<String> listSymbols = new ArrayList<>();
if(reader.next().equalsIgnoreCase("y")){
pickSymbols(listSymbols, numberOfSymbols);
}
else {
listSymbols = Symbols.Numbers.getSymbols();
}
List<Constraint> listConstraints = getListConstraints();
System.out.println("Now that we have the size of our sudoku, would you rather have a single grid ('one', default), " +
"or a a multidoku composed of 5 subgrids ('multi') ?");
MultiDoku doku;
if (reader.next().equalsIgnoreCase("multi")) {
doku = SudokuFactory.createBasicXShapedMultidoku(width, height, listConstraints);
} else {
}
else {
doku = SudokuFactory.createBasicEmptyRectangleDoku(width, height, listConstraints);
}
RenderableMultidoku rm = RenderableMultidoku.fromMultidoku(doku);
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))");
SudokuPrinter.printMultiDoku(rm, listSymbols, width, height);
System.out.println("We now will fill this sudoku.");
System.out.println("What level of difficulty would you like? ('very easy', 'easy', 'medium' (default), 'hard', 'full' (sudoku fully completed))");
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;
else {
generatePartialDoku(doku, difficulty);
}
System.out.println("Here's your sudoku !");
SudokuPrinter.printMultiDoku(rm, listSymbols, width, height);
}
public int getBlockWidth() {
@@ -143,55 +89,36 @@ public class ConsoleInterface {
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);
private void pickSymbols(List<String> listSymbols, int numberOfSymbols) {
System.out.println("You have chosen to pick your own symbols.");
for (int i = 0; i < numberOfSymbols; i++) {
System.out.println("Choose for the symbol number " + i + ": ");
String newSymbol = reader.next();
while (listSymbols.contains(newSymbol)) {
System.out.println("This symbol has already been given. Try again:");
newSymbol = reader.next();
}
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();
};
listSymbols.add(newSymbol);
}
System.out.println("You chose the symbols: " + listSymbols.toString());
}
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());
private List<Constraint> getListConstraints() {
List<Constraint> listConstraints = SudokuFactory.DEFAULT_CONSTRAINTS;
System.out.println("The sudoku have constraints of blocks, lines and columns. Would you like to add the diagonal constraints ? (y/n, default 'no')");
if(reader.next().equalsIgnoreCase("y")){
listConstraints.add(Constraint.Diagonal);
}
return listConstraints;
}
private void generatePartialDoku(MultiDoku doku, String difficultyName) {
Difficulty difficulty;
switch (difficultyName) {
case "very easy":
difficulty = Difficulty.VeryEasy;
case "easy":
difficulty = Difficulty.Easy;
case "hard":
difficulty = Difficulty.Hard;
default:
difficulty = Difficulty.Medium;
switch (difficultyName){
case "very easy": difficulty = Difficulty.VeryEasy;
case "easy": difficulty = Difficulty.Easy;
case "hard": difficulty = Difficulty.Hard;
default: difficulty = Difficulty.Medium;
}
try {
SudokuFactory.fillDoku(doku, difficulty);
@@ -204,102 +131,4 @@ public class ConsoleInterface {
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,7 +1,7 @@
package sudoku.io;
import gui.RenderableMultidoku;
import gui.constants.Symbols;
import gui.Symbols;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
@@ -21,73 +21,39 @@ public class SudokuPrinter {
printRectangleSudoku(s, blockWidth, blockHeight, symbols.getSymbols());
}
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, List<String> listSymbols) {
public static void printRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, List<String> listSymbols){
for (int y = 0; y < s.getSize(); y++) {
if (y % blockHeight == 0 && y > 0) {
System.out.println();
}
StringBuilder line = new StringBuilder("[ ");
for (int x = 0; x < s.getSize(); x++) {
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);
if (y % blockHeight == 0 && y > 0) {
System.out.println();
}
}
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(" ");
StringBuilder line = new StringBuilder("[ ");
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) {
header.append(" ");
line.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);
}
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) {
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("__".repeat(Math.max(0, rm.getWidth()+nBlockInWidth))).append("_\n");
}
line.append("[ ");
for (int x = 0; x < rm.getWidth(); x++) {
@@ -98,63 +64,26 @@ public class SudokuPrinter {
if (cell != null) {
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
line.append("- ");
} else {
}
else {
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
}
} else {
}
else {
line.append(" ");
}
}
line.append("]\n");
}
line.append("__".repeat(Math.max(0, rm.getWidth() + nBlockInWidth))).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) {
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) {
public static String toStringRectangleSudoku(final Sudoku s, int blockWidth, int blockHeight, List<String> listSymbols) {
StringBuilder result = new StringBuilder();
for (int y = 0; y < s.getSize(); y++) {
// Ajouter une ligne vide entre les blocs horizontaux
@@ -167,7 +96,8 @@ public class SudokuPrinter {
Cell cell = s.getCell(x, y);
if (cell.getSymbolIndex() == Cell.NOSYMBOL) {
line.append(" ");
} else {
}
else {
line.append(listSymbols.get(cell.getSymbolIndex())).append(" ");
}
@@ -182,21 +112,12 @@ public class SudokuPrinter {
return result.toString();
}
public static void printMultiDoku(final MultiDoku doku, int blockWidth, int blockHeight, Symbols symbols) {
if (doku.getNbSubGrids() == 1) {
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 {
}
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

@@ -12,7 +12,6 @@ import org.json.JSONArray;
import org.json.JSONObject;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
@@ -45,7 +44,7 @@ public class SudokuSerializer {
}
int blockID = blockIds.indexOf(block);
assert (blockID >= 0);
assert(blockID >= 0);
int symbolIndex = cell.getSymbolIndex();
JSONObject cellJsonObject = new JSONObject();
@@ -100,17 +99,8 @@ public class SudokuSerializer {
// 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é !");
}
for (Constraint cons : sudoku.getConstraints()) {
constraintsJsonArray.put(cons.ordinal());
}
jsonSudoku.put("constraints", constraintsJsonArray);
@@ -134,14 +124,17 @@ public class SudokuSerializer {
* @return String, the path of the save.
*/
public static String saveMultiDoku(final MultiDoku doku) {
JSONObject jsonRoot = serializeSudoku(doku);
File f = new File("save", "save.json");
int i = 0;
while (f.exists()) {
String newName = "save-" + ++i + ".json";
f = new File("save", newName);
}
try (FileWriter file = new FileWriter(f)) {
file.write(jsonRoot.toString(3));
} catch (IOException e) {
@@ -150,25 +143,6 @@ public class SudokuSerializer {
return f.getAbsolutePath();
}
public static String saveMultiDoku(final MultiDoku doku, final int saveToOverwrite) {
File f;
if (saveToOverwrite == 0) {
f = new File("save", "save.json");
} else {
f = new File("save", "save-" + saveToOverwrite + ".json");
}
if (!f.exists()) {
return saveMultiDoku(doku);
} else {
try (FileWriter file = new FileWriter(f)) {
file.write(serializeSudoku(doku).toString(3));
} catch (IOException e) {
e.printStackTrace();
}
return f.getAbsolutePath();
}
}
/**
* Get a MultiDoku from a pre-existing json save file.
*
@@ -243,7 +217,7 @@ public class SudokuSerializer {
List<Cell> sudokuCells = new ArrayList<>();
List<Block> sudokuBlocks = new ArrayList<>();
List<IConstraint> sudokuConstraints = new ArrayList<>();
List<Constraint> sudokuConstraints = new ArrayList<>();
for (int j = 0; j < sudokuCellsJsonArray.length(); j++) {
int cellID = sudokuCellsJsonArray.getInt(j);
@@ -257,7 +231,7 @@ public class SudokuSerializer {
for (int j = 0; j < sudokuConstraintsJsonArray.length(); j++) {
int constraintID = sudokuConstraintsJsonArray.getInt(j);
sudokuConstraints.add(Constraint.values()[constraintID].getConstraint());
sudokuConstraints.add(Constraint.values()[constraintID]);
}
Sudoku s = new Sudoku(sudokuCells, sudokuBlocks, sudokuConstraints);

View File

@@ -15,7 +15,7 @@ public class BacktrackingSolver implements Solver {
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
public boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
@@ -34,14 +34,14 @@ public class BacktrackingSolver implements Solver {
}
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
if (this.solve(doku)) {
return true;
} else {
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
}
}
return false;
}

View File

@@ -1,54 +0,0 @@
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

@@ -4,7 +4,7 @@ import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import gui.constants.Symbols;
import gui.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
@@ -19,7 +19,7 @@ public class HumanSolver implements Solver {
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
public boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
@@ -28,7 +28,7 @@ public class HumanSolver implements Solver {
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth(),
Symbols.Numbers));
Symbols.Numbers));
if (doku.isSolved()) {
return true;
@@ -47,9 +47,8 @@ public class HumanSolver implements Solver {
}
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
addStep(cellToFill, steps);
return this.solve(doku, steps);
return this.solve(doku);
}
return doku.isSolved();

View File

@@ -5,23 +5,23 @@ import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import gui.constants.Symbols;
import gui.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class MixedSolver implements Solver {
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) {
@Override
public boolean solve(MultiDoku doku) {
Random rand = new Random();
if (Thread.interrupted()) {
@@ -34,40 +34,46 @@ public class MixedSolver implements Solver {
sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth(),
Symbols.Numbers));
Symbols.Numbers));
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
List<Cell> cellsToFill = doku.getEmptyCells();
if (cellsToFill.isEmpty()) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
// Règles de déduction
for (Cell cellToFill : cellsToFill) {
if (possibleSymbols.size() == 1) {
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
return true;
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() != 1) {
continue;
}
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
return this.solve(doku);
}
// Si ça ne marche pas
// On fait du backtracking
Cell cellToFill = doku.getRandomEmptyCell(rand);
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)) {
if (this.solve(doku)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
possibleSymbols.remove(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;

View File

@@ -5,7 +5,7 @@ import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import gui.constants.Symbols;
import gui.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
@@ -13,16 +13,17 @@ 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
* @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.
*/
@Override
public boolean solve(MultiDoku doku, List<SolverStep> steps) {
@Override
public boolean solve(MultiDoku doku) {
Random rand = new Random();
if (Thread.interrupted())
@@ -51,12 +52,10 @@ public class RandomSolver implements Solver {
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
addStep(cellToFill, steps);
if (this.solve(doku, steps)) {
if (this.solve(doku)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
addStep(cellToFill, steps);
possibleSymbols.remove(nextPossibleSymbolIndex);
}

View File

@@ -8,18 +8,14 @@ import sudoku.structure.MultiDoku;
public interface Solver {
/**
/**
* Log du Solver, qui garde trace des actions réalisées.
*/
public static final Logger logger = Logger.getLogger("SolverLogger");
boolean solve(MultiDoku doku, List<SolverStep> solverSteps);
boolean solve(MultiDoku doku);
default boolean solve(MultiDoku doku) {
return solve(doku, null);
}
/**
/**
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
*
* @param doku MultiDoku, MultiDoku dont on veut le nombre de solutions.
@@ -42,20 +38,10 @@ public interface Solver {
cellToFill.setSymbolIndex(symbol);
if (solve(doku)) {
result++;
if (result > 1) {
doku.getStateManager().popState();
return result;
}
}
doku.getStateManager().popState();
}
return result;
}
default void addStep(Cell cell, List<SolverStep> steps) {
if (steps == null)
return;
steps.add(new SolverStep(cell));
}
}

View File

@@ -1,23 +0,0 @@
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

@@ -126,8 +126,6 @@ public class Cell {
}
public boolean trySetValue(int newValue) {
if (!isMutable())
return false;
if (!canHaveValue(newValue))
return false;
setSymbolIndex(newValue);

View File

@@ -1,10 +1,6 @@
package sudoku.structure;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.*;
import sudoku.io.SudokuSerializer;
@@ -81,9 +77,9 @@ public class MultiDoku {
}
/**
* Check si le MultiDoku est résolu, c'est à dire complet et cohérent avec ses contraintes.
* Check si le MultiDoku est valide, en fonction de ses sous-Sudokus.
*
* @return boolean, true s'il est résolu et false sinon.
* @return boolean, true s'il est valide et false sinon.
*/
public boolean isSolved() {
for (Sudoku sudoku : this.subGrids) {
@@ -182,18 +178,4 @@ public class MultiDoku {
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

@@ -15,35 +15,27 @@ public class StateManager {
this.doku = doku;
}
public Map<Cell, Integer> pushState() {
states.add(saveState());
return states.getLast();
public void pushState() {
states.add(new HashMap<>());
saveState();
}
public void popState() {
assert (states.size() > 0);
restoreState(states.pop());
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()) {
private void restoreState() {
for (var entry : this.states.getLast().entrySet()) {
entry.getKey().setSymbolIndex(entry.getValue());
}
}
private Map<Cell, Integer> saveState() {
Map<Cell, Integer> state = new HashMap<>();
private void saveState() {
for (Cell cell : this.doku.getCells()) {
state.put(cell, cell.getSymbolIndex());
states.getLast().put(cell, cell.getSymbolIndex());
}
return state;
}
}

View File

@@ -1,11 +1,13 @@
package sudoku.structure;
import sudoku.constraint.BlockConstraint;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.io.SudokuPrinter;
import java.util.ArrayList;
import java.util.List;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
/**
* @class Sudoku
* @brief Représent un Sudoku
@@ -23,14 +25,13 @@ public class Sudoku {
/**
* Liste des contraintes (TODO) du Sudoku.
*/
private final List<IConstraint> constraints;
private final List<Constraint> constraints;
/**
* Largeur des Blocks s'ils sont rectangulaires, valant 0 si ce n'est pas le
* cas.
* Largeur des Blocks s'ils sont rectangulaires, valant 0 si ce n'est pas le cas.
*/
private int blockWidth;
public Sudoku(List<Cell> cells, List<Block> blocks, List<IConstraint> constraints) {
public Sudoku(List<Cell> cells, List<Block> blocks, List<Constraint> constraints) {
this.cells = cells;
this.blocks = blocks;
this.constraints = constraints;
@@ -48,7 +49,6 @@ public class Sudoku {
/**
* Transforme des coordonées d'une Cell en index.
*
* @param x int, abscisse.
* @param y int, ordonnée.
* @return int, index correspondant.
@@ -59,9 +59,7 @@ public class Sudoku {
/**
* Vérifie que des coordonnées correspondent bien à une Cell dans le Sudoku.
*
* @return boolean, valant true si les coordonnées sont dans les bornes du
* Sudoku, false sinon.
* @return boolean, valant true si les coordonnées sont dans les bornes du Sudoku, false sinon.
*/
public boolean isValidCoords(int x, int y) {
int index = toIndex(x, y);
@@ -70,25 +68,21 @@ public class Sudoku {
/**
* Vérifie que l'index correspond bien à une Cell dans le Sudoku.
*
* @return boolean, valant true si l'index est dans les bornes du Sudoku, false
* sinon.
* @return boolean, valant true si l'index est dans les bornes du Sudoku, false sinon.
*/
public boolean isValidCoords(int index) {
return index < getSize() * getSize();
}
/**
* Teste si on peut placer la value dans la Cell aux coordonnées x, y d'après
* les contraintes du Sudoku.
*
* Teste si on peut placer la value dans la Cell aux coordonnées x, y d'après les contraintes du Sudoku.
* @param x int, abscisse de la Cell voulue.
* @param y int, ordonnée de la Cell voulue.
* @param value int, index du symbole qu'on veut placer.
* @return boolean, true si on peut la placer et false sinon.
*/
public boolean canBePlaced(int x, int y, int value) {
for (IConstraint constraint : this.constraints) {
for (Constraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return false;
}
@@ -98,7 +92,6 @@ public class Sudoku {
/**
* Vide la Cell dotn les coordonnées sont renseignées de son symbole.
*
* @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue.
*/
@@ -126,7 +119,6 @@ public class Sudoku {
/**
* Place le symbole d'index value dans la Cell de coordonnées précisées.
*
* @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue.
* @param value int, index du symbole à placer.
@@ -134,7 +126,7 @@ public class Sudoku {
*/
public Cell setCellSymbol(int x, int y, int value) {
assert (isValidCoords(x, y));
for (IConstraint constraint : this.constraints) {
for (Constraint constraint : this.constraints) {
if (!constraint.canBePlaced(this, x, y, value)) {
return null;
}
@@ -146,7 +138,6 @@ public class Sudoku {
/**
* Place les symboles d'index contenus dans values dans les cases du Sudoku.
*
* @param values List<Integer>, liste des index des symboles à placer.
* @return boolean, vaut true si les symboles ont été placés, false sinon.
*/
@@ -164,9 +155,7 @@ public class Sudoku {
}
/**
* Place les symboles d'index contenus dans values dans les cases du Sudoku et
* rend ces cases immuables.
*
* Place les symboles d'index contenus dans values dans les cases du Sudoku et rend ces cases immuables.
* @param values List<Integer>, liste des index des symboles à placer.
* @return boolean, vaut true si les symboles ont été placés, false sinon.
*/
@@ -203,7 +192,7 @@ public class Sudoku {
return this.cells.get(i);
}
public List<IConstraint> getConstraints() {
public List<Constraint> getConstraints() {
return constraints;
}
@@ -221,7 +210,6 @@ public class Sudoku {
/**
* 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.
*/
@@ -245,7 +233,6 @@ public class Sudoku {
/**
* Renvoie la 1re Cell vide du Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas.
*/
public Cell getFirstEmptyCell() {
@@ -258,9 +245,7 @@ public class Sudoku {
}
/**
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses
* contraintes.
*
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses contraintes.
* @return boolean, valant true si le Sudoku est résolu, false sinon.
*/
public boolean isSolved() {
@@ -271,7 +256,6 @@ public class Sudoku {
/**
* Vérifie que le Sudoku est complet, soit qu'il n'y ait aucune case vide.
*
* @return boolean, true si le Sudoku est complet, false sinon.
*/
private boolean isComplete() {
@@ -279,9 +263,7 @@ public class Sudoku {
}
/**
* Vérifie si le Sudoku est valide, soit qu'il est cohérent avec ses
* contraintes.
*
* Vérifie si le Sudoku est valide, soit qu'il est cohérent avec ses contraintes.
* @return bollean, true si le Sudoku est valide, false sinon
*/
private boolean isValid() {
@@ -307,7 +289,7 @@ public class Sudoku {
}
public boolean hasConstraint(Constraint constraint) {
return this.constraints.contains(constraint.getConstraint());
return this.constraints.contains(constraint);
}
}

View File

@@ -10,7 +10,6 @@ import java.util.Map;
import java.util.Random;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import sudoku.io.SudokuSerializer;
import sudoku.solver.RandomSolver;
import sudoku.solver.Solver;
@@ -26,13 +25,11 @@ public class SudokuFactory {
* Liste des contraintes par défaut d'un Multi- ou Sudoku.
* Comprend les contraintes de blocs, de lignes, et de colonnes.
*/
public static List<IConstraint> DEFAULT_CONSTRAINTS = SudokuFactory
.fromConstraints(Arrays.asList(Constraint.Block, Constraint.Column,
Constraint.Line));
public static List<Constraint> DEFAULT_CONSTRAINTS = 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.
*/
@@ -45,11 +42,9 @@ public class SudokuFactory {
}
/**
* Créée des Blocks de taille width par height à partir des cellules données, et
* les met dans une liste.
*
* @param cells List<Cell>, liste des Cells à découper en Blocks.
* @param width int, largeur des Blocks à créer.
* Créée des Blocks de taille width par height à partir des cellules données, et les met dans une liste.
* @param cells List<Cell>, liste des Cells à découper en Blocks.
* @param width int, largeur des Blocks à créer.
* @param height int, hauteur des Blocks à créer.
* @return List<Block>, liste des Blocks créés.
*/
@@ -77,36 +72,29 @@ public class SudokuFactory {
}
/**
* Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par
* heightBlock.
*
* @param widthBlock int, largeur des Blocks.
* Créée un MultiDoku vide dont les Blocks sont de taille widthBlock par heightBlock.
* @param widthBlock int, largeur des Blocks.
* @param heightBlock int, hauteur des Blocks.
* @return MultiDoku, MultiDoku vide.
*/
public static MultiDoku createBasicEmptyRectangleDoku(int widthBlock, int heightBlock,
List<IConstraint> constraints) {
List<Constraint> constraints) {
return new MultiDoku(Arrays.asList(createRectangleSudoku(widthBlock, heightBlock, constraints)));
}
/**
* Créée un MultiDoku vide dont les Blocks sont carrés de longueur size.
*
* @param size int, taille des Blocks.
* @return MultiDoku, MultiDoku vide.
*/
public static MultiDoku createBasicEmptySquareDoku(int size, List<IConstraint> constraints) {
public static MultiDoku createBasicEmptySquareDoku(int size, List<Constraint> constraints) {
return new MultiDoku(Arrays.asList(createSquareSudoku(size, constraints)));
}
/**
* Place des Cells immutables de valeurs fournies, aux Coordinate fournies dans
* le MultiDoku doku fourni.
*
* 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.
* @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) -> {
@@ -125,10 +113,8 @@ public class SudokuFactory {
*
* @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.
* @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 {
@@ -142,28 +128,33 @@ public class SudokuFactory {
List<Cell> cellsThatCanBeEmptied = doku.getFilledCells();
int index = random.nextInt(cellsThatCanBeEmptied.size());
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
while (!cellsThatCanBeEmptied.isEmpty()) {
int index = random.nextInt(cellsThatCanBeEmptied.size());
Cell cellToEmpty = cellsThatCanBeEmptied.get(index);
cellToEmpty.empty();
int oldSymbol = cellToEmpty.empty();
int nbDokuSultions = solver.countSolution(doku);
if (nbDokuSultions == 1) {
return newDokuFromFilledOne(doku, --nbCellsToEmpty, solver);
int nbDokuSultions = solver.countSolution(doku);
if (nbDokuSultions == 1) {
if (newDokuFromFilledOne(doku, --nbCellsToEmpty, solver)) {
return true;
}
}
cellToEmpty.setSymbolIndex(oldSymbol);
cellsThatCanBeEmptied.remove(cellToEmpty);
}
return false;
return newDokuFromFilledOne(doku, --nbCellsToEmpty, solver);
}
/**
* Créée un Sudoku vide dont les Blocks sont de taille widthBlock par
* heightBlock.
*
* 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) {
private static Sudoku createRectangleSudoku(int widthBlock, int heightBlock, List<Constraint> constraints) {
int symbolCount = widthBlock * heightBlock;
List<Cell> cases = initCells(symbolCount);
List<Block> blocs = initRectangleBlocs(cases, widthBlock, heightBlock);
@@ -177,37 +168,34 @@ public class SudokuFactory {
/**
* Créée un Sudoku vide dont les Blocks sont carrés de longueur size.
*
* @param size int, taille des Blocks.
* @return Sudoku, Sudoku vide.
*/
private static Sudoku createSquareSudoku(int size, List<IConstraint> constraints) {
private static Sudoku createSquareSudoku(int size, List<Constraint> constraints) {
return createRectangleSudoku(size, size, constraints);
}
/**
* Connecte deux Sudokus selon la décalage offset fourni.
*
* @param sudoku1 Sudoku, premier sudoku à connecter.
* @param sudoku2 Sudoku, second sudoku à connecter.
* @param offset Coordinate, décalage entre les deux Sudokus.
*/
private static void linkRectangleSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
private static void linkSquareSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
int blockWidth = sudoku1.getBlockWidth();
int blockHeight = sudoku1.getSize() / blockWidth;
for (int dx = 0; dx < blockHeight; dx++) {
for (int dx = 0; dx < blockWidth; dx++) {
for (int dy = 0; dy < blockWidth; dy++) {
int block1X = dx + offset.getX();
int block1Y = dy + offset.getY();
int block2X = dx;
int block2Y = dy;
if ((block1X < blockHeight) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
Block block1 = sudoku1.getBlocks().get(block1Y * blockHeight + block1X);
Block block2 = sudoku2.getBlocks().get(block2Y * blockHeight + block2X);
if ((block1X < blockWidth) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
Block block1 = sudoku1.getBlocks().get(block1Y * blockWidth + block1X);
Block block2 = sudoku2.getBlocks().get(block2Y * blockWidth + block2X);
// on remplace le bloc
sudoku2.getBlocks().set(block2Y * blockHeight + block2X, block1);
sudoku2.getBlocks().set(block2Y * blockWidth + block2X, block1);
block1.getSudokus().add(sudoku2);
// on remplace les cellules
@@ -224,97 +212,61 @@ public class SudokuFactory {
}
/**
* Créée un MultiDoku de Blocks carrés de taille size composé de cinq Sudokus,
* dont un central qui partage chacun de ses Blockss d'angle avec un autre
* Sudoku.
*
* Créée un MultiDoku de Blocks carrés de taille size composé de cinq Sudokus, dont un central qui partage chacun de ses Blockss d'angle avec un autre Sudoku.
* @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) {
public static MultiDoku createBasicXShapedMultidoku(int size, List<Constraint> constraints) {
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
* 1
* 4 5
*/
Sudoku sudoku1 = createSquareSudoku(size, constraints);
Sudoku sudoku2 = createSquareSudoku(size, constraints);
Sudoku sudoku3 = createSquareSudoku(size, constraints);
Sudoku sudoku4 = createSquareSudoku(size, constraints);
Sudoku sudoku5 = createSquareSudoku(size, constraints);
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size));
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size));
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1));
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(size - 1, size - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
/**
* 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<Constraint> constraints) {
assert (width > 1 && height > 1);
/*
* 2 3
* 1
* 4 5
*/
Sudoku sudoku1 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku2 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku3 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 1 - width));
linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(height - 1, 1 - width));
linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - height, width - 1));
linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(height - 1, width - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
/**
* 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));
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - width, 1 - height));
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(width - 1, 1 - height));
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - width, height - 1));
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(width - 1, height - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
}
@@ -324,6 +276,9 @@ public class SudokuFactory {
solver.solve(doku);
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
boolean successfull = newDokuFromFilledOne(doku, nbCellsToEmpty, solver);
if (!successfull) {
throw new Exception("Canno't create this doku with this difficulty");
}
doku.setFilledCellsImmutable();
}
@@ -338,13 +293,14 @@ public class SudokuFactory {
}
}
public static MultiDoku createBasicEmptyRandomBlockDoku(int blockSize, List<IConstraint> constraints) {
public static MultiDoku createBasicEmptyRandomBlockDoku(int blockSize, List<Constraint> constraints) {
int blockCellCount = blockSize * blockSize;
List<Cell> cells = initCells(blockCellCount);
List<Cell> homeLessCells = new ArrayList<>(cells);
List<Cell> homeLessCells = new ArrayList<>();
homeLessCells.addAll(cells);
List<Block> blocks = new ArrayList<>();
Random r = new Random();
for (int i = 0; i < blockCellCount; i++) {
for (int i = 0 ; i < blockCellCount; i++) {
Block b = new Block();
for (int j = 0; j < blockCellCount; j++) {
int cellIndex = r.nextInt(homeLessCells.size());
@@ -360,12 +316,4 @@ public class SudokuFactory {
}
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

@@ -1,12 +1,7 @@
package sudoku.solver;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import gui.Symbols;
import org.junit.jupiter.api.Test;
import gui.constants.Symbols;
import sudoku.io.SudokuPrinter;
import sudoku.io.SudokuSerializer;
import sudoku.structure.Cell;
@@ -14,10 +9,17 @@ import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
import sudoku.structure.SudokuFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Random;
class SolverTest {
@Test
void solveTest() {
Random rand = new Random();
MultiDoku dokuToTest = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);
MultiDoku dokuResult = SudokuFactory.createBasicEmptySquareDoku(3, SudokuFactory.DEFAULT_CONSTRAINTS);