46 Commits

Author SHA1 Message Date
b87bd5183e create package org.polytech.ryuk
All checks were successful
Linux arm64 / Build (push) Successful in 31s
2025-02-01 14:47:46 +01:00
a20a5387a7 chore: bundle deps in jar 2025-02-01 14:34:19 +01:00
a1032335a5 chore: remove unused deps 2025-02-01 14:10:15 +01:00
336d8378ae fix: slower background animation speed by default
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-02-01 13:45:44 +01:00
c165ecdae5 Merge pull request 'Fixes #15' (#36) from multiplayer into master
All checks were successful
Linux arm64 / Build (push) Successful in 39s
Reviewed-on: #36
2025-02-01 12:43:13 +00:00
352aee49e4 feat: make timer stop game (Fixes #15)
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-02-01 13:41:13 +01:00
f22debdf5f fix: score display
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 12:54:11 +01:00
02089c649b feat: select game duration
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 12:27:50 +01:00
e98199e1ec refactor: remove sysout
All checks were successful
Linux arm64 / Build (push) Successful in 25s
2025-02-01 11:59:05 +01:00
438252a8ca feat: first player progress display 2025-02-01 11:58:42 +01:00
caf6569409 fix: synced timer
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-02-01 11:22:59 +01:00
3863c812c8 fix: format timer
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-02-01 10:56:02 +01:00
6d96455ac4 feat: display wrong timer
All checks were successful
Linux arm64 / Build (push) Successful in 28s
2025-02-01 00:19:00 +01:00
a5c046f891 feat: good leaderboard 2025-02-01 00:09:25 +01:00
Melvyn
b7f9ca8a98 fix : MixedSolver
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-31 18:26:44 +01:00
a160042ef4 feat: uggly leaderboard
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-31 13:48:51 +01:00
f47e4cc309 feat: animated background
All checks were successful
Linux arm64 / Build (push) Successful in 10m56s
2025-01-30 22:28:26 +01:00
25c2270a37 feat: multi synced player scores
All checks were successful
Linux arm64 / Build (push) Successful in 31s
2025-01-30 22:16:29 +01:00
bcded60fbe small fix 2025-01-30 21:46:55 +01:00
edfffaf061 feat: multi select sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-30 18:35:41 +01:00
a74bf42e59 refactor solvers
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-30 18:05:18 +01:00
1f92c49f3c feat: select solve algorithm
All checks were successful
Linux arm64 / Build (push) Successful in 25m12s
2025-01-30 17:28:43 +01:00
c262007ca8 fix multithreading issue 2025-01-30 17:28:22 +01:00
73f572ee18 fix merge
All checks were successful
Linux arm64 / Build (push) Successful in 42s
2025-01-30 16:37:10 +01:00
ec07d88577 Merge branch 'symbols' 2025-01-30 16:35:05 +01:00
6caf5d5c54 feat: add cyrilic
All checks were successful
Linux arm64 / Build (push) Successful in 29s
2025-01-30 16:32:09 +01:00
Janet-Doe
696062e9db merge image branch with main
All checks were successful
Linux arm64 / Build (push) Successful in 39s
2025-01-30 16:23:07 +01:00
Janet-Doe
c825807aea set background picture 2025-01-30 16:23:03 +01:00
39529e0b64 fix agaaaaain 2025-01-30 16:22:47 +01:00
3fa22a4cf0 fix build.gradle (agin) 2025-01-30 16:22:43 +01:00
337911d038 bye bye png lib 2025-01-30 16:21:53 +01:00
1930bc02bd aaaaaa
# Conflicts:
#	app/src/main/java/sudoku/Main.java
#	app/src/main/java/sudoku/solver/Solver.java
2025-01-30 16:21:43 +01:00
b9788d6a51 application du cours d'APO de 15h
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 15:24:57 +01:00
7789209651 feat: change symbols
All checks were successful
Linux arm64 / Build (push) Successful in 27s
2025-01-30 15:23:54 +01:00
Melvyn
54a4bd9f22 feat : diminue automatiquement la difficulté si elle n'est pas possible
All checks were successful
Linux arm64 / Build (push) Successful in 38s
2025-01-30 14:59:19 +01:00
8596781ce3 Fixes #14
All checks were successful
Linux arm64 / Build (push) Successful in 40s
2025-01-30 14:51:21 +01:00
Melvyn
d6c3504bc7 feat : mixedSolve
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 14:32:15 +01:00
44a4432ac0 Merge branch 'master' of git.ale-pri.com:Ryuk/Sudoku
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 13:21:05 +01:00
a42ec2f27c fix merge 2025-01-30 13:14:43 +01:00
bff7abcd02 Merge branch 'serialize-fix' 2025-01-30 13:13:44 +01:00
Melvyn
bf67afe4a9 refactor : Solver
All checks were successful
Linux arm64 / Build (push) Successful in 37s
2025-01-30 12:03:03 +01:00
67da77af2e feat: add states
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2025-01-30 11:54:23 +01:00
c4becf2d55 fix: serialize 2025-01-30 11:54:21 +01:00
b9a6617967 feat: add states
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-30 09:34:00 +01:00
03f577828b fix: serialize 2025-01-30 00:51:22 +01:00
9b776d4b0f custom symbols
All checks were successful
Linux arm64 / Build (push) Successful in 26s
2025-01-29 19:47:46 +01:00
96 changed files with 3228 additions and 1241 deletions

BIN
app/background.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 399 KiB

View File

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

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,52 +0,0 @@
package game;
import java.util.HashMap;
import java.util.Map;
import sudoku.structure.MultiDoku;
public class Game {
public static enum GameState {
GameNotStarted, GameGoing, GameEnd
}
private final Map<Integer, Player> players;
private GameState gameState;
private MultiDoku doku;
public Game() {
this.players = new HashMap<>();
this.gameState = GameState.GameNotStarted;
}
public Player getPlayerById(int id) {
return players.get(id);
}
public void addPlayer(Player player) {
players.put(player.getId(), player);
}
public void removePlayer(int id) {
players.remove(id);
}
public Map<Integer, Player> getPlayers() {
return players;
}
public void startGame(MultiDoku doku) {
this.doku = doku;
this.gameState = GameState.GameGoing;
}
public GameState getGameState() {
return gameState;
}
public MultiDoku getDoku() {
return doku;
}
}

View File

@@ -1,24 +0,0 @@
package gui;
import imgui.ImFont;
import imgui.ImGui;
public class Fonts {
public static ImFont ARIAL;
public static ImFont ARIAL_BOLD;
public static ImFont CHERI;
public static ImFont COMIC;
public static ImFont INFECTED;
private static final String baseDir = "";
public static void createFonts() {
COMIC = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "comic.ttf", 50.0f);
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial_bold.ttf", 50.0f);
ARIAL = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial.ttf", 50.0f);
CHERI = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "cheri.ttf", 50.0f);
INFECTED = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "INFECTED.ttf", 50.0f);
}
}

View File

@@ -1,37 +0,0 @@
package gui.menu;
import gui.SudokuRenderer;
import imgui.ImGui;
import network.client.Client;
import network.server.Server;
public class MultiPlayerDokuView extends BaseView{
private final Client client;
private final Server server;
private final SudokuRenderer sudokuRenderer;
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.client.onDisconnect.connect(this::onDisconnect);
}
public void onDisconnect() {
if (server == null) {
closeMenu();
}
}
@Override
public void render() {
this.sudokuRenderer.render();
if (ImGui.button("Quitter")) {
this.client.stop();
this.closeMenu(3);
}
}
}

View File

@@ -1,18 +0,0 @@
package gui.menu;
import imgui.ImGui;
public class OptionsMenu extends BaseView {
public OptionsMenu(StateMachine stateMachine) {
super(stateMachine);
}
@Override
public void render() {
// TODO Auto-generated method stub
ImGui.text("Options");
renderReturnButton();
}
}

View File

@@ -1,76 +0,0 @@
package network.client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import game.Player;
import network.Connexion;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
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 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));
this.client = client;
}
@Override
public void close() {
if (!this.isClosed()) {
super.close();
client.onDisconnect.emit();
}
}
@Override
public void visitPacket(ConnexionInfoPacket packet) {
this.player = this.client.getGame().getPlayerById(packet.getConnectionId());
client.onConnect.emit();
}
@Override
public void visitPacket(KeepAlivePacket packet) {
// we just send the packet back to the server
sendPacket(packet);
}
@Override
public void visitPacket(DisconnectPacket packet) {
this.client.disconnectReason = packet.getReason();
close();
}
@Override
public void visitPacket(LoginPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketLogin'");
}
@Override
public void visitPacket(PlayerJoinPacket packet) {
this.client.addPlayer(packet.getPlayer());
System.out.println("[Client] " + packet.getPlayer().getPseudo() + " joined the game !");
}
@Override
public void visitPacket(PlayerLeavePacket packet) {
this.client.getGame().removePlayer(packet.getPlayer());
}
@Override
public void visitPacket(StartGamePacket packet) {
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()));
this.client.onGameStarted.emit();
}
}

View File

@@ -1,25 +0,0 @@
package network.protocol;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
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;
public interface PacketVisitor {
default void visitPacket(Packet packet) {
packet.accept(this);
}
void visitPacket(ConnexionInfoPacket packet);
void visitPacket(DisconnectPacket packet);
void visitPacket(KeepAlivePacket packet);
void visitPacket(LoginPacket packet);
void visitPacket(PlayerJoinPacket packet);
void visitPacket(PlayerLeavePacket packet);
void visitPacket(StartGamePacket packet);
}

View File

@@ -1,7 +0,0 @@
package network.protocol;
public enum Packets {
ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame
}

View File

@@ -1,26 +0,0 @@
package network.protocol.packets;
import network.protocol.Packet;
import network.protocol.PacketVisitor;
import network.protocol.Packets;
public class StartGamePacket extends Packet {
static private final long serialVersionUID = Packets.StartGame.ordinal();
private final String serializedSudoku;
public StartGamePacket(String serializedSudoku) {
this.serializedSudoku = serializedSudoku;
}
public String getSerializedSudoku() {
return serializedSudoku;
}
@Override
public void accept(PacketVisitor packetVisitor) {
packetVisitor.visitPacket(this);
}
}

View File

@@ -1,105 +0,0 @@
package network.server;
import java.io.IOException;
import java.net.Socket;
import game.Player;
import game.Game.GameState;
import network.Connexion;
import network.protocol.packets.ConnexionInfoPacket;
import network.protocol.packets.DisconnectPacket;
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 sudoku.io.SudokuSerializer;
public class ServerConnexion extends Connexion {
private final Server server;
private final KeepAliveHandler keepAliveHandler;
private boolean shouldClose = false;
private Player player = null;
public ServerConnexion(Socket socket, Server server) throws IOException {
super(socket);
this.server = server;
this.keepAliveHandler = new KeepAliveHandler(this);
}
public boolean update() {
if (shouldClose | isClosed())
return false;
return this.keepAliveHandler.update();
}
public void nukeConnection() {
if (player != null) {
sendPacket(new DisconnectPacket("Le serveur a été fermé !"));
this.server.broadcastPacket(new PlayerLeavePacket(player.getId()));
this.server.getGame().removePlayer(player.getId());
}
}
@Override
public synchronized void close() {
if(shouldClose)
return;
super.close();
shouldClose = true;
System.out.println("[Server] Closing 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())
sendPacket(new PlayerJoinPacket(p));
}
this.server.broadcastPacket(new PlayerJoinPacket(player));
sendPacket(new ConnexionInfoPacket(player.getId()));
if (this.server.getGame().getGameState() == GameState.GameGoing) {
sendPacket(new StartGamePacket(SudokuSerializer.serializeSudoku(this.server.getGame().getDoku()).toString()));
}
}
@Override
public void visitPacket(KeepAlivePacket packet) {
this.keepAliveHandler.recievedKeepAlive(packet.getKeepAliveId());
}
@Override
public void visitPacket(DisconnectPacket packet) {
close();
}
@Override
public void visitPacket(LoginPacket packet) {
if (this.player != null)
return;
this.player = this.server.addPlayer(packet.getPseudo());
finishLogin();
}
@Override
public void visitPacket(ConnexionInfoPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketConnexionInfo'");
}
@Override
public void visitPacket(PlayerJoinPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketPlayerJoin'");
}
@Override
public void visitPacket(PlayerLeavePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketPlayerLeave'");
}
@Override
public void visitPacket(StartGamePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketStartGame'");
}
}

View File

@@ -0,0 +1,27 @@
package org.polytech.ryuk.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,4 +1,4 @@
package common; package org.polytech.ryuk.common;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;

View File

@@ -0,0 +1,86 @@
package org.polytech.ryuk.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 org.polytech.ryuk.sudoku.structure.MultiDoku;
public class Game {
public static enum GameState {
GameNotStarted, GameGoing
}
private final Map<Integer, Player> players;
private final List<Player> leaderboard;
private GameState gameState;
private MultiDoku doku;
private Instant startTime = null;
private long gameDuration;
public Game() {
this.players = new HashMap<>();
this.leaderboard = new ArrayList<>();
this.gameState = GameState.GameNotStarted;
}
public Player getPlayerById(int id) {
return players.get(id);
}
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);
}
public Map<Integer, Player> getPlayers() {
return players;
}
public void startGame(MultiDoku doku, Instant startTime, long gameDuration) {
this.doku = doku;
this.gameState = GameState.GameGoing;
this.startTime = startTime;
this.gameDuration = gameDuration;
}
public void stopGame() {
this.gameState = GameState.GameNotStarted;
}
public GameState getGameState() {
return gameState;
}
public MultiDoku getDoku() {
return doku;
}
public List<Player> getLeaderboard() {
return leaderboard;
}
public Instant getStartTime() {
return startTime;
}
public long getGameDuration() {
return gameDuration;
}
}

View File

@@ -1,4 +1,4 @@
package game; package org.polytech.ryuk.game;
import java.io.Serializable; import java.io.Serializable;
@@ -8,10 +8,20 @@ public class Player implements Serializable {
private final String pseudo; private final String pseudo;
private final int id; private final int id;
private int score;
public Player(int id, String pseudo) { public Player(int id, String pseudo) {
this.pseudo = pseudo; this.pseudo = pseudo;
this.id = id; this.id = id;
this.score = 0;
}
public int getRemainingCells() {
return score;
}
void setRemainingCells(int score) {
this.score = score;
} }
public String getPseudo() { public String getPseudo() {

View File

@@ -0,0 +1,30 @@
package org.polytech.ryuk.gui;
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,4 +1,4 @@
package gui; package org.polytech.ryuk.gui;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@@ -0,0 +1,34 @@
package org.polytech.ryuk.gui;
import imgui.ImFont;
import imgui.ImFontConfig;
import imgui.ImFontGlyphRangesBuilder;
import imgui.ImGui;
public class Fonts {
public static ImFont ARIAL;
public static ImFont ARIAL_BOLD;
public static ImFont CHERI;
public static ImFont COMIC;
public static ImFont INFECTED;
public static ImFont EMOJIS;
private static final String baseDir = "";
public static void createFonts() {
ImFontGlyphRangesBuilder builder = new ImFontGlyphRangesBuilder();
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesDefault());
builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesCyrillic());
// builder.addRanges(ImGui.getIO().getFonts().getGlyphRangesChineseFull());
ImFontConfig cfg = new ImFontConfig();
cfg.setGlyphRanges(builder.buildRanges());
COMIC = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "comic.ttf", 50.0f);
ARIAL_BOLD = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial_bold.ttf", 50.0f);
ARIAL = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "arial.ttf", 50.0f, cfg);
CHERI = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "cheri.ttf", 50.0f);
INFECTED = ImGui.getIO().getFonts().addFontFromFileTTF(baseDir + "INFECTED.ttf", 50.0f);
}
}

View File

@@ -0,0 +1,39 @@
package org.polytech.ryuk.gui;
import java.nio.ByteBuffer;
import org.lwjgl.opengl.GL11;
import org.lwjgl.stb.STBImage;
public class Images {
public static int BACKGROUND;
private static int loadTexture(String fileName) {
int[] width = new int[1];
int[] height = new int[1];
int[] channelCount = new int[1];
ByteBuffer pixels = STBImage.stbi_load(fileName, width, height, channelCount, 4);
int textureID = GL11.glGenTextures();
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureID);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); // Not on WebGL/ES
GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_PIXELS, 0); // Not on WebGL/ES
GL11.glPixelStorei(GL11.GL_UNPACK_SKIP_ROWS, 0); // Not on WebGL/ES
GL11.glPixelStorei(GL11.GL_UNPACK_ROW_LENGTH, 0); // Not on WebGL/ES
GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, width[0], height[0], 0,
GL11.GL_RGBA,
GL11.GL_UNSIGNED_BYTE, pixels);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
return textureID;
}
public static void loadImages() {
BACKGROUND = loadTexture("background.png");
}
}

View File

@@ -1,8 +1,8 @@
package gui; package org.polytech.ryuk.gui;
import org.polytech.ryuk.gui.menu.MainMenu;
import org.polytech.ryuk.gui.menu.StateMachine;
import gui.menu.MainMenu;
import gui.menu.StateMachine;
import imgui.ImGui;
import imgui.app.Application; import imgui.app.Application;
import imgui.app.Configuration; import imgui.app.Configuration;
@@ -26,6 +26,12 @@ public class Main extends Application {
Fonts.createFonts(); Fonts.createFonts();
stateMachine.pushState(new MainMenu(stateMachine)); stateMachine.pushState(new MainMenu(stateMachine));
} }
@Override
protected void preRun() {
super.preRun();
Images.loadImages();
}
@Override @Override
public void process() { public void process() {

View File

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

View File

@@ -1,15 +1,15 @@
package gui; package org.polytech.ryuk.gui;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import sudoku.structure.Block; import org.polytech.ryuk.sudoku.structure.Block;
import sudoku.structure.Cell; import org.polytech.ryuk.sudoku.structure.Cell;
import sudoku.structure.Coordinate; import org.polytech.ryuk.sudoku.structure.Coordinate;
import sudoku.structure.MultiDoku; import org.polytech.ryuk.sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public class RenderableMultidoku { public class RenderableMultidoku {
@@ -27,10 +27,6 @@ public class RenderableMultidoku {
this.doku = doku; this.doku = doku;
} }
public boolean isResolved() {
return this.doku.isSolved();
}
public int getWidth() { public int getWidth() {
return width; return width;
} }
@@ -51,21 +47,7 @@ public class RenderableMultidoku {
return cells.get(index); return cells.get(index);
} }
public boolean setCellValue(Cell cell, int value) {
for (Sudoku s : doku.getSubGrids()) {
int cellIndex = s.getCells().indexOf(cell);
// la cellule existe
if (cellIndex != -1) {
int cellX = cellIndex % s.getSize();
int cellY = cellIndex / s.getSize();
if (!s.canBePlaced(cellX, cellY, value)) {
return false;
}
}
}
cell.setSymbolIndex(value);
return true;
}
private static record PositionConstraint(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) { private static record PositionConstraint(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
} }

View File

@@ -0,0 +1,63 @@
package org.polytech.ryuk.gui;
import java.util.List;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.SudokuFactory;;
public enum SudokuType {
Square("Carré", 1,
(constraints, params) -> SudokuFactory.createBasicEmptySquareDoku(params[0], constraints)),
Rectangle("Rectangle", 2,
(constraints, params) -> SudokuFactory.createBasicEmptyRectangleDoku(params[0], params[1], constraints)),
RandomBloc("Blocs aléatoires", 1,
(constraints, params) -> SudokuFactory.createBasicEmptyRandomBlockDoku(params[0], constraints)),
MultiDokuSquare("Multidoku carré (X)", 1,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], constraints)),
MultidokuRectangle("Multidoku rectangle (X)", 2,
(constraints, params) -> SudokuFactory.createBasicXShapedMultidoku(params[0], params[1], constraints));
String displayName;
SudokuMaker maker;
int paramCount;
private SudokuType(String displayName, int paramCount, SudokuMaker maker) {
this.displayName = displayName;
this.maker = maker;
this.paramCount = paramCount;
}
public String getDisplayName() {
return this.displayName;
}
public MultiDoku createDoku(List<Constraint> constraints, int... params) {
return maker.makeSudoku(constraints, params);
}
public int getMakerParamCount() {
return this.paramCount;
}
@FunctionalInterface
private static interface SudokuMaker {
MultiDoku makeSudoku(List<Constraint> constraints, int... params);
}
private static final String[] dokuNames;
static {
SudokuType[] types = SudokuType.values();
dokuNames = new String[types.length];
for (int i = 0; i < types.length; i++) {
dokuNames[i] = types[i].getDisplayName();
}
}
public static String[] getTypeNames() {
return dokuNames;
}
}

View File

@@ -0,0 +1,83 @@
package org.polytech.ryuk.gui;
import java.util.ArrayList;
import java.util.List;
public enum Symbols {
Numbers("Nombres", getNumbers()),
Letters("Lettres", getLetters()),
Russian("Cyrilique", getRussian()),
Emojis("Emojis (Console uniquement)", getEmojis());
String displayName;
List<String> symbols;
private Symbols(String displayName, List<String> symbols) {
this.symbols = symbols;
this.displayName = displayName;
}
public String getDisplayName() {
return displayName;
}
public List<String> getSymbols() {
return symbols;
}
private static List<String> getNumbers() {
List<String> sym = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
sym.add(Integer.toString(i));
}
return sym;
}
private static List<String> getLetters() {
List<String> sym = new ArrayList<>();
for (int i = 0; i < 100; i++) {
int currentOffset = i;
String letter = "";
while (currentOffset >= 26) {
letter += Character.toString((char) ('A' + currentOffset % 26));
currentOffset /= 26;
currentOffset--;
}
letter += Character.toString((char) ('A' + currentOffset % 26));
sym.add(new StringBuilder(letter).reverse().toString());
}
return sym;
}
private static List<String> getRussian() {
List<String> sym = new ArrayList<>();
for (int i = 0; i < 100; i++) {
sym.add(new String(Character.toChars(0X0400 + i)));
}
return sym;
}
private static List<String> getEmojis() {
List<String> sym = new ArrayList<>();
for (int i = 0; i < 100; i++) {
sym.add(new String(Character.toChars(0X1F600 + i)));
}
return sym;
}
private static final String[] symbolNames;
static {
Symbols[] symbols = Symbols.values();
symbolNames = new String[symbols.length];
for (int i = 0; i < symbols.length; i++) {
symbolNames[i] = symbols[i].getDisplayName();
}
}
public static String[] getSymbolsNames() {
return symbolNames;
}
}

View File

@@ -1,4 +1,4 @@
package gui.menu; package org.polytech.ryuk.gui.menu;
import imgui.ImGui; import imgui.ImGui;

View File

@@ -1,11 +1,12 @@
package gui.menu; package org.polytech.ryuk.gui.menu;
import java.io.IOException; import java.io.IOException;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import org.polytech.ryuk.network.client.Client;
import org.polytech.ryuk.network.server.Server;
import imgui.ImGui; import imgui.ImGui;
import network.client.Client;
import network.server.Server;
public class ConnexionStatusView extends BaseView { public class ConnexionStatusView extends BaseView {

View File

@@ -0,0 +1,50 @@
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.gui.ColorGenerator;
import org.polytech.ryuk.gui.widget.SudokuRenderer;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import imgui.ImGui;
import imgui.ImVec4;
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

@@ -1,4 +1,4 @@
package gui.menu; package org.polytech.ryuk.gui.menu;
import imgui.ImGui; import imgui.ImGui;
import imgui.ImVec2; import imgui.ImVec2;

View File

@@ -1,4 +1,4 @@
package gui.menu; package org.polytech.ryuk.gui.menu;
import java.io.IOException; import java.io.IOException;

View File

@@ -0,0 +1,69 @@
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.gui.widget.LeaderboardRenderer;
import org.polytech.ryuk.gui.widget.MultiPlayerCompleteProgress;
import org.polytech.ryuk.gui.widget.SudokuRenderer;
import org.polytech.ryuk.gui.widget.TimerRenderer;
import org.polytech.ryuk.network.client.Client;
import org.polytech.ryuk.network.server.Server;
import org.polytech.ryuk.sudoku.solver.BacktrackingSolver;
import org.polytech.ryuk.sudoku.solver.Solver;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import imgui.ImGui;
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() {
if (server == null) {
closeMenu();
}
}
@Override
public void render() {
this.timerRenderer.render();
this.leaderboardRenderer.render();
this.completeProgress.render();
this.sudokuRenderer.render();
if (ImGui.button("Quitter")) {
this.client.stop();
this.closeMenu(3);
}
}
}

View File

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

View File

@@ -0,0 +1,30 @@
package org.polytech.ryuk.gui.menu;
import org.polytech.ryuk.gui.Options;
import org.polytech.ryuk.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);
}
@Override
public void render() {
ImGui.text("Options");
if(ImGui.combo("Jeu de symboles", currentValue, Symbols.getSymbolsNames())){
Options.Symboles = Symbols.values()[currentValue.get()];
}
if(ImGui.sliderFloat("Vitesse d'animation de l'arrière plan", backgroundSpeed, 0.0f, 10.0f)){
Options.BackgroundSpeed = backgroundSpeed[0];
}
renderReturnButton();
}
}

View File

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

View File

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

View File

@@ -1,14 +1,17 @@
package gui.menu; package org.polytech.ryuk.gui.menu;
import java.util.Random;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import gui.SudokuRenderer; import org.polytech.ryuk.gui.widget.SudokuRenderer;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import org.polytech.ryuk.sudoku.solver.BacktrackingSolver;
import org.polytech.ryuk.sudoku.solver.HumanSolver;
import org.polytech.ryuk.sudoku.solver.MixedSolver;
import org.polytech.ryuk.sudoku.solver.Solver;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import imgui.ImGui; import imgui.ImGui;
import imgui.ImGuiStyle; import imgui.ImGuiStyle;
import sudoku.io.SudokuSerializer;
import sudoku.solver.Solver;
import sudoku.structure.MultiDoku;
public class SudokuView extends BaseView { public class SudokuView extends BaseView {
@@ -66,34 +69,52 @@ public class SudokuView extends BaseView {
stopResolve(); stopResolve();
} }
private void startSolve(Solver solver) {
resolveThread = new Thread(() -> {
try {
solver.solve(this.doku);
} catch (CancellationException e) {
System.out.println("The user is bored !");
}
stopResolve();
});
}
private void renderSolvePopup() {
if (ImGui.beginPopup("solve")) {
if (ImGui.button("Résoudre avec backtrace")) {
startSolve(new BacktrackingSolver());
ImGui.closeCurrentPopup();
}
if (ImGui.button("Résoudre avec déduction")) {
startSolve(new HumanSolver());
ImGui.closeCurrentPopup();
}
if (ImGui.button("Résoudre avec déduction et backtrace")) {
startSolve(new MixedSolver());
ImGui.closeCurrentPopup();
}
ImGui.endPopup();
}
}
private void renderSolveButton() { private void renderSolveButton() {
if (resolveThread != null) if (resolveThread != null)
ImGui.beginDisabled(); ImGui.beginDisabled();
boolean beginSolve = false; if (!this.resolved && centeredButton("Résoudre")) {
// beginSolve = true;
if (!resolved && centeredButton("Résoudre")) { ImGui.openPopup("solve");
beginSolve = true;
} }
if (resolveThread != null) if (resolveThread != null)
ImGui.endDisabled(); ImGui.endDisabled();
if (beginSolve) { if (this.resolved) {
resolveThread = new Thread(() -> {
try {
Random rand = new Random();
Solver.solveRandom(doku, rand);
Thread.sleep(200);
} catch (CancellationException | InterruptedException e) {
System.out.println("The user is bored !");
}
stopResolve();
});
}
if (resolved) {
ImGui.text("Bravo !"); ImGui.text("Bravo !");
} }
renderSolvePopup();
} }
private void renderSaveButton() { private void renderSaveButton() {

View File

@@ -0,0 +1,74 @@
package org.polytech.ryuk.gui.widget;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Player;
import imgui.ImGui;
import imgui.ImVec2;
import imgui.ImVec4;
import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar;
public class LeaderboardRenderer {
private final Game game;
private final Player currentPlayer;
private final float cellHeight = 75;
private final ImVec2 cellSize = new ImVec2(12 * cellHeight, cellHeight);
private final ImVec2 rankSize = new ImVec2(cellHeight, cellHeight);
private final ImVec2 scoreSize = rankSize;
private final ImVec2 nameSize = new ImVec2(cellSize.x - cellHeight * 2.0f, cellHeight);
private final ImVec4 cellColorPlayer = new ImVec4(0.20f, 0.67f, 1.0f, 0.5f);
private final ImVec4 cellColorEnemy = new ImVec4(1.0f, 0.0f, 0.0f, 0.5f);
private final int maxPlayersShowed = 2;
private final int emptyCellCount;
public LeaderboardRenderer(Game game, Player player) {
this.game = game;
this.currentPlayer = player;
this.emptyCellCount = game.getDoku().getEmptyCells().size();
}
private void renderRank(int rank) {
ImGui.button(Integer.toString(rank), rankSize);
}
private void renderName(String name) {
ImGui.button(name, nameSize);
}
private void renderScore(int score) {
ImGui.button(Integer.toString(score), scoreSize);
}
private void renderCell(Player player, int rank, ImVec4 color) {
ImGui.pushStyleColor(ImGuiCol.Button, color);
ImGui.pushStyleColor(ImGuiCol.ButtonHovered, color);
ImGui.pushStyleColor(ImGuiCol.ButtonActive, color);
ImGui.beginChild(player.getPseudo() + "##" + player.getId(), cellSize);
renderRank(rank);
ImGui.sameLine();
renderName(player.getPseudo());
ImGui.sameLine();
renderScore(emptyCellCount - player.getRemainingCells());
ImGui.endChild();
ImGui.popStyleColor(3);
}
public void render() {
var displaySize = ImGui.getIO().getDisplaySize();
ImGui.setCursorPosX(displaySize.x / 2.0f - cellSize.x / 2.0f);
ImGui.beginChild("Leaderboard", new ImVec2(cellSize.x + 15.0f, cellHeight * maxPlayersShowed));
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2());
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 3.0f);
for (int i = 0; i < game.getLeaderboard().size(); i++) {
Player player = game.getLeaderboard().get(i);
renderCell(player, i + 1, player == currentPlayer ? cellColorPlayer : cellColorEnemy);
}
ImGui.popStyleVar(2);
ImGui.endChild();
}
}

View File

@@ -0,0 +1,29 @@
package org.polytech.ryuk.gui.widget;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Player;
import imgui.ImGui;
import imgui.ImVec2;
public class MultiPlayerCompleteProgress {
private final Game game;
private final int emptyCellCount;
private final ImVec2 progressSize = new ImVec2(700, 50);
private final SmoothProgressBar progressBar;
public MultiPlayerCompleteProgress(Game game) {
this.game = game;
this.emptyCellCount = game.getDoku().getEmptyCells().size();
this.progressBar = new SmoothProgressBar();
}
public void render() {
Player firstPlayer = game.getLeaderboard().getFirst();
ImGui.setCursorPosX(ImGui.getIO().getDisplaySizeX() / 2.0f - progressSize.x / 2.0f);
String progressText = firstPlayer.getPseudo() + " - " + (emptyCellCount - firstPlayer.getRemainingCells()) + "/" + emptyCellCount;
this.progressBar.render(progressText, progressSize, 1.0f - firstPlayer.getRemainingCells() / (float) emptyCellCount);
}
}

View File

@@ -0,0 +1,21 @@
package org.polytech.ryuk.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,4 +1,4 @@
package gui; package org.polytech.ryuk.gui.widget;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@@ -6,18 +6,25 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import common.Signal; import org.polytech.ryuk.common.ConsumerSignal;
import gui.ColorGenerator.Color; import org.polytech.ryuk.common.Signal;
import org.polytech.ryuk.gui.ColorGenerator;
import org.polytech.ryuk.gui.ColorGenerator.Color;
import org.polytech.ryuk.gui.Fonts;
import org.polytech.ryuk.gui.Options;
import org.polytech.ryuk.gui.RenderableMultidoku;
import org.polytech.ryuk.gui.Symbols;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.Block;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
import imgui.ImGui; import imgui.ImGui;
import imgui.ImVec2; import imgui.ImVec2;
import imgui.ImVec4; import imgui.ImVec4;
import imgui.flag.ImGuiCol; import imgui.flag.ImGuiCol;
import imgui.flag.ImGuiStyleVar; import imgui.flag.ImGuiStyleVar;
import sudoku.constraint.Constraint;
import sudoku.structure.Block;
import sudoku.structure.Cell;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
public class SudokuRenderer { public class SudokuRenderer {
@@ -33,6 +40,7 @@ public class SudokuRenderer {
private final Set<Cell> diagonals = new HashSet<>(); private final Set<Cell> diagonals = new HashSet<>();
public final Signal onResolve = new Signal(); public final Signal onResolve = new Signal();
public final ConsumerSignal<Cell> onCellChange = new ConsumerSignal<>();
public SudokuRenderer(MultiDoku doku) { public SudokuRenderer(MultiDoku doku) {
this.doku = RenderableMultidoku.fromMultidoku(doku); this.doku = RenderableMultidoku.fromMultidoku(doku);
@@ -72,12 +80,14 @@ public class SudokuRenderer {
if (currentCell.getSymbolIndex() == i) { if (currentCell.getSymbolIndex() == i) {
if (ImGui.button("X", cellSize)) { if (ImGui.button("X", cellSize)) {
currentCell.setSymbolIndex(Cell.NOSYMBOL); currentCell.setSymbolIndex(Cell.NOSYMBOL);
this.onCellChange.emit(currentCell);
ImGui.closeCurrentPopup(); ImGui.closeCurrentPopup();
} }
} else { } else {
if (ImGui.button(Integer.toString(i + 1), cellSize)) { if (ImGui.button(Options.Symboles.getSymbols().get(i), cellSize)) {
this.doku.setCellValue(currentCell, i); if (currentCell.trySetValue(i))
if (this.doku.isResolved()) this.onCellChange.emit(currentCell);
if (this.doku.getDoku().isSolved())
this.onResolve.emit(); this.onResolve.emit();
ImGui.closeCurrentPopup(); ImGui.closeCurrentPopup();
} }
@@ -88,6 +98,9 @@ public class SudokuRenderer {
} }
public void render() { public void render() {
if (Options.Symboles == Symbols.Russian) {
ImGui.pushFont(Fonts.ARIAL);
}
final float sudokuViewWidth = cellSize.x * doku.getWidth(); final float sudokuViewWidth = cellSize.x * doku.getWidth();
final float displayWidth = ImGui.getIO().getDisplaySizeX(); final float displayWidth = ImGui.getIO().getDisplaySizeX();
float offsetX = displayWidth / 2.0f - sudokuViewWidth / 2.0f; float offsetX = displayWidth / 2.0f - sudokuViewWidth / 2.0f;
@@ -95,7 +108,7 @@ public class SudokuRenderer {
if (offsetX > 0) { if (offsetX > 0) {
ImGui.setCursorPosX(offsetX); ImGui.setCursorPosX(offsetX);
} }
ImGui.beginChild(1, new ImVec2(cellSize.x * doku.getWidth(), cellSize.y * doku.getHeight())); ImGui.beginChild("sudokuChild", new ImVec2(cellSize.x * doku.getWidth(), cellSize.y * doku.getHeight()));
ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 2.0f); ImGui.pushStyleVar(ImGuiStyleVar.FrameBorderSize, 2.0f);
ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2(0.0f, 0.0f)); ImGui.pushStyleVar(ImGuiStyleVar.ItemSpacing, new ImVec2(0.0f, 0.0f));
@@ -123,7 +136,7 @@ public class SudokuRenderer {
ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(blockColor.r, blockColor.g, blockColor.b, 1.0f)); ImGui.pushStyleColor(ImGuiCol.Button, new ImVec4(blockColor.r, blockColor.g, blockColor.b, 1.0f));
String cellText = ""; String cellText = "";
if (symbol != -1) if (symbol != -1)
cellText += Integer.toString(symbol + 1); cellText += Options.Symboles.getSymbols().get(symbol);
if (ImGui.button(cellText + "##" + index, cellSize) && cell.isMutable()) { if (ImGui.button(cellText + "##" + index, cellSize) && cell.isMutable()) {
ImGui.openPopup("editPopup"); ImGui.openPopup("editPopup");
currentCell = cell; currentCell = cell;
@@ -135,6 +148,9 @@ public class SudokuRenderer {
ImGui.popStyleVar(2); ImGui.popStyleVar(2);
renderPopup(); renderPopup();
ImGui.endChild(); ImGui.endChild();
if (Options.Symboles == Symbols.Russian) {
ImGui.popFont();
}
} }
} }

View File

@@ -1,22 +1,24 @@
package gui; package org.polytech.ryuk.gui.widget;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import common.Signal; import org.polytech.ryuk.common.ConsumerSignal;
import org.polytech.ryuk.gui.SudokuType;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.structure.Difficulty;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.SudokuFactory;
import imgui.ImGui; import imgui.ImGui;
import imgui.extension.imguifiledialog.ImGuiFileDialog; import imgui.extension.imguifiledialog.ImGuiFileDialog;
import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags; import imgui.extension.imguifiledialog.flag.ImGuiFileDialogFlags;
import imgui.type.ImBoolean; import imgui.type.ImBoolean;
import imgui.type.ImInt; import imgui.type.ImInt;
import sudoku.constraint.Constraint;
import sudoku.structure.Difficulty;
import sudoku.structure.MultiDoku;
import sudoku.structure.SudokuFactory;
public class SudokuSelector { public class SudokuSelector {
public final Signal onSelect = new Signal(); public final ConsumerSignal<MultiDoku> onSelect = new ConsumerSignal<>();
private MultiDoku doku; private MultiDoku doku;
private final boolean canGenEmptyGrid; private final boolean canGenEmptyGrid;
@@ -26,16 +28,16 @@ public class SudokuSelector {
private final ImInt difficulty = new ImInt(Difficulty.Medium.ordinal()); private final ImInt difficulty = new ImInt(Difficulty.Medium.ordinal());
private final List<ImBoolean> contraints = new ArrayList<>(); 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 sudokuSize = new ImInt(3);
private final ImInt sudokuWidth = new ImInt(3); private final ImInt sudokuWidth = new ImInt(3);
private final ImInt sudokuHeight = new ImInt(3); private final ImInt sudokuHeight = new ImInt(3);
public SudokuSelector(boolean canGenEmptyGrid) { private final String confirmMessage;
public SudokuSelector(boolean canGenEmptyGrid, String confirmMessage) {
this.canGenEmptyGrid = canGenEmptyGrid; this.canGenEmptyGrid = canGenEmptyGrid;
this.confirmMessage = confirmMessage;
initConstraints(); initConstraints();
} }
@@ -63,7 +65,7 @@ public class SudokuSelector {
e.printStackTrace(); e.printStackTrace();
} }
} }
this.onSelect.emit(); this.onSelect.emit(this.doku);
} }
public void renderFileDialog() { public void renderFileDialog() {
@@ -75,7 +77,7 @@ public class SudokuSelector {
String filePath = entry.getValue(); String filePath = entry.getValue();
this.doku = SudokuFactory.fromfile(filePath); this.doku = SudokuFactory.fromfile(filePath);
if (this.doku != null) if (this.doku != null)
this.onSelect.emit(); this.onSelect.emit(this.doku);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@@ -86,7 +88,6 @@ public class SudokuSelector {
} }
public void render() { public void render() {
ImGui.combo("Type de Sudoku", sudokuType, sudokuTypes);
ImGui.combo("Difficulté", difficulty, Difficulty.getDifficultyNames()); ImGui.combo("Difficulté", difficulty, Difficulty.getDifficultyNames());
if (ImGui.treeNode("Constraintes")) { if (ImGui.treeNode("Constraintes")) {
for (Constraint cons : Constraint.values()) { for (Constraint cons : Constraint.values()) {
@@ -94,54 +95,40 @@ public class SudokuSelector {
} }
ImGui.treePop(); ImGui.treePop();
} }
switch (sudokuType.get()) { ImGui.combo("Type de Sudoku", sudokuType, SudokuType.getTypeNames());
case SQUARE: SudokuType currentType = SudokuType.values()[sudokuType.get()];
switch (currentType.getMakerParamCount()) {
case 1:
ImGui.inputInt("Taille", sudokuSize); ImGui.inputInt("Taille", sudokuSize);
if (ImGui.button("Résoudre un sudoku")) { if (ImGui.button(confirmMessage)) {
selectSudoku(SudokuFactory.createBasicEmptySquareDoku(sudokuSize.get(), getConstraints()), false); selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), false);
} }
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) { if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
selectSudoku(SudokuFactory.createBasicEmptySquareDoku(sudokuSize.get(), getConstraints()), true); selectSudoku(currentType.createDoku(getConstraints(), sudokuSize.get()), true);
} }
break; break;
case RECTANGLE: case 2:
ImGui.inputInt("Largeur", sudokuHeight); ImGui.inputInt("Largeur", sudokuHeight);
ImGui.inputInt("Longueur", sudokuWidth); ImGui.inputInt("Longueur", sudokuWidth);
if (ImGui.button("Résoudre un sudoku")) { if (ImGui.button(confirmMessage)) {
selectSudoku( selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()),
SudokuFactory.createBasicEmptyRectangleDoku(sudokuWidth.get(), sudokuHeight.get(),
getConstraints()),
false); false);
} }
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) { if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
selectSudoku( selectSudoku(currentType.createDoku(getConstraints(), sudokuWidth.get(), sudokuHeight.get()), true);
SudokuFactory.createBasicEmptyRectangleDoku(sudokuWidth.get(), sudokuHeight.get(),
getConstraints()),
true);
} }
break; break;
case MULTIDOKU:
ImGui.inputInt("Taille", sudokuSize);
if (ImGui.button("Résoudre un sudoku")) {
selectSudoku(SudokuFactory.createBasicXShapedMultidoku(sudokuSize.get(), getConstraints()), false);
}
if (canGenEmptyGrid && ImGui.button("Générer une grille vide")) {
selectSudoku(SudokuFactory.createBasicXShapedMultidoku(sudokuSize.get(), getConstraints()), true);
}
default: default:
assert (false);
break; break;
} }
if (ImGui.button("À partir d'un fichier")) { if (ImGui.button("À partir d'un fichier")) {
ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", "."); ImGuiFileDialog.openDialog("browse-sudoku", "Choisissez un fichier", ".json", ".");
} }
renderFileDialog(); renderFileDialog();
} }
public MultiDoku getDoku() {
return doku;
}
} }

View File

@@ -0,0 +1,29 @@
package org.polytech.ryuk.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

@@ -1,11 +1,11 @@
package network; package org.polytech.ryuk.network;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.net.Socket; import java.net.Socket;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
public abstract class Connexion implements PacketVisitor { public abstract class Connexion implements PacketVisitor {

View File

@@ -1,9 +1,9 @@
package network; package org.polytech.ryuk.network;
import java.io.IOException; import java.io.IOException;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
public class ConnexionThread extends Thread { public class ConnexionThread extends Thread {
@@ -22,7 +22,7 @@ public class ConnexionThread extends Thread {
// System.out.println(objectInputStream.available()); // System.out.println(objectInputStream.available());
Object o = objectInputStream.readObject(); Object o = objectInputStream.readObject();
if (o instanceof Packet packet) { if (o instanceof Packet packet) {
connexion.visitPacket(packet); connexion.visit(packet);
} }
} catch (ClassNotFoundException | IOException e) { } catch (ClassNotFoundException | IOException e) {
e.printStackTrace(); e.printStackTrace();

View File

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

View File

@@ -0,0 +1,98 @@
package org.polytech.ryuk.network.client;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.Connexion;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.ConnexionInfoPacket;
import org.polytech.ryuk.network.protocol.packets.DisconnectPacket;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerJoinPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerLeavePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.network.protocol.packets.UpdatePlayerScorePacket;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
public class ClientConnexion extends Connexion {
private final Client client;
public ClientConnexion(String address, short port, Client client) throws UnknownHostException, IOException {
super(new Socket(address, port));
this.client = client;
}
@Override
public void close() {
if (!this.isClosed()) {
super.close();
client.onDisconnect.emit();
}
}
@Override
public void visitPacket(ConnexionInfoPacket packet) {
this.client.player = this.client.getGame().getPlayerById(packet.getConnectionId());
client.onConnect.emit();
}
@Override
public void visitPacket(KeepAlivePacket packet) {
// we just send the packet back to the server
sendPacket(packet);
}
@Override
public void visitPacket(DisconnectPacket packet) {
this.client.disconnectReason = packet.getReason();
close();
}
@Override
public void visitPacket(LoginPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketLogin'");
}
@Override
public void visitPacket(PlayerJoinPacket packet) {
this.client.addPlayer(packet.getPlayer());
System.out.println("[Client] " + packet.getPlayer().getPseudo() + " joined the game !");
}
@Override
public void visitPacket(PlayerLeavePacket packet) {
this.client.getGame().removePlayer(packet.getPlayer());
}
@Override
public void visitPacket(StartGamePacket packet) {
this.client.getGame().startGame(SudokuSerializer.deserializeSudoku(packet.getSerializedSudoku()),
packet.getInstant(), packet.getGameDuration());
this.client.onGameStarted.emit();
}
@Override
public void visitPacket(EndGamePacket packet) {
Player winner = this.client.getGame().getLeaderboard().getFirst();
this.client.getGame().stopGame();
this.client.onGameEnd.emit(winner);
}
@Override
public void visitPacket(UpdatePlayerScorePacket packet) {
Player player = this.client.getGame().getPlayerById(packet.getPlayerId());
assert (player != null);
this.client.getGame().setPlayerRemainingCells(player, packet.getCellsLeft());
}
@Override
public void visitPacket(ChangeCellPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketChangeCell'");
}
}

View File

@@ -1,4 +1,4 @@
package network.protocol; package org.polytech.ryuk.network.protocol;
import java.io.Serializable; import java.io.Serializable;

View File

@@ -0,0 +1,31 @@
package org.polytech.ryuk.network.protocol;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.ConnexionInfoPacket;
import org.polytech.ryuk.network.protocol.packets.DisconnectPacket;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerJoinPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerLeavePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.network.protocol.packets.UpdatePlayerScorePacket;
public interface PacketVisitor {
default void visit(Packet packet) {
packet.accept(this);
}
void visitPacket(ConnexionInfoPacket packet);
void visitPacket(DisconnectPacket packet);
void visitPacket(KeepAlivePacket packet);
void visitPacket(LoginPacket packet);
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

@@ -0,0 +1,7 @@
package org.polytech.ryuk.network.protocol;
public enum Packets {
ConnectionInfo, KeepAlive, Disconnect, Login, PlayerJoin, PlayerLeave, StartGame, ChangeCell, EndGame, UpdatePlayerScore
}

View File

@@ -0,0 +1,38 @@
package org.polytech.ryuk.network.protocol.packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.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,8 +1,8 @@
package network.protocol.packets; package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
import network.protocol.Packets; import org.polytech.ryuk.network.protocol.Packets;
public class ConnexionInfoPacket extends Packet { public class ConnexionInfoPacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets; package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
import network.protocol.Packets; import org.polytech.ryuk.network.protocol.Packets;
public class DisconnectPacket extends Packet { public class DisconnectPacket extends Packet {

View File

@@ -0,0 +1,18 @@
package org.polytech.ryuk.network.protocol.packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.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,8 +1,8 @@
package network.protocol.packets; package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
import network.protocol.Packets; import org.polytech.ryuk.network.protocol.Packets;
public class KeepAlivePacket extends Packet { public class KeepAlivePacket extends Packet {

View File

@@ -1,8 +1,8 @@
package network.protocol.packets; package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
import network.protocol.Packets; import org.polytech.ryuk.network.protocol.Packets;
public class LoginPacket extends Packet { public class LoginPacket extends Packet {

View File

@@ -1,9 +1,9 @@
package network.protocol.packets; package org.polytech.ryuk.network.protocol.packets;
import game.Player; import org.polytech.ryuk.game.Player;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
import network.protocol.Packets; import org.polytech.ryuk.network.protocol.Packets;
public class PlayerJoinPacket extends Packet{ public class PlayerJoinPacket extends Packet{

View File

@@ -1,8 +1,8 @@
package network.protocol.packets; package org.polytech.ryuk.network.protocol.packets;
import network.protocol.Packet; import org.polytech.ryuk.network.protocol.Packet;
import network.protocol.PacketVisitor; import org.polytech.ryuk.network.protocol.PacketVisitor;
import network.protocol.Packets; import org.polytech.ryuk.network.protocol.Packets;
public class PlayerLeavePacket extends Packet{ public class PlayerLeavePacket extends Packet{

View File

@@ -0,0 +1,41 @@
package org.polytech.ryuk.network.protocol.packets;
import java.time.Instant;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.network.protocol.Packets;
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) {
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

@@ -0,0 +1,32 @@
package org.polytech.ryuk.network.protocol.packets;
import org.polytech.ryuk.network.protocol.Packet;
import org.polytech.ryuk.network.protocol.PacketVisitor;
import org.polytech.ryuk.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

@@ -1,8 +1,8 @@
package network.server; package org.polytech.ryuk.network.server;
import java.util.Random; import java.util.Random;
import network.protocol.packets.KeepAlivePacket; import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
public class KeepAliveHandler { public class KeepAliveHandler {

View File

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

View File

@@ -1,4 +1,4 @@
package network.server; package org.polytech.ryuk.network.server;
import java.io.IOException; import java.io.IOException;
import java.net.Socket; import java.net.Socket;

View File

@@ -0,0 +1,167 @@
package org.polytech.ryuk.network.server;
import java.io.IOException;
import java.net.Socket;
import org.polytech.ryuk.game.Game;
import org.polytech.ryuk.game.Game.GameState;
import org.polytech.ryuk.game.Player;
import org.polytech.ryuk.network.Connexion;
import org.polytech.ryuk.network.protocol.packets.ChangeCellPacket;
import org.polytech.ryuk.network.protocol.packets.ConnexionInfoPacket;
import org.polytech.ryuk.network.protocol.packets.DisconnectPacket;
import org.polytech.ryuk.network.protocol.packets.EndGamePacket;
import org.polytech.ryuk.network.protocol.packets.KeepAlivePacket;
import org.polytech.ryuk.network.protocol.packets.LoginPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerJoinPacket;
import org.polytech.ryuk.network.protocol.packets.PlayerLeavePacket;
import org.polytech.ryuk.network.protocol.packets.StartGamePacket;
import org.polytech.ryuk.network.protocol.packets.UpdatePlayerScorePacket;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public class ServerConnexion extends Connexion {
private final Server server;
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);
this.server = server;
this.keepAliveHandler = new KeepAliveHandler(this);
}
public boolean update() {
if (shouldClose || isClosed())
return false;
return this.keepAliveHandler.update();
}
public void nukeConnection() {
if (player != null) {
sendPacket(new DisconnectPacket("Le serveur a été fermé !"));
this.server.broadcastPacket(new PlayerLeavePacket(player.getId()));
this.server.getGame().removePlayer(player.getId());
}
}
@Override
public synchronized void close() {
if (shouldClose)
return;
super.close();
shouldClose = true;
System.out.println("[Server] Closing 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()) {
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()));
}
}
@Override
public void visitPacket(KeepAlivePacket packet) {
this.keepAliveHandler.recievedKeepAlive(packet.getKeepAliveId());
}
@Override
public void visitPacket(DisconnectPacket packet) {
close();
}
@Override
public void visitPacket(LoginPacket packet) {
if (this.player != null)
return;
this.player = this.server.addPlayer(packet.getPseudo());
finishLogin();
}
@Override
public void visitPacket(ConnexionInfoPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketConnexionInfo'");
}
@Override
public void visitPacket(PlayerJoinPacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketPlayerJoin'");
}
@Override
public void visitPacket(PlayerLeavePacket packet) {
throw new UnsupportedOperationException("Unimplemented method 'visitPacketPlayerLeave'");
}
@Override
public void visitPacket(StartGamePacket packet) {
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

@@ -1,4 +1,4 @@
package network.server; package org.polytech.ryuk.network.server;
public class ServerLogicThread extends Thread { public class ServerLogicThread extends Thread {
@@ -19,7 +19,7 @@ public class ServerLogicThread extends Thread {
try { try {
Thread.sleep(50); Thread.sleep(50);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// e.printStackTrace(); e.printStackTrace();
break; break;
} }
} }

View File

@@ -1,9 +1,9 @@
/* /*
* This Java source file was generated by the Gradle 'init' task. * This Java source file was generated by the Gradle 'init' task.
*/ */
package sudoku; package org.polytech.ryuk.sudoku;
import sudoku.io.ConsoleInterface; import org.polytech.ryuk.sudoku.io.ConsoleInterface;
public class Main { public class Main {
public String getGreeting() { public String getGreeting() {

View File

@@ -1,7 +1,7 @@
package sudoku.constraint; package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Block; import org.polytech.ryuk.sudoku.structure.Block;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public class BlockConstraint implements IConstraint{ public class BlockConstraint implements IConstraint{

View File

@@ -1,7 +1,7 @@
package sudoku.constraint; package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Cell; import org.polytech.ryuk.sudoku.structure.Cell;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public class ColumnConstraint implements IConstraint { public class ColumnConstraint implements IConstraint {

View File

@@ -1,8 +1,8 @@
package sudoku.constraint; package org.polytech.ryuk.sudoku.constraint;
import java.util.List; import java.util.List;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public enum Constraint { public enum Constraint {

View File

@@ -1,6 +1,6 @@
package sudoku.constraint; package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public class DiagonalConstraint implements IConstraint { public class DiagonalConstraint implements IConstraint {

View File

@@ -1,9 +1,9 @@
package sudoku.constraint; package org.polytech.ryuk.sudoku.constraint;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public interface IConstraint { public interface IConstraint {

View File

@@ -1,6 +1,6 @@
package sudoku.constraint; package org.polytech.ryuk.sudoku.constraint;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public class LineConstraint implements IConstraint { public class LineConstraint implements IConstraint {

View File

@@ -1,17 +1,16 @@
package sudoku.io; package org.polytech.ryuk.sudoku.io;
import sudoku.constraint.*;
import sudoku.solver.Solver;
import sudoku.structure.Difficulty;
import sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku;
import sudoku.structure.SudokuFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Random;
import java.util.Scanner; import java.util.Scanner;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.solver.RandomSolver;
import org.polytech.ryuk.sudoku.structure.Difficulty;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
import org.polytech.ryuk.sudoku.structure.SudokuFactory;
public class ConsoleInterface { public class ConsoleInterface {
public Scanner reader = new Scanner(System.in); public Scanner reader = new Scanner(System.in);
@@ -133,7 +132,7 @@ public class ConsoleInterface {
} }
private void generateFullDoku(MultiDoku doku) { private void generateFullDoku(MultiDoku doku) {
Solver.solveRandom(doku, new Random()); new RandomSolver().solve(doku);
} }
} }

View File

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

View File

@@ -1,7 +1,7 @@
package sudoku.io; package org.polytech.ryuk.sudoku.io;
import sudoku.structure.MultiDoku; import org.polytech.ryuk.sudoku.structure.MultiDoku;
import sudoku.structure.Sudoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
public class SudokuPrinter { public class SudokuPrinter {

View File

@@ -1,4 +1,4 @@
package sudoku.io; package org.polytech.ryuk.sudoku.io;
public class SudokuSave { public class SudokuSave {

View File

@@ -1,7 +1,8 @@
package sudoku.io; package org.polytech.ryuk.sudoku.io;
import java.io.*; import java.io.File;
import java.nio.charset.StandardCharsets; import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList; import java.util.ArrayList;
@@ -9,22 +10,20 @@ import java.util.List;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.polytech.ryuk.sudoku.constraint.Constraint;
import sudoku.constraint.Constraint; import org.polytech.ryuk.sudoku.structure.Block;
import sudoku.structure.Block; import org.polytech.ryuk.sudoku.structure.Cell;
import sudoku.structure.Cell; import org.polytech.ryuk.sudoku.structure.MultiDoku;
import sudoku.structure.MultiDoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
import sudoku.structure.Sudoku;
import sudoku.structure.SudokuFactory;
public class SudokuSerializer { public class SudokuSerializer {
public static JSONObject serializeSudoku(final MultiDoku multidoku) { public static JSONObject serializeSudoku(final MultiDoku multidoku) {
List<Cell> cellIds = new ArrayList<>(); List<Cell> cellIds = new ArrayList<>();
List<Block> blockIds = new ArrayList<>(); List<Block> blockIds = new ArrayList<>();
JSONObject jsonRoot = new JSONObject(); JSONObject jsonRoot = new JSONObject();
JSONArray jsonCells = new JSONArray(); JSONArray jsonCells = new JSONArray();
JSONArray jsonBlocks = new JSONArray(); JSONArray jsonBlocks = new JSONArray();
JSONArray jsonSudokus = new JSONArray(multidoku.getNbSubGrids()); JSONArray jsonSudokus = new JSONArray(multidoku.getNbSubGrids());
@@ -33,9 +32,10 @@ public class SudokuSerializer {
// init cells // init cells
for (Cell cell : sudoku.getCells()) { for (Cell cell : sudoku.getCells()) {
if (!cellIds.contains(cell)) { if (cellIds.contains(cell))
cellIds.add(cell); continue;
}
cellIds.add(cell);
Block block = cell.getBlock(); Block block = cell.getBlock();
if (!blockIds.contains(block)) { if (!blockIds.contains(block)) {
@@ -43,6 +43,7 @@ public class SudokuSerializer {
} }
int blockID = blockIds.indexOf(block); int blockID = blockIds.indexOf(block);
assert(blockID >= 0);
int symbolIndex = cell.getSymbolIndex(); int symbolIndex = cell.getSymbolIndex();
JSONObject cellJsonObject = new JSONObject(); JSONObject cellJsonObject = new JSONObject();
@@ -58,16 +59,17 @@ public class SudokuSerializer {
// init blocks // init blocks
for (Block blockId : blockIds) { for (Block blockId : blockIds) {
JSONObject blockJsonObject = new JSONObject(); JSONObject blockJsonObject = new JSONObject();
JSONArray cellsJsonArray = new JSONArray(); JSONArray cellsJsonArray = new JSONArray();
for (Cell cell : blockId.getCells()) { for (Cell cell : blockId.getCells()) {
int cellID = cellIds.indexOf(cell); int cellID = cellIds.indexOf(cell);
cellsJsonArray.put(cellID); assert (cellID >= 0);
} cellsJsonArray.put(cellID);
blockJsonObject.put("cellIDs", cellsJsonArray); }
jsonBlocks.put(blockJsonObject); blockJsonObject.put("cellIDs", cellsJsonArray);
} jsonBlocks.put(blockJsonObject);
}
for (int i = 0; i < multidoku.getNbSubGrids(); i++) { for (int i = 0; i < multidoku.getNbSubGrids(); i++) {
// serialise sub grid // serialise sub grid
@@ -82,6 +84,7 @@ public class SudokuSerializer {
for (Cell cell : sudoku.getCells()) { for (Cell cell : sudoku.getCells()) {
int cellID = cellIds.indexOf(cell); int cellID = cellIds.indexOf(cell);
assert (cellID >= 0);
cellsJsonArray.put(cellID); cellsJsonArray.put(cellID);
} }
@@ -89,6 +92,7 @@ public class SudokuSerializer {
for (Block block : sudoku.getBlocks()) { for (Block block : sudoku.getBlocks()) {
int blockID = blockIds.indexOf(block); int blockID = blockIds.indexOf(block);
assert (blockID >= 0);
blocksJsonArray.put(blockID); blocksJsonArray.put(blockID);
} }
@@ -114,6 +118,7 @@ public class SudokuSerializer {
/** /**
* Save a serialized MultiDoku in a JSON file. * Save a serialized MultiDoku in a JSON file.
*
* @param doku MultiDoku, MultiDoku to save. * @param doku MultiDoku, MultiDoku to save.
* @return String, the path of the save. * @return String, the path of the save.
*/ */
@@ -139,6 +144,7 @@ public class SudokuSerializer {
/** /**
* Get a MultiDoku from a pre-existing json save file. * Get a MultiDoku from a pre-existing json save file.
*
* @param numberSave int, number of the save file to open. * @param numberSave int, number of the save file to open.
* @return MultiDoku, MultoDoku contained in the file. * @return MultiDoku, MultoDoku contained in the file.
* @throws Exception when the given save file does not exist. * @throws Exception when the given save file does not exist.
@@ -158,20 +164,6 @@ public class SudokuSerializer {
throw new Exception("This save does not exist."); throw new Exception("This save does not exist.");
} else { } else {
fileContent = new String(Files.readAllBytes(Paths.get("save/" + fileName))); fileContent = new String(Files.readAllBytes(Paths.get("save/" + fileName)));
/*
try {
FileReader file = new FileReader(f);
char[] rawFileContent = {};
int length = 1000;
while (file.read(rawFileContent, 0, length) != -1) {
rawFileContent = new char[]{};
length = length * 10;
}
fileContent = new String(rawFileContent);
} catch (IOException e) {
throw new Exception("Error reading file.");
}
*/
return deserializeSudoku(fileContent); return deserializeSudoku(fileContent);
} }
} }

View File

@@ -0,0 +1,49 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
public class BacktrackingSolver implements Solver {
/**
* Résout le MultiDoku passé en paramètre, avec backtracking.
*
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.isEmpty()) {
return false;
}
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
if (this.solve(doku)) {
return true;
} else {
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
}
}
return false;
}
}

View File

@@ -0,0 +1,55 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import org.polytech.ryuk.sudoku.io.SudokuPrinter;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class HumanSolver implements Solver {
/**
* Résout le MultiDoku passé en paramètre, avec règles de déduction.
*
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
List<Cell> cellsToFill = doku.getEmptyCells();
if (cellsToFill.isEmpty()) {
return false;
}
for (Cell cellToFill : cellsToFill) {
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() != 1) {
continue;
}
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
return this.solve(doku);
}
return doku.isSolved();
}
}

View File

@@ -0,0 +1,71 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import org.polytech.ryuk.sudoku.io.SudokuPrinter;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.sudoku.structure.Sudoku;
public class MixedSolver implements Solver{
/**
* Résout le MultiDoku passé en paramètre, avec règles de déduction et
* backtracking.
*
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
@Override
public boolean solve(MultiDoku doku) {
Random rand = new Random();
if (Thread.interrupted()) {
throw new CancellationException("User wants to stop the solver");
}
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(
sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
if (possibleSymbols.size() == 1) {
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
if (this.solve(doku)) {
return true;
}
}
while (!possibleSymbols.isEmpty()) {
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
if (this.solve(doku)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;
}
}

View File

@@ -0,0 +1,63 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import org.polytech.ryuk.sudoku.io.SudokuPrinter;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.sudoku.structure.MultiDoku;
import org.polytech.ryuk.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) {
Random rand = new Random();
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
while (!possibleSymbols.isEmpty()) {
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
if (this.solve(doku)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;
}
}

View File

@@ -0,0 +1,47 @@
package org.polytech.ryuk.sudoku.solver;
import java.util.List;
import java.util.logging.Logger;
import org.polytech.ryuk.sudoku.structure.Cell;
import org.polytech.ryuk.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);
/**
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
*
* @param doku MultiDoku, MultiDoku dont on veut le nombre de solutions.
* @return int, nombre de solutions possibles.
*/
default int countSolution(MultiDoku doku) {
int result = 0;
if (doku.isSolved()) {
return 1;
}
Cell cellToFill = doku.getFirstEmptyCell();
assert (cellToFill != null);
List<Integer> possibleSymbols = cellToFill.getPossibleSymbols();
for (int symbol : possibleSymbols) {
doku.getStateManager().pushState();
cellToFill.setSymbolIndex(symbol);
if (solve(doku)) {
result++;
}
doku.getStateManager().popState();
}
return result;
}
}

View File

@@ -1,10 +1,9 @@
package sudoku.solver; package org.polytech.ryuk.sudoku.solver;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import sudoku.structure.Coordinate; import org.polytech.ryuk.sudoku.structure.MultiDoku;
import sudoku.structure.MultiDoku; import org.polytech.ryuk.sudoku.structure.Sudoku;
import sudoku.structure.Sudoku;
/** /**
* Class de test non utilisé * Class de test non utilisé
@@ -24,9 +23,8 @@ public class StupidSolver {
if (!sudoku.getCell(index).isMutable()) if (!sudoku.getCell(index).isMutable())
return solve(sudoku, index + 1); return solve(sudoku, index + 1);
Coordinate coords = sudoku.toCoords(index);
for (int symbol = 0; symbol < sudoku.getSize(); symbol++) { for (int symbol = 0; symbol < sudoku.getSize(); symbol++) {
if (sudoku.tryPlaceCellSymbol(coords.getX(), coords.getY(), symbol)) { if (sudoku.getCell(index).trySetValue(symbol)) {
// on tente de placer sur la case suivante // on tente de placer sur la case suivante
if (solve(sudoku, index + 1)) { if (solve(sudoku, index + 1)) {
return true; return true;
@@ -34,7 +32,7 @@ public class StupidSolver {
} }
} }
// on a tout essayé et rien n'a fonctionné // on a tout essayé et rien n'a fonctionné
sudoku.clearCell(coords.getX(), coords.getY()); sudoku.getCell(index).empty();
return false; return false;
} }

View File

@@ -1,4 +1,4 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@@ -1,4 +1,4 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -24,28 +24,21 @@ public class Cell {
* Il est initialisé à Cell.NOSYMBOL. * Il est initialisé à Cell.NOSYMBOL.
*/ */
private int symbolIndex = Cell.NOSYMBOL; private int symbolIndex = Cell.NOSYMBOL;
/**
* Liste des index de symbole possibles pour cette Cell,
* en fonction des contraintes de sudoku dans lequel elle est.
*/
private final List<Integer> possibleSymbols;
/** /**
* Si cette Cell peut être modififié ou non. * Si cette Cell peut être modififié ou non.
*/ */
private boolean isMutable = true; private boolean isMutable = true;
public Cell() { public Cell() {
this.possibleSymbols = new ArrayList<>(); this(Cell.NOSYMBOL);
} }
public Cell(int symbolIndex) { public Cell(int symbolIndex) {
this.symbolIndex = symbolIndex; this.symbolIndex = symbolIndex;
this.possibleSymbols = new ArrayList<>();
} }
public Cell(int symbolIndex, boolean isMutable) { public Cell(int symbolIndex, boolean isMutable) {
this.symbolIndex = symbolIndex; this.symbolIndex = symbolIndex;
this.possibleSymbols = new ArrayList<>();
this.isMutable = isMutable; this.isMutable = isMutable;
} }
@@ -57,11 +50,6 @@ public class Cell {
this.symbolIndex = symbolIndex; this.symbolIndex = symbolIndex;
} }
public void setPossibleSymbols(List<Integer> possibleSymbols) {
this.possibleSymbols.clear();
this.possibleSymbols.addAll(possibleSymbols);
}
/** /**
* Rend la Cell immuable. * Rend la Cell immuable.
*/ */
@@ -95,14 +83,6 @@ public class Cell {
return this.symbolIndex == Cell.NOSYMBOL; return this.symbolIndex == Cell.NOSYMBOL;
} }
public void removeSymbolFromPossibilities(int indexSymbol) {
possibleSymbols.remove(indexSymbol);
}
public List<Integer> getPossibleSymbols() {
return this.possibleSymbols;
}
/** /**
* Renvoie si la Cell est modifiable * Renvoie si la Cell est modifiable
* @return boolean, true si elle est modifiable ou false sinon. * @return boolean, true si elle est modifiable ou false sinon.
@@ -120,4 +100,37 @@ public class Cell {
this.symbolIndex = Cell.NOSYMBOL; this.symbolIndex = Cell.NOSYMBOL;
return oldSymbol; return oldSymbol;
} }
public boolean canHaveValue(int value) {
for (Sudoku s :getBlock().getSudokus()) {
int cellIndex = s.getCells().indexOf(this);
// la cellule existe
if (cellIndex != -1) {
int cellX = cellIndex % s.getSize();
int cellY = cellIndex / s.getSize();
if (!s.canBePlaced(cellX, cellY, value)) {
return false;
}
}
}
return true;
}
public List<Integer> getPossibleSymbols() {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < getBlock().getSudokus().get(0).getSize(); i++) {
if (canHaveValue(i))
result.add(i);
}
return result;
}
public boolean trySetValue(int newValue) {
if (!isMutable())
return false;
if (!canHaveValue(newValue))
return false;
setSymbolIndex(newValue);
return true;
}
} }

View File

@@ -1,4 +1,4 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
/** /**
* Représente les coordonnées d'une Cell * Représente les coordonnées d'une Cell

View File

@@ -1,12 +1,12 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
//TODO: melvyn va passer par //TODO: melvyn va passer par
public enum Difficulty { public enum Difficulty {
VeryEasy("Très facile", 0.1), Easy("Facile", 0.25), Medium("Moyen", 0.5), Hard("Difficile", 0.75); VeryEasy("Très facile", 0.1), Easy("Facile", 0.25), Medium("Moyen", 0.5), Hard("Difficile", 0.75), VeryHard("Impossible", 0.78);
double factor; final double factor;
String displayName; final String displayName;
private Difficulty(String displayName, double factor) { private Difficulty(String displayName, double factor) {
this.factor = factor; this.factor = factor;

View File

@@ -1,11 +1,12 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Random;
import java.util.Set; import java.util.Set;
import sudoku.io.SudokuSerializer; import org.polytech.ryuk.sudoku.io.SudokuSerializer;
/** /**
* @class MultiDoku * @class MultiDoku
@@ -19,90 +20,60 @@ public class MultiDoku {
*/ */
private final List<Sudoku> subGrids; private final List<Sudoku> subGrids;
private final StateManager stateManager;
public MultiDoku(List<Sudoku> subGrids) { public MultiDoku(List<Sudoku> subGrids) {
this.subGrids = subGrids; this.subGrids = subGrids;
} this.stateManager = new StateManager(this);
public MultiDoku clone() {
//TODO: ahhhhhhhhhhhhhhhhhhhhhhh
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
} }
/** /**
* Renvoie le nombre de sudoku contenu dans ce MultiDoku. * Renvoie le nombre de sudoku contenu dans ce MultiDoku.
*
* @return int * @return int
*/ */
public int getNbSubGrids(){ public int getNbSubGrids() {
return subGrids.size(); return subGrids.size();
} }
/** /**
* Renvoie la ie sudoku contenue dans ce MultiDoku. * Renvoie la ie sudoku contenue dans ce MultiDoku.
*
* @param i int, indice du sudoku à renvoyer. * @param i int, indice du sudoku à renvoyer.
* @return Sudoku, ie Sudoku * @return Sudoku, ie Sudoku
*/ */
public Sudoku getSubGrid(int i){ public Sudoku getSubGrid(int i) {
return subGrids.get(i); return subGrids.get(i);
} }
/** /**
* Renvoie la liste des Cells contenue dans ce MultiDoku, * Renvoie la liste des Cells contenue dans ce MultiDoku,
* soit les Cells contenues de chaques sous-Sudoku. * soit les Cells contenues de chaques sous-Sudoku.
*
* @return List<Cell> * @return List<Cell>
*/ */
public List<Cell> getCells(){ public List<Cell> getCells() {
Set<Cell> cellsSet = new HashSet<>(); Set<Cell> cellsSet = new HashSet<>();
for (Sudoku sudoku : subGrids){ for (Sudoku sudoku : subGrids) {
cellsSet.addAll(sudoku.getCells()); cellsSet.addAll(sudoku.getCells());
} }
return new ArrayList<>(cellsSet); return new ArrayList<>(cellsSet);
}
/**
* Met à jour les symboles possibles de chaque Cell.
* @throws Exception, si ce n'est pas possible.
*/
public void updateSymbolsPossibilities() throws Exception {
for (Sudoku sudoku : subGrids){
sudoku.updateSymbolsPossibilities();
}
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Multidoku {"); sb.append("Multidoku {");
for (Sudoku sudoku : subGrids){ for (Sudoku sudoku : subGrids) {
sb.append("\n\t").append(sudoku.toString()); sb.append("\n\t").append(sudoku.toString());
} }
sb.append("\n}"); sb.append("\n}");
return sb.toString(); return sb.toString();
} }
/**
* Renvoie les symboles possibles d'une Cell donnée.
* @param cellToFill Cell.
* @return List<Integer>, liste des symboles possible.
*/
public List<Integer> getPossibleSymbolsOfCell(Cell cellToFill) {
List<Integer> result = new ArrayList<>();
boolean hasBeenFill = false;
for (Sudoku sudoku : this.subGrids) {
if (sudoku.contains(cellToFill)) {
if (!hasBeenFill) {
result.addAll(sudoku.getPossibleSymbolsOfCell(cellToFill));
hasBeenFill = true;
} else {
result.retainAll(sudoku.getPossibleSymbolsOfCell(cellToFill));
}
}
}
return result;
}
/** /**
* Renvoie les sous-Sudoku * Renvoie les sous-Sudoku
*
* @return List<Sudoku> * @return List<Sudoku>
*/ */
public List<Sudoku> getSubGrids() { public List<Sudoku> getSubGrids() {
@@ -111,43 +82,26 @@ public class MultiDoku {
/** /**
* Check si le MultiDoku est valide, en fonction de ses sous-Sudokus. * Check si le MultiDoku est valide, en fonction de ses sous-Sudokus.
*
* @return boolean, true s'il est valide et false sinon. * @return boolean, true s'il est valide et false sinon.
*/ */
public boolean isSolved() { public boolean isSolved() {
boolean result = true;
for (Sudoku sudoku : this.subGrids) { for (Sudoku sudoku : this.subGrids) {
result = sudoku.isSolved() && result; if (!sudoku.isSolved())
}
return result;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof MultiDoku)) {
return false;
}
if (this.getNbSubGrids() != ((MultiDoku) object).getNbSubGrids()) {
return false;
}
for (int i = 0; i < this.getNbSubGrids(); i++) {
if (!this.getSubGrid(i).equals(((MultiDoku) object).getSubGrid(i))) {
return false; return false;
}
} }
return true; return true;
} }
/** /**
* Renvoie la 1re Cell vide des sous-Sudoku. * Renvoie la 1re Cell vide des sous-Sudoku.
*
* @return Cell, une Cell vide, ou null s'il n'y en a pas. * @return Cell, une Cell vide, ou null s'il n'y en a pas.
*/ */
public Cell getFirstEmptyCell() { public Cell getFirstEmptyCell() {
for (Sudoku sudoku : this.subGrids) { for (Sudoku sudoku : this.subGrids) {
Cell cellTmp = sudoku.getFirstEmptyCell(); Cell cellTmp = sudoku.getFirstEmptyCell();
if (cellTmp != null && cellTmp.isEmpty()) { if (cellTmp != null) {
return cellTmp; return cellTmp;
} }
} }
@@ -156,11 +110,12 @@ public class MultiDoku {
/** /**
* Renvoie la liste des Cells préalablement remplies du MultiDoku. * Renvoie la liste des Cells préalablement remplies du MultiDoku.
*
* @return List<Cell>, vide si aucune Cell n'est remplie. * @return List<Cell>, vide si aucune Cell n'est remplie.
*/ */
public List<Cell> getFilledCells() { public List<Cell> getFilledCells() {
List<Cell> result = new ArrayList<>(); List<Cell> result = new ArrayList<>();
for (Cell cell : this.getCells()){ for (Cell cell : this.getCells()) {
if (!cell.isEmpty()) { if (!cell.isEmpty()) {
result.add(cell); result.add(cell);
} }
@@ -170,11 +125,12 @@ public class MultiDoku {
/** /**
* Renvoie la liste des Cells vides du MultiDoku. * Renvoie la liste des Cells vides du MultiDoku.
*
* @return List<Cell>, vide si aucune Cell ne l'est. * @return List<Cell>, vide si aucune Cell ne l'est.
*/ */
public List<Cell> getEmptyCells() { public List<Cell> getEmptyCells() {
List<Cell> result = new ArrayList<>(); List<Cell> result = new ArrayList<>();
for (Cell cell : this.getCells()){ for (Cell cell : this.getCells()) {
if (cell.isEmpty()) { if (cell.isEmpty()) {
result.add(cell); result.add(cell);
} }
@@ -182,9 +138,9 @@ public class MultiDoku {
return result; return result;
} }
/** /**
* Vide une Cell donnée. * Vide une Cell donnée.
*
* @param cell Cell, à vider. * @param cell Cell, à vider.
*/ */
public void empty(Cell cell) { public void empty(Cell cell) {
@@ -195,6 +151,7 @@ public class MultiDoku {
/** /**
* Renvoie le nombre de Cell contenue dans le MultiDoku. * Renvoie le nombre de Cell contenue dans le MultiDoku.
*
* @return int, nombre de Cell dans le MultiDoku. * @return int, nombre de Cell dans le MultiDoku.
*/ */
public int getNbCells() { public int getNbCells() {
@@ -209,5 +166,34 @@ public class MultiDoku {
filledCell.setImmutable(); filledCell.setImmutable();
} }
} }
}
public StateManager getStateManager() {
return stateManager;
}
/**
* Renvoie une Cell vide choisie aléatoirement.
*
* @param rand Random, pour le choix aléatoire.
* @return Cell, une Cell vide.
*/
public Cell getRandomEmptyCell(Random rand) {
List<Cell> emptyCells = getEmptyCells();
int randomIndex = rand.nextInt(emptyCells.size());
return emptyCells.get(randomIndex);
}
public void clearMutableCells() {
for (Sudoku s : getSubGrids()) {
for (Cell cell : s.getCells()) {
if (cell.isMutable())
cell.clearCurrentSymbol();
}
}
}
public MultiDoku clone() {
//TODO: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah
return SudokuSerializer.deserializeSudoku(SudokuSerializer.serializeSudoku(this));
}
}

View File

@@ -0,0 +1,41 @@
package org.polytech.ryuk.sudoku.structure;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
//TODO: doc
public class StateManager {
private final Stack<Map<Cell, Integer>> states;
private final MultiDoku doku;
public StateManager(MultiDoku doku) {
this.states = new Stack<>();
this.doku = doku;
}
public void pushState() {
states.add(new HashMap<>());
saveState();
}
public void popState() {
assert (states.size() > 0);
restoreState();
states.pop();
}
private void restoreState() {
for (var entry : this.states.getLast().entrySet()) {
entry.getKey().setSymbolIndex(entry.getValue());
}
}
private void saveState() {
for (Cell cell : this.doku.getCells()) {
states.getLast().put(cell, cell.getSymbolIndex());
}
}
}

View File

@@ -1,12 +1,10 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
import sudoku.constraint.BlockConstraint;
import sudoku.constraint.Constraint;
import sudoku.constraint.IConstraint;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.polytech.ryuk.sudoku.constraint.Constraint;
/** /**
* @class Sudoku * @class Sudoku
* @brief Représent un Sudoku * @brief Représent un Sudoku
@@ -89,22 +87,6 @@ public class Sudoku {
return true; return true;
} }
/**
* Tente de placer le symbole value dans la Cell de coordonnées x, y.
* @param x int, abscisse de la Cell voulue.
* @param y int, coordonnée de la Cell voulue;
* @param value int, index du symbole que l'on veut placer.
* @return boolean, true si le symbole a été placé, false sinon
*/
public boolean tryPlaceCellSymbol(int x, int y, int value) {
assert (isValidCoords(x, y));
if (!canBePlaced(x, y, value))
return false;
Cell cell = getCell(x, y);
cell.setSymbolIndex(value);
return true;
}
/** /**
* Vide la Cell dotn les coordonnées sont renseignées de son symbole. * Vide la Cell dotn les coordonnées sont renseignées de son symbole.
* @param x int, abscisse de la Cell voulue. * @param x int, abscisse de la Cell voulue.
@@ -194,7 +176,7 @@ public class Sudoku {
} }
public Cell getCell(int x, int y) { public Cell getCell(int x, int y) {
int index = y * getSize() + x; int index = toIndex(x, y);
assert (isValidCoords(x, y)); assert (isValidCoords(x, y));
try { try {
return this.cells.get(index); return this.cells.get(index);
@@ -232,62 +214,6 @@ public class Sudoku {
return this.cells.contains(cell); return this.cells.contains(cell);
} }
/**
* Localise la Cell dans le Sudoku.
* @param c Cell, cellule dont on veut les coordonées.
* @return Coordinate, coordonnées de la Cell.
* @throws Exception si la Cell n'appartient pas au Sudoku.
*/
private Coordinate getCoordinateCell(Cell c) throws Exception {
int x = 0, y = 0;
int size = this.getSize();
if (!this.contains(c)) {
throw new Exception("The given cell is not in this sudoku.");
}
// TODO: use this.cells.indexOf();
for (Cell cell : this.cells) {
if (cell == c) {
return new Coordinate(x, y);
}
if (x == size - 1) {
y += 1;
x = 0;
} else {
x += 1;
}
}
return new Coordinate(x, y);
}
/**
* Met à jour les symboles possibles des Cells du Sudoku.
*
*/
public void updateSymbolsPossibilities() {
for (Constraint constraint : constraints) {
List<Cell> cells = this.getCells();
for (Cell cell : cells) {
Coordinate coord = null;
try {
coord = this.getCoordinateCell(cell);
} catch (Exception e) {
System.out.println("Cas jamais atteint.");
}
List<Integer> newPossibleSymbols = cell.getPossibleSymbols();
newPossibleSymbols.retainAll(constraint.getPossibleSymbols(
this,
coord.getX(),
coord.getY()
));
cell.setPossibleSymbols(newPossibleSymbols);
}
}
}
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("Sudoku {"); sb.append("Sudoku {");
@@ -315,30 +241,6 @@ public class Sudoku {
return null; return null;
} }
/**
* Renvoie l'index des symboles possibles de la Cell passée en paramètres.
* @param cellToFill Cell, cellule dont on cherche les symboles posisbles.
* @return List<Integer>, la liste des index des symboles possibles, vide si la Cell n'appartient pas au Sudoku.
*/
public List<Integer> getPossibleSymbolsOfCell(Cell cellToFill) {
List<Integer> result = new ArrayList<>();
Coordinate cellCoordinates;
try {
cellCoordinates = this.getCoordinateCell(cellToFill);
} catch (Exception e) {
return result;
}
for (int i = 0; i < this.constraints.size(); i++) {
Constraint constraint = this.constraints.get(i);
if (i == 0) {
result.addAll(constraint.getPossibleSymbols(this, cellCoordinates.getX(), cellCoordinates.getY()));
} else {
result.retainAll(constraint.getPossibleSymbols(this, cellCoordinates.getX(), cellCoordinates.getY()));
}
}
return result;
}
/** /**
* Vérifie si le Sudoku est résolue, soit complet et cohérent avec ses contraintes. * 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. * @return boolean, valant true si le Sudoku est résolu, false sinon.
@@ -362,89 +264,20 @@ public class Sudoku {
* @return bollean, true si le Sudoku est valide, false sinon * @return bollean, true si le Sudoku est valide, false sinon
*/ */
private boolean isValid() { private boolean isValid() {
for (Cell cell : this.getFilledCells()) { for (int i = 0; i < cells.size(); i++) {
for (Constraint constraint : this.constraints) { Cell cell = getCell(i);
try { if (cell.isEmpty())
Coordinate coords = this.getCoordinateCell(cell); continue;
int symbolPlaced = cell.empty(); Coordinate coordinate = toCoords(i);
List<Integer> possibleSymbols = constraint.getPossibleSymbols(
this,
coords.getX(),
coords.getY()
);
cell.setSymbolIndex(symbolPlaced); int symbolPlaced = cell.empty();
if (!possibleSymbols.contains(symbolPlaced)) { if (!canBePlaced(coordinate.getX(), coordinate.getY(), symbolPlaced)) {
return false; cell.setSymbolIndex(symbolPlaced);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return true;
}
/**
* Renvoie la liste des Cells remplies.
* @return List<Cell>
*/
private List<Cell> getFilledCells() {
List<Cell> result = new ArrayList<>();
for (Cell cell : getCells()) {
if (!cell.isEmpty()) {
result.add(cell);
}
}
return result;
}
/**
* Renvoie la liste des Cells modifiables.
* @return List<Cell>
*/
private List<Cell> getEmptyCells() {
List<Cell> result = new ArrayList<>();
for (Cell cell : getCells()) {
if (cell.isMutable()) {
result.add(cell);
}
}
return result;
}
/**
* Renvoie la liste des Cells immuables.
* @return List<Cell>
*/
private List<Cell> getImmutableCells() {
List<Cell> result = new ArrayList<>();
for (Cell cell : getCells()) {
if (!cell.isMutable()) {
result.add(cell);
}
}
return result;
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Sudoku)) {
return false;
}
if (this.getSize() != ((Sudoku) object).getSize()) {
return false;
}
for (int i = 0; i < this.getSize(); i++) {
if (this.getCell(i).getSymbolIndex() != ((Sudoku) object).getCell(i).getSymbolIndex()) {
return false; return false;
} }
cell.setSymbolIndex(symbolPlaced);
} }
return true; return true;
} }

View File

@@ -1,4 +1,4 @@
package sudoku.structure; package org.polytech.ryuk.sudoku.structure;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
@@ -9,15 +9,10 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import sudoku.io.SudokuSerializer; import org.polytech.ryuk.sudoku.constraint.Constraint;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import sudoku.constraint.BlockConstraint; import org.polytech.ryuk.sudoku.solver.RandomSolver;
import sudoku.constraint.ColumnConstraint; import org.polytech.ryuk.sudoku.solver.Solver;
import sudoku.constraint.Constraint;
import sudoku.constraint.DiagonalConstraint;
import sudoku.constraint.IConstraint;
import sudoku.constraint.LineConstraint;
import sudoku.solver.Solver;
public class SudokuFactory { public class SudokuFactory {
@@ -121,9 +116,8 @@ public class SudokuFactory {
* @return boolean, valant true si un MultiDoku de difficulté donnée peut être créée, false sinon. * @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. * @throws Exception si la difficulté n'est pas compatible avec la taille du MultiDoku.
*/ */
public static boolean newDokuFromFilledOne(MultiDoku doku, int nbCellsToEmpty) throws Exception { public static boolean newDokuFromFilledOne(MultiDoku doku, int nbCellsToEmpty, Solver solver) throws Exception {
System.out.println("nbCellsToEmpty : "+nbCellsToEmpty);
if (nbCellsToEmpty >= doku.getCells().size()) { if (nbCellsToEmpty >= doku.getCells().size()) {
throw new Exception(); throw new Exception();
} }
@@ -140,10 +134,9 @@ public class SudokuFactory {
int oldSymbol = cellToEmpty.empty(); int oldSymbol = cellToEmpty.empty();
int nbDokuSultions = Solver.countSolution(doku); int nbDokuSultions = solver.countSolution(doku);
System.out.println("oldSymbol : "+oldSymbol);
if (nbDokuSultions == 1) { if (nbDokuSultions == 1) {
if (newDokuFromFilledOne(doku, --nbCellsToEmpty)) { if (newDokuFromFilledOne(doku, --nbCellsToEmpty, solver)) {
return true; return true;
} }
} }
@@ -188,21 +181,22 @@ public class SudokuFactory {
* @param sudoku2 Sudoku, second sudoku à connecter. * @param sudoku2 Sudoku, second sudoku à connecter.
* @param offset Coordinate, décalage entre les deux Sudokus. * @param offset Coordinate, décalage entre les deux Sudokus.
*/ */
private static void linkSquareSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) { private static void linkRectangleSudokus(Sudoku sudoku1, Sudoku sudoku2, Coordinate offset) {
int blockWidth = sudoku1.getBlockWidth(); int blockWidth = sudoku1.getBlockWidth();
for (int dx = 0; dx < blockWidth; dx++) { int blockHeight = sudoku1.getSize() / blockWidth;
for (int dx = 0; dx < blockHeight; dx++) {
for (int dy = 0; dy < blockWidth; dy++) { for (int dy = 0; dy < blockWidth; dy++) {
int block1X = dx + offset.getX(); int block1X = dx + offset.getX();
int block1Y = dy + offset.getY(); int block1Y = dy + offset.getY();
int block2X = dx; int block2X = dx;
int block2Y = dy; int block2Y = dy;
if ((block1X < blockWidth) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) { if ((block1X < blockHeight) && (block1X >= 0) && (block1Y >= 0) && (block1Y < blockWidth)) {
Block block1 = sudoku1.getBlocks().get(block1Y * blockWidth + block1X); Block block1 = sudoku1.getBlocks().get(block1Y * blockHeight + block1X);
Block block2 = sudoku2.getBlocks().get(block2Y * blockWidth + block2X); Block block2 = sudoku2.getBlocks().get(block2Y * blockHeight + block2X);
// on remplace le bloc // on remplace le bloc
sudoku2.getBlocks().set(block2Y * blockWidth + block2X, block1); sudoku2.getBlocks().set(block2Y * blockHeight + block2X, block1);
block1.getSudokus().add(sudoku2); block1.getSudokus().add(sudoku2);
// on remplace les cellules // on remplace les cellules
@@ -238,10 +232,10 @@ public class SudokuFactory {
Sudoku sudoku4 = createSquareSudoku(size, constraints); Sudoku sudoku4 = createSquareSudoku(size, constraints);
Sudoku sudoku5 = createSquareSudoku(size, constraints); Sudoku sudoku5 = createSquareSudoku(size, constraints);
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size)); linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - size, 1 - size));
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size)); linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(size - 1, 1 - size));
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1)); linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - size, size - 1));
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(size - 1, size - 1)); linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(size - 1, size - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5)); return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
} }
@@ -270,21 +264,19 @@ public class SudokuFactory {
Sudoku sudoku4 = createRectangleSudoku(width, height, constraints); Sudoku sudoku4 = createRectangleSudoku(width, height, constraints);
Sudoku sudoku5 = createRectangleSudoku(width, height, constraints); Sudoku sudoku5 = createRectangleSudoku(width, height, constraints);
linkSquareSudokus(sudoku1, sudoku2, new Coordinate(1 - width, 1 - height)); linkRectangleSudokus(sudoku1, sudoku2, new Coordinate(1 - height, 1 - width));
linkSquareSudokus(sudoku1, sudoku3, new Coordinate(width - 1, 1 - height)); linkRectangleSudokus(sudoku1, sudoku3, new Coordinate(height - 1, 1 - width));
linkSquareSudokus(sudoku1, sudoku4, new Coordinate(1 - width, height - 1)); linkRectangleSudokus(sudoku1, sudoku4, new Coordinate(1 - height, width - 1));
linkSquareSudokus(sudoku1, sudoku5, new Coordinate(width - 1, height - 1)); linkRectangleSudokus(sudoku1, sudoku5, new Coordinate(height - 1, width - 1));
return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5)); return new MultiDoku(Arrays.asList(sudoku1, sudoku2, sudoku3, sudoku4, sudoku5));
} }
public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception { public static void fillDoku(MultiDoku doku, Difficulty difficulty) throws Exception {
Solver.solveRandom(doku, random); Solver solver = new RandomSolver();
solver.solve(doku);
int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells()); int nbCellsToEmpty = (int) (difficulty.getFactor() * doku.getNbCells());
boolean successfull = newDokuFromFilledOne(doku, nbCellsToEmpty); boolean successfull = newDokuFromFilledOne(doku, nbCellsToEmpty, solver);
if (!successfull) {
throw new Exception("Canno't create this doku with this difficulty");
}
doku.setFilledCellsImmutable(); doku.setFilledCellsImmutable();
} }
@@ -298,4 +290,28 @@ public class SudokuFactory {
return null; return null;
} }
} }
public static MultiDoku createBasicEmptyRandomBlockDoku(int blockSize, List<Constraint> constraints) {
int blockCellCount = blockSize * blockSize;
List<Cell> cells = initCells(blockCellCount);
List<Cell> homeLessCells = new ArrayList<>();
homeLessCells.addAll(cells);
List<Block> blocks = new ArrayList<>();
Random r = new Random();
for (int i = 0 ; i < blockCellCount; i++) {
Block b = new Block();
for (int j = 0; j < blockCellCount; j++) {
int cellIndex = r.nextInt(homeLessCells.size());
Cell cell = homeLessCells.remove(cellIndex);
b.addCell(cell);
cell.setBlock(b);
}
blocks.add(b);
}
Sudoku sudoku = new Sudoku(cells, blocks, constraints);
for (Block block : blocks) {
block.getSudokus().add(sudoku);
}
return new MultiDoku(Arrays.asList(sudoku));
}
} }

View File

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

View File

@@ -1,177 +0,0 @@
package sudoku.solver;
import sudoku.io.SudokuPrinter;
import sudoku.structure.MultiDoku;
import sudoku.structure.Cell;
import sudoku.structure.Sudoku;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CancellationException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Solver {
/**
* Log du Solver, qui garde trace des actions réalisées.
*/
private static final Logger logger = Logger.getLogger("SolverLogger");
/**
* Résout, si possible, le multidoku passé en paramètre
* en testant toutes les possibilités, de manière aléatoire, avec un algorithme
* de backtracking.
*
* @param doku Multidoku, à résoudre
* @param rand Random, pour tester aléatoirement les symboles
* @return boolean, true s'il est résolu ou false s'il ne l'est pas.
*/
public static boolean solveRandom(MultiDoku doku, Random rand) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
while (!possibleSymbols.isEmpty()) {
int nextPossibleSymbolIndex = rand.nextInt(possibleSymbols.size());
int nextSymbol = possibleSymbols.get(nextPossibleSymbolIndex);
cellToFill.setSymbolIndex(nextSymbol);
if (Solver.solveRandom(doku, rand)) {
return true;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
possibleSymbols.remove(nextPossibleSymbolIndex);
}
return false;
}
/**
* Compte le nombre de solutions possibles au MultiDoku passé en paramètres.
* @param oldDoku MultiDoku, MultiDoku dont on veut le nombre de solutions.
* @return int, nombre de solutions possibles.
*/
public static int countSolution(MultiDoku oldDoku) {
int result = 0;
MultiDoku doku = oldDoku.clone();
if (doku.isSolved()) {
return 1;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
System.out.println("AAAAAAAAAAAAAA");
return 0;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
System.out.println("symbol : "+symbol);
System.out.println("doku.isSolved() || Solver.solve(doku) ? "+ (doku.isSolved() || Solver.solve(doku)));
if (doku.isSolved() || Solver.solve(doku)) {
result++;
}
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
}
return result;
}
/**
* Résout le MultiDoku passé en paramètre, avec backtracking.
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
public static boolean solve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
if (doku.isSolved()) {
return true;
}
Cell cellToFill = doku.getFirstEmptyCell();
if (cellToFill == null) {
return false;
}
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
if (possibleSymbols.isEmpty()) {
return false;
}
for (int symbol : possibleSymbols) {
cellToFill.setSymbolIndex(symbol);
if (Solver.solve(doku)) {
return true;
} else {
cellToFill.setSymbolIndex(Cell.NOSYMBOL);
}
}
return false;
}
/**
* Résout le MultiDoku passé en paramètre, sans backtracking.
* @param doku MultiDoku, MultiDoku à résoudre.
* @return boolean, valant true si le MultiDoku est résolu, false sinon.
*/
public static boolean humanSolve(MultiDoku doku) {
if (Thread.interrupted())
throw new CancellationException("User wants to stop the solver");
List<Cell> cellsToFill = doku.getEmptyCells();
while (!cellsToFill.isEmpty()) {
Sudoku sudoku = doku.getSubGrid(0);
logger.log(Level.FINE,
'\n' + SudokuPrinter.toStringRectangleSudoku(sudoku,
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getBlockWidth(),
sudoku.getBlockWidth() == 0 ? sudoku.getSize() : sudoku.getSize() / sudoku.getBlockWidth()));
boolean blocked = true;
for (Cell cellToFill : cellsToFill) {
List<Integer> possibleSymbols = doku.getPossibleSymbolsOfCell(cellToFill);
if (possibleSymbols.size() != 1) {
continue;
}
cellToFill.setSymbolIndex(possibleSymbols.getFirst());
cellsToFill.remove(cellToFill);
blocked = false;
break;
}
if (blocked) {
break;
}
}
return doku.isSolved();
}
}

View File

@@ -1,14 +0,0 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package sudoku;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test void appHasAGreeting() {
Main classUnderTest = new Main();
assertNotNull(classUnderTest.getGreeting(), "app should have a greeting");
}
}

View File

@@ -1,36 +1,41 @@
package sudoku; package sudoku;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File; import java.io.File;
import java.util.Random; import java.util.Random;
import org.json.JSONObject; import org.json.JSONObject;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.polytech.ryuk.sudoku.io.SudokuSerializer;
import sudoku.io.SudokuSerializer; import org.polytech.ryuk.sudoku.solver.RandomSolver;
import sudoku.solver.Solver; import org.polytech.ryuk.sudoku.structure.MultiDoku;
import sudoku.structure.MultiDoku; import org.polytech.ryuk.sudoku.structure.SudokuFactory;
import sudoku.structure.SudokuFactory;
public class SudokuSerializerTest { public class SudokuSerializerTest {
void testSerializeWithSize(int blockWidth, int blockHeight, Random r) { void testSerializeWithSize(int blockWidth, int blockHeight) {
MultiDoku sudoku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight, var sudoku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
SudokuFactory.DEFAULT_CONSTRAINTS); SudokuFactory.DEFAULT_CONSTRAINTS);
Solver.solveRandom(sudoku, r); new RandomSolver().solve(sudoku);
JSONObject data = SudokuSerializer.serializeSudoku(sudoku); JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data); MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
assert (data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString())); assertTrue(data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
} }
void testSaveWithSize(int blockWidth, int blockHeight, Random r) { void testSaveWithSize(int blockWidth, int blockHeight) {
MultiDoku doku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight, MultiDoku doku = SudokuFactory.createBasicEmptyRectangleDoku(blockWidth, blockHeight,
SudokuFactory.DEFAULT_CONSTRAINTS); SudokuFactory.DEFAULT_CONSTRAINTS);
Solver.solveRandom(doku, r); new RandomSolver().solve(doku);
String savePath = SudokuSerializer.saveMultiDoku(doku); String savePath = SudokuSerializer.saveMultiDoku(doku);
MultiDoku otherDoku = null; MultiDoku otherDoku = null;
try { try {
otherDoku = SudokuFactory.fromfile(savePath); otherDoku = SudokuFactory.fromfile(savePath);
assert (otherDoku != null); assert (otherDoku != null);
assertEquals(SudokuSerializer.serializeSudoku(doku).toString(),
SudokuSerializer.serializeSudoku(otherDoku).toString());
// clean file after test // clean file after test
File fileToDelete = new File(savePath); File fileToDelete = new File(savePath);
fileToDelete.delete(); fileToDelete.delete();
@@ -38,27 +43,35 @@ public class SudokuSerializerTest {
e.printStackTrace(); e.printStackTrace();
assert false; assert false;
} }
assert (doku.equals(otherDoku)); }
void testSerializeX(int size) {
var sudoku = SudokuFactory.createBasicXShapedMultidoku(size, SudokuFactory.DEFAULT_CONSTRAINTS);
new RandomSolver().solve(sudoku);
JSONObject data = SudokuSerializer.serializeSudoku(sudoku);
MultiDoku multiDoku = SudokuSerializer.deserializeSudoku(data);
assertTrue(data.toString().equals(SudokuSerializer.serializeSudoku(multiDoku).toString()));
} }
@Test @Test
void testSerialize() { void testSerialize() {
Random r = new Random(); Random r = new Random();
testSerializeWithSize(3, 3, r); int testCount = 20;
/**
int testCount = 5;
for (int i = 0; i < testCount; i++) { for (int i = 0; i < testCount; i++) {
int blockWidth = r.nextInt(10) + 1; int blockWidth = r.nextInt(4) + 1;
int blockHeight = r.nextInt(10) + 1; int blockHeight = r.nextInt(4) + 1;
testSerializeWithSize(blockWidth, blockHeight, r); testSerializeWithSize(blockWidth, blockHeight);
} }
for (int i = 0; i < testCount; i++) { for (int i = 0; i < testCount; i++) {
int blockWidth = r.nextInt(10) + 1; int blockWidth = r.nextInt(4) + 1;
int blockHeight = r.nextInt(10) + 1; int blockHeight = r.nextInt(4) + 1;
testSaveWithSize(blockWidth, blockHeight, r); testSaveWithSize(blockWidth, blockHeight);
}
for (int i = 0; i < testCount; i++) {
int size = r.nextInt(2) + 2;
testSerializeX(size);
} }
*/
} }
} }

View File

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